skoro v0.0.0

A pose graph

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.

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:

cargo run --release -p skoro --example pose_graph
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.
A pose graph on a closed circuit: the truth, the drifting dead-reckoned start, and the Levenberg–Marquardt estimate with its 90% ellipses A pose graph, estimated One of 100 datasets: 73 poses on SE(3) around a closed circuit, 24 landmarks, 278 sightings dead reckoning ends 1.49 m off 5 m Top view (x, y) Height along the circuit, which the top view hides side view: the height axis is stretched 0 m +1 m +2 m +3 m +4 m 0 10 20 30 40 50 60 70 tick Where the circuit closes: top view, at true scale 25 cm Truth (drawn from the model) Dead reckoning on the odometry: the start Estimated poses, with 90% ellipses Estimated landmarks, with 90% ellipses True landmarks 1.49 m → 34 cm largest error, height included dead reckoning → estimate 92.0% of true poses in their 90% ellipsoid over 100 datasets, ±5.0% allowed

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, on SE(3)SE(3) for the poses and the odometry and on R3\R^3 for the rest:

crates/skoro/examples/common/model.rs lines 24–78
/// 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, 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:

crates/skoro/examples/common/batch.rs lines 27–61
/// 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:

columns: the model's quantitiesx₀x₁x₂⋯x₇₂m₀m₁⋯m₂₃rows: datasets0⋯⋯1⋯⋯2⋯⋯⋮⋮⋮⋮⋱⋮⋮⋮⋱⋮99⋯⋯Row 0 is one dataset: its own truth, measurements, start and estimate.Each column holds one value per row: a pose's 7 numbers, a landmark's 3.The rows share programs and passes, and nothing else.

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:

The batch: the whole trajectoryposeslandmarks012345670123first posemotion and odometrylandmark priorssightingsA sliding window: its last five posesposeslandmarks34567123the past, replacedmotion and odometrylandmark priorssightingsrows: residual components, a block per termcolumns: tangent coordinates, a block per quantity: 6 for a pose, 3 for a landmark

The last sighting, of m0m_0 from x7x_7, reaches back to the start: it closes the loop, and it is why the batch recovers what dead reckoning lost. The sliding window 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 m0m_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:

crates/skoro/examples/pose_graph.rs lines 60–74
// 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 ff for the negative log-density of a row’s query, and x^\hat \point for the row’s current point. Linearized there, in the chart at x^\hat \point, it is a least-squares problem in the tangent step v\tangent:

f(x^⊕v)≈m(v)=f(x^)+12∣Jv+r∣2−12∣r∣2, f(\hat \point \oplus \tangent) \approx m(\tangent) = f(\hat \point) + \tfrac12 \lvert J \tangent + r \rvert^2 - \tfrac12 \lvert r \rvert^2 ,

with rr the stacked whitened residuals of every term and JJ their Jacobian, the matrix drawn above; the log-volumes of the terms on SE(3)SE(3) are folded into rr, so that mm agrees with ff to first order. Its gradient at v=0\tangent = 0 is the gradient of ff in the chart, g=J⊤rg = J\transpose r. A Levenberg–Marquardt step minimizes mm with a penalty on its length, 12λ v⊤Dv\tfrac12 \lambda\, \tangent\transpose D \tangent, with DD Marquardt’s diagonal (2), so that (J⊤J+λD) v=−g(J\transpose J + \lambda D)\, \tangent = -g, and the decrease of mm it promises is

Δ(v)=m(0)−m(v)=12∣Jv∣2+λ v⊤Dv, \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 ff, and it does not depend on how the chart’s coordinates are scaled, where the norm of gg or of v\tangent would.

When a row stops#

The step is taken if ff actually decreased, if the gain (4), the decrease obtained over Δ(v)\Delta(\tangent), is positive, and λ\lambda is updated from the gain by Nielsen’s schedule (5). The row stops, Status::Converged, at the first step that promises Δ(v)≤ϵ\Delta(\tangent) \le \epsilon, with ϵ=10−9\epsilon = 10^{-9} nats, whether that step was taken or not. Near the mode a step promises little more than the rounding of ff, u∣f∣≈4×10−13u \lvert f \rvert \approx 4 \times 10^{-13} nats with ∣f∣≈3700\lvert f \rvert \approx 3700 here and uu 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×10−121.7 \times 10^{-12} nats, and its gain is −0.27-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 101010^{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 λ=0\lambda = 0 the step is Gauss–Newton’s, v0=−(J⊤J)−1g\tangent_0 = -(J\transpose J)^{-1} g, and its promise, the decrement, is

δ=12∣Jv0∣2=12 g⊤(J⊤J)−1g ≥ ∣g∣22 hmax⁡, \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 hmax⁡h_{\max} the largest eigenvalue of J⊤JJ\transpose J. Every pose has a prior or a motion term and every landmark a prior, so JJ has full rank, J⊤JJ\transpose J is invertible, and δ\delta is zero exactly where gg is: where the point is stationary for ff, log-volumes included. decrement computes it for every row, and stationary fails the example unless every row’s is at most 10 ϵ10\, \epsilon. It is the decrease of ff a full Gauss–Newton step would still give, in nats, so the check says that no step left could gain more than 10−810^{-8} nats.

Are the uncertainties honest?#

At the mode, 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 says why, and how large a difference the approximation itself should make.

The normalized errors of every pose and landmark of every dataset, against the chi-squared density each follows when its marginal is calibrated.
Histograms of the normalized errors of the poses and the landmarks against the chi-squared densities they follow when the Laplace marginals are calibrated Are the uncertainties honest? The truth's distance from every estimate, in its own marginal's units, over 100 datasets Poses (6 dimensions) 0 4 8 12 16 20 24 28 normalized error |W (q* ⊖ q̂)|² χ²₆(0.9) = 10.64 the 90% ellipsoid’s edge 92.0% inside their 90% ellipsoid: 90.0% ± 5.0% expected 7,300 errors Landmarks (3 dimensions) 0 4 8 12 16 20 normalized error |W (q* ⊖ q̂)|² χ²₃(0.9) = 6.25 the 90% ellipsoid’s edge 92.3% inside their 90% ellipsoid: 90.0% ± 5.4% expected 2,400 errors How often each normalized error occurred The chi-squared density it follows when the marginals are calibrated

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:

crates/skoro/examples/pose_graph.rs lines 215–226
// 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:

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

How this came to be

The development behind this page, newest first:

Built on by