Documentation
¶
Overview ¶
Package hpastar is a universal solver of paths over a state space: the cheapest sequence of states from one state to another, found by A* over any graph a Transitions and a Heuristic describe, a puzzle, a plan or a grid alike, and by HPA* between ends far apart where the states lie in a plane.
A Solver is made once over a graph.Implicit by NewSolver and shared; each goroutine asks it through a Search of its own, whose Path writes the path into the caller's buffer and allocates nothing once warm. Reaches says whether a path exists at all, and Stats counts what a Search did.
import (
"github.com/kjkrol/hpastar"
"github.com/kjkrol/hpastar/graph"
)
solver := hpastar.NewSolver(graph.Implicit[point]{Forward: steps, Heuristic: manhattan})
search := solver.Search()
n, found := search.Path(from, to, dst) // dst[:n], from first
A path is the cheapest where its graph keeps the contract package graph states: a Transition's Cost added to the path's and never negative, a Heuristic never estimating more than the cheapest cost left, a step refused a Transition not generated. A Heuristic scaled above the cheapest cost left (Weighted A*) expands fewer states and trades the cheapest path for one found sooner.
HPA* ¶
Where the states lie at integer coordinates in a plane (a square or a hex grid, a torus through its Transitions), a graph's Layout has paths between ends far apart found by HPA*, not A*: Hierarchical Path-Finding A* (Botea, Müller and Schaeffer, 2004). The plane is cut into clusters, and those into clusters of clusters, level over level; each cluster keeps entrances on its borders and the cheapest paths between them within it; a path is searched over the entrances of the highest level its ends' distance allows and refined down the paths kept only as far as the caller's buffer holds, so a path asked again from its last state goes on from there cheaply. Its paths cost about 1.02 times the cheapest on average and 1.05 at worst on the tests' maps. Ends nearer than WithNear asks, a state Coords places nowhere and any path asked while the hierarchy is not Ready are found by A*, the cheapest; ends no path joins are told apart off the hierarchy's labels of connected entrances, not by searching all a start reaches.
The graph may change while its Solver lives: a step added or taken away, the cost of a step or the classes it refuses changed. Changed marks the first-level clusters a changed state's steps run through, ChangedAll every one, and Update rebuilds them, and the clusters above only as far as the change reaches, a budget of work at a time: the same calls make the same progress on any machine. Paths asked meanwhile are found by A*.
Classes ¶
A graph may serve up to 8 classes of search at once, each with steps of its own: a step some classes cannot take carries their bits in its Refuses (graph.Implicit's Classes). A Search asks for one class at a time (Search.Class), its paths, reaches and expansions those of a Solver over the steps the class takes alone; the hierarchy keeps a view of each class, read off the graph once a cluster, so its memory and its fills grow with the classes. A graph of one class reads no Refuses.
Concurrency ¶
The Searches of one Solver may ask at once, each on its own goroutine, and the functions of its graph and Layout are called by all of them at once; Changed, ChangedAll and Update run between their asks, never during one.
Packages ¶
The module's root holds the Solver, the Search and their options, and package graph the contract they take. The engines behind them are internal, a package each: the A* search, its heap and its dictionaries, the fill from several sources, and the hierarchy of HPA* with its build and its climbs. The Solver and the Search call the engines, the hierarchy calls A* and the fill, and neither of those knows the hierarchy.
Example (Layout) ¶
package main
import (
"fmt"
"math"
"github.com/kjkrol/hpastar"
"github.com/kjkrol/hpastar/graph"
)
type point struct{ X, Y int }
func main() {
const size = 48
// open ground, a wall down the middle open at the bottom, mud past it
wall := make(map[point]bool)
for y := range 40 {
wall[point{X: size / 2, Y: y}] = true
}
share := func(p point) float64 {
switch {
case p.X < 0 || p.Y < 0 || p.X >= size || p.Y >= size || wall[p]:
return 0
case p.X > 30 && p.Y > 30:
return 0.3
}
return 1
}
dirs := [8]point{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}
length := func(i int) float64 { return 1 + (math.Sqrt2-1)*float64(i/4) }
// a step costs its length over the share of the cell it enters
forward := func(from, _ point, buf []graph.Transition[point]) []graph.Transition[point] {
for i, d := range dirs {
if to := (point{X: from.X + d.X, Y: from.Y + d.Y}); share(to) > 0 {
buf = append(buf, graph.Transition[point]{To: to, Cost: length(i) / share(to)})
}
}
return buf
}
// the same steps seen from where they end
backward := func(to, _ point, buf []graph.Transition[point]) []graph.Transition[point] {
for i, d := range dirs {
if from := (point{X: to.X - d.X, Y: to.Y - d.Y}); share(from) > 0 && share(to) > 0 {
buf = append(buf, graph.Transition[point]{To: from, Cost: length(i) / share(to)})
}
}
return buf
}
octile := func(a, b point) float64 {
dx, dy := math.Abs(float64(a.X-b.X)), math.Abs(float64(a.Y-b.Y))
return max(dx, dy) + (math.Sqrt2-1)*min(dx, dy)
}
g := graph.Implicit[point]{
Forward: forward,
Heuristic: octile,
Index: func(p point) int { return p.Y*size + p.X },
Size: size * size,
}
exact := hpastar.NewSolver(g).Search()
g.Layout = &graph.Layout[point]{
Coords: func(p point) (int, int, bool) { return p.X, p.Y, true },
At: func(x, y int, buf []point) []point {
if p := (point{X: x, Y: y}); share(p) > 0 {
buf = append(buf, p)
}
return buf
},
Width: size,
Height: size,
Backward: backward,
}
solver := hpastar.NewSolver(g, hpastar.WithClusterSide(8))
solver.Update(0)
search := solver.Search()
cost := func(path []point) (sum float64) {
for i := 1; i < len(path); i++ {
step := 1.0
if path[i].X != path[i-1].X && path[i].Y != path[i-1].Y {
step = math.Sqrt2
}
sum += step / share(path[i])
}
return sum
}
// the path asked a piece at a time, each from where the last ended: climbed while the goal
// is far, the last piece near it found by A*
start, goal := point{X: 2, Y: 2}, point{X: 45, Y: 3}
route, piece := []point{start}, make([]point, 24)
for from := start; from != goal; from = route[len(route)-1] {
n, _ := search.Path(from, goal, piece)
route = append(route, piece[1:n]...)
}
cheapest := make([]point, size*size)
n, _ := exact.Path(start, goal, cheapest)
st := search.Stats()
fmt.Printf("%d states at %.2f, the cheapest at %.2f; %d pieces climbed, %d by A*\n",
len(route), cost(route), cost(cheapest[:n]), st.Climbs, st.Exact)
// a gap opened in the wall near the top: the graph changed there and is rebuilt
for y := 2; y <= 4; y++ {
delete(wall, point{X: size / 2, Y: y})
solver.Changed(point{X: size / 2, Y: y})
}
solver.Update(0)
whole := make([]point, size*size)
n, _ = search.Path(start, goal, whole)
k, _ := exact.Path(start, goal, cheapest)
fmt.Printf("through the gap: %d states at %.2f, the cheapest at %.2f\n", n, cost(whole[:n]),
cost(cheapest[:k]))
fmt.Println("reaches the goal:", search.Reaches(start, goal))
}
Output: 76 states at 92.81, the cheapest at 92.81; 3 pieces climbed, 1 by A* through the gap: 44 states at 44.24, the cheapest at 43.41 reaches the goal: true
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option func(*config)
Option configures a Solver as NewSolver makes it.
func WithClusterSide ¶
WithClusterSide sets the side of a cluster of the hierarchy's first level, in coordinates: 16 by default, 4 the least.
func WithNear ¶
WithNear sets how far apart, by the Heuristic, a path's ends must lie for HPA* to find it, four times farther a level up, nearer paths found by A*. It is twice a first-level cluster's side by default, for a Heuristic counting a step as 1.
func WithTreeMemory ¶
WithTreeMemory sets the memory the first level's trees of each class may take, in bytes, 64 MB by default; past it a leg is searched within its cluster instead of walked, to the same states.
type Search ¶
type Search[T comparable] struct { // contains filtered or unexported fields }
Search asks a Solver's paths on one goroutine, for one class at a time, with memory and counters of its own. The Searches of one Solver may ask at once, never while it changes or updates.
func (*Search[T]) Class ¶ added in v1.4.0
Class has the next Paths and Reaches asked for class k, 0 until it is set, as over a graph of the steps k takes alone. It panics where the graph has no class k.
Example ¶
package main
import (
"fmt"
"math"
"github.com/kjkrol/hpastar"
"github.com/kjkrol/hpastar/graph"
)
type point struct{ X, Y int }
func main() {
// a wall down the middle, open at the bottom and at a door, which class 1 cannot step into
const width, height = 7, 5
door := point{X: 3, Y: 2}
open := func(p point) bool {
inside := p.X >= 0 && p.Y >= 0 && p.X < width && p.Y < height
return inside && (p.X != 3 || p.Y == height-1 || p == door)
}
dirs := [4]point{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
steps := func(from, _ point, buf []graph.Transition[point]) []graph.Transition[point] {
for _, d := range dirs {
to := point{X: from.X + d.X, Y: from.Y + d.Y}
if !open(to) {
continue
}
step := graph.Transition[point]{To: to, Cost: 1}
if to == door {
step.Refuses = 1 << 1
}
buf = append(buf, step)
}
return buf
}
solver := hpastar.NewSolver(graph.Implicit[point]{
Forward: steps,
Heuristic: func(a, b point) float64 {
return math.Abs(float64(a.X-b.X)) + math.Abs(float64(a.Y-b.Y))
},
Index: func(p point) int { return p.Y*width + p.X },
Size: width * height,
Classes: 2,
})
search := solver.Search()
path := make([]point, width*height)
for class := range 2 {
search.Class(class)
n, found := search.Path(point{X: 0, Y: 2}, point{X: 6, Y: 2}, path)
fmt.Println(class, found, path[:n])
}
}
Output: 0 true [{0 2} {1 2} {2 2} {3 2} {4 2} {5 2} {6 2}] 1 true [{0 2} {1 2} {2 2} {2 3} {2 4} {3 4} {4 4} {5 4} {6 4} {6 3} {6 2}]
func (*Search[T]) Path ¶
Path writes the path from from to to into dst, from first, as many states as dst holds, and reports how many; false only where no path joins them. It is the cheapest, by A*, unless the hierarchy is Ready and the ends far apart, when HPA* climbs it, refined as far as dst holds.
Example ¶
package main
import (
"fmt"
"math"
"github.com/kjkrol/hpastar"
"github.com/kjkrol/hpastar/graph"
)
type point struct{ X, Y int }
// a cell's share of full speed: 1 open ground, 0.3 mud, 0 a wall
var shares = [][]float64{
{1, 1, 1},
{1, 0.3, 1},
{1, 0, 1},
}
func main() {
width, height := len(shares[0]), len(shares)
// the Manhattan distance never exceeds the cost left: no share exceeds 1, so no step costs
// less than its length
manhattan := func(a, b point) float64 {
return math.Abs(float64(a.X-b.X)) + math.Abs(float64(a.Y-b.Y))
}
dirs := [4]point{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
steps := func(from, prev point, buf []graph.Transition[point]) []graph.Transition[point] {
for _, d := range dirs {
to := point{X: from.X + d.X, Y: from.Y + d.Y}
if to.X < 0 || to.Y < 0 || to.X >= width || to.Y >= height || to == prev {
continue
}
share := shares[to.Y][to.X]
if share == 0 { // a wall: a step not generated
continue
}
buf = append(buf, graph.Transition[point]{To: to, Cost: 1 / share})
}
return buf
}
solver := hpastar.NewSolver(graph.Implicit[point]{
Forward: steps,
Heuristic: manhattan,
Index: func(p point) int { return p.Y*width + p.X },
Size: width * height,
})
search := solver.Search()
path := make([]point, width*height)
n, found := search.Path(point{X: 0, Y: 2}, point{X: 2, Y: 2}, path)
fmt.Println(found, path[:n])
}
Output: true [{0 2} {0 1} {0 0} {1 0} {2 0} {2 1} {2 2}]
type Solver ¶
type Solver[T comparable] struct { // contains filtered or unexported fields }
Solver finds paths over one graph, made once and shared by the Searches of many goroutines. With a Layout it keeps the graph's HPA* hierarchy, rebuilt where the graph changes.
func NewSolver ¶
func NewSolver[T comparable](g graph.Implicit[T], opts ...Option) *Solver[T]
NewSolver is a Solver over g, its hierarchy laid out where g has a Layout but built by Update alone. It panics where g lacks Forward or Heuristic, has more than 8 classes, or has a Layout lacking Coords, At, Backward, a plane or the graph's Index.
func (*Solver[T]) Changed ¶
func (s *Solver[T]) Changed(state T)
Changed marks for Update the clusters a change to the steps from or into state may alter, the classes a step refuses among them, the graph already changed: state's own and those across the borders it lies on. Without a Layout it does nothing.
func (*Solver[T]) ChangedAll ¶
func (s *Solver[T]) ChangedAll()
ChangedAll marks every cluster of the hierarchy's first level to be rebuilt, the levels above following where those change.
func (*Solver[T]) Ready ¶
Ready says nothing is left stale, so a Path between ends far apart climbs the hierarchy; without a Layout it is always true.
func (*Solver[T]) Search ¶
Search is a Search over the graph's own steps, for class 0.
Example ¶
package main
import (
"fmt"
"math"
"sync"
"github.com/kjkrol/hpastar"
"github.com/kjkrol/hpastar/graph"
)
type point struct{ X, Y int }
func main() {
const size = 32
door := point{X: size / 2, Y: 4}
wall := make(map[point]bool)
for y := range 24 {
if y != door.Y {
wall[point{X: size / 2, Y: y}] = true
}
}
open := func(p point) bool {
return p.X >= 0 && p.Y >= 0 && p.X < size && p.Y < size && !wall[p]
}
dirs := [4]point{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
steps := func(at, _ point, buf []graph.Transition[point]) []graph.Transition[point] {
for _, d := range dirs {
if to := (point{X: at.X + d.X, Y: at.Y + d.Y}); open(to) {
buf = append(buf, graph.Transition[point]{To: to, Cost: 1})
}
}
return buf
}
solver := hpastar.NewSolver(graph.Implicit[point]{
Forward: steps,
Heuristic: func(a, b point) float64 {
return math.Abs(float64(a.X-b.X)) + math.Abs(float64(a.Y-b.Y))
},
Index: func(p point) int { return p.Y*size + p.X },
Size: size * size,
Layout: &graph.Layout[point]{
Coords: func(p point) (int, int, bool) { return p.X, p.Y, true },
At: func(x, y int, buf []point) []point {
if p := (point{X: x, Y: y}); open(p) {
buf = append(buf, p)
}
return buf
},
Width: size,
Height: size,
Backward: steps,
},
}, hpastar.WithClusterSide(8))
solver.Update(0)
pairs := []struct{ from, to point }{
{point{X: 2, Y: 2}, point{X: 29, Y: 2}},
{point{X: 4, Y: 12}, point{X: 27, Y: 8}},
{point{X: 10, Y: 1}, point{X: 22, Y: 16}},
{point{X: 3, Y: 28}, point{X: 28, Y: 30}},
}
lengths := make([]int, len(pairs))
queries := make(chan int)
var done sync.WaitGroup
for range 3 {
// each worker asks through a Search of its own, made once and reused for every query
search, path := solver.Search(), make([]point, size*size)
go func() {
for i := range queries {
lengths[i], _ = search.Path(pairs[i].from, pairs[i].to, path)
done.Done()
}
}()
}
ask := func() {
done.Add(len(pairs))
for i := range pairs {
queries <- i
}
done.Wait()
}
ask()
fmt.Println("through the door:", lengths)
// the graph changes, and Changed and Update run, between batches, never during one
wall[door] = true
solver.Changed(door)
solver.Update(0)
ask()
fmt.Println("round the wall:", lengths)
close(queries)
}
Output: through the door: [32 36 28 28] round the wall: [72 52 44 28]
func (*Solver[T]) SearchVia ¶
func (s *Solver[T]) SearchVia(forward, backward graph.Transitions[T]) *Search[T]
SearchVia is a Search for class 0 over forward and backward, read as its goroutine reads them, which step and price as the graph's do, in the same order, but may leave out the steps the Search's class refuses; a nil one takes the graph's.
func (*Solver[T]) Update ¶
Update rebuilds what changes left stale, budget steps of work (a step about an edge a fill relaxes) and the step that spends them, all of it for a budget of 0, and reports how many clusters it finished and how many are left stale. The same calls make the same progress on any machine; without a Layout it does nothing.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
maps
command
Maps sets a Solver with a Layout, whose long paths HPA* finds, against one without, whose paths A* finds, on a map generated from a seed: the hierarchy's build, then each pair's time, expansions and cost, and the pairs no path joins.
|
Maps sets a Solver with a Layout, whose long paths HPA* finds, against one without, whose paths A* finds, on a map generated from a seed: the hierarchy's build, then each pair's time, expansions and cost, and the pairs no path joins. |
|
Package graph is the contract between a state space and the solver of package hpastar: an Implicit graph, the steps from each state (Transitions, each a Transition) and the estimate of the cost left (Heuristic), with an Index for the fastest dictionary and a Layout placing the states in a plane for HPA*.
|
Package graph is the contract between a state space and the solver of package hpastar: an Implicit graph, the steps from each state (Transitions, each a Transition) and the estimate of the cost left (Heuristic), with an Index for the fastest dictionary and a Layout placing the states in a plane for HPA*. |
|
internal
|
|
|
astar
Package astar is the A* engine of package hpastar: the cheapest path between two states of a graph, a search's states in arrays by an integer id, the open set a heap of their keys and ids and one dictionary holding every state's node, open or closed, its memory kept across searches.
|
Package astar is the A* engine of package hpastar: the cheapest path between two states of a graph, a search's states in arrays by an integer id, the open set a heap of their keys and ids and one dictionary holding every state's node, open or closed, its memory kept across searches. |
|
dict
Package dict is the dictionaries of the searches of package hpastar, from a state to the id of its node: a map by the states or by an index, a slot a state by an index, whose marks a search wipes a 255th part at a time, and the slots of a hierarchy's clusters and levels.
|
Package dict is the dictionaries of the searches of package hpastar, from a state to the id of its node: a map by the states or by an index, a slot a state by an index, whose marks a search wipes a 255th part at a time, and the slots of a hierarchy's clusters and levels. |
|
dijkstra
Package dijkstra is the fill of package hpastar's hierarchy: the states a graph's Transitions reach from several sources, settled in order of cost within a bound until given targets are, with each settled state's cost and parent, on the A* engine's heap and dictionaries.
|
Package dijkstra is the fill of package hpastar's hierarchy: the states a graph's Transitions reach from several sources, settled in order of cost within a bound until given targets are, with each settled state's cost and parent, on the A* engine's heap and dictionaries. |
|
heap
Package heap is the open set the searches of package hpastar share: a binary heap of keys and node ids, the least key first, a node's key changed in place, ties broken as container/heap breaks them.
|
Package heap is the open set the searches of package hpastar share: a binary heap of keys and node ids, the least key first, a node's key changed in place, ties broken as container/heap breaks them. |
|
hierarchy
Package hierarchy is the HPA* of package hpastar (Hierarchical Path-Finding A*: Botea, Müller and Schaeffer, 2004): a graph laid out in a plane cut into clusters, level over level, each keeping entrances on its borders and the cheapest paths between them as every class of the graph sees them, rebuilt in steps of work as far as a change reaches, and the climbs that search a level for one class and refine a path down them.
|
Package hierarchy is the HPA* of package hpastar (Hierarchical Path-Finding A*: Botea, Müller and Schaeffer, 2004): a graph laid out in a plane cut into clusters, level over level, each keeping entrances on its borders and the cheapest paths between them as every class of the graph sees them, rebuilt in steps of work as far as a change reaches, and the climbs that search a level for one class and refine a path down them. |
|
testmap
Package testmap is the maps the tests and the benchmarks of package hpastar search: square maps generated from a seed, rough ground and walls in short lines, a torus or not, walked eight ways, as hexagons or with a second state over a stretch, their steps refused to classes and each class's graph alone, and the small grids of costs the A* engine's paths are pinned on.
|
Package testmap is the maps the tests and the benchmarks of package hpastar search: square maps generated from a seed, rough ground and walls in short lines, a torus or not, walked eight ways, as hexagons or with a second state over a stretch, their steps refused to classes and each class's graph alone, and the small grids of costs the A* engine's paths are pinned on. |