Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

bellmanforddemo.gno

9.43 Kb · 248 lines
  1// Package bellmanforddemo is a small gnoweb demo of the shortest-path search
  2// provided by the [p/moul/x/daily/bellmanford](/p/moul/x/daily/bellmanford/v0)
  3// library: cheapest routes across a network where one hop pays a rebate, and
  4// the answer a routing table has to give when no cheapest route exists at all.
  5//
  6// It contains no search logic of its own. Stateless, so Render is
  7// deterministic: every figure below comes from the fixed graphs declared at
  8// the top of this file, never from chain state, which is what lets an example
  9// test pin the page.
 10package bellmanforddemo
 11
 12import (
 13	"strconv"
 14	"strings"
 15
 16	"gno.land/p/moul/kit/ui/v0"
 17	"gno.land/p/moul/x/daily/bellmanford/v0"
 18)
 19
 20// link is one arc of a worked example.
 21type link struct {
 22	from, to string
 23	cost     int
 24}
 25
 26// fees is a payment network with one rebate in it. The arc depot -> market
 27// pays 3 back, which is what makes the four-hop route to market cheaper than
 28// the one-hop arc of 4, and what moves depot's own best route too.
 29var fees = []link{
 30	{"gate", "hubA", 7},
 31	{"gate", "hubB", 2},
 32	{"gate", "market", 4},
 33	{"hubB", "hubA", 1},
 34	{"hubA", "depot", 2},
 35	{"hubB", "depot", 4},
 36	{"depot", "market", -3},
 37	{"market", "vault", 2},
 38}
 39
 40// loop is the same shape with one arc changed: loopB -> loopC now pays more
 41// back than the rest of the ring costs, so going round it is free money and
 42// nothing downstream has a cheapest route any more.
 43var loop = []link{
 44	{"mint", "safe", 5},
 45	{"mint", "loopA", 1},
 46	{"loopA", "loopB", 2},
 47	{"loopB", "loopC", -4},
 48	{"loopC", "loopA", 1},
 49	{"loopC", "sink", 3},
 50}
 51
 52const (
 53	feeSource  = "gate"
 54	loopSource = "mint"
 55	// isolated is in the fee graph with no arcs at all, to show that
 56	// unreachable is an answer rather than an error.
 57	isolated = "cold"
 58	// rebated names the arc the first section is about.
 59	rebated = "depot"
 60)
 61
 62// Render renders the demo for gnoweb.
 63//
 64//	Render("") / Render("/") -> the full demo
 65func Render(path string) string {
 66	var b strings.Builder
 67
 68	b.WriteString("# Bellman-Ford\n\n")
 69	b.WriteString("Cheapest routes across a graph whose arcs may cost less ")
 70	b.WriteString("than nothing, demoing the ")
 71	b.WriteString("[`p/moul/x/daily/bellmanford`](/p/moul/x/daily/bellmanford/v0) library.\n\n")
 72
 73	g := build(fees)
 74	g.AddNode(isolated)
 75	r := g.From(feeSource)
 76
 77	b.WriteString("## A fee table with a rebate in it\n\n")
 78	b.WriteString(strconv.Itoa(g.Len()) + " nodes, " + strconv.Itoa(g.Edges()))
 79	b.WriteString(" one-way arcs, priced from `" + feeSource + "`. One of them ")
 80	b.WriteString("is negative: `" + rebated + "` pays 3 back for sending on.\n\n")
 81	b.WriteString(arcTable(fees) + "\n")
 82	b.WriteString("`" + isolated + "` is in the graph with no arcs at all.\n\n")
 83
 84	b.WriteString("## Cheapest route to each node\n\n")
 85	b.WriteString(routeTable(g, r) + "\n")
 86	b.WriteString("The two rows worth reading twice are `market` and `vault`. ")
 87	b.WriteString("`market` sits one arc from the source at a cost of 4, and ")
 88	b.WriteString("the cheapest way to it is the four-arc detour through the ")
 89	b.WriteString("rebate, at 2. A search that settles a node at its best ")
 90	b.WriteString("known cost and never looks at it again would have stopped ")
 91	b.WriteString("at 4, because `" + rebated + "` is only priced later, and ")
 92	b.WriteString("`vault` would have inherited the mistake.\n\n")
 93
 94	b.WriteString("## What the rebate is worth\n\n")
 95	b.WriteString("The same network with that one arc priced at +3 instead, ")
 96	b.WriteString("so the detour is a detour and nothing else.\n\n")
 97	plain := g.From(feeSource)
 98	withoutRebate := build(repriced(fees, rebated, "market", 3))
 99	withoutRebate.AddNode(isolated)
100	noRebate := withoutRebate.From(feeSource)
101	ct := ui.NewTable("node", "with the rebate", "without it")
102	for _, n := range g.Names() {
103		ct.Row(ui.Cell(n), distCell(plain, n), distCell(noRebate, n))
104	}
105	b.WriteString(ct.String() + "\n")
106	b.WriteString("One arc, two answers changed. That is the whole reason ")
107	b.WriteString("to pay O(V*E) instead of O((V+E) log V).\n\n")
108
109	b.WriteString("## How many passes it took\n\n")
110	b.WriteString("The algorithm relaxes every arc, over and over, until a ")
111	b.WriteString("pass changes nothing. A shortest path visits each node at ")
112	b.WriteString("most once, so it is at most V-1 arcs long, and one pass ")
113	b.WriteString("extends every known route by at least one arc.\n\n")
114	pt := ui.NewTable("figure", "value", "meaning")
115	pt.Row("nodes", strconv.Itoa(g.Len()), "V")
116	pt.Row("arcs", strconv.Itoa(g.Edges()), "E")
117	pt.Row("bound", strconv.Itoa(g.Len()-1), "V-1 passes, the worst case")
118	pt.Row("passes made", strconv.Itoa(r.Rounds()), "it stopped as soon as a pass changed nothing")
119	pt.Row("improvements", strconv.Itoa(r.Relaxations()), "arcs that actually lowered a distance")
120	b.WriteString(pt.String() + "\n")
121	b.WriteString("The passes figure is decided by the order the arcs were ")
122	b.WriteString("added in, not by the graph, so it is the number to watch ")
123	b.WriteString("when gas matters.\n\n")
124
125	b.WriteString("## When there is no cheapest route at all\n\n")
126	h := build(loop)
127	hr := h.From(loopSource)
128	b.WriteString("Change one price and the ring `loopA -> loopB -> loopC` ")
129	b.WriteString("pays more back than it costs.\n\n")
130	b.WriteString(arcTable(loop) + "\n")
131	b.WriteString("Going round it once saves ")
132	b.WriteString(strconv.Itoa(-hr.CycleWeight()))
133	b.WriteString(", so going round it twice saves twice as much, and asking ")
134	b.WriteString("for the cheapest route to anything it reaches has no ")
135	b.WriteString("answer. The run says so instead of returning the total ")
136	b.WriteString("after an arbitrary number of turns:\n\n")
137	st := ui.NewTable("node", "state", "distance", "route")
138	for _, n := range h.Names() {
139		st.Row(ui.Cell(n), hr.State(n).String(), distCell(hr, n), route(hr.Path(n)))
140	}
141	b.WriteString(st.String() + "\n")
142	ct2 := ui.NewTable("what the run found", "value")
143	ct2.Row("the cycle", route(hr.Cycle()))
144	ct2.Row("one turn costs", strconv.Itoa(hr.CycleWeight()))
145	ct2.Row("nodes it poisons", names(hr.UnboundedNodes()))
146	b.WriteString(ct2.String() + "\n")
147	b.WriteString("`" + loopSource + "` and `safe` keep real distances: the ")
148	b.WriteString("cycle cannot reach them, so nothing it does changes what ")
149	b.WriteString("they are worth. Reporting the blast radius rather than ")
150	b.WriteString("failing the whole query is the difference between a fee ")
151	b.WriteString("table a realm can act on and one it has to throw away.\n\n")
152
153	b.WriteString("## What it will not do\n\n")
154	lt := ui.NewTable("limit", "value", "why")
155	lt.Row("`MaxNodes`", strconv.Itoa(bellmanford.MaxNodes), "V bounds the pass count")
156	lt.Row("`MaxEdges`", strconv.Itoa(bellmanford.MaxEdges), "E bounds the work per pass")
157	lt.Row("`MaxWeight`", strconv.Itoa(bellmanford.MaxWeight), "V times this is the largest total, well inside an int")
158	lt.Row("unknown source", "panics", "a typo must not read as \"nothing is reachable\"")
159	lt.Row("negative cycle", "reported", "it is an answer, not an error")
160	b.WriteString(lt.String() + "\n")
161	b.WriteString("There is no unreachable sentinel on `Dist`, and there ")
162	b.WriteString("cannot be: a negative total is a legitimate answer here, ")
163	b.WriteString("so every value it could reserve is one a real route might ")
164	b.WriteString("have. Ask `State` when the reason matters.\n")
165
166	return b.String()
167}
168
169// build turns a link list into a graph, arcs in declaration order, which is
170// also the order the search relaxes them in.
171func build(links []link) *bellmanford.Graph {
172	g := bellmanford.New()
173	for _, l := range links {
174		g.AddEdge(l.from, l.to, l.cost)
175	}
176	return g
177}
178
179// repriced copies a link list with one arc's cost replaced, so the two runs
180// above differ by exactly that arc and nothing else.
181func repriced(links []link, from, to string, cost int) []link {
182	out := make([]link, len(links))
183	for i, l := range links {
184		out[i] = l
185		if l.from == from && l.to == to {
186			out[i].cost = cost
187		}
188	}
189	return out
190}
191
192// arcTable renders a link list.
193func arcTable(links []link) string {
194	t := ui.NewTable("from", "to", "cost")
195	for _, l := range links {
196		t.Row(ui.Cell(l.from), ui.Cell(l.to), strconv.Itoa(l.cost))
197	}
198	return t.String()
199}
200
201// routeTable renders one run: what each node is worth and how it is reached.
202func routeTable(g *bellmanford.Graph, r *bellmanford.Result) string {
203	t := ui.NewTable("node", "state", "distance", "arrives via", "route")
204	for _, n := range g.Names() {
205		via, hasVia := r.Via(n)
206		if !hasVia && r.State(n) == bellmanford.Settled {
207			via = "source"
208		}
209		t.Row(ui.Cell(n), r.State(n).String(), distCell(r, n), ui.Cell(via), route(r.Path(n)))
210	}
211	return t.String()
212}
213
214// distCell renders a distance, or the state when there is no distance to
215// render. A blank cell would read like zero, which is a real distance here.
216func distCell(r *bellmanford.Result, node string) string {
217	d, ok := r.Dist(node)
218	if !ok {
219		return r.State(node).String()
220	}
221	return strconv.Itoa(d)
222}
223
224// route joins a path with an arrow. Each node name is escaped on its own and
225// the separator never is: running the whole joined string through the escaper
226// would turn the arrows into a literal backslash soup.
227func route(path []string) string {
228	if len(path) == 0 {
229		return ""
230	}
231	cells := make([]string, len(path))
232	for i, n := range path {
233		cells[i] = ui.Cell(n)
234	}
235	return strings.Join(cells, " -> ")
236}
237
238// names renders a node list as a comma-separated cell, escaped the same way.
239func names(in []string) string {
240	if len(in) == 0 {
241		return ""
242	}
243	cells := make([]string, len(in))
244	for i, n := range in {
245		cells[i] = ui.Cell(n)
246	}
247	return strings.Join(cells, ", ")
248}