---
title: A sliding window
summary: "The example sliding_window, read top-down: a model kept to its last few poses as a robot drives an open path, each tick appended, solved and the oldest retired with a linearized replacement, and its estimates set beside the truth and the batch."
order: 5
depends_on: [guide/pose-graph]
---

# A sliding window

A robot that drives on cannot keep every pose it has had.
The example `sliding_window` keeps a window: the last five poses, the landmarks they see, and one factor standing in for everything before.
At every tick it appends the new pose and its measurements, finds the window's mode, and retires the oldest pose with the landmarks only it still sees, replacing their terms by their linearization.
It is the model of [the pose graph](/guide/pose-graph.md), on an open path, built one tick at a time:

```sh
cargo run --release -p skoro --example sliding_window
```

<ExampleFigure
	name="sliding-window" alt="An open path of 80 poses, from above and from the side.
	Dead reckoning drifts by about 3 m, almost all of it in height; the window's filtered estimates and the batch's both stay within about a metre of the truth, the window's error mostly under its 90% radius." caption="One of the hundred datasets: the path from above and from the side, and each tick's position error in all three dimensions, for dead reckoning, the window as each pose arrives, and the batch with every measurement.
	Dead reckoning drifts mostly in height, which only the side view shows."
/>

## A tick

The truth and the measurements come from the whole path's model, drawn as the batch draws them.
The window is a second model, written by its own `Writer`, which observes the measurements as they arrive:

From `crates/skoro/examples/sliding_window.rs`, lines 55–125:

```rust
// The window's number of nodes after each tick.
let mut nodes: Vec<usize> = Vec::new();
for k in 0..=scenario.last() {
    // 1. Append, and start what was appended.
    let previous = live.newest();
    let landmarks = &mut live.landmarks;
    let appended = window.build(|| tick(&scenario, k, previous, landmarks))?;
    live.append(k, &appended, &whole.ticks[k], &whole.truth)?;
    live.start(&scenario, k, &appended, N, &target)?;

    // 2. Solve, from the previous mode.
    let snapshot = window.snapshot();
    let query = Query::log_density().given(live.observations());
    let linearizer = Linearizer::new(&snapshot, &query, &target, Assembly::Residual)?;
    let schedule = linearizer.schedule()?;
    let minimized = method.minimize(&linearizer, &schedule, &live.point)?;
    let context = format!("the window at tick {k}");
    converged(&minimized.rows, &context)?;
    stationary(
        &decrement(&linearizer, &schedule, &minimized.point)?,
        bound,
        &context,
    )?;
    iterations.extend(minimized.rows.iter().map(|o| o.iterations as f64));
    live.point = minimized.point;

    // 3. Report the newest pose's marginal: the window's filtering law of it.
    let truth = Values::new().with(
        appended.pose,
        value(&whole.truth, whole.ticks[k].pose)?.clone(),
    );
    let quantities = linearizer.layout().quantities().to_vec();
    let chart = linearizer.at_in_chart(&live.point, &quantities)?;
    let marginal =
        normalized_errors(&linearizer, &chart, &live.point, &truth, appended.pose.id())?;
    variance = marginal
        .spread
        .into_iter()
        .flatten()
        .fold(variance, f64::max);
    filtering.push(marginal.errors);
    if figures::wanted() {
        let at = rows(&live.point, appended.pose)?;
        filtered.push(Json::Object(vec![
            ("mode", figures::position(&at, 7, FIGURE_ROW)),
            ("covariance", Json::numbers(&marginal.position[FIGURE_ROW])),
        ]));
    }

    // 4. Retire the oldest pose once the window holds more than W, with the landmarks only it
    // still sees, replacing their terms by their linearization at the window's mode.
    if live.len() > W {
        let a = k - W;
        let (addresses, observed) = live.retiring(a);
        let retirement = window.retire(addresses, observed)?;
        let keep: Vec<QDyn> = retirement.plan().blanket.iter().map(|(q, ..)| *q).collect();
        let replacing = Replacing::new(&retirement, &keep, &Observations::new(), &target)?;
        let replacement = replacing.at(&live.point)?;
        retirement.replace(|_| replacement.build())?;
        live.retire(a);
    }
    nodes.push(window.snapshot().len());
}
// A retirement frees what it leaves needed by nothing, so the window stops growing once it is
// full: its count after tick 2w stays within 1.5 times its largest over the first full
// windows, the spread of the landmarks in view.
let largest = |ticks: &[usize]| ticks.iter().copied().max().unwrap_or(0);
let (first, later) = (largest(&nodes[W + 1..=2 * W]), largest(&nodes[2 * W + 1..]));
check(2 * later <= 3 * first, || {
    format!("the window grew from {first} nodes to {later}")
})?;
```

**Walkthrough: A window of two poses, retiring as it goes.** The window's probabilistic graph. A solid arrow runs from a quantity to a term conditioned on it, a dotted arrow from a term to the quantity it scores. The odometry $\otherRandomPoint_k$ and the sightings $\bfz_{kj}$ are observed; the poses $\randomPoint_k$ and the landmarks $\bfm_j$ are free. A replacement $\psi$ is a likelihood factor over the blanket of what it replaced.

1. Tick 0: the window appends the first pose with its prior, and its sighting of the landmark $\bfm_1$, seen for the first time, with its prior. (at `let appended = window.build(`; appears: $t_0$ (Term scoring a quantity), $\randomPoint_0$ (Free quantity), $t^z_{01}$ (Term scoring a quantity), $\bfz_{01}$ (Observed quantity), $\bfm_1$ (Free quantity), $t^m_1$ (Term scoring a quantity))
2. Tick 1: the next pose, the motion term from the last, the odometry between them, and a second sighting of $\bfm_1$. The odometry and the sightings are observed, at the values the whole model drew. (at `let appended = window.build(`, `live.append(`; appears: $t^u_1$ (Term scoring a quantity), $\randomPoint_1$ (Free quantity), $t^y_0$ (Term scoring a quantity), $\otherRandomPoint_0$ (Observed quantity), $t^z_{11}$ (Term scoring a quantity), $\bfz_{11}$ (Observed quantity))
3. Tick 2: a third pose, and a new landmark $\bfm_2$. (at `let appended = window.build(`; appears: $t^u_2$ (Term scoring a quantity), $\randomPoint_2$ (Free quantity), $t^y_1$ (Term scoring a quantity), $\otherRandomPoint_1$ (Observed quantity), $t^z_{22}$ (Term scoring a quantity), $\bfz_{22}$ (Observed quantity), $\bfm_2$ (Free quantity), $t^m_2$ (Term scoring a quantity))
4. The window solves for its mode, from the last mode and the starts of what was just appended. It now holds three poses, more than $w = 2$. (at `let minimized = method.minimize(`)
5. The oldest pose $\randomPoint_0$ retires, with the odometry and the sighting taken from it, observed. No landmark retires: $\randomPoint_1$ still sees $\bfm_1$. (at `let (addresses, observed) = live.retiring(a);`; becomes: $\randomPoint_0$ → Retiring quantity, $\otherRandomPoint_0$ → Retiring measurement, $\bfz_{01}$ → Retiring measurement)
6. Every term joined to them goes: the prior $t_0$, the odometry and sighting terms, and the motion term $t^u_1$, which scores $\randomPoint_1$ but is conditioned on $\randomPoint_0$. What they involve beyond the retired quantities is the Markov blanket: $\randomPoint_1$ and $\bfm_1$. (at `let retirement = window.retire(addresses, observed)?;`; becomes: $t_0$ → Term joined to them, $t^u_1$ → Term joined to them, $t^y_0$ → Term joined to them, $t^z_{01}$ → Term joined to them, $\randomPoint_1$ → Quantity in the blanket, $\bfm_1$ → Quantity in the blanket)
7. The retired terms, linearized at the window's mode and integrated over $\randomPoint_0$, leave one factor $\psi_1$ over the blanket, and the retirement puts it in their place. $\randomPoint_1$ is now scored by nothing but is held by $\psi_1$. (at `let replacing = Replacing::new(`, `let replacement = replacing.at(&live.point)?;`, `retirement.replace(|_| replacement.build())?;`; appears: $\psi_1$ (Replacement); becomes: $\randomPoint_1$ → Free quantity, $\bfm_1$ → Free quantity; goes: $\randomPoint_0$, $t_0$, $t^u_1$, $t^y_0$, $\otherRandomPoint_0$, $t^z_{01}$, $\bfz_{01}$)
8. Tick 3: the window appends a pose and its sighting of $\bfm_2$, and solves again. (at `let appended = window.build(`, `let minimized = method.minimize(`; appears: $t^u_3$ (Term scoring a quantity), $\randomPoint_3$ (Free quantity), $t^y_2$ (Term scoring a quantity), $\otherRandomPoint_2$ (Observed quantity), $t^z_{32}$ (Term scoring a quantity), $\bfz_{32}$ (Observed quantity))
9. Now $\randomPoint_1$ retires, and with it $\bfm_1$, which no other pose of the window sees. A path that never returns never sights it again. (at `let (addresses, observed) = live.retiring(a);`; becomes: $\randomPoint_1$ → Retiring quantity, $\bfm_1$ → Retiring quantity, $\otherRandomPoint_1$ → Retiring measurement, $\bfz_{11}$ → Retiring measurement)
10. The terms joined to them include the replacement $\psi_1$ and the prior of $\bfm_1$. Their blanket is $\randomPoint_2$ alone. (at `let retirement = window.retire(addresses, observed)?;`; becomes: $\psi_1$ → Replacement joined to them, $t^m_1$ → Term joined to them, $t^u_2$ → Term joined to them, $t^y_1$ → Term joined to them, $t^z_{11}$ → Term joined to them, $\randomPoint_2$ → Quantity in the blanket)
11. One factor $\psi_2$ over $\randomPoint_2$ replaces them all, and the window holds its last two poses again. Everything before them is in $\psi_2$. (at `retirement.replace(|_| replacement.build())?;`, `live.retire(a);`; appears: $\psi_2$ (Replacement); becomes: $\randomPoint_2$ → Free quantity; goes: $\randomPoint_1$, $\bfm_1$, $t^m_1$, $\psi_1$, $t^u_2$, $t^y_1$, $\otherRandomPoint_1$, $t^z_{11}$, $\bfz_{11}$)

Each tick builds itself with the same `tick` as the batch, and starts from the window's previous mode, so a solve takes six or seven iterations.
The newest pose's marginal is the window's estimate of where the robot is now, given everything measured so far.
A [retirement](/guide/least-squares.md#a-replacement-for-what-is-retired) names the oldest pose, the odometry and sightings taken from it, and every landmark no other pose of the window sees; their terms are replaced by one factor over what is left, linearized at the window's mode.
A landmark leaves the window with the last pose that sees it, since the path does not come back.

## What is reported

Every tick of every row is checked to have stopped at a stationary point, by its [decrement](/guide/pose-graph.md#why-the-point-is-stationary), as the batch is.
The window's size is checked too: a retirement [frees](/concepts/terms.md#what-a-retirement-frees) the scales, anchors and replacements it leaves needed by nothing, so the number of nodes the window holds stops growing once it is full.
Its largest count after tick $2w$ must be within 1.5 times its largest over the first full windows, ticks $w + 1$ to $2w$, which is how far the number of landmarks in view varies, and the example prints the largest count and the last.
Each tick makes its own scales from numbers, so nothing the window keeps is shared with what it retires; a model that made a measurement noise once for the whole run, as a constant every tick reads, would [pin](/concepts/terms.md#pins) it.
Two figures are reported and not checked: how often the truth falls in the window's 90% ellipsoid, beside the batch's tolerance, and how far the window's last pose is from the batch's, in the batch's standard deviations.
Each replacement is linearized at points the window later moves away from, and the error that makes is not one the mathematics bounds; checking it against the batch's tolerance would claim more than is known.

> [!DECISION] The window's calibration is reported, not checked
> [Examples that run](/archive/examples/math.md#a-sliding-window) decided it, and leaves a claim about it to a later entry on where replacements are linearized.
