hpastar

package module
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 5 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

kjkrol/hpastar

kjkrol/hpastar Logo
Go Version GoDoc License Go Quality Check

kjkrol/hpastar is a universal path solver for Go: the cheapest sequence of states from one state to another, found by A* over any state space a transition function and a heuristic describe — a puzzle, a plan, a network or a map. Where the states lie in a plane, long paths are found by HPA* over a hierarchy that follows the graph as it changes.

What is A*?

The A* (A-star) algorithm is a graph traversal and state-space search algorithm heavily used in computer science due to its completeness, optimality, and optimal efficiency. It is widely considered the industry standard for finding the shortest path or optimal sequence of transitions between nodes.

The solver knows nothing of the domain: you give it the steps a state may take (Transitions) and an estimate of the cost left (Heuristic), both of the package graph, and it is a pathfinder, a puzzle solver or a planner alike.

Installation

hpastar requires Go 1.25 or newer and depends on nothing but the standard library.

go get github.com/kjkrol/hpastar

The module's root package hpastar holds the Solver, its Search and the options; the package graph holds what a solver is given: the graph, graph.Implicit, and its steps and estimate.

import (
	"github.com/kjkrol/hpastar"
	"github.com/kjkrol/hpastar/graph"
)

The contract

A* finds the cheapest path when, and only when, what it is given keeps to four rules, which the package graph states:

  1. A Transition's Cost is added to the path's cost and is never negative.
  2. The Heuristic never estimates more than the cheapest cost left to the goal; one that does still finds a path, but not the cheapest.
  3. A consistent Heuristic — never more than a step's cost plus the estimate from the step's end — has no state expanded twice; an inconsistent one may reopen a closed state, which the search does, keeping the path the cheapest.
  4. A step that cannot be taken is a Transition not generated: there is no cost that means "never". A step only some classes cannot take is generated with their bits in its Refuses (see Classes).

Getting started

A Solver is made once over a graph.Implicit and shared; each goroutine asks it through a Search of its own, whose Path writes the path into your buffer.

A grid whose cells carry a share of full speed: 1 open ground, 0.3 mud, 0 a wall. A step costs its length divided by the share, so no step costs less than its length and the Manhattan distance never overestimates: rule 2 holds by construction.

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])
	// true [{0 2} {0 1} {0 0} {1 0} {2 0} {2 1} {2 2}]
}

Over the top costs 6; through the mud 1 + 3.33 + 1 + 1 = 6.33, so the path goes round. Lower the mud to 0.5 and it wades through: [{0 2} {0 1} {1 1} {2 1} {2 2}].

Three things to know as you scale up:

  • Index and Size give the fastest dictionary, a slot a state, 5 bytes each: the index must lie in [0, Size), any other panics. With an Index and no Size the indices key a map, and with no Index the states themselves do.
  • Path writes as many states as your buffer holds and reports how many; with Index and Size, a Search reusing its memory allocates nothing once warm, and keeps its own house — there is nothing to wipe.
  • One Search a goroutine: the Searches of one Solver may ask at once, and the graph's functions are called by all of them; SearchVia gives a goroutine's Search its own Transitions where it reads the graph its own way. ExampleSolver_Search asks from a pool of workers, a Search each, and changes the graph between two batches. Stats counts what a Search did.

Long paths: HPA*

Give the graph a Layout — where each state lies on a plane of integer coordinates, the states at a place, and the same steps seen from where they end — and paths between ends far apart are found by HPA* (Hierarchical Path-Finding A*: A. Botea, M. Müller, J. Schaeffer, Near Optimal Hierarchical Path-Finding, Journal of Game Development 1(1), 2004), not A*:

  • the plane is cut into clusters of WithClusterSide coordinates a side (16), and those into clusters of four by four, level over level, until the top has 16 clusters or fewer: 256x256 has two levels, 1024x1024 three, 4096x4096 four;
  • each cluster keeps a few entrances on its borders — the ends of every stretch of the border crossed alike, the cheapest crossing every few states, every local minimum of the crossing's cost (a road) — and the cheapest paths between them within it, with the trees that walk them;
  • Path inserts its ends into their clusters, searches the abstract graph of entrances on the highest level the ends' distance allows, and refines the path down the trees only as far as your buffer holds, so a path asked a piece at a time costs a search of the abstract graph a piece.

