Autonomy: rangefinders, maps, avoidance and precision landing · 7 MIN READ

Behaviour trees for autonomy: sequences, fallbacks, conditions and actions ticked every step

Build a behaviour tree from Sequence, Fallback, Condition and Action nodes that return Success, Failure or Running, tick it at 10 Hz to fly 'inspect then return; on low battery return; on obstacle hold', trace its ticks deterministically and compare it with the flight-modes lesson's state machine.

The flight-modes lesson wrote the vehicle's modes as a transition table. A table works while every state can be listed, but autonomy adds reactions that apply everywhere: whatever the drone is doing, a low battery sends it home and an obstacle ahead stops it. In a table, each such reaction is a row from every state, plus a way back to whatever it interrupted. A behaviour tree writes each reaction once, as a branch in priority order, and evaluates the tree again on every control step. Game AI made behaviour trees popular, and robotics adopted them for the same reason: reactive behaviour that stays readable as it grows.

drones · A MAP OF THE IDEA

  1. Conditions read the world
  2. Safety branches first
  3. Mission steps idempotent
  4. Tick, trace, halt

Useful when

  • A new reaction is one branch, not a row per state.
  • Priorities are visible in the order of the branches.

Watch out

  • Conditions without hysteresis chatter at thresholds.
  • Restarted sequences repeat work unless steps are idempotent.

Implementation & operation cost: Four node types, a blackboard, a fixed tick rate and a trace of every status change.

01

Four kinds of node, three answers

Every node answers a tick with Success, Failure or Running, and Running means 'not finished, tick me again'. Conditions check the world and never command anything: battery below 30 percent, or an obstacle within 6 m ahead. Actions command the vehicle once when they start and then report progress: Running while the go-to flies, Success on arrival, Failure after a crash. A Sequence ticks its children in order and stops at the first that does not succeed, so it fits a guard followed by an action, or the steps of a mission. A Fallback, also called a Selector, ticks its children in order and stops at the first that does not fail, so its children are alternatives in priority order. Both are written here in their reactive form, like ReactiveSequence and ReactiveFallback in BehaviorTree.CPP. Every tick starts again from the first child, so conditions are checked again every 100 ms, and a running action is halted as soon as a condition before it changes.

go
// Sequence ticks its children from the first on every tick and returns the
// first status that is not Success (BehaviorTree.CPP's ReactiveSequence).
type Sequence []Node

// Fallback ticks its children from the first on every tick and returns the
// first status that is not Failure (ReactiveFallback): earlier children have
// priority.
type Fallback []Node

func (s Sequence) Tick() Status { return tick(s, Success) }
func (f Fallback) Tick() Status { return tick(f, Failure) }
func (s Sequence) Halt()        { halt(s) }
func (f Fallback) Halt()        { halt(f) }

func tick(children []Node, next Status) Status {
	for i, c := range children {
		if st := c.Tick(); st != next {
			halt(children[i+1:]) // they may have been running on the last tick
			return st
		}
	}
	return next
}
Read the code

The two composites differ in one value: a Sequence moves on while children return Success, a Fallback while they return Failure. Whatever stops the loop is returned, and every later child is halted, because one of them may have been running on the previous tick. When the obstacle condition starts to succeed, the obstacle branch returns Running, and the mission's go-to, further along the Fallback, is halted before the hold action commands the vehicle.

02

The tree, and what Running means for a mission

The root is a Fallback of three branches, highest priority first. The first branch is battery below 30 percent, then return home. The second is an obstacle within 6 m on the line to the current target, then hold. The third is the mission: take off; inspect A, B and C with three seconds of photos each; return home. A reactive sequence restarts from its first child on every tick and after every halt, so mission steps must not repeat work. Each records its success on the blackboard, the state the nodes share, and answers Success at once from then on. The blackboard also carries the current target, and the obstacle condition looks along it with d.Range. That condition has hysteresis: it turns true below 6 m and false again only beyond 8 m. A hold stops the drone near the threshold, where 3 cm of sensor noise could flip a single-threshold condition on every tick and make the drone alternate between hold and go-to.

03

Two flights, one tree

Both flights tick the same tree at 10 Hz, one tick every five physics steps, to inspect a 40 m tower from three points 10 m away at 12 m altitude. The first flight starts on a full battery on a clear site. The second starts on 35 percent, with a crane standing on the leg from A to B. The trace prints a line whenever the ticked action, its status or the vehicle's mode changes, together with the condition that put a safety branch in charge.

go
package main

import (
	"fmt"
	"log"
	"math"
	"strings"

	"gopherforge.app/drone"
)

type Status int

const (
	Failure Status = iota
	Success
	Running
)

func (s Status) String() string { return [...]string{"FAILURE", "SUCCESS", "RUNNING"}[s] }

