Steps and replacements
Linearize a model's density at a point and iterate damped Gauss–Newton steps to its mode, and retire part of a model with a linearized replacement that keeps what it said, with the crate skoro-linearize, from its own tests.
The crate skoro-linearize reads a model as least squares.
This page shows what a user writes with it: a Gauss–Newton loop that finds the mode of a model of rotations, and a retirement whose replacement is computed from the retired terms rather than written by hand.
Each step quotes the crate’s tests, so every line shown compiles and runs.
The concepts page explains what each piece computes.
A step to the mode#
A model is linearized for a density query, which says what is observed. Here a chain of two rotations is measured once, through the normal on the rotations, and a batch of two starting points is given for the free rotations:
crates/skoro-linearize/tests/common/mod.rs lines 249–286/// A chain of rotations: `r₀ ~ N(μ₀, 0.3²)`, `r₁ ~ N(r₀, diag(0.2, 0.25, 0.15)²)`, and an observed
/// measurement `z ~ N(r₁, 0.1²)`, each a normal on the rotations, whose log-volume is folded; with
/// a batch of two points.
pub fn rotations(target: &Target) -> (Writer, Query, Values) {
let unit = |q: [f64; 4]| {
let n = q.iter().map(|x| x * x).sum::<f64>().sqrt();
q.map(|x| x / n)
};
let mut writer = Writer::new();
let (r0, r1, z) = writer
.build(|| {
let r0 = quantity("r0", Rotation);
Normal::on(
Rotation,
constant(Rotation, unit([0.9, 0.1, -0.3, 0.2])),
Scale::sd(0.3),
)
.score(r0);
let r1 = quantity("r1", Rotation);
Normal::on(Rotation, r0, Scale::sds(&[0.2, 0.25, 0.15])).score(r1);
let z = quantity("z", Rotation);
Normal::on(Rotation, r1, Scale::sd(0.1)).score(z);
(r0, r1, z)
})
.unwrap();
let query =
Query::log_density().given(Observations::new().observe(z, unit([0.7, 0.3, -0.4, 0.5])));
let a = [unit([0.8, 0.2, -0.3, 0.1]), unit([0.95, 0.0, -0.2, 0.25])].concat();
let b = [
unit([0.75, 0.25, -0.35, 0.45]),
unit([0.6, 0.35, -0.3, 0.6]),
]
.concat();
let point = Values::new()
.with(r0, points(&a, 2, 4, target))
.with(r1, points(&b, 2, 4, target));
(writer, query, point)
}A Linearizer is built once for the snapshot, the query, the target and the assembly, here the residual linearization of Gauss–Newton.
Its schedule, the order and the junction tree of the elimination, is computed once too.
Each iteration linearizes at the current batch, eliminates every row along the schedule, and retracts the step onto the quantities:
crates/skoro-linearize/tests/linearize.rs lines 499–523#[test]
fn steps_converge_on_rotations() {
let target = Target::host();
let (writer, query, point) = rotations(&target);
let snapshot = writer.snapshot();
let linearizer = Linearizer::new(&snapshot, &query, &target, Assembly::Residual).unwrap();
let layout = linearizer.layout().clone();
let schedule = linearizer.schedule().unwrap();
let mut at = point;
for _ in 0..60 {
let step = linearizer
.at(&at)
.unwrap()
.eliminate(&schedule, None)
.unwrap()
.minimizer(&target)
.unwrap();
at = layout.retract(&at, &step, &target).unwrap();
}
// A stationary point of f itself, log-volumes included: the query's gradient vanishes.
for g in gradient(&snapshot, &query, &layout, &at, &target) {
let norm = g.iter().map(|g| g * g).sum::<f64>().sqrt();
assert!(norm < 1e-9, "|g| = {norm}");
}
}The loop stops where the query’s own gradient vanishes, log-volumes included: the mode of the density, not of the residuals alone.
Undamped, a step far from the mode can overshoot.
The crate’s LevenbergMarquardt is the loop to use: it damps each row of the batch on its own, takes a row’s step only where it decreased the density’s negative logarithm, and stops each row when a step promises less than a tolerance in nats.
Every row ends with a status, and decrement checks that where it stopped is stationary:
crates/skoro-linearize/tests/minimize.rs lines 82–99fn levenberg_marquardt_finds_the_mode_on_rotations() {
let target = Target::host();
let (writer, query, point) = rotations(&target);
let snapshot = writer.snapshot();
let linearizer = Linearizer::new(&snapshot, &query, &target, Assembly::Residual).unwrap();
let layout = linearizer.layout().clone();
let d = layout.dimension();
let schedule = linearizer.schedule().unwrap();
let method = LevenbergMarquardt::default();
let bound = 10.0 * method.tolerance;
let minimized = method.minimize(&linearizer, &schedule, &point).unwrap();
for row in &minimized.rows {
assert_eq!(row.status, Status::Converged, "{row:?}");
}
let decrements = decrement(&linearizer, &schedule, &minimized.point).unwrap();
for &delta in &decrements {
assert!(delta <= bound, "decrement {delta}");
}The concepts page says how the damping and the stop are chosen.
A schedule kept on some quantities, schedule_keeping, gives their marginal covariance, and at_in_chart the linearization a Laplace approximation reads its evidence and draws from.
A replacement for what is retired#
A retirement removes the quantities at some addresses and needs a replacement for the terms joined to them. On the core’s scalar chain, a position, its measurement, the next position and its measurement:
crates/skoro-linearize/tests/replacement.rs lines 23–41/// The core's scalar chain: `x0 ~ N(a, s²)`, `z0 | x0 ~ N(x0, r²)`, `x1 | x0 ~ N(x0, q²)`,
/// `z1 | x1 ~ N(x1, r²)`, each a normal.
fn chain() -> (Writer, [Q<Real>; 4]) {
let mut writer = Writer::new();
let quantities = writer
.build(|| {
let x0 = quantity("tick/0/x", Real);
Normal::on(Real, constant(Real, A), Scale::sd(S)).score(x0);
let z0 = quantity("tick/0/z", Real);
Normal::on(Real, x0, Scale::sd(R)).score(z0);
let x1 = quantity("tick/1/x", Real);
Normal::on(Real, x0, Scale::sd(QN)).score(x1);
let z1 = quantity("tick/1/z", Real);
Normal::on(Real, x1, Scale::sd(R)).score(z1);
[x0, z0, x1, z1]
})
.unwrap();
(writer, quantities)
}retiring the first tick is three steps: read the retirement, linearize the replacement at a point of the quantities it integrates and keeps, and build it in the retirement’s own scope:
crates/skoro-linearize/tests/replacement.rs lines 80–95
/// Retires `addresses` with `observed`, replacing them by the linearized replacement at `at`,
/// keeping `keep`: the factor added.
fn retire(
writer: &mut Writer,
addresses: Addresses,
observed: Observations,
keep: &[QDyn],
at: &Values,
) -> TermHandle {
let target = Target::host();
let retirement = writer.retire(addresses, observed).unwrap();
let replacing = Replacing::new(&retirement, keep, &Observations::new(), &target).unwrap();
let linearized = replacing.at(at).unwrap();
retirement.replace(|_| linearized.build()).unwrap().unwrap()
}The quantity to keep is named, and the measurement retired with the first tick is observed, so the replacement integrates the first position alone. For terms like these, linear and Gaussian, the replacement is exact wherever it is linearized, and it is the Kalman filter’s update and prediction:
crates/skoro-linearize/tests/replacement.rs lines 99–135#[test]
fn retiring_the_scalar_chain_is_the_kalman_filter() {
let target = Target::host();
// [](eq:archive/core/math/kalman): the evidence of ẑ0, and the predicted mean and variance.
let gain = S * S / (S * S + R * R);
let mean = A + gain * (Z0 - A);
let variance = (1.0 - gain) * S * S + QN * QN;
let evidence = log_normal(Z0, A, (S * S + R * R).sqrt());
for linearized_at in [[0.0, 0.0], [1.3, -0.4]] {
let (mut writer, [x0, z0, x1, _]) = chain();
let at = Values::new()
.with(x0, points(&[linearized_at[0]], 1, 1, &target))
.with(x1, points(&[linearized_at[1]], 1, 1, &target));
let observed = Observations::new().observe(z0, Z0);
let factor = retire(
&mut writer,
Addresses::new().under("tick/0"),
observed,
&[x1.untyped()],
&at,
);
let values = density_of(
&writer.snapshot(),
&[factor.id()],
Observations::new().observe(x1, Rows(XS.to_vec())),
);
let expected: Vec<f64> = XS
.iter()
.map(|&x| evidence + log_normal(x, mean, variance.sqrt()))
.collect();
close(
&values,
&expected,
1e-10,
"the Kalman filter's update and prediction",
);
}The factor the retirement adds is the normal’s improper factor, with its residual bound, so a later linearization reads it as it reads any term: retiring one tick after another runs the filter. Where the retired terms do not determine what is kept, as for a landmark seen along one bearing, the replacement keeps what they say, and replacements over the same quantity add up until they do.
How this came to be
The development behind this page, newest first:
- Least squares, motivated from MAP estimation and trust regions Done This entry reordered the mathematics' part on least squares and Gaussian approximations so that it begins with the estimate sought and ends with the linear algebra that computes it. Five notes are…
- Examples that run Done This entry gave skoro two examples that run, in the umbrella crate, each a cargo run --example target that CI runs and that fails when a check of its mathematics fails. pose_graph draws a hundred…
- Linearization and elimination Done This entry brought back the two pieces every least-squares method rests on, as two crates. skoro-elimination is the note on elimination in square-root form as code: factored problems over blocks of…
Built on by
- 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.