package main
import (
"testing"
"algo/metrics"
)
func testWGraph() *WGraph { return buildWeightedTrails(1000, 62, 12, 1) }
// tableWGraph is the six-node graph from the lesson's trace. Edges are added in
// this order, so every node's neighbour list is in this order too.
//
// edges (a-b:cost): 0-1:4 0-2:1 1-2:2 1-3:5 2-4:12 3-4:3 3-5:2
func tableWGraph() *WGraph {
g := NewWGraph(6)
for _, e := range [][3]int32{
{0, 1, 4}, {0, 2, 1}, {1, 2, 2}, {1, 3, 5}, {2, 4, 12}, {3, 4, 3}, {3, 5, 2},
} {
g.AddEdge(e[0], e[1], e[2])
}
return g
}
// isWPath checks a path is real and that its edges add up to the reported cost.
func isWPath(g *WGraph, p []int32, from, to, cost int32) bool {
if len(p) == 0 || p[0] != from || p[len(p)-1] != to {
return false
}
total := int32(0)
for i := 1; i < len(p); i++ {
found := false
for _, e := range g.Neighbors(p[i-1]) {
if e.To == p[i] {
total += e.Cost
found = true
break
}
}
if !found {
return false
}
}
return total == cost
}
// refDistances is the reference: the true cheapest cost to every node, by
// Bellman-Ford — slow and simple, and sharing nothing with Dijkstra.
func refDistances(g *WGraph, from int32) []int32 {
const inf = int32(1) << 30
d := make([]int32, g.Nodes())
for i := range d {
d[i] = inf
}
d[from] = 0
for round := 0; round < g.Nodes(); round++ {
changed := false
for v := 0; v < g.Nodes(); v++ {
if d[v] == inf {
continue
}
for _, e := range g.Neighbors(int32(v)) {
if d[v]+e.Cost < d[e.To] {
d[e.To] = d[v] + e.Cost
changed = true
}
}
}
if !changed {
break
}
}
return d
}
func wpathsEqual(a, b []int32) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// THE TABLE IS THE SPECIFICATION. 0 -> 4 on the lesson's graph: the cheapest
// route is [0 2 1 3 4] at 11 days, found by settling all six nodes and spending
// exactly nine units of heap work. These numbers were produced by running the
// algorithm, not by hand.
func TestDijkstraHeapReproducesTheTable(t *testing.T) {
var c metrics.Counter
p, cost, settled, ok := DijkstraHeap(tableWGraph(), 0, 4, &c)
want := []int32{0, 2, 1, 3, 4}
if !ok || !wpathsEqual(p, want) || cost != 11 || settled != 6 || c.N() != 9 {
t.Errorf("DijkstraHeap 0 to 4: found=%v path=%v cost=%d settled=%d work=%d; want path %v cost 11 settled 6 work 9",
ok, p, cost, settled, c.N(), want)
}
}
// THE HEAP MUST AGREE WITH AN INDEPENDENT REFERENCE for every reachable
// destination — cost and path both.
func TestDijkstraHeapFindsTheCheapestRoute(t *testing.T) {
g := testWGraph()
ref := refDistances(g, 0)
const inf = int32(1) << 30
var c metrics.Counter
checked := 0
for to := int32(1); int(to) < g.Nodes(); to++ {
p, cost, _, ok := DijkstraHeap(g, 0, to, &c)
if ref[to] == inf {
if ok {
t.Fatalf("node %d: reached, but it is not reachable", to)
}
continue
}
if !ok {
t.Fatalf("node %d: missed, but the cheapest route costs %d", to, ref[to])
}
if cost != ref[to] {
t.Fatalf("node %d: cost %d, the cheapest is %d", to, cost, ref[to])
}
if !isWPath(g, p, 0, to, cost) {
t.Fatalf("node %d: the path does not add up to %d", to, cost)
}
checked++
}
if checked < 100 {
t.Fatalf("only %d destinations checked", checked)
}
t.Logf("%d destinations, every one at the cheapest cost", checked)
}
// LAZY DELETION MEANS THE HEAP HOLDS MORE ENTRIES THAN THERE ARE NODES. If a
// version of this settles exactly one entry per node, it is doing decrease-key,
// which is a different structure with a different cost.
func TestTheHeapHoldsStaleEntries(t *testing.T) {
g := testWGraph()
var c metrics.Counter
pushes, settled := 0, 0
// Re-run the search counting pushes by hand.
const inf = int32(1) << 30
dist := make([]int32, g.Nodes())
done := make([]bool, g.Nodes())
for i := range dist {
dist[i] = inf
}
dist[0] = 0
h := NewNodeHeap(g.Nodes())
h.Push(0, 0, &c)
pushes++
for h.Len() > 0 {
v, d, _ := h.Pop(&c)
if done[v] {
continue
}
done[v] = true
settled++
for _, e := range g.Neighbors(v) {
if nd := d + e.Cost; nd < dist[e.To] {
dist[e.To] = nd
h.Push(e.To, nd, &c)
pushes++
}
}
}
if pushes <= settled {
t.Fatalf("%d pushes for %d settled nodes — no stale entries, so this is not lazy deletion", pushes, settled)
}
t.Logf("%d pushes settled %d nodes: %d stale entries skipped (%.2f pushes per node)",
pushes, settled, pushes-settled, float64(pushes)/float64(settled))
}
// THE HONEST LIMIT, ASSERTED. Dijkstra requires non-negative weights. Given a
// negative edge it does not slow down or error — it returns a WRONG answer,
// because it settles a node before a cheaper route to it has been found.
//
// The graph, searching from 0 to 2:
//
// 0 --1--- 2 the direct route, cost 1
// 0 --2--- 1 --(-5)--- 2 the detour, cost 2 + (-5) = -3
//
// Node 2 is reached at 1 and SETTLED before node 1 is ever popped, so the
// cheaper detour is never considered. The order in which nodes are settled is
// the whole of Dijkstra's argument, and a negative edge destroys it: settling a
// node no longer means its distance is final.
func TestDijkstraIsWrongOnNegativeWeights(t *testing.T) {
g := NewWGraph(3)
g.AddEdge(0, 2, 1)
g.AddEdge(0, 1, 2)
g.AddEdge(1, 2, -5)
var c metrics.Counter
_, cost, _, ok := DijkstraHeap(g, 0, 2, &c)
if !ok {
t.Fatal("no route found at all")
}
const truth = int32(-3)
if cost == truth {
t.Fatal("Dijkstra returned the true optimum on a negative edge — " +
"that is luck, not correctness, and the demonstration is gone")
}
t.Logf("Dijkstra answered %d; the true cheapest route costs %d", cost, truth)
}
// The same graph, the same pair, with no queue at all: the same path and cost,
// and thirty-six units of work — six choices, each looking at all six nodes —
// against the heap's nine.
func TestDijkstraScanReproducesTheTable(t *testing.T) {
var c metrics.Counter
p, cost, settled, ok := DijkstraScan(tableWGraph(), 0, 4, &c)
want := []int32{0, 2, 1, 3, 4}
if !ok || !wpathsEqual(p, want) || cost != 11 || settled != 6 || c.N() != 36 {
t.Errorf("DijkstraScan 0 to 4: found=%v path=%v cost=%d settled=%d work=%d; want path %v cost 11 settled 6 work 36",
ok, p, cost, settled, c.N(), want)
}
}
// Lesson 14's route on the same graph: two hops, and 13 days — two days more
// than the cheapest.
func TestBFSWReproducesTheTable(t *testing.T) {
g := tableWGraph()
var c metrics.Counter
p, ok := BFSW(g, 0, 4, &c)
want := []int32{0, 2, 4}
if !ok || !wpathsEqual(p, want) || g.PathCost(p) != 13 {
t.Errorf("BFSW 0 to 4: found=%v path=%v cost=%d; want path %v cost 13",
ok, p, g.PathCost(p), want)
}
}
// THE TWO FRONTIERS MUST AGREE. Swapping the priority queue changes how long the
// search takes and nothing else — which is what makes the comparison in step 6
// meaningful at all.
func TestBothFrontiersReturnTheSameCost(t *testing.T) {
g := testWGraph()
var hc, sc metrics.Counter
checked := 0
for to := int32(1); int(to) < g.Nodes(); to++ {
hp, hcost, _, ok1 := DijkstraHeap(g, 0, to, &hc)
_, scost, _, ok2 := DijkstraScan(g, 0, to, &sc)
if ok1 != ok2 {
t.Fatalf("node %d: heap found %v, scan found %v", to, ok1, ok2)
}
if !ok1 {
continue
}
checked++
if hcost != scost {
t.Fatalf("node %d: heap cost %d, scan cost %d", to, hcost, scost)
}
if !isWPath(g, hp, 0, to, hcost) {
t.Fatalf("node %d: the heap's path does not add up to %d", to, hcost)
}
}
if checked < 100 {
t.Fatalf("only %d destinations checked", checked)
}
t.Logf("%d destinations, identical cost every time; heap queue work %d, scan %d (%.1fx)",
checked, hc.N(), sc.N(), float64(sc.N())/float64(hc.N()))
}
// FEWEST HOPS IS NOT CHEAPEST. Lesson 14's answer is never better than
// Dijkstra's and is often worse — asserted so the distinction survives.
func TestFewestHopsIsNotCheapest(t *testing.T) {
g := testWGraph()
var bc, hc metrics.Counter
worse, equal := 0, 0
var worstGap int32
for to := int32(1); int(to) < g.Nodes(); to++ {
bp, ok1 := BFSW(g, 0, to, &bc)
_, cost, _, ok2 := DijkstraHeap(g, 0, to, &hc)
if !ok1 || !ok2 {
continue
}
bcost := g.PathCost(bp)
if bcost < cost {
t.Fatalf("node %d: BFS route costs %d, cheaper than the cheapest (%d)", to, bcost, cost)
}
if bcost == cost {
equal++
} else {
worse++
if gap := bcost - cost; gap > worstGap {
worstGap = gap
}
}
}
if worse == 0 {
t.Fatal("the fewest-hops route was always the cheapest — then the weights are doing nothing")
}
t.Logf("BFS route: cheapest %d, more expensive %d, worst excess %d days", equal, worse, worstGap)
}
func BenchmarkDijkstraHeap(b *testing.B) {
g := testWGraph()
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
DijkstraHeap(g, 0, 999, &c)
}
}
func BenchmarkDijkstraScan(b *testing.B) {
g := testWGraph()
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
DijkstraScan(g, 0, 999, &c)
}
}
func BenchmarkDijkstraHeapAllPairs(b *testing.B) {
g := testWGraph()
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
for to := int32(1); int(to) < g.Nodes(); to += 10 {
DijkstraHeap(g, 0, to, &c)
}
}
}
func BenchmarkDijkstraScanAllPairs(b *testing.B) {
g := testWGraph()
var c metrics.Counter
b.ResetTimer()
for i := 0; i < b.N; i++ {
for to := int32(1); int(to) < g.Nodes(); to += 10 {
DijkstraScan(g, 0, to, &c)
}
}
}