// Node is ticked on every control step. Halt stops a node that was running
// when a branch before it takes over.
type Node interface {
	Tick() Status
	Halt()
}

// Sequence ticks its children from the first on every tick and returns the
// first status that is not Success (BehaviorTree.CPP's ReactiveSequence).
type Sequence []Node

// Fallback ticks its children from the first on every tick and returns the
// first status that is not Failure (ReactiveFallback): earlier children have
// priority.
type Fallback []Node

func (s Sequence) Tick() Status { return tick(s, Success) }
func (f Fallback) Tick() Status { return tick(f, Failure) }
func (s Sequence) Halt()        { halt(s) }
func (f Fallback) Halt()        { halt(f) }

func tick(children []Node, next Status) Status {
	for i, c := range children {
		if st := c.Tick(); st != next {
			halt(children[i+1:]) // they may have been running on the last tick
			return st
		}
	}
	return next
}

func halt(nodes []Node) {
	for _, n := range nodes {
		n.Halt()
	}
}

// Blackboard is what the nodes share.
type Blackboard struct {
	Active, Why string          // the action ticked last, and the condition behind it
	Done        map[string]bool // mission steps already achieved
	Target      drone.Vec3      // where the vehicle is meant to fly
}

// Condition checks the world; it never commands the vehicle.
type Condition struct {
	bb   *Blackboard
	Test func() (bool, string)
}

func (c *Condition) Tick() Status {
	if ok, why := c.Test(); ok {
		c.bb.Why = why
		return Success
	}
	return Failure
}
func (c *Condition) Halt() {}

// Action commands the vehicle once when it starts, then reports progress.
// A mission step (Once) keeps reporting Success after it has succeeded, so a
// sequence restarted from its first child skips what is already done.
type Action struct {
	Name    string
	bb      *Blackboard
	Once    bool
	Start   func() error
	Check   func() Status
	running bool
}

func (a *Action) Tick() Status {
	if a.Once && a.bb.Done[a.Name] {
		return Success
	}
	if !a.running {
		if err := a.Start(); err != nil {
			return Failure
		}
		a.running = true
	}
	a.bb.Active = a.Name
	st := a.Check()
	if st != Running {
		a.running = false
		a.bb.Done[a.Name] = a.Once && st == Success
	}
	return st
}
func (a *Action) Halt() { a.running = false }

const alt = 12.0

// tree is "inspect then return; on low battery return; on obstacle hold".
func tree(sim *drone.Sim, d *drone.Drone, bb *Blackboard) Node {
	// until is Running until done holds, and Failure after a crash.
	until := func(done func() bool) func() Status {
		return func() Status {
			switch {
			case d.State().Mode == drone.Crashed:
				return Failure
			case done():
				return Success
			}
			return Running
		}
	}
	home := func(branch string) *Action {
		return &Action{Name: branch + "/return home", bb: bb, Once: true,
			Start: func() error { bb.Target = d.Home(); return d.ReturnHome() },
			Check: until(func() bool { return d.State().Landed })}
	}
	inspect := func(name string, p drone.Vec3) *Action {
		since := -1.0
		return &Action{Name: "mission/inspect " + name, bb: bb, Once: true,
			Start: func() error { bb.Target, since = p, -1; return d.GoTo(p) },
			Check: until(func() bool {
				if since < 0 && d.Arrived() {
					since = sim.Time()
				}
				return since >= 0 && sim.Time()-since >= 3 // three seconds of photos
			})}
	}
	near := false
	return Fallback{
		Sequence{
			&Condition{bb, func() (bool, string) {
				b := d.Telemetry().Battery
				return b < 30, fmt.Sprintf("battery %.0f%%", b)
			}},
			home("battery"),
		},
		Sequence{
			&Condition{bb, func() (bool, string) {
				to := bb.Target.Sub(d.State().Pos).Horizontal()
				r := d.Range(math.Atan2(to.Y, to.X))
				near = r < to.Len() && (r < 6 || near && r < 8) // hysteresis: no chatter
				return near, fmt.Sprintf("obstacle %.1f m ahead", r)
			}},
			&Action{Name: "obstacle/hold", bb: bb, Start: d.Hold, Check: func() Status { return Running }},
		},
		Sequence{
			&Action{Name: "mission/take off", bb: bb, Once: true, Check: until(d.Arrived),
				Start: func() error {
					if err := d.Arm(); err != nil {
						return err
					}
					return d.TakeOff(alt)
				}},
			inspect("A", drone.Vec3{X: 30, Y: -10, Z: alt}),
			inspect("B", drone.Vec3{X: 40, Z: alt}),
			inspect("C", drone.Vec3{X: 30, Y: 10, Z: alt}),
			home("mission"),
		},
	}
}

func fly(title, file string, cfg drone.Config) {
	sim := drone.New(cfg)
	d := sim.Drone()
	bb := &Blackboard{Done: map[string]bool{}}
	root := tree(sim, d, bb)
	fmt.Println(title)
	last, ticks := "", 0
	for st := Running; st == Running && sim.Time() < 300; ticks++ {
		bb.Why = ""
		st = root.Tick() // 10 Hz: one tick every five physics steps
		if line := fmt.Sprintf("%-20s %-8s %-7s", bb.Active, st, d.State().Mode); line != last {
			fmt.Printf("  %5.1f s  %s\n", sim.Time(), strings.TrimSpace(line+" "+bb.Why))
			last = line
		}
		sim.Run(0.1, nil)
	}
	fmt.Printf("  %d ticks, battery %.0f%%\n", ticks, d.State().Battery)
	if err := sim.SaveAs(file); err != nil {
		log.Fatal(err)
	}
}

func main() {
	tower := drone.Obstacle{Name: "tower", X: 30, Radius: 1.5, Height: 40}
	crane := drone.Obstacle{Name: "crane", X: 37, Y: -3, Radius: 1.5, Height: 25}
	wind := drone.Vec3{X: 2, Y: 1}
	fly("clear site, battery 100%:", "clear", drone.Config{Wind: wind, Gust: 1, MaxSpeed: 5, Seed: 4,
		Obstacles: []drone.Obstacle{tower}})
	fly("crane on the leg to B, battery 35%:", "flight", drone.Config{Wind: wind, Gust: 1, MaxSpeed: 5, Seed: 4,
		Battery: 35, Obstacles: []drone.Obstacle{tower, crane}})
}
Read the code

On the clear site only the mission branch runs. After the take-off, each inspection shows GOTO and then HOLD while the photos are taken, the return home goes RTL and then LAND, and the root succeeds at 50.1 s after 502 ticks with 89 percent left. In the second flight the first four lines are the same. At 17.0 s, 0.9 s after inspect B started, 'obstacle 5.6 m ahead' puts obstacle/hold in charge and halts the go-to. The drone holds for 9.6 s, until the battery branch, earlier in the Fallback, takes over at 26.6 s with 'battery 29%' and flies home. The root succeeds at 46.7 s with 25 percent left, and B and C are never inspected. Neither safety branch knows about the other; their order sets the priority.

04

The same behaviour as a state machine

As a transition table in the style of the flight-modes lesson, this behaviour needs a state per mission step (TAKEOFF, INSPECT_A, INSPECT_B, INSPECT_C, RETURN) plus HOLD and RTL. Battery low needs a row from each airborne state to RTL, and the obstacle a row from each moving state to HOLD. HOLD then needs a way back to the step it interrupted, which a flat table can express only with one HOLD state per step or a remembered history. Every new reaction multiplies the rows, while in the tree it is one more branch in the right place. The table still wins where it is strong: it lists every allowed transition, rejects everything else with a reason, and can be checked for completeness. Autopilots keep their own modes as explicit state machines, and the tree here commands those modes rather than replacing them. When the autopilot changes mode by itself, a condition should notice, just as the flight-modes lesson reconciles its table with the vehicle.

05

Tick rate, halting and tests

A tree reacts only as fast as it is ticked. At 10 Hz a drone at 5 m/s moves 0.5 m between ticks, which is why the obstacle was 5.6 m ahead, not 6.0 m, when the hold began. Long actions never block a tick: they command, return Running and check again on the next tick. Halt must be cheap and must leave the vehicle ready for the next command. Here it only forgets that an action had started, and the branch that takes over sends the new command. The tree reads the world only through conditions and is ticked by the program, so a test can drive it with a scripted vehicle and assert the trace, and the two flights here are such tests. BehaviorTree.CPP, a C++ library whose main use is robotics, adds asynchronous actions, trees loaded from XML at run time, and logging that records every status change for replay and analysis, for example in its Groot2 editor.

06

Fly it in GopherForge

In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. Output lists clear.gfflight, the full inspection, and flight.gfflight, in which the drone stops short of the crane and flies home on a low battery; the timeline shows each go-to, the hold and the return. Start the second flight on 60 percent and the hold lasts until 159.2 s, when the battery reaches 29 percent. Move the crane to Y: -15, off the leg, and the battery branch interrupts the go-to C instead, at 25.8 s.

TAKE THIS WITH YOU

A behaviour tree ticks Sequences, Fallbacks, Conditions and Actions on every control step, and each node answers Success, Failure or Running. Put safety branches first in a reactive Fallback, guard each with a condition, and halt whatever they pre-empt. Give conditions hysteresis, and make mission steps idempotent so that restarting a sequence costs nothing. Keep the autopilot's own mode machine underneath.

Check your understanding

A reactive Fallback has three children: a battery-low branch, an obstacle branch and the mission. What does it return on a tick?

Go to the source

Progress stays in this browser. No account needed.