Its paths cost about 1.02 times the cheapest on average, 1.05 at worst, on the tests' maps. Path decides by itself: ends nearer than WithNear (two clusters' sides), a state the Layout places nowhere and any path asked while the hierarchy is not Ready are found by A*, the cheapest; ends no path joins are told off the hierarchy's labels of connected entrances in microseconds, where A* would search all the start reaches. Reaches answers from the same labels. A square grid, a hex grid and a torus (through its Transitions) are all planes; two states may share a place (a bridge over a ford).

Abstract gives the route climbed without refining it, for a caller that moves along the hierarchy's graph on its own: the entrances of the clusters of the level the climb searched that the route passes through, and the cost of each leg from the start through them to the goal, written into your buffers as Path writes; ends too near to climb take one leg, the cheapest path's cost.

n, found := search.Abstract(from, to, entrances, costs) // entrances[:n], costs[:n+1]
g.Layout = &graph.Layout[point]{
	Coords:   func(p point) (int, int, bool) { return p.X, p.Y, true },
	At:       statesAt, // every state at x, y
	Width:    width,
	Height:   height,
	Backward: stepsInto, // the steps into a state, from where they start
}
solver := hpastar.NewSolver(g)
solver.Update(0) // build the hierarchy whole

With a Layout the graph needs an Index. At lists every state Coords places at a place, but for ends of your own (a goal no state is) whose steps stay within their cluster, and Backward mirrors Forward. The package's example (Example_layout) asks a path a piece at a time and opens a gap in a wall.

A graph that changes

The graph may change while its Solver lives: a step added or taken away, the cost of a step changed. Tell the Solver which states' steps changed, between asks, and rebuild:

solver.Changed(state)                // its steps, or the steps into it, changed
built, left := solver.Update(budget) // budget steps of work; 0 rebuilds all that is stale

Changed marks the state's first-level cluster and the ones across the borders it lies on; Update rebuilds them, the lowest level first, and the clusters above only as far as the change reaches: a cluster whose entrances, their twins and the costs between them come out the same leaves the one above it as it is; one whose costs alone changed has the one above fill its costs again over the entrances it keeps; one whose entrances changed has it choose its own again. The labels of connected entrances stay where a cluster's connectivity holds, the clusters whose connectivity changed are named again from their neighbours', and the whole is worked out anew only where a component may have come apart.

The budget counts work, not time: a step is about an edge a fill relaxes (a transition read off the graph, a state settled and the checks of an edge kept weighed alike), some 0.01 µs on the test maps. A cluster is built in steps — its graph read and its entrances chosen, a fill from each entrance, its edges kept a node at a time — and a call stops on the step that spends its budget, the next going on from there, so a cluster of a high level is spread over as many calls as its work asks. built counts the clusters finished, left those still stale, the labels as one while they are worked out. The same calls make the same progress on any machine: whether a path climbs the hierarchy or is found by A* never hangs on the machine's speed. While anything is stale Path falls back to A*, so every answer is right in the meantime. On 1024x1024 a whole build takes 3 s; a cell changed amid the map is followed in 16 ms (its first-level cluster 0.64 ms, the clusters above it the rest, the labels kept), one on the borders of every level in 65 ms; on 4096x4096 either in 17 ms, the fourth level left as it is (BENCHMARKS.md has every level's share).

Classes

One graph may serve several classes of search at once, up to 8, each taking steps of its own: a step some classes cannot take carries their bits in its Refuses, and a Search asks for one class at a time.

// a step class 1 cannot take
buf = append(buf, graph.Transition[point]{To: to, Cost: 1, Refuses: 1 << 1})

solver := hpastar.NewSolver(graph.Implicit[point]{Forward: steps, Heuristic: h, Classes: 2})
search := solver.Search()
search.Class(1) // the next paths and reaches are class 1's

