---
title: A pose graph
summary: "The example pose_graph, read top-down: a robot's poses and landmarks on SE(3) built tick by tick, a hundred datasets drawn from the model, estimated together by Levenberg–Marquardt, and the Laplace marginals checked for calibration against the truth."
order: 4
depends_on: [guide/least-squares]
---

# A pose graph

A robot drives a closed circuit.
It measures its own motion between ticks by odometry, and the landmarks it passes by a range sensor that returns their positions in its frame.
The example `pose_graph`, in the umbrella crate's `examples/`, builds that model once, draws a hundred datasets from it, each with its own truth, and estimates all of them together: the mode of every dataset, and a Laplace marginal for every pose and landmark.
Then it asks whether those marginals are honest, by counting how often the truth falls inside them.
It runs in CI, and fails when a check fails:

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

<ExampleFigure
	name="pose-graph" alt="A closed circuit of 73 poses and 24 landmarks.
	Dead reckoning on the odometry drifts by up to 1.49 m; the estimate follows the dashed truth to within 34 cm, and a zoom at true scale shows each estimated pose with its 90% ellipse around the truth." caption="One of the hundred datasets: the truth, the start dead reckoning gives, and the estimate with its 90% ellipses, from above and from the side."
/>

## The model, tick by tick

Each tick adds a pose, scored by a prior at the first tick and by the commanded motion from the previous pose after it; the odometry, the relative motion between the two poses with an error; each landmark seen for the first time, with a broad prior about its nominal position; and each sighting, the landmark's position in the pose's frame with an error.
Every term is a [normal](/concepts/the-normal.md), on $SE(3)$ for the poses and the odometry and on $\R^3$ for the rest:

From `crates/skoro/examples/common/model.rs`, lines 24–78:

```rust
/// Adds tick `k` inside the open scope: the pose `pose/k`, scored by the prior at `k = 0` and by
/// the motion term from `previous` after; the odometry `odometry/{k-1}` from `previous`; each
/// landmark `landmark/j` first sighted at `k`, scored by its prior; each sighting `sighting/k/j`.
/// `landmarks` holds every landmark already in the model, by index, and gains the new ones.
pub fn tick(
    scenario: &Scenario,
    k: usize,
    previous: Option<Q<Pose>>,
    landmarks: &mut BTreeMap<usize, Q<Vector<3>>>,
) -> Tick {
    let scales = &scenario.scales;
    let pose = quantity(format!("pose/{k}"), Pose);
    let odometry = match previous {
        None => {
            let first = constant(Pose, scenario.nominal[0]);
            Normal::on(Pose, first, Scale::sds(&scales.first)).score(pose);
            None
        }
        Some(previous) => {
            // The command u_{k-1}, the nominal motion between the ticks, as a mapped value of
            // constants.
            let command = constant(Pose, scenario.nominal[k - 1])
                .between(constant(Pose, scenario.nominal[k]));
            Normal::on(Pose, previous * command, Scale::sds(&scales.motion)).score(pose);
            let odometry = quantity(format!("odometry/{}", k - 1), Pose);
            Normal::on(Pose, previous.between(pose), Scale::sds(&scales.odometry)).score(odometry);
            Some(odometry)
        }
    };
    let mut new_landmarks = Vec::new();
    let mut sightings = Vec::new();
    for &(_, j) in scenario.sightings.iter().filter(|&&(at, _)| at == k) {
        let landmark = *landmarks.entry(j).or_insert_with(|| {
            let m = quantity(format!("landmark/{j}"), Vector::<3>);
            let nominal = constant(Vector::<3>, scenario.landmarks[j]);
            Normal::on(Vector::<3>, nominal, Scale::sd(scales.landmark)).score(m);
            new_landmarks.push((j, m));
            m
        });
        let z = quantity(format!("sighting/{k}/{j}"), Vector::<3>);
        Normal::on(
            Vector::<3>,
            pose.untransform(landmark),
            Scale::sd(scales.sighting),
        )
        .score(z);
        sightings.push((j, z));
    }
    Tick {
        pose,
        odometry,
        new_landmarks,
        sightings,
    }
}
```

The same function serves [the sliding window](/guide/sliding-window.md), which calls it once per tick in a build of its own.
Which landmark each pose sights is fixed from the nominal trajectory, before anything is drawn: the structure of a model is not random.

## A hundred datasets

The whole circuit is built in one build.
Generating from it with nothing observed draws the truth and its measurements together, a hundred rows of them, each its own dataset with the one structure.
The query observes the measurements, row by row, with `observe_value`, and each row starts where dead reckoning on its own odometry puts it:

From `crates/skoro/examples/common/batch.rs`, lines 27–61:

```rust
/// Builds the scenario's model, draws `rows` datasets from `seed` with nothing observed, observes
/// every odometry and sighting at the drawn rows, and starts every row.
pub fn dataset(scenario: &Scenario, rows: usize, seed: u64, target: &Target) -> Result<Dataset> {
    let mut writer = Writer::new();
    let ticks: Vec<Tick> = writer.build(|| {
        let mut landmarks = BTreeMap::new();
        let mut previous = None;
        (0..=scenario.last())
            .map(|k| {
                let t = tick(scenario, k, previous, &mut landmarks);
                previous = Some(t.pose);
                t
            })
            .collect()
    })?;
    let snapshot = writer.snapshot();
    let truth = snapshot
        .generate(&Observations::new(), &Key::from_seed(seed), rows, target)?
        .values;
    let mut given = Observations::new();
    for t in &ticks {
        for q in measurements(t) {
            given = given.observe_value(q, value(&truth, q)?);
        }
    }
    let start = start(scenario, &ticks, &truth, rows, target)?;
    Ok(Dataset {
        snapshot,
        ticks,
        truth,
        given,
        start,
        rows,
    })
}
```

Since the truth is drawn from the model, the model is right by construction: what the example tests is the estimation, not the modelling.

## Rows, and what each solves

A **row**, in skoro, is one independent copy of the whole computation, as a batch of tensors has rows: here, one dataset.
It is not a coordinate of the state, nor a row of a Jacobian.
Every value the model holds, generated, observed or estimated, has one entry per row, and the rows never meet:

<Matrices kind="rows" />

So the hundred datasets are estimated _together_ only in that they share the compiled programs, the schedule and every pass.
Each row is its own estimation problem, and each is a **batch** estimate in the sense of state estimation: one least-squares problem over every pose and every landmark of its trajectory at once, a smoother rather than a filter.
Its Jacobian has a row for each component of each term's residual and a column for each tangent coordinate, 1,776 rows and 510 columns here, 6 for each of the 73 poses and 3 for each of the 24 landmarks.
Its sparsity is the graph's, drawn here for a graph of eight poses and four landmarks:

<Matrices kind="jacobians" />

The last sighting, of $m_0$ from $x_7$, reaches back to the start: it closes the loop, and it is why the batch recovers what dead reckoning lost.
[The sliding window](/guide/sliding-window.md) solves a problem of the same kind over its last five poses alone, with everything before them folded into one dense replacement over what they still share with the past.
It never makes that closing sighting, since $m_0$ has already been retired.

## The mode of every row

One linearizer and one schedule serve all hundred rows.
`LevenbergMarquardt` finds each row's mode, damping and stopping each row on its own, and `decrement` checks that every row stopped at a stationary point of its density:

From `crates/skoro/examples/pose_graph.rs`, lines 60–74:

```rust
// 2. The mode of every row.
let linearizer = Linearizer::new(&snapshot, &query, &target, Assembly::Residual)?;
let schedule = linearizer.schedule()?;
let method = LevenbergMarquardt::default();
let minimized = method.minimize(&linearizer, &schedule, &start)?;
converged(&minimized.rows, "the batch")?;
let mode = minimized.point;

// 3. Stationarity, by the undamped decrement.
let bound = 10.0 * method.tolerance;
stationary(
    &decrement(&linearizer, &schedule, &mode)?,
    bound,
    "the batch",
)?;
```

Every row converges, in eight or nine iterations.
The two checks the code makes, `converged` and `stationary`, test different things, and the rest of this section says what.

### What a step promises

Write $f$ for the negative log-density of a row's query, and $\hat \point$ for the row's current point.
Linearized there, in the chart at $\hat \point$, it is a least-squares problem in the tangent step $\tangent$:

$$
	f(\hat \point \oplus \tangent) \approx m(\tangent) = f(\hat \point) + \tfrac12 \lvert J \tangent + r \rvert^2 - \tfrac12 \lvert r \rvert^2 ,
$$

with $r$ the stacked whitened residuals of every term and $J$ their Jacobian, the matrix drawn above; the log-volumes of the terms on $SE(3)$ are folded into $r$, so that $m$ agrees with $f$ to first order.
Its gradient at $\tangent = 0$ is the gradient of $f$ in the chart, $g = J\transpose r$.
A Levenberg–Marquardt step minimizes $m$ with a penalty on its length, $\tfrac12 \lambda\, \tangent\transpose D \tangent$, with $D$ Marquardt's diagonal [](eq:math/levenberg-marquardt/marquardt), so that $(J\transpose J + \lambda D)\, \tangent = -g$, and the decrease of $m$ it promises is

$$
	\Delta(\tangent) = m(0) - m(\tangent) = \tfrac12 \lvert J \tangent \rvert^2 + \lambda\, \tangent\transpose D \tangent ,
$$

which is `Problem::promised`.
It is measured in nats, like $f$, and it does not depend on how the chart's coordinates are scaled, where the norm of $g$ or of $\tangent$ would.

### When a row stops

The step is taken if $f$ actually decreased, if the gain [](eq:math/levenberg-marquardt/gain), the decrease obtained over $\Delta(\tangent)$, is positive, and $\lambda$ is updated from the gain by Nielsen's schedule [](eq:math/levenberg-marquardt/schedule).
The row stops, `Status::Converged`, at the first step that promises $\Delta(\tangent) \le \epsilon$, with $\epsilon = 10^{-9}$ nats, whether that step was taken or not.
Near the mode a step promises little more than the rounding of $f$, $u \lvert f \rvert \approx 4 \times 10^{-13}$ nats with $\lvert f \rvert \approx 3700$ here and $u$ the unit roundoff of double precision, and the gain of such a step is rounding of either sign: the last step of the first row promises $1.7 \times 10^{-12}$ nats, and its gain is $-0.27$.
Waiting for an acceptance would raise $\lambda$ until the row was reported as failing when it had converged.
A row whose $\lambda$ passes $10^{10}$, or whose iterations pass a hundred, ends with another status, and `converged` fails the example on it.

### Why the point is stationary

A small promise bounds the distance to the mode only while $\lambda$ is small: with $\lambda$ large, $\Delta$ is small because the damping shortened the step, not because there is nowhere to go.
So stationarity is checked apart from the stop, at the final point and with no damping.
With $\lambda = 0$ the step is Gauss–Newton's, $\tangent_0 = -(J\transpose J)^{-1} g$, and its promise, the **decrement**, is

$$
	\delta = \tfrac12 \lvert J \tangent_0 \rvert^2 = \tfrac12\, g\transpose (J\transpose J)^{-1} g \ \ge\ \frac{\lvert g \rvert^2}{2\, h_{\max}} ,
$$

with $h_{\max}$ the largest eigenvalue of $J\transpose J$.
Every pose has a prior or a motion term and every landmark a prior, so $J$ has full rank, $J\transpose J$ is invertible, and $\delta$ is zero exactly where $g$ is: where the point is stationary for $f$, log-volumes included.
`decrement` computes it for every row, and `stationary` fails the example unless every row's is at most $10\, \epsilon$.
It is the decrease of $f$ a full Gauss–Newton step would still give, in nats, so the check says that no step left could gain more than $10^{-8}$ nats.

## Are the uncertainties honest?

At the mode, the [Laplace approximation](/concepts/linearization.md#steps-marginals-and-the-laplace-approximation) gives every pose and landmark a normal marginal in its own chart.
The truth's tangent at the estimate, from `Layout::local`, whitened by the marginal, is the normalized error; if the marginals are calibrated it follows the chi-squared law with as many degrees of freedom as the quantity has dimensions, and the 90% ellipsoid holds the truth nine times in ten, over datasets drawn from the model.
[The note on calibration](/math/calibration.md) says why, and how large a difference the approximation itself should make.

<ExampleFigure
	name="calibration" alt="Two histograms, of 7,300 pose errors and 2,400 landmark errors, lying on the chi-squared densities with 6 and 3 degrees of freedom; 92.0% of poses and 92.3% of landmarks fall inside their 90% ellipsoids, within the tolerances of 5.0 and 5.4 points." caption="The normalized errors of every pose and landmark of every dataset, against the chi-squared density each follows when its marginal is calibrated."
/>

The example checks it, with a tolerance fixed before it runs, not tuned to its result:

From `crates/skoro/examples/pose_graph.rs`, lines 215–226:

```rust
// 4, checked: the scales are in the regime the tolerance was designed for.
check(variance <= SIGMA_PHI * SIGMA_PHI, || {
    format!(
        "the largest rotational standard deviation {:.4} exceeds {SIGMA_PHI}: the scales \
         left the regime the check's tolerance was designed for",
        variance.sqrt()
    )
})?;
// 5. The calibrations, each against its tolerance.
let kappa = variance;
calibrated("poses", &pose_calibration, SLOPE_6 * kappa)?;
calibrated("landmarks", &landmark_calibration, SLOPE_3 * kappa)?;
```

## Drawing it

With `SKORO_FIGURES` naming a directory, the example also writes the data of these figures, and `bin/figures` draws them:

```sh
SKORO_FIGURES=/tmp/figures cargo run --release -p skoro --example pose_graph
bin/figures /tmp/figures
```