A class is answered exactly: its paths, its reaches and the states expanded are those a Solver over the steps it takes alone would give, with a Layout or without, climbed or not. The hierarchy keeps a whole view of each class — its entrances, the costs and trees between them, its labels of connected entrances — read off the graph once a cluster, so its memory and its rebuilds grow with the classes, the reading of the graph does not, and WithTreeMemory bounds each class's trees on its own. Changing a Search's class allocates nothing.

A change to the classes a step refuses is a change of the steps: Changed the states it touches. Backward mirrors Refuses as it mirrors the cost, and the transitions of SearchVia may leave out the steps their Search's class refuses. The labels join steps taken either way, so where a class may leave a state it cannot enter, Reaches may say true where no path is; a graph refuses such a class the steps out of the state too where that matters. A graph of one class (Classes 0 or 1) reads no Refuses, and builds, finds and counts as before, to the byte. ExampleSearch_Class has a door one class cannot pass, and its way round.

Performance

One run a scenario on an Intel Core i5-8265U (Go 1.27.1, -cpu=1), the far pair of a map generated from a seed (shares 0.13–1, 5% walls in short lines), an eighth of the side in from opposite corners, eight ways: v1.2.0's SolveInto against v1.3.0's Path without a Layout (A*) and with one (HPA*), time a path · states expanded.

Map v1.2.0 SolveInto Path, no Layout (A*) Path, a Layout (HPA*)
256x256 21.9 ms · 52,153 22.0 ms · 52,153 0.562 ms (39×) · 1,560
1024x1024 347 ms · 736,844 350 ms · 736,844 1.38 ms (251×) · 3,319
4096x4096 7.57 s · 12,450,466 7.51 s · 12,450,466 28.8 ms (263×) · 47,221

Every path allocates nothing once warm, the graphs here giving Index and Size. Without a Layout, Path is v1.2.0's search to the expansion, within one run's noise of its time; with one, the paths cost 1.016–1.019× the cheapest here. The hierarchy holds 44–48 bytes a cell (2.9 MB on 256x256, 50 MB on 1024x1024; 34 on 4096x4096, 567 MB, its trees capped at 64 MB), built whole in 0.16 s, 3.0 s and 50 s; a Search adds a dictionary of 5 bytes a slot once it searches by A*. On 1024x1024 the example below finds 100 random paths 107× faster on average at 1.017× the cheapest cost, and denies a pair no path joins in 114 µs where A* searches 995,034 states in 464 ms.

BENCHMARKS.md has every regime, the method and the history: the A* engine's own benchmarks keep their v1 names (Solver_*, in internal/astar), and v1.2.0's search in arrays by an integer id, a heap of keys and ids and one dictionary is where its speed comes from.

The example

examples/maps sets a Solver with a Layout against one without on a map generated from a seed (ground of shares 0.13–1 from smooth noise, walls in short lines, squares walled off as islands): the hierarchy's build, its time and the memory it holds, then for random pairs at least 64 apart each one's time and expansions by A* and by HPA* (the whole path and its first 64 states), the cost over the cheapest, and the pairs no path joins, which A* searches the whole map to deny.

make example-maps (1024x1024, 100 pairs) · go run ./examples/maps -size 256 · go run ./examples/maps -size 4096 -pairs 10 -islands 1 (A* takes seconds a pair there). Flags: -size (from 128; 1024), -side 16, -pairs 100, -seed 1, -walls 0.05, -islands 4, -wrap.

Packages

Package What it holds
hpastar Solver, NewSolver, Search, Stats and the options
hpastar/graph the contract: Implicit, Layout, Transition, Transitions, Heuristic
internal/astar the A* engine
internal/dijkstra the fill from several sources inserting a path's ends into the hierarchy
internal/hierarchy HPA*: the clusters, their labels, their build in steps of work, the climb
internal/heap, internal/dict the open set and the dictionaries the searches share

graph imports nothing of the module; heap and dict serve astar and dijkstra, which serve hierarchy, which the root calls with them.

Weighted A*

The contract's second rule is a trade you may make knowingly: a heuristic scaled above the cheapest cost left (h × w, w > 1, or step costs scaled down) expands far fewer states and gives up the cheapest path for one found sooner — Weighted A*.

License

kjkrol/hpastar is licensed under the MIT License. See the LICENSE file for more details.

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. Abstract gives the route climbed unrefined, for a caller moving along it on its own: the entrances it passes through on the level searched and the cost of each leg between them.

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

View Source
var (
	ErrNotReady = hierarchy.ErrNotReady
	ErrMismatch = hierarchy.ErrMismatch
	ErrNoOf     = hierarchy.ErrNoOf
	ErrCorrupt  = hierarchy.ErrCorrupt
)

What Save, Load and Dump fail with: a hierarchy not Ready, a file of a hierarchy of another shape or over another graph, a graph without Of, a file that does not read as one saved.

Functions

This section is empty.

Types

type Option

type Option func(*config)

Option configures a Solver as NewSolver makes it.

func WithClusterSide

func WithClusterSide(side int) Option

WithClusterSide sets the side of a cluster of the hierarchy's first level, in coordinates: 16 by default, 4 the least.

func WithNear

func WithNear(distance float64) Option

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

func WithTreeMemory(bytes int) Option

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[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]) Abstract added in v1.5.0

func (q *Search[T]) Abstract(from, to T, dst []T, costs []float64) (int, bool)

Abstract writes the route HPA* climbs from from to to, unrefined, and reports how many states it wrote: into dst the entrances it passes through on the level searched, as many as dst holds and costs holds less one, and into costs the cost of each leg from from through them to to. Ends too near to climb take a single leg, the cheapest path's, and false says no path joins the ends or the hierarchy tells no route: without a Layout, not Ready or an end off the plane.

func (*Search[T]) Class added in v1.4.0

func (q *Search[T]) Class(k int)

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

func (q *Search[T]) Path(from, to T, dst []T) (int, bool)

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}]

func (*Search[T]) Reaches

func (q *Search[T]) Reaches(from, to T) bool

Reaches says whether to can be reached from from, by A* without a Layout. With one it reads the hierarchy's labels, false only where it cannot: true while they are rebuilt or where an end lies off the plane.

func (*Search[T]) Stats

func (q *Search[T]) Stats() Stats

Stats is what the Search has done so far.

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]) Dump added in v1.6.0

func (s *Solver[T]) Dump(w io.Writer) (clusters int, err error)

Dump appends to w the records of what Update built since Save or Dump last wrote, the clusters finished and not stale again and the labels worked out anew, and reports how many clusters it wrote: a file Save wrote with the Dumps appended loads as the hierarchy stood after the last. Nothing without a Layout.

func (*Solver[T]) Load added in v1.6.0

func (s *Solver[T]) Load(r io.Reader) error

Load reads into the hierarchy a file Save wrote, the Dumps appended to it taken in order, and leaves it Ready, whatever it was building dropped: ErrMismatch where the file holds a hierarchy of another shape or over another graph, ErrNoOf where the graph has no Of, ErrCorrupt where the file does not read as saved, and ErrNotReady without a Layout; whatever it fails with, the hierarchy stands as before.

func (*Solver[T]) Ready

func (s *Solver[T]) Ready() bool

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]) Save added in v1.6.0

func (s *Solver[T]) Save(w io.Writer) error

Save writes the hierarchy whole to w, to be loaded by a Solver over the same graph with the same options in another run, so that none builds it again: ErrNotReady while it is not Ready, ErrNotReady too without a Layout. It writes what Dump would and leaves nothing to dump.

func (*Solver[T]) Search

func (s *Solver[T]) Search() *Search[T]

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

func (s *Solver[T]) Update(budget int) (built, left int)

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.

type Stats

type Stats struct {
	Paths      uint64 // the calls of Path
	Climbs     uint64 // the paths found by climbing the hierarchy, HPA*
	Exact      uint64 // the paths found by A*, the cheapest
	Expansions uint64 // the states expanded, the hierarchy's nodes among them
}

Stats counts what a Search has done.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL