diff --git a/.github/workflows/deploy-book.yml b/.github/workflows/deploy-book.yml
index f4297507..3eba5bd4 100644
--- a/.github/workflows/deploy-book.yml
+++ b/.github/workflows/deploy-book.yml
@@ -1,10 +1,21 @@
name: Deploy mdBook to GitHub Pages
+# The book and the API documentation it links to are built on every pull request that could
+# change them, and deployed only from `main`. Until #383 the build ran on `main` alone, so a
+# page that failed to build -- or a link into a page that had been deleted -- was first seen
+# on the live site.
on:
push:
branches: [ "main" ]
-# pull_request:
-# branches: [ "main" ]
+ pull_request:
+ paths:
+ - "book/**"
+ - "core/**"
+ - "sim/**"
+ - "geonav/**"
+ - "CONTRIBUTING.md"
+ - "katex-header.html"
+ - ".github/workflows/deploy-book.yml"
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
@@ -12,38 +23,66 @@ permissions:
pages: write
id-token: write
-# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
-# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
+# One deployment at a time, never cancelling one in progress. Pull-request builds get their
+# own group so they neither queue behind nor cancel a deployment.
concurrency:
- group: "pages"
- cancel-in-progress: false
+ group: ${{ github.event_name == 'pull_request' && format('book-pr-{0}', github.event.pull_request.number) || 'pages' }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
runs-on: ubuntu-latest
- timeout-minutes: 20
+ timeout-minutes: 45
steps:
- name: Checkout repository
uses: actions/checkout@v4
- - name: Setup Rust
- uses: dtolnay/rust-toolchain@stable
-
- # `+stable` is deliberate. `rust-toolchain.toml` pins the workspace to 1.91 for lint
- # reproducibility, and that pin would otherwise apply here too -- building a
+ # `+stable` for mdBook is deliberate. `rust-toolchain.toml` pins the workspace to 1.91
+ # for lint reproducibility, and that pin would otherwise apply here too -- building a
# third-party tool against an older toolchain than it supports is the classic way to
# break a docs deploy for a reason that has nothing to do with the docs.
+ - name: Setup Rust (stable, for mdBook)
+ uses: dtolnay/rust-toolchain@stable
+
+ - name: Setup Rust (pinned, for rustdoc)
+ uses: dtolnay/rust-toolchain@1.91
+
+ - uses: Swatinem/rust-cache@v2
+
- name: Install mdBook
run: |
- cargo +stable install mdbook --version 0.4.40
+ cargo +stable install mdbook --version 0.4.40 --locked
mdbook --version
- name: Build the book
+ run: mdbook build book
+
+ # The API reference is published inside the book, under /api/, so the book can link to
+ # the documentation of the exact commit it was built from. docs.rs only has a crate's
+ # documentation once that version is on crates.io.
+ #
+ # `-D warnings` makes a broken intra-doc link fail the build. RUSTDOCFLAGS replaces the
+ # `rustdocflags` in .cargo/config.toml rather than adding to it, so the KaTeX header is
+ # repeated here, with an absolute path because rustdoc runs from each crate's directory.
+ - name: Build the API documentation
+ env:
+ RUSTDOCFLAGS: -D warnings --html-in-header ${{ github.workspace }}/katex-header.html
run: |
- cd book
- mdbook build
+ cargo doc --workspace --no-deps --all-features --locked
+ cp -r target/doc/. book/book/api/
+
+ # Offline: checks every relative link between book pages and into the API docs,
+ # without depending on external sites being up. 404.html is mdBook's generated error
+ # page; its `` (from `site-url`) is root-relative, which an
+ # offline check of local files cannot resolve.
+ - name: Check links
+ uses: lycheeverse/lychee-action@v2
+ with:
+ args: --offline --no-progress --exclude-path book/book/api --exclude-path book/book/404.html 'book/book/**/*.html'
+ fail: true
- name: Upload artifact
+ if: github.event_name == 'push'
uses: actions/upload-pages-artifact@v3
with:
path: ./book/book
@@ -55,7 +94,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
needs: build
- if: github.ref == 'refs/heads/main'
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps:
- name: Deploy to GitHub Pages
id: deployment
diff --git a/CLAUDE.md b/CLAUDE.md
index a21d5236..279aa9fd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -22,7 +22,7 @@ The core library implementing strapdown INS algorithms and simulation framework:
- **kalman.rs**: Kalman-style navigation filters including Unscented Kalman Filter (UKF) for nonlinear state estimation
- **particle.rs**: Particle-filter building blocks (the `Particle` trait, resampling and averaging strategies); not a filter on its own
- **rbpf.rs**: The Rao-Blackwellized particle filter, after Canciani & Raquet (2017) -- the one concrete particle filter
-- **measurements.rs**: Measurement models (GPS position/velocity, barometric altitude, pseudorange, carrier phase) implementing the `MeasurementModel` trait
+- **measurements.rs**: Measurement models (GPS position/velocity, barometric altitude, magnetometer yaw, ZUPT/ZARU) implementing the `MeasurementModel` trait. Loosely coupled only: there are no pseudorange or carrier-phase models
- **messages.rs**: Event stream handling for GNSS scheduling and fault injection scenarios
- **sim.rs**: Simulation utilities, CSV data loading (Sensor Logger format), dead reckoning and closed-loop functions
- **linalg.rs**: Linear algebra utilities for matrix operations
@@ -43,12 +43,15 @@ Command-line tool for running INS simulations with GNSS degradation:
- GNSS fault simulation: dropouts, reduced update rates, measurement corruption, bias injection
- Input: CSV files with IMU and GNSS measurements (Sensor Logger format)
- Output: **the CLI writes CSV only.** Every path through `strapdown-sim` ends in
- `NavigationResult::to_csv`, and `OUTPUT_FILE_EXTENSIONS` in `sim/src/common.rs` is `["csv"]`,
- so any other extension is rejected rather than filled with CSV. `to_hdf5`, `to_netcdf` and
- `to_mcap` exist as **library** writers on `NavigationResult`, reachable from Rust but not
- from this binary. There is no Parquet writer at all
+ `NavigationResult::to_csv`. In `sim/src/common.rs`, a `-o` ending in `.csv`
+ (`OUTPUT_FILE_EXTENSIONS`) names a file; one whose extension names another data format
+ (`REFUSED_OUTPUT_EXTENSIONS`: h5, hdf5, nc, netcdf, mcap, parquet, json, yaml, yml, toml, txt)
+ is refused unless it is an existing directory; anything else is a directory of CSV results.
+ `syn` must be given a `.csv` file. `to_hdf5`, `to_netcdf` and `to_mcap` exist as **library**
+ writers on `NavigationResult`, reachable from Rust but not from this binary. There is no
+ Parquet writer at all
- Configuration: TOML/YAML/JSON scenario files or command-line arguments
-- Built-in logging: Use `--log-level` and `--log-file` flags (see LOGGING.md for details)
+- Built-in logging: Use `--log-level` and `--log-file` flags (see `book/src/user-guide/logging.md`)
**Free Core scope**: Basic GNSS degradation (outages, noise, reduced availability)
**Future Pro scope**: Advanced faults (spoofing, jamming, multipath, terrain masking)
@@ -58,7 +61,7 @@ Command-line tool for running INS simulations with GNSS degradation:
- Loads NetCDF geophysical maps (gravity/magnetic anomaly grids)
- Integrates geophysical measurements with INS/GNSS filters
- Provides alternative PNT in GNSS-denied environments
-- Built-in logging: Use `--log-level` and `--log-file` flags (see LOGGING.md for details)
+- Built-in logging: Use `--log-level` and `--log-file` flags (see `book/src/user-guide/logging.md`)
- Status: Experimental feature for research, may be commercialized in future roadmap
### 4. `analysis` (/analysis, Python)
@@ -68,7 +71,7 @@ Post-processing and experiment tooling, exposed as the `analyze` CLI:
`_magnetic.nc` maps beside each trajectory. `just preprocess` runs it at **10 Hz**, which
gives 10 Hz inertial propagation against the ~1 Hz the GNSS was actually recorded at (the
GNSS columns stay NaN in nine rows out of ten; do not interpolate them up). `data/input` is
- the one directory every consumer reads -- all 21 `conf/*.toml`, `geo-stats`, `postprocess`
+ the one directory every consumer reads -- all 15 `conf/*.toml`, `geo-stats`, `postprocess`
and `geoperf-*` -- so change the rate, not the path. `just preprocess-1hz` is the 1 Hz
variant, which is the rate every result before the geophysical fixes used
- **geostats.py**: characterises the geophysical measurements against those maps -- per-field
@@ -186,8 +189,8 @@ The Free Core implementation must achieve the following capabilities:
5. **Output Formats**:
- CSV, HDF5, NetCDF and MCAP export for analysis in Python/MATLAB/R. **These are
`NavigationResult` methods, not CLI output modes**: `strapdown-sim` writes CSV and
- rejects every other extension, so reaching the other three means calling `to_hdf5`,
- `to_netcdf` or `to_mcap` from Rust
+ refuses an output path naming another data format, so reaching the other three means
+ calling `to_hdf5`, `to_netcdf` or `to_mcap` from Rust
- Parquet is deliberately **not** supported at either layer: `sim/src/common.rs` refuses
`.parquet` rather than naming a file Parquet and filling it with CSV
- Navigation solution time series with position, velocity, attitude estimates
@@ -229,8 +232,10 @@ The Free Core implementation must achieve the following capabilities:
- Users control via `is_enu` boolean flags and sign conventions; `StrapdownState::to_ned`
and `to_enu` convert an existing state between the two
- Vertical velocity: positive down in NED, positive up in ENU
- - `altitude` is height above the ellipsoid -- positive up -- in **both** frames, valid over
- [-11,000m, 30,000m]. It is not a "down" coordinate in NED
+ - `altitude` is height above the ellipsoid -- positive up -- in **both** frames. The
+ mechanization is valid over [-11,000m, 30,000m], but nothing enforces that by default: the
+ health check's default altitude band is +/-1e8 m (`DEFAULT_HEALTH_ALT_{MIN,MAX}_M`), so
+ narrow `HealthLimits::alt_m` to make it a gate. It is not a "down" coordinate in NED
- `TestDataRecord` carries no frame tag, so every entry point that loads one takes the
frame from its caller: `sim::dead_reckoning(records, is_enu)` and `is_enu` on
`UkfConfig`/`EkfConfig`/`EskfConfig`, all defaulting to NED. On the CLI that is `--enu`
@@ -254,7 +259,8 @@ The Free Core implementation must achieve the following capabilities:
- **Forward propagation**: Uses `StrapdownState::propagate()` with strapdown equations (Chapter 5.4-5.5)
- **Measurement models**: Implement the `MeasurementModel` trait for update step
- Trait provides `predict_measurement()` and `innovation_covariance()` methods
- - Implemented models: GPS position, GPS velocity, barometric altitude, pseudorange, carrier phase
+ - Implemented models: GPS position, velocity, and position+velocity; relative (barometric)
+ altitude; magnetometer yaw; ZUPT and ZARU. Geophysical models live in `strapdown-geonav`
- **UKF implementation**:
- Uses unscented transform with sigma points for nonlinear state estimation
- Handles full 9-state navigation solution
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 279df8e3..acf23a08 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -39,15 +39,21 @@ or put the release binary on your `PATH`.
## Before you open a pull request
-The workspace enforces a strict lint gate rather than a warning-level one. Both of these must
+The workspace enforces a strict lint gate rather than a warning-level one. All of these must
be clean, and CI runs exactly the same commands on the same pinned 1.91 toolchain:
```bash
cargo fmt-check # cargo fmt --all -- --check
cargo lint # cargo clippy --workspace --all-targets --all-features -- -D warnings
+cargo lint-min # cargo clippy -p strapdown-core --all-targets --no-default-features -- -D warnings
cargo test --workspace --all-features
+cargo test-min # cargo test -p strapdown-core --no-default-features
```
+`cargo lint` alone is not the whole gate. The two configurations disagree about what is dead:
+an item used only behind a feature gate is live under `--all-features` and unused without it,
+so `cargo lint-min` and `cargo test-min` catch what `cargo lint` cannot.
+
`clippy::pedantic` and `clippy::nursery` are denied workspace-wide, as are `missing_docs` and
the zero-panic lints (`unwrap_used`, `expect_used`, `panic`) in library code -- return a
`StrapdownError` instead. Every `pub` item, including struct fields and enum variants, needs a
diff --git a/Cargo.lock b/Cargo.lock
index 24126e44..23b953fd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1239,22 +1239,6 @@ dependencies = [
"simd-adler32",
]
-[[package]]
-name = "nalgebra"
-version = "0.32.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4"
-dependencies = [
- "approx",
- "matrixmultiply",
- "nalgebra-macros 0.2.2",
- "num-complex",
- "num-rational",
- "num-traits",
- "simba 0.8.1",
- "typenum",
-]
-
[[package]]
name = "nalgebra"
version = "0.34.2"
@@ -1281,25 +1265,14 @@ dependencies = [
"glam 0.31.1",
"glam 0.32.1",
"matrixmultiply",
- "nalgebra-macros 0.3.0",
+ "nalgebra-macros",
"num-complex",
"num-rational",
"num-traits",
- "simba 0.9.1",
+ "simba",
"typenum",
]
-[[package]]
-name = "nalgebra-macros"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 2.0.117",
-]
-
[[package]]
name = "nalgebra-macros"
version = "0.3.0"
@@ -1311,15 +1284,6 @@ dependencies = [
"syn 2.0.117",
]
-[[package]]
-name = "nav-types"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "79beb749c537c9cccddfa3039ace093404d4bb42c28313c28cac0342f3d4fd23"
-dependencies = [
- "nalgebra 0.32.6",
-]
-
[[package]]
name = "ndarray"
version = "0.17.2"
@@ -1978,19 +1942,6 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
-[[package]]
-name = "simba"
-version = "0.8.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae"
-dependencies = [
- "approx",
- "num-complex",
- "num-traits",
- "paste",
- "wide",
-]
-
[[package]]
name = "simba"
version = "0.9.1"
@@ -2036,8 +1987,7 @@ dependencies = [
"log",
"mcap",
"memmap2",
- "nalgebra 0.34.2",
- "nav-types",
+ "nalgebra",
"netcdf",
"rand",
"rand_distr",
@@ -2059,7 +2009,7 @@ dependencies = [
"assert_approx_eq",
"chrono",
"log",
- "nalgebra 0.34.2",
+ "nalgebra",
"netcdf",
"strapdown-core",
"world_magnetic_model",
@@ -2073,7 +2023,7 @@ dependencies = [
"clap",
"env_logger",
"log",
- "nalgebra 0.34.2",
+ "nalgebra",
"plotters",
"rand",
"rayon",
diff --git a/Cargo.toml b/Cargo.toml
index c05d2dd5..8cb6a655 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -14,7 +14,7 @@ resolver = "3"
authors = ["James Brodovsky"]
edition = "2024"
license = "MIT"
-homepage = "https://www.strapdown.rs"
+homepage = "https://jbrodovsky.github.io/strapdown-rs/"
repository = "https://github.com/jbrodovsky/strapdown-rs"
# Minimum supported Rust version. Keep this in sync with `channel` in
# rust-toolchain.toml, `msrv` in clippy.toml and the CI toolchain pins; raising
diff --git a/book/EKF_GEONAV.md b/book/EKF_GEONAV.md
deleted file mode 100644
index 983eb55f..00000000
--- a/book/EKF_GEONAV.md
+++ /dev/null
@@ -1,212 +0,0 @@
-# EKF-based Geophysical Navigation
-
-This document describes the Extended Kalman Filter (EKF) implementation for geophysical navigation in the `strapdown-rs` project.
-
-## Overview
-
-The EKF-based geophysical INS provides an alternative to the Unscented Kalman Filter (UKF) for integrating inertial navigation with geophysical measurements (gravity and magnetic anomalies). While the UKF uses sigma points to propagate uncertainty through nonlinear transformations, the EKF uses first-order Taylor series approximations (Jacobians) to linearize the system dynamics and measurement models.
-
-## Features
-
-- **15-state EKF**: Position (3), velocity (3), attitude (3), and IMU biases (6)
-- **Geophysical measurements**: Gravity and magnetic anomaly measurements from geophysical maps
-- **Numerical Jacobians**: Map gradients computed using finite differences for measurement updates
-- **Health monitoring**: Integrated with existing health check framework
-- **Compatible with UKF**: Drop-in replacement via CLI flag
-
-## Implementation Details
-
-### State Vector
-
-The EKF uses a 15-dimensional state vector (when biases are enabled):
-
-```
-x = [lat, lon, alt, v_n, v_e, v_d, roll, pitch, yaw, b_ax, b_ay, b_az, b_gx, b_gy, b_gz]
-```
-
-Where:
-- `lat, lon, alt`: Position in geodetic coordinates (radians, radians, meters)
-- `v_n, v_e, v_d`: Velocity in local-level frame (m/s)
-- `roll, pitch, yaw`: Attitude Euler angles (radians)
-- `b_ax, b_ay, b_az`: Accelerometer biases (m/s²)
-- `b_gx, b_gy, b_gz`: Gyroscope biases (rad/s)
-
-### Predict Step
-
-The predict step propagates the state and covariance using:
-
-1. **Nonlinear state propagation**: Uses the `forward()` function to integrate IMU measurements through the strapdown mechanization equations
-2. **Linearized covariance propagation**: $\bar{P} = F P F^T + Q$ where:
- - $F$ is the state transition Jacobian (computed in `core/src/linearize.rs`)
- - $Q$ is the process noise covariance
-
-### Update Step
-
-The update step incorporates measurements to correct the state estimate:
-
-1. **Measurement prediction**: $\hat{z} = h(\bar{x})$
-2. **Innovation covariance**: $S = H \bar{P} H^T + R$
-3. **Kalman gain**: $K = \bar{P} H^T S^{-1}$
-4. **State correction**: $x = \bar{x} + K(z - \hat{z})$
-5. **Covariance update**: $P = (I - KH)\bar{P}(I - KH)^T + KRK^T$ (Joseph form)
-
-Where:
-- $H$ is the measurement Jacobian
-- $R$ is the measurement noise covariance
-
-### Geophysical Measurements
-
-#### Gravity Anomaly Measurements
-
-Gravity measurements depend on:
-- Position (lat, lon) for map lookup
-- Velocity (for Eotvos correction)
-- Altitude (for free-air correction)
-
-The measurement Jacobian is computed numerically using finite differences on the geophysical map:
-
-```rust
-let (dlat, dlon) = map.get_gradient(&lat, &lon, epsilon);
-```
-
-#### Magnetic Anomaly Measurements
-
-Magnetic anomaly measurements depend on:
-- Position (lat, lon) for map lookup
-- Altitude (for reference field computation via WMM)
-- Date (for WMM temporal variation)
-
-Similar to gravity, the Jacobian is computed numerically from the map gradient.
-
-### Numerical Gradient Computation
-
-The `GeoMap::get_gradient()` method computes map gradients using central finite differences:
-
-```
-∂z/∂lat ≈ (z(lat+ε) - z(lat-ε)) / (2ε)
-∂z/∂lon ≈ (z(lon+ε) - z(lon-ε)) / (2ε)
-```
-
-With automatic fallback to forward/backward differences at map boundaries.
-
-## Usage
-
-### Command Line
-
-```bash
-# Run with EKF (instead of the default ESKF)
-strapdown-geonav \
- --input sensor_data.csv \
- --output navigation_solution.csv \
- --filter ekf \
- --geo-type gravity \
- --geo-noise-std 100.0
-
-# Run with magnetic anomalies
-strapdown-geonav \
- --input sensor_data.csv \
- --output navigation_solution.csv \
- --filter ekf \
- --geo-type magnetic \
- --geo-noise-std 50.0
-```
-
-### Programmatic API
-
-```rust
-use std::rc::Rc;
-use strapdown::kalman::{ExtendedKalmanFilter, InitialState};
-use strapdown::sim::run_closed_loop;
-use geonav::{GeoMap, build_event_stream};
-
-// Initialize EKF
-let initial_state = InitialState { /* ... */ };
-let mut ekf = ExtendedKalmanFilter::new(
- initial_state,
- vec![0.0; 6], // IMU biases
- cov_diagonal,
- process_noise,
- true, // use 15-state with biases
-);
-
-// Load geophysical map
-let geomap = GeoMap::load_geomap(map_path, measurement_type)?;
-
-// Build event stream
-// `?`: an empty record slice cannot supply the stream's start time or altitude reference.
-let events = build_event_stream(
- &records,
- &config,
- Some(Rc::new(geomap)),
- Some(noise_std),
- None, // no magnetic map
- None,
- frequency,
-)?;
-
-// Run EKF navigation. The geonav-specific `geo_closed_loop_*` drivers were removed in
-// favour of the one driver in `strapdown-core`, which takes any `NavigationFilter`.
-let results = run_closed_loop(&mut ekf, events, None, None)?;
-```
-
-## Performance Comparison: EKF vs UKF
-
-| Aspect | EKF | UKF |
-|--------|-----|-----|
-| **Computational Cost** | Lower (linear algebra only) | Higher (sigma point propagation) |
-| **Memory Usage** | Lower | Higher (stores sigma points) |
-| **Accuracy** | First-order approximation | Second-order approximation |
-| **Nonlinearity Handling** | Good for mildly nonlinear systems | Better for highly nonlinear systems |
-| **Deterministic** | Yes | Yes |
-| **Implementation Complexity** | Requires Jacobian computation | Requires careful sigma point selection |
-
-### When to Use EKF
-
-- Computational resources are limited
-- System dynamics are mildly nonlinear
-- Jacobians can be computed efficiently
-- Faster iteration cycles are needed for development
-
-### When to Use UKF
-
-- High accuracy is paramount
-- System has significant nonlinearities
-- Jacobians are difficult to compute or verify
-- Computational resources are available
-
-## Testing
-
-The EKF geophysical navigation includes comprehensive tests:
-
-```bash
-# Run all core EKF tests (31 tests)
-cargo test --package strapdown-core --lib kalman
-
-# Run geophysical EKF tests (17 tests including Jacobian tests)
-cargo test --package strapdown-geonav --lib
-```
-
-Key test coverage:
-- EKF construction (9-state and 15-state)
-- Predict step with various motion profiles
-- Update step with different measurement types
-- Geophysical measurement Jacobians
-- Map gradient computation
-- Angle wrapping and covariance reduction
-
-## References
-
-1. Groves, P. D. "Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, 2nd Edition", Chapter 14.2
-2. Bar-Shalom, Y., et al. "Estimation with Applications to Tracking and Navigation", Chapter 5
-3. Julier, S. & Uhlmann, J. "Unscented Filtering and Nonlinear Estimation" (for UKF comparison)
-
-## Future Enhancements
-
-Potential improvements to the EKF geophysical navigation:
-
-1. **Analytic Jacobians**: Compute analytic gradients for bilinear map interpolation
-2. **Adaptive Process Noise**: Adjust Q based on motion dynamics
-3. **Map Uncertainty**: Incorporate geophysical map uncertainty into R
-4. **Multi-resolution Maps**: Support hierarchical map representations
-5. **Terrain-aided Navigation**: Add terrain elevation as additional measurement
-6. **Error-State Formulation**: Implement error-state EKF for improved numerical stability
diff --git a/book/EKF_USAGE.md b/book/EKF_USAGE.md
deleted file mode 100644
index b0649e11..00000000
--- a/book/EKF_USAGE.md
+++ /dev/null
@@ -1,419 +0,0 @@
-# Extended Kalman Filter (EKF) Usage Guide
-
-## Overview
-
-The Extended Kalman Filter (EKF) has been added to the strapdown-rs library as an alternative to the Unscented Kalman Filter (UKF). The EKF provides a linearized Gaussian approximation for navigation state estimation using analytic Jacobians for efficient uncertainty propagation.
-
-## Features
-
-- **9-state and 15-state configurations**: Support for navigation-only (9-state) or navigation + IMU biases (15-state)
-- **Analytic Jacobians**: Uses pre-computed Jacobians from the `linearize` module for efficient computation
-- **Multiple measurement types**: Supports GPS position, GPS velocity, combined position+velocity, and barometric altitude
-- **Comprehensive testing**: 16 unit tests and 5 integration tests validate correctness
-- **Well-documented**: Extensive LaTeX/KaTeX doccomments explain the mathematical foundations
-
-## API Usage
-
-### Basic Initialization
-
-```rust
-use strapdown::kalman::{ExtendedKalmanFilter, InitialState, NavigationFilter};
-use strapdown::measurements::GPSPositionMeasurement;
-use strapdown::IMUData;
-use nalgebra::{DMatrix, DVector, Vector3};
-
-// Define initial state
-let initial_state = InitialState {
- latitude: 45.0,
- longitude: -122.0,
- altitude: 100.0,
- northward_velocity: 0.0,
- eastward_velocity: 0.0,
- vertical_velocity: 0.0,
- roll: 0.0,
- pitch: 0.0,
- yaw: 0.0,
- in_degrees: true,
- is_enu: true,
-};
-
-// Initial covariance diagonal.
-//
-// Latitude and longitude are held in RADIANS and altitude in metres, so the three position
-// entries are not in the same unit and cannot be filled from one literal. `vec![1e-6; 15]`
-// -- what this example used to show -- reads as a 6.4 km initial horizontal uncertainty, not
-// as a small number; see "Default Parameters" below and issue #308. Write the uncertainty in
-// metres once and convert where it is used.
-let horizontal_std_rad = 10.0 * strapdown::earth::METERS_TO_RADIANS; // a 10 m GNSS fix
-let mut initial_covariance = vec![
- horizontal_std_rad.powi(2), // latitude, rad^2
- horizontal_std_rad.powi(2), // longitude, rad^2
- 10.0_f64.powi(2), // altitude, m^2
-];
-initial_covariance.extend([0.25; 3]); // velocity, (m/s)^2 -- a 0.5 m/s fix
-initial_covariance.extend([1e-4; 3]); // attitude, rad^2 -- ~0.6 deg
-initial_covariance.extend([1e-3; 3]); // accel bias, (m/s^2)^2
-initial_covariance.extend([1e-8; 3]); // gyro bias, (rad/s)^2
-
-// Initialize 15-state EKF with biases
-let mut ekf = ExtendedKalmanFilter::new(
- initial_state,
- vec![0.0; 6], // IMU biases (3 accel + 3 gyro)
- initial_covariance.clone(), // cloned so the 9-state example below can reuse it
- // Process noise. The crate's own default, which is built the same way -- one metric
- // constant converted once. `vec![1e-9; 15]` is a 201 m horizontal term.
- DMatrix::from_diagonal(&DVector::from_vec(
- strapdown::sim::DEFAULT_PROCESS_NOISE_DENSITY.to_vec(),
- )),
- true, // use_biases = true for 15-state
-);
-
-// Predict step with IMU data
-let imu_data = IMUData {
- accel: Vector3::new(0.0, 0.0, 9.81),
- gyro: Vector3::zeros(),
-};
-ekf.predict(imu_data, 0.01); // dt = 0.01 seconds
-
-// Update step with GPS measurement
-let gps_meas = GPSPositionMeasurement {
- latitude: 45.0,
- longitude: -122.0,
- altitude: 100.0,
- horizontal_noise_std: 5.0,
- vertical_noise_std: 2.0,
-};
-ekf.update(&gps_meas);
-
-// Get state estimate
-let state = ekf.get_estimate();
-let covariance = ekf.get_certainty();
-```
-
-### 9-State Configuration (No Biases)
-
-```rust
-// The leading nine entries of the 15-state diagonal built above -- the same unit caveat
-// applies, and for the same reason.
-let initial_covariance_9 = initial_covariance[0..9].to_vec();
-
-// Initialize 9-state EKF without biases
-let mut ekf = ExtendedKalmanFilter::new(
- initial_state,
- vec![0.0; 6], // Biases ignored when use_biases = false
- initial_covariance_9, // Initial covariance for 9 states
- DMatrix::from_diagonal(&DVector::from_vec(
- strapdown::sim::DEFAULT_PROCESS_NOISE_DENSITY[0..9].to_vec(),
- )), // Process noise for 9 states
- false, // use_biases = false for 9-state
-);
-```
-
-### Using `initialize_ekf` Helper Function
-
-For simulation workflows, use the `initialize_ekf` helper:
-
-```rust
-use strapdown::sim::{EkfConfig, initialize_ekf, TestDataRecord};
-
-// Assuming you have TestDataRecord from sensor data
-let initial_pose = TestDataRecord::default();
-
-// `EkfConfig::default()` is the 15-state filter in NED, with the crate's default
-// covariances, biases and process noise. Override only what you need.
-let ekf = initialize_ekf(&initial_pose, EkfConfig::default());
-
-// A Sensor Logger recording is ENU, so say so -- a `TestDataRecord` carries no frame
-// tag, and declaring the wrong one is rejected rather than integrated at 2 g.
-// `EkfConfig` is `#[non_exhaustive]`: outside `strapdown-core` it can be neither written as a
-// struct literal nor updated with `..default()`, so it is built from `default()` and assigned.
-let mut enu_config = EkfConfig::default();
-enu_config.is_enu = true;
-let ekf_enu = initialize_ekf(&initial_pose, enu_config);
-```
-
-## Measurement Types
-
-The EKF supports all measurement types from the `measurements` module:
-
-### GPS Position
-```rust
-use strapdown::measurements::GPSPositionMeasurement;
-
-let meas = GPSPositionMeasurement {
- latitude: 45.0, // degrees
- longitude: -122.0, // degrees
- altitude: 100.0, // meters
- horizontal_noise_std: 5.0, // meters
- vertical_noise_std: 2.0, // meters
-};
-ekf.update(&meas);
-```
-
-### GPS Velocity
-```rust
-use strapdown::measurements::GPSVelocityMeasurement;
-
-let meas = GPSVelocityMeasurement {
- northward_velocity: 10.0, // m/s
- eastward_velocity: 5.0, // m/s
- vertical_velocity: 0.0, // m/s
- horizontal_noise_std: 0.5, // m/s
- vertical_noise_std: 0.5, // m/s
-};
-ekf.update(&meas);
-```
-
-### Combined GPS Position + Velocity
-```rust
-use strapdown::measurements::GPSPositionAndVelocityMeasurement;
-
-let meas = GPSPositionAndVelocityMeasurement {
- latitude: 45.0,
- longitude: -122.0,
- altitude: 100.0,
- northward_velocity: 10.0,
- eastward_velocity: 5.0,
- horizontal_noise_std: 5.0,
- vertical_noise_std: 2.0,
- velocity_noise_std: 0.5,
-};
-ekf.update(&meas);
-```
-
-### Barometric Altitude
-```rust
-use strapdown::measurements::RelativeAltitudeMeasurement;
-
-let meas = RelativeAltitudeMeasurement {
- relative_altitude: 5.0, // meters above reference
- reference_altitude: 95.0, // meters (reference altitude)
-};
-ekf.update(&meas);
-```
-
-## Command Line Usage (Simulator)
-
-The EKF is now fully integrated into the simulator and can be used via command line:
-
-```bash
-# Run closed-loop simulation with EKF (linearized Jacobians)
-strapdown-sim cl --filter ekf --input data.csv --output results.csv
-
-# Run with UKF (sigma point propagation)
-strapdown-sim cl --filter ukf --input data.csv --output results.csv
-
-# Run with the ESKF (the default; omitting --filter selects it)
-strapdown-sim cl --filter eskf --input data.csv --output results.csv
-
-# With a scenario config. `--config` supplies the whole run, so `--filter`, `--input` and
-# `--output` are ignored alongside it -- set `closed_loop.filter`, `input` and `output`
-# inside the file and invoke the config on its own.
-strapdown-sim --config gnss_config.toml
-
-# View available options
-strapdown-sim cl --help
-```
-
-The `--filter` option accepts `eskf`, `ukf` or `ekf`. Since #258 the default is `eskf`, the
-15-state error-state filter: it estimates the IMU biases online rather than carrying whatever
-turn-on bias the sensor happened to have, which the 9-state UKF and EKF cannot observe.
-
-## Performance Characteristics
-
-### Advantages of EKF
-- **Computational efficiency**: No sigma point generation/propagation
-- **Deterministic**: Produces identical results on repeated runs
-- **Lower memory**: Smaller footprint than UKF
-- **Well-understood**: Decades of theory and applications
-
-### Limitations
-- **Linearization errors**: First-order Taylor approximation may introduce errors for highly nonlinear systems
-- **Potential divergence**: Can diverge if linearization is poor or process noise underestimated
-- **Gaussian assumption**: Like UKF, assumes Gaussian distributions
-
-### EKF vs UKF Comparison
-
-Based on integration tests with real data:
-- **Similar accuracy**: EKF and UKF achieve comparable RMS horizontal errors (typically within 50% of each other)
-- **Speed**: EKF is generally faster due to no sigma point propagation
-- **Stability**: Both filters maintain bounded errors over extended periods
-- **GNSS outages**: Both filters handle intermittent GNSS well with appropriate process noise tuning
-
-## Testing
-
-### Unit Tests
-Run EKF-specific unit tests:
-```bash
-cargo test -p strapdown-core --lib kalman::tests::ekf
-```
-
-All 16 EKF unit tests cover:
-- Construction (9-state and 15-state)
-- Predict/update steps
-- All measurement types
-- Motion profiles (free fall, hover, horizontal motion)
-- Covariance reduction
-- Angle wrapping
-
-### Integration Tests
-Run EKF integration tests:
-```bash
-cargo test -p strapdown-core --test integration_tests test_ekf
-```
-
-Integration tests include:
-- End-to-end 15-state EKF simulation
-- 9-state configuration verification
-- EKF vs UKF performance comparison
-- GNSS outage handling
-- Bounded drift vs dead reckoning
-
-**Note**: Integration tests are marked `#[ignore]` as they require test data files. Remove the ignore attribute and provide data to run them.
-
-## Default Parameters
-
-### Process Noise
-Default process noise diagonal (for 15-state). Note that the three position entries are
-**not** in the same unit as one another: the filter holds latitude and longitude in radians
-and altitude in metres, so a horizontal uncertainty written in metres has to be converted
-before it can go on the diagonal. The crate does that once, from a single metric constant:
-
-```rust
-// strapdown::sim
-pub const POSITION_PROCESS_NOISE_M_PER_ROOT_S: f64 = 0.1; // metres per root-second
-
-const HORIZONTAL: f64 = {
- let radians = POSITION_PROCESS_NOISE_M_PER_ROOT_S * strapdown::earth::METERS_TO_RADIANS;
- radians * radians // 2.467e-16 rad^2
-};
-
-const DEFAULT_PROCESS_NOISE_DENSITY: [f64; 15] = [
- HORIZONTAL, // latitude, rad^2
- HORIZONTAL, // longitude, rad^2
- 1e-2, // altitude, m^2 -- its own constant, see below
- 1e-3, // velocity north
- 1e-3, // velocity east
- 1e-3, // velocity down
- 1e-5, // roll
- 1e-5, // pitch
- 1e-5, // yaw
- 1e-6, // accel bias x
- 1e-6, // accel bias y
- 1e-6, // accel bias z
- 1e-8, // gyro bias x
- 1e-8, // gyro bias y
- 1e-8, // gyro bias z
-];
-```
-
-The altitude entry keeps its own constant, `VERTICAL_POSITION_PROCESS_NOISE_M2_PER_S`, rather
-than being spelled as `POSITION_PROCESS_NOISE_M_PER_ROOT_S` squared -- though since #328 that is
-exactly what it evaluates to, `1e-2 m^2/s`, a 10 cm standard deviation per root-second.
-
-It was `1e-4` until then. #308 deliberately left it alone, on the grounds
-that a units fix is not the place to retune the vertical channel; #328 did the retune, on
-evidence that it was the only one of three candidate knobs that moved three-sigma altitude
-containment the right way. It is still short of where it should be -- see #372 -- so treat
-`1e-2` as the current best value rather than a settled one.
-
-If you write the horizontal entries directly in rad^2, be aware what the numbers mean:
-`1e-6 rad^2/s` is a **6.4 km** standard deviation per root-second, not a small number. Writing it
-next to an altitude term of `1e-2 m^2` (10 cm) is the defect issue #308 fixed -- the filter
-is told its own prediction is worthless, so it discards it and lands on each fix instead of
-filtering, and innovation gating cannot function. `1e-9 rad^2` is the same mistake three
-orders of magnitude smaller: a 201 m standard deviation.
-
-### Initial Covariance
-Everything above is about $Q$, and every word of it applies to $P_0$: latitude and longitude
-are radians there too. `1e-6` as an initial variance is a 6.4 km initial horizontal
-uncertainty, which is how #303 first noticed the problem.
-
-Recommended initial covariance based on sensor accuracy. Convert metres to **radians**, not
-degrees -- `METERS_TO_DEGREES` alone leaves the value 57.3x too large as a standard deviation
-and 3283x in variance:
-
-- Position: `(horizontal_accuracy * METERS_TO_RADIANS)²` for latitude and longitude,
- `vertical_accuracy²` for altitude
-- Velocity: `(speed_accuracy)²`
-- Attitude: `1e-9` (radians²) is what the `initialize_*` helpers use, which assumes the
- record's own attitude is trusted. Seeding from a coarse alignment instead, use something
- like the `1e-4` rad² (~0.6°) in the worked example above -- the two differ by five orders
- of magnitude because they describe different situations, not because one is wrong
-- Accelerometer and gyroscope biases: `1e-3`, all six entries
-
-`sim::initialize_ekf` and `sim::initialize_ukf` build the position and velocity blocks from a
-`TestDataRecord`'s own reported accuracies and the rest from those defaults, and `sim::initialize_eskf` and
-`engine::InsEngine` use `sim::DEFAULT_INITIAL_POSITION_UNCERTAINTY_M` (10 m) when there is no
-record to read. For a derivation from an IMU grade rather than a hand-picked constant, see
-`IMUQuality::auto_covariance`.
-
-## Mathematical Background
-
-The EKF implementation follows the standard formulation:
-
-### Predict Step
-$$
-\begin{aligned}
-\bar{x}_{k+1} &= f(x_k, u_k) \\
-\bar{P}_{k+1} &= F_k P_k F_k^T + G_k Q_k G_k^T
-\end{aligned}
-$$
-
-where:
-- $F_k$ is the state transition Jacobian computed using `linearize::state_transition_jacobian`
-- $G_k$ is the process noise Jacobian computed using `linearize::process_noise_jacobian`
-- $Q_k$ is the process noise covariance
-
-### Update Step
-$$
-\begin{aligned}
-K_k &= \bar{P}_k H_k^T (H_k \bar{P}_k H_k^T + R_k)^{-1} \\
-x_k &= \bar{x}_k + K_k (z_k - h(\bar{x}_k)) \\
-P_k &= (I - K_k H_k) \bar{P}_k
-\end{aligned}
-$$
-
-where:
-- $H_k$ is the measurement Jacobian (e.g., `linearize::gps_position_jacobian`)
-- $R_k$ is the measurement noise covariance
-- $K_k$ is the Kalman gain
-
-For detailed mathematical derivations, see:
-- Groves, P. D. "Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, 2nd Edition", Chapter 14.2
-- In-code documentation with LaTeX/KaTeX equations
-
-## Troubleshooting
-
-### Filter Divergence
-If the EKF diverges (unbounded errors):
-1. Increase process noise (Q matrix)
-2. Check IMU bias initialization
-3. Verify coordinate frame consistency (ENU vs NED)
-4. Ensure measurement noise is realistic
-
-### Poor Performance vs UKF
-If EKF significantly underperforms UKF:
-1. Check for highly nonlinear motion (e.g., aggressive maneuvers)
-2. Verify Jacobian computations are appropriate for your scenario
-3. Consider using UKF for highly nonlinear regimes
-
-### Numerical Issues
-If experiencing numerical instability:
-1. Covariance regularization is applied automatically (eps = 1e-9)
-2. Joseph form covariance update is used for numerical stability
-3. Robust SPD solver is used for Kalman gain computation
-
-## Future Work
-
-- CLI integration once particle filter stubs are resolved
-- Example configurations and datasets
-- Performance benchmarking suite
-- Extended documentation with real-world examples
-- Support for additional measurement types (pseudorange, carrier phase)
-
-## References
-
-1. Groves, P. D. (2013). "Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, 2nd Edition"
-2. Bar-Shalom, Y., et al. (2001). "Estimation with Applications to Tracking and Navigation"
-3. Simon, D. (2006). "Optimal State Estimation: Kalman, H∞, and Nonlinear Approaches"
diff --git a/book/GITHUB_PAGES_SETUP.md b/book/GITHUB_PAGES_SETUP.md
deleted file mode 100644
index e86aaf2d..00000000
--- a/book/GITHUB_PAGES_SETUP.md
+++ /dev/null
@@ -1,305 +0,0 @@
-# GitHub Pages Setup Guide for Strapdown-rs
-
-This guide provides step-by-step instructions for setting up and deploying the Strapdown-rs documentation website using GitHub Pages and mdBook.
-
-## Overview
-
-The strapdown-rs project now includes a comprehensive documentation website built with mdBook. This guide covers:
-
-1. Local development and testing
-2. GitHub Pages configuration
-3. Automatic deployment via GitHub Actions
-4. Custom domain setup
-
-## Project Structure
-
-```
-book/
-├── book.toml # mdBook configuration
-├── custom.css # Custom styling
-├── src/ # Documentation source files
-│ ├── SUMMARY.md # Table of contents
-│ ├── introduction.md
-│ ├── quick-start.md
-│ ├── installation/
-│ ├── user-guide/
-│ ├── filters/
-│ ├── geonav/
-│ ├── gnss/
-│ ├── api/
-│ ├── examples/
-│ ├── development/
-│ ├── resources/
-│ └── faq.md
-└── book/ # Generated HTML (gitignored)
-```
-
-## Local Development
-
-### Prerequisites
-
-1. **Install Rust and Cargo** (if not already installed):
- ```bash
- curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- ```
-
-2. **Install mdBook**:
- ```bash
- cargo install mdbook
- ```
-
-### Building and Serving Locally
-
-1. **Build the book**:
- ```bash
- cd book
- mdbook build
- ```
- The generated HTML will be in `book/book/`.
-
-2. **Serve the book locally** (with live reload):
- ```bash
- cd book
- mdbook serve
- ```
- Open http://localhost:3000 in your browser.
-
-3. **Watch for changes** (automatic rebuild):
- ```bash
- cd book
- mdbook watch
- ```
-
-### Adding New Content
-
-1. **Create a new markdown file** in the appropriate directory under `book/src/`.
-
-2. **Add the file to SUMMARY.md**:
- ```markdown
- # Summary
-
- - [New Chapter](./path/to/new-chapter.md)
- ```
-
-3. **Build and test** locally before committing.
-
-## GitHub Pages Configuration
-
-### Step 1: Enable GitHub Pages
-
-1. Go to your repository on GitHub: https://github.com/jbrodovsky/strapdown-rs
-
-2. Click **Settings** → **Pages**
-
-3. Under "Build and deployment":
- - **Source**: Select "GitHub Actions"
- - This enables the workflow-based deployment
-
-4. Save the settings.
-
-### Step 2: Verify Workflow Permissions
-
-1. Go to **Settings** → **Actions** → **General**
-
-2. Under "Workflow permissions":
- - Select "Read and write permissions"
- - Check "Allow GitHub Actions to create and approve pull requests"
-
-3. Save the settings.
-
-### Step 3: Deploy
-
-The GitHub Actions workflow (`.github/workflows/deploy-book.yml`) automatically:
-- Builds the book when you push to `main`
-- Deploys it to GitHub Pages
-- Makes it available at: https://jbrodovsky.github.io/strapdown-rs/
-
-**First deployment**: After merging the PR, the site should be live within 2-5 minutes.
-
-## Custom Domain Setup
-
-To use your custom domain (www.strapdown.rs):
-
-### Step 1: Configure DNS
-
-Add these DNS records with your domain registrar:
-
-**For apex domain (strapdown.rs)**:
-```
-Type: A
-Name: @
-Value: 185.199.108.153
- 185.199.109.153
- 185.199.110.153
- 185.199.111.153
-```
-
-**For www subdomain (www.strapdown.rs)**:
-```
-Type: CNAME
-Name: www
-Value: jbrodovsky.github.io
-```
-
-### Step 2: Configure GitHub Pages
-
-1. Go to **Settings** → **Pages**
-
-2. Under "Custom domain":
- - Enter: `www.strapdown.rs`
- - Click **Save**
-
-3. Check **Enforce HTTPS** (wait a few minutes for the certificate)
-
-### Step 3: Update book.toml
-
-The `book.toml` already includes:
-```toml
-[output.html]
-cname = "www.strapdown.rs"
-site-url = "/"
-```
-
-This creates a `CNAME` file in the build output.
-
-### Step 4: Verify
-
-After DNS propagation (can take up to 48 hours but usually minutes):
-- Visit https://www.strapdown.rs
-- Verify HTTPS works
-- Check that redirects work correctly
-
-## Workflow Details
-
-The GitHub Actions workflow (`.github/workflows/deploy-book.yml`) performs these steps:
-
-1. **Checkout**: Gets the repository code
-2. **Setup Rust**: Installs the Rust toolchain
-3. **Install mdBook**: Installs mdBook via cargo
-4. **Build**: Runs `mdbook build` in the `book/` directory
-5. **Upload**: Uploads the build artifact
-6. **Deploy**: Deploys to GitHub Pages (only on `main` branch)
-
-### Triggering Deployment
-
-Deployment happens automatically when:
-- You push to the `main` branch
-- A PR is merged into `main`
-- You manually trigger via "Run workflow" in the Actions tab
-
-### Monitoring Deployment
-
-1. Go to **Actions** tab in GitHub
-2. Click on the latest "Deploy mdBook to GitHub Pages" workflow
-3. Check the build and deploy steps
-4. If successful, visit the site URL
-
-## Troubleshooting
-
-### Build Fails Locally
-
-**Error**: "command not found: mdbook"
-- **Solution**: Install mdBook: `cargo install mdbook`
-
-**Error**: "Invalid configuration file"
-- **Solution**: Check `book.toml` syntax with `mdbook build --verbose`
-
-### Build Fails on GitHub
-
-**Error**: Permission denied
-- **Solution**: Check workflow permissions in Settings → Actions
-
-**Error**: mdBook installation fails
-- **Solution**: The workflow should install mdBook automatically. Check the workflow logs.
-
-### Site Not Updating
-
-1. **Check workflow status**: Actions tab should show successful deployment
-2. **Clear browser cache**: Use Ctrl+Shift+R or Cmd+Shift+R
-3. **Wait for propagation**: Can take 1-2 minutes after deployment
-4. **Check GitHub Pages settings**: Ensure source is set to "GitHub Actions"
-
-### Custom Domain Not Working
-
-1. **Verify DNS records**: Use `dig www.strapdown.rs` or https://dnschecker.org
-2. **Check CNAME file**: Should be present in the deployed site
-3. **Wait for DNS propagation**: Can take up to 48 hours
-4. **Check HTTPS**: May need time to provision certificate
-
-## Customization
-
-### Styling
-
-Edit `book/custom.css` to customize the appearance:
-- Colors and themes
-- Typography
-- Layout and spacing
-- Mobile responsiveness
-
-### Configuration
-
-Edit `book/book.toml` to change:
-- Site title and description
-- Theme preferences
-- Search settings
-- MathJax support
-- Git integration
-
-### Theme
-
-mdBook includes several built-in themes:
-- Light (default)
-- Navy
-- Coal
-- Rust
-- Ayu
-
-Users can switch themes using the theme selector in the top menu.
-
-## Maintenance
-
-### Updating Content
-
-1. Edit markdown files in `book/src/`
-2. Test locally with `mdbook serve`
-3. Commit and push to `main`
-4. GitHub Actions automatically deploys
-
-### Updating mdBook
-
-To update to the latest mdBook version:
-
-```bash
-cargo install mdbook --force
-```
-
-Update the version in `.github/workflows/deploy-book.yml` if needed.
-
-### Monitoring
-
-- Check GitHub Actions for build/deployment status
-- Monitor GitHub Pages analytics (if enabled)
-- Review issues/feedback from users
-
-## Best Practices
-
-1. **Always test locally** before pushing to main
-2. **Use descriptive commit messages** for documentation changes
-3. **Keep navigation organized** in SUMMARY.md
-4. **Cross-reference pages** using relative links
-5. **Include code examples** where appropriate
-6. **Update the table of contents** when adding pages
-7. **Use proper markdown formatting** for consistency
-
-## Additional Resources
-
-- [mdBook Documentation](https://rust-lang.github.io/mdBook/)
-- [GitHub Pages Documentation](https://docs.github.com/en/pages)
-- [GitHub Actions Documentation](https://docs.github.com/en/actions)
-- [Markdown Guide](https://www.markdownguide.org/)
-
-## Support
-
-For issues or questions:
-- Open an issue on [GitHub](https://github.com/jbrodovsky/strapdown-rs/issues)
-- Contact the maintainer: jbrodovsky@temple.edu
diff --git a/book/PROJECT_SUMMARY.md b/book/PROJECT_SUMMARY.md
deleted file mode 100644
index 94751597..00000000
--- a/book/PROJECT_SUMMARY.md
+++ /dev/null
@@ -1,346 +0,0 @@
-# Strapdown-rs Documentation Website - Implementation Summary
-
-## Overview
-
-A comprehensive GitHub Pages website has been successfully developed for the strapdown-rs project using mdBook, a modern documentation tool built with Rust. The website provides easy-to-navigate documentation, tutorials, API references, and usage instructions.
-
-## What Has Been Implemented
-
-### 1. Documentation Structure
-
-A complete book structure with the following sections:
-
-- **Introduction**: Project overview, features, and getting started
-- **Installation**: System requirements, dependencies, and installation methods
-- **Quick Start**: Fast-track guide to running first simulations
-- **User Guide**: Comprehensive usage documentation
- - Core concepts and theory
- - Simulation modes (open-loop, closed-loop, particle filter)
- - Data formats and configuration
- - Logging and debugging
-- **Navigation Filters**: Detailed filter documentation
- - Extended Kalman Filter (EKF)
- - Unscented Kalman Filter (UKF)
- - Particle Filters and RBPF
- - Comparison and selection guide
-- **Geophysical Navigation**: Gravity and magnetic anomaly navigation
-- **GNSS Degradation**: Fault simulation scenarios
-- **API Reference**: Module-level documentation structure
-- **Examples**: Tutorials and configuration examples
-- **Development**: Contributing guidelines and architecture
-- **FAQ**: Common questions and troubleshooting
-- **Resources**: Publications, links, and glossary
-
-### 2. Technical Implementation
-
-#### mdBook Configuration (`book/book.toml`)
-
-Configured with:
-- MathJax support for mathematical equations
-- Custom CSS for improved styling
-- GitHub repository integration
-- Edit links to source files
-- Search functionality
-- Responsive design
-- Custom domain support (www.strapdown.rs)
-
-#### Custom Styling (`book/custom.css`)
-
-Custom CSS providing:
-- Improved code block styling
-- Warning/info/note boxes
-- Better mobile responsiveness
-- Enhanced table formatting
-- Consistent link styling
-
-#### GitHub Actions Workflow (`.github/workflows/deploy-book.yml`)
-
-Automated deployment workflow that:
-- Builds the book on every push to main
-- Installs mdBook automatically
-- Deploys to GitHub Pages
-- Supports manual triggering
-- Uses proper GitHub Pages deployment action
-
-### 3. Key Content Pages Created
-
-The following pages have substantial content:
-
-1. **Introduction** (`book/src/introduction.md`)
- - Project overview
- - Key features
- - Target audience
- - Getting help
-
-2. **Quick Start** (`book/src/quick-start.md`)
- - Installation commands
- - First simulation examples
- - Configuration file usage
- - Next steps
-
-3. **Installation Guide** (`book/src/installation/installation.md`)
- - System requirements
- - Installation methods
- - Platform-specific instructions
- - Troubleshooting
-
-4. **System Requirements** (`book/src/installation/requirements.md`)
- - Hardware requirements
- - Software requirements
- - Platform notes
- - Development tools
-
-5. **User Guide Overview** (`book/src/user-guide/overview.md`)
- - Guide structure
- - Simulation modes
- - State models
- - Common workflows
-
-6. **EKF Documentation** (`book/src/filters/ekf.md`)
- - Mathematical foundation
- - Usage examples
- - Configuration guide
- - Performance characteristics
-
-7. **FAQ** (`book/src/faq.md`)
- - General questions
- - Installation help
- - Usage guidance
- - Troubleshooting
-
-### 4. Setup Documentation
-
-#### GITHUB_PAGES_SETUP.md
-
-Comprehensive guide covering:
-- Local development workflow
-- GitHub Pages configuration
-- Custom domain setup (DNS, CNAME)
-- Workflow details and monitoring
-- Troubleshooting common issues
-- Maintenance and best practices
-
-## File Structure
-
-```
-book/
-├── book.toml # mdBook configuration
-├── custom.css # Custom styling
-├── .gitignore # Ignore build output
-└── src/
- ├── SUMMARY.md # Table of contents
- ├── introduction.md # Main introduction
- ├── quick-start.md # Quick start guide
- ├── faq.md # FAQ
- ├── installation/ # Installation docs
- ├── user-guide/ # User guide pages
- ├── filters/ # Filter documentation
- ├── geonav/ # Geophysical navigation
- ├── gnss/ # GNSS scenarios
- ├── api/ # API reference
- ├── examples/ # Tutorials
- ├── development/ # Contributing
- └── resources/ # Additional resources
-```
-
-## How to Use
-
-### Local Development
-
-1. Install mdBook:
- ```bash
- cargo install mdbook
- ```
-
-2. Build and serve locally:
- ```bash
- cd book
- mdbook serve
- ```
-
-3. View at http://localhost:3000
-
-### Adding Content
-
-1. Create or edit markdown files in `book/src/`
-2. Update `SUMMARY.md` if adding new pages
-3. Build locally to test
-4. Commit and push to trigger deployment
-
-### Deployment
-
-**Automatic**: Push to `main` branch triggers GitHub Actions workflow
-
-**Manual**:
-1. Go to Actions tab on GitHub
-2. Select "Deploy mdBook to GitHub Pages"
-3. Click "Run workflow"
-
-## GitHub Pages Setup Required
-
-After merging this PR, you'll need to:
-
-1. **Enable GitHub Pages**:
- - Go to Settings → Pages
- - Set source to "GitHub Actions"
- - Save
-
-2. **Verify Permissions**:
- - Settings → Actions → General
- - Enable "Read and write permissions"
-
-3. **Wait for Deployment**:
- - First deployment takes 2-5 minutes
- - Site will be available at: https://jbrodovsky.github.io/strapdown-rs/
-
-4. **Optional - Custom Domain**:
- - Configure DNS records (see GITHUB_PAGES_SETUP.md)
- - Add domain in Settings → Pages
- - Enable HTTPS
-
-## Features
-
-### For Users
-
-- **Easy Navigation**: Sidebar with hierarchical structure
-- **Search**: Full-text search across all pages
-- **Responsive**: Works on desktop and mobile
-- **Dark Mode**: Built-in theme switcher
-- **Printable**: Print-friendly styling
-- **MathJax**: Mathematical equation rendering
-- **Code Highlighting**: Syntax highlighting for Rust and other languages
-
-### For Maintainers
-
-- **Automatic Deployment**: Push to main = instant updates
-- **Edit Links**: Each page has "Edit on GitHub" link
-- **Version Control**: All docs in Git
-- **Easy Updates**: Markdown-based authoring
-- **No Build Dependencies**: GitHub Actions handles everything
-
-## What's Next
-
-### Content to Expand
-
-Many pages are currently placeholders. Priority areas to fill:
-
-1. **API Reference**: Detailed module documentation
-2. **Tutorials**: Step-by-step examples
-3. **Core Concepts**: INS theory and implementation
-4. **Examples**: More configuration examples
-5. **Measurement Models**: Detailed measurement documentation
-
-### Enhancements
-
-Possible future improvements:
-
-1. **Search Optimization**: Tune search indexing
-2. **More Examples**: Add code examples to more pages
-3. **Diagrams**: Add visual diagrams and flowcharts
-4. **Videos**: Embed tutorial videos
-5. **Interactive Demos**: WebAssembly demos
-
-## Integration with Existing Docs
-
-The website complements existing documentation:
-
-- **docs/**: Technical documentation (can be moved to book)
-- **README.md**: Updated with link to full documentation
-- **API Docs**: docs.rs remains the Rust API reference
-- **Examples**: Configuration examples remain in `examples/`
-
-## Custom Domain Setup
-
-The book is pre-configured for www.strapdown.rs:
-
-1. **DNS Records**:
- - A records pointing to GitHub Pages IPs
- - CNAME for www subdomain
-
-2. **Configuration**:
- - `cname = "www.strapdown.rs"` in book.toml
- - Automatic CNAME file generation
-
-3. **Verification**:
- - Visit https://www.strapdown.rs after DNS propagation
- - HTTPS automatically provisioned
-
-See GITHUB_PAGES_SETUP.md for detailed DNS instructions.
-
-## Maintenance
-
-### Regular Updates
-
-1. Keep content current with code changes
-2. Update examples when APIs change
-3. Add new sections as features are added
-4. Review and address user feedback
-
-### Monitoring
-
-1. Check GitHub Actions for build failures
-2. Review GitHub Pages analytics (if enabled)
-3. Monitor issues for documentation questions
-4. Keep mdBook updated
-
-### Contributing
-
-Users can contribute documentation:
-
-1. Fork the repository
-2. Edit files in `book/src/`
-3. Submit pull request
-4. Preview builds automatically
-
-## Benefits
-
-### For the Project
-
-- **Professional presentation**
-- **Better discoverability**
-- **Reduced support burden** (better docs = fewer questions)
-- **Easier onboarding** for new users
-- **Research credibility** (important for academic projects)
-
-### For Users
-
-- **Centralized documentation**
-- **Easy to search and navigate**
-- **Always up-to-date**
-- **Mobile-friendly**
-- **Offline capable** (can download HTML)
-
-## Conclusion
-
-A complete, production-ready documentation website has been implemented for strapdown-rs. The site is:
-
-- ✅ Built with modern tools (mdBook)
-- ✅ Automatically deployed via GitHub Actions
-- ✅ Well-structured with comprehensive content outline
-- ✅ Styled for readability and professionalism
-- ✅ Configured for custom domain
-- ✅ Ready for immediate use
-- ✅ Easy to maintain and extend
-
-The foundation is solid. Content can be expanded incrementally as the project evolves. The setup guide ensures that anyone can contribute or maintain the documentation going forward.
-
-## Files Changed
-
-### Created:
-- `book/` - Complete mdBook project
-- `.github/workflows/deploy-book.yml` - Deployment workflow
-- `GITHUB_PAGES_SETUP.md` - Setup instructions
-- `PROJECT_SUMMARY.md` - This file
-
-### Modified:
-- `.gitignore` - Added book output exclusion
-- `README.md` - Updated documentation link
-
-### Total:
-- 60+ markdown files
-- 1 GitHub Actions workflow
-- 2 configuration files
-- 1 CSS stylesheet
-- 2 guide documents
-
-All ready for immediate deployment upon merge!
diff --git a/book/QUICK_REFERENCE.md b/book/QUICK_REFERENCE.md
deleted file mode 100644
index f262a65e..00000000
--- a/book/QUICK_REFERENCE.md
+++ /dev/null
@@ -1,166 +0,0 @@
-# Quick Reference - GitHub Pages Deployment
-
-## After Merge: Immediate Next Steps
-
-### 1. Enable GitHub Pages (2 minutes)
-
-1. Go to https://github.com/jbrodovsky/strapdown-rs/settings/pages
-2. Under "Build and deployment":
- - **Source**: Select "GitHub Actions"
-3. Click **Save**
-
-### 2. Verify Permissions (1 minute)
-
-1. Go to https://github.com/jbrodovsky/strapdown-rs/settings/actions
-2. Under "Workflow permissions":
- - Select **"Read and write permissions"**
- - Check **"Allow GitHub Actions to create and approve pull requests"**
-3. Click **Save**
-
-### 3. Trigger First Deployment (automatic)
-
-The merge to `main` will automatically trigger the deployment workflow.
-
-Or manually trigger:
-1. Go to https://github.com/jbrodovsky/strapdown-rs/actions
-2. Click "Deploy mdBook to GitHub Pages"
-3. Click "Run workflow" → "Run workflow"
-
-### 4. Verify Deployment (2-5 minutes)
-
-1. Wait for the workflow to complete (green checkmark)
-2. Visit: https://jbrodovsky.github.io/strapdown-rs/
-3. Verify the site loads correctly
-
-## Custom Domain Setup (Optional)
-
-### DNS Configuration
-
-Add these records to your domain registrar:
-
-**For strapdown.rs:**
-```
-Type: A
-Name: @
-Values:
- 185.199.108.153
- 185.199.109.153
- 185.199.110.153
- 185.199.111.153
-```
-
-**For www.strapdown.rs:**
-```
-Type: CNAME
-Name: www
-Value: jbrodovsky.github.io
-```
-
-### GitHub Configuration
-
-1. Go to https://github.com/jbrodovsky/strapdown-rs/settings/pages
-2. Under "Custom domain":
- - Enter: `www.strapdown.rs`
- - Click **Save**
-3. Wait a few minutes, then check **"Enforce HTTPS"**
-
-### Verify
-
-After DNS propagation (up to 48 hours, usually minutes):
-- Visit https://www.strapdown.rs
-- Verify HTTPS works
-- Check redirect from http:// to https://
-
-## Quick Commands
-
-### Build locally:
-```bash
-cd book
-mdbook build
-```
-
-### Serve locally (with live reload):
-```bash
-cd book
-mdbook serve
-```
-
-### Check for errors:
-```bash
-cd book
-mdbook build --verbose
-```
-
-## File Structure
-
-```
-book/
-├── book.toml # Configuration
-├── custom.css # Styling
-└── src/
- ├── SUMMARY.md # Table of contents (edit to add pages)
- └── *.md # Content pages
-```
-
-## Common Tasks
-
-### Add a new page:
-1. Create `book/src/path/to/page.md`
-2. Add to `book/src/SUMMARY.md`:
- ```markdown
- - [Page Title](./path/to/page.md)
- ```
-3. Build and test locally
-4. Commit and push
-
-### Update existing page:
-1. Edit the markdown file
-2. Test locally with `mdbook serve`
-3. Commit and push
-4. Deployment happens automatically
-
-### Change styling:
-1. Edit `book/custom.css`
-2. Test locally
-3. Commit and push
-
-## Monitoring
-
-### Check deployment status:
-https://github.com/jbrodovsky/strapdown-rs/actions
-
-### View deployed site:
-https://jbrodovsky.github.io/strapdown-rs/
-
-### Check workflow logs:
-Actions tab → Latest "Deploy mdBook to GitHub Pages" run
-
-## Troubleshooting
-
-### Build fails:
-```bash
-cd book
-mdbook build --verbose
-```
-Check error messages, fix markdown syntax
-
-### Site not updating:
-1. Check GitHub Actions (should show green checkmark)
-2. Clear browser cache (Ctrl+Shift+R)
-3. Wait 1-2 minutes for CDN propagation
-
-### Custom domain not working:
-1. Verify DNS: `dig www.strapdown.rs`
-2. Check CNAME file is present in deployment
-3. Wait for DNS propagation (up to 48 hours)
-
-## Support
-
-- **Setup Guide**: See GITHUB_PAGES_SETUP.md for detailed instructions
-- **Project Summary**: See PROJECT_SUMMARY.md for implementation details
-- **mdBook Docs**: https://rust-lang.github.io/mdBook/
-- **GitHub Pages**: https://docs.github.com/en/pages
-
-## Contact
-
-Questions? Open an issue or contact: jbrodovsky@temple.edu
diff --git a/book/RBPF.md b/book/RBPF.md
deleted file mode 100644
index 4cfa1c58..00000000
--- a/book/RBPF.md
+++ /dev/null
@@ -1,715 +0,0 @@
-# Rao-Blackwellized Particle Filter Implementation
-
-## Overview
-
-The Rao-Blackwellized Particle Filter (RBPF) partitions the 15-state INS into nonlinear states (position: 3) estimated via particles and conditionally linear states (velocity: 3, attitude: 3, biases: 6) estimated via per-particle **EKF** filters. This reduces computational burden while improving bias estimation and maintaining the existing 2.5D vertical channel approach.
-
-**Note:** The current implementation uses an **Extended Kalman Filter (EKF)** instead of an Unscented Kalman Filter (UKF) for improved computational efficiency. The EKF uses Jacobian-based linearization which is faster than the UKF's sigma point approach, providing approximately 3-5x speedup while maintaining acceptable accuracy for the conditionally-linear states.
-
-## State Partitioning
-
-**Nonlinear states (particles):**
-- Latitude (rad)
-- Longitude (rad)
-- Altitude (m)
-
-**Linear/Conditionally-Gaussian states (per-particle EKF):**
-- Velocity: v_north, v_east, v_vertical (m/s)
-- Attitude: roll, pitch, yaw (rad)
-- Accelerometer biases: b_ax, b_ay, b_az (m/s²)
-- Gyroscope biases: b_gx, b_gy, b_gz (rad/s)
-
-## Implementation Steps
-
-### Step 1: Create new structs for RBPF state representation
-
-**Location:** `core/src/particle.rs`
-
-#### 1.1 Define `RBParticle` struct
-
-```rust
-pub struct RBParticle {
- /// Position states: [latitude (rad), longitude (rad), altitude (m)]
- pub position: Vector3,
-
- /// Per-particle UKF for linear states (9-state: velocity, attitude, biases)
- pub kalman_filter: PerParticleUKF,
-
- /// Importance weight (unnormalized likelihood)
- pub weight: f64,
-}
-```
-
-**Methods to implement:**
-- `to_state_vector(&self) -> DVector` - Convert to 15-state vector for compatibility
-- `from_state_vector(state: &DVector) -> Self` - Create from state vector
-- `get_position(&self) -> Vector3` - Access position
-- `get_linear_states(&self) -> DVector` - Access velocity, attitude, biases from UKF
-
-#### 1.2 Define `PerParticleEKF` struct
-
-```rust
-pub struct PerParticleEKF {
- /// Mean state: [v_n, v_e, v_v, roll, pitch, yaw, b_ax, b_ay, b_az, b_gx, b_gy, b_gz]
- pub mean_state: DVector,
-
- /// Covariance matrix (12×12)
- pub covariance: DMatrix,
-}
-```
-
-**Methods to implement:**
-- `new(initial_state: DVector, initial_cov: DMatrix) -> Self`
-- `predict(&mut self, position: &Vector3, imu_data: IMUData, process_noise: &DMatrix, dt: f64, is_enu: bool)` - EKF predict step conditioned on particle position, uses Jacobian computation
-- `update(&mut self, position: &Vector3, measurement: &M) -> f64` - EKF update, returns marginal likelihood for particle weighting
-- `get_estimate(&self) -> DVector` - Return mean state
-- `get_covariance(&self) -> DMatrix` - Return covariance
-- `compute_state_transition_jacobian(...)` - Compute F matrix for linearization
-- `compute_measurement_jacobian(...)` - Compute H matrix for measurement update
-
-#### 1.3 Define `RBProcessNoise` struct
-
-```rust
-pub struct RBProcessNoise {
- /// Position noise standard deviations [σ_lat, σ_lon, σ_h] (rad, rad, m)
- pub position_std: Vector3,
-
- /// Linear state noise covariance matrix (9×9) for per-particle UKF
- /// Includes: velocity (3), attitude (3), accel biases (3), gyro biases (3)
- pub linear_states_covariance: DMatrix,
-}
-```
-
-**Default implementation:**
-```rust
-impl Default for RBProcessNoise {
- fn default() -> Self {
- // Position noise (for particle diffusion)
- let position_std = Vector3::new(1e-3, 1e-3, 5e-2);
-
- // Linear state noise (for UKF predict)
- let linear_noise_diag = vec![
- 1e-2, 1e-2, 1e-1, // velocity (2.5D: large v_v)
- 1e-3, 1e-3, 1e-3, // attitude
- 1e-3, 1e-3, 1e-3, // accel biases
- 1e-4, 1e-4, 1e-4, // gyro biases
- ];
- let linear_states_covariance = DMatrix::from_diagonal(&DVector::from_vec(linear_noise_diag));
-
- RBProcessNoise {
- position_std,
- linear_states_covariance,
- }
- }
-}
-```
-
-### Step 2: Implement `RaoBlackwellizedParticleFilter` struct
-
-**Location:** `core/src/particle.rs`
-
-#### 2.1 Main struct definition
-
-```rust
-pub struct RaoBlackwellizedParticleFilter {
- /// Ensemble of RB particles
- particles: Vec,
-
- /// Number of particles
- num_particles: usize,
-
- /// Process noise parameters
- process_noise: RBProcessNoise,
-
- /// Vertical channel mode (2.5D simplified)
- vertical_channel_mode: VerticalChannelMode,
-
- /// Resampling strategy
- resampling_strategy: ResamplingStrategy,
-
- /// Effective particle threshold for resampling
- effective_particle_threshold: f64,
-
- /// Random number generator (seeded)
- rng: StdRng,
-
- /// Coordinate frame flag
- is_enu: bool,
-
- /// UKF parameters for per-particle filters
- ukf_alpha: f64,
- ukf_beta: f64,
- ukf_kappa: f64,
-}
-```
-
-#### 2.2 Constructor
-
-```rust
-impl RaoBlackwellizedParticleFilter {
- pub fn new(
- initial_state: InitialState,
- imu_biases: Vec,
- covariance_diagonal: Vec, // 15-element: 3 position + 9 linear + 3 biases
- process_noise: RBProcessNoise,
- num_particles: usize,
- vertical_mode: VerticalChannelMode,
- resampling_strategy: ResamplingStrategy,
- ukf_alpha: f64,
- ukf_beta: f64,
- ukf_kappa: f64,
- seed: Option,
- ) -> Self {
- // 1. Initialize RNG
- // 2. Sample initial positions from Gaussian (first 3 elements of covariance_diagonal)
- // 3. Initialize identical per-particle UKFs with velocity, attitude, biases
- // (elements 3-14 of covariance_diagonal)
- // 4. Set uniform weights
- // ...
- }
-}
-```
-
-#### 2.3 Implement `NavigationFilter` trait
-
-```rust
-impl NavigationFilter for RaoBlackwellizedParticleFilter {
- fn predict(&mut self, imu_data: IMUData, dt: f64) {
- // For each particle:
- for particle in &mut self.particles {
- // 1. Get current velocity and attitude from UKF
- let linear_states = particle.kalman_filter.get_estimate();
- let velocity = linear_states.fixed_rows::<3>(0);
- let attitude = linear_states.fixed_rows::<3>(3);
-
- // 2. Propagate position using forward_2_5d_rbpf (attitude, velocity given)
- forward_2_5d_rbpf(
- &mut particle.position,
- &velocity,
- &attitude,
- dt
- );
-
- // 3. Add process noise to position
- add_position_noise(&mut particle.position, &self.process_noise.position_std, dt, &mut self.rng);
-
- // 4. UKF predict for linear states (conditioned on new position)
- let biases = linear_states.fixed_rows::<6>(3);
- let bias_corrected_imu = IMUData {
- accel: imu_data.accel - biases.fixed_rows::<3>(0),
- gyro: imu_data.gyro - biases.fixed_rows::<3>(3),
- };
- particle.kalman_filter.predict(
- &particle.position,
- bias_corrected_imu,
- &self.process_noise.linear_states_covariance,
- dt
- );
- }
- }
-
- fn update(&mut self, measurement: &M) {
- // 1. Compute marginal likelihood for each particle
- for particle in &mut self.particles {
- // UKF update returns marginal likelihood p(z|position)
- let log_likelihood = particle.kalman_filter.update(
- &particle.position,
- measurement
- );
- particle.weight *= log_likelihood.exp();
- }
-
- // 2. Normalize weights
- self.normalize_weights();
-
- // 3. Check ESS and resample if needed
- let ess = self.effective_particle_count();
- if ess < self.effective_particle_threshold {
- self.resample();
- }
- }
-
- fn get_estimate(&self) -> DVector {
- // 1. Weighted average of positions
- let mean_position = self.weighted_position_mean();
-
- // 2. Weighted average of per-particle UKF means
- let mean_linear_states = self.weighted_linear_states_mean();
-
- // 3. Concatenate into 15-state vector
- let mut state = DVector::zeros(15);
- state.fixed_rows_mut::<3>(0).copy_from(&mean_position);
- state.fixed_rows_mut::<12>(3).copy_from(&mean_linear_states);
- state
- }
-
- fn get_certainty(&self) -> DMatrix {
- // Combined covariance from:
- // 1. Particle position covariance (empirical from weighted samples)
- // 2. Weighted average of per-particle UKF covariances
- // 3. Cross terms (position-linear states correlation)
- self.compute_combined_covariance()
- }
-}
-```
-
-### Step 3: Add RBPF-specific propagation functions
-
-**Location:** `core/src/particle.rs`
-
-#### 3.1 Position propagation function
-
-```rust
-/// Propagate position states for RBPF given velocity and attitude from UKF.
-///
-/// This is the position-only component of 2.5D navigation. The velocity and
-/// attitude are provided as inputs (from per-particle UKF) rather than being
-/// propagated together with position.
-///
-/// # Arguments
-/// * `position` - Mutable reference to position [lat, lon, alt]
-/// * `velocity` - Velocity vector [v_n, v_e, v_v] from UKF
-/// * `attitude` - Attitude angles [roll, pitch, yaw] from UKF
-/// * `dt` - Time step
-pub fn forward_2_5d_rbpf(
- position: &mut Vector3,
- velocity: &Vector3,
- attitude: &Vector3,
- dt: f64,
-) {
- // 1. Update horizontal position (lat, lon) using geodetic equations
- // Similar to position_update() but only using horizontal velocities
-
- // 2. Update altitude using vertical velocity (2.5D: simple integration)
- // alt(t+dt) = alt(t) + v_v * dt
-
- // Uses earth model and geodetic calculations from crate::earth
-}
-```
-
-#### 3.2 UKF predict with position conditioning
-
-```rust
-impl PerParticleUKF {
- /// UKF predict step conditioned on particle position.
- ///
- /// Propagates the 9-state linear system: velocity, attitude, biases.
- /// The nonlinear coupling with position comes through gravity, Earth rate,
- /// and transport rate terms which are evaluated at the given position.
- pub fn predict(
- &mut self,
- position: &Vector3, // Given by particle
- imu_data: IMUData,
- process_noise: &DMatrix,
- dt: f64,
- ) {
- // 1. Generate sigma points for 9-state UKF
- let sigma_points = self.get_sigma_points();
-
- // 2. Propagate each sigma point
- // - Velocity: use velocity_update_horizontal and vertical velocity dynamics
- // - Attitude: use attitude_update with gyro measurements
- // - Biases: random walk
- let propagated_sigma_points = self.propagate_sigma_points(
- &sigma_points,
- position, // Earth parameters evaluated here
- imu_data,
- dt
- );
-
- // 3. Compute predicted mean and covariance
- let mut mean_predicted = DVector::zeros(9);
- for (i, sigma_point) in propagated_sigma_points.column_iter().enumerate() {
- mean_predicted += self.weights_mean[i] * sigma_point;
- }
-
- let mut cov_predicted = DMatrix::zeros(9, 9);
- for (i, sigma_point) in propagated_sigma_points.column_iter().enumerate() {
- let diff = sigma_point - &mean_predicted;
- cov_predicted += self.weights_cov[i] * (&diff * diff.transpose());
- }
- cov_predicted += process_noise;
-
- self.mean_state = mean_predicted;
- self.covariance = symmetrize(&cov_predicted);
- }
-}
-```
-
-#### 3.3 UKF update with marginal likelihood
-
-```rust
-impl PerParticleUKF {
- /// UKF update step, returns marginal log-likelihood for particle weighting.
- ///
- /// Performs standard UKF measurement update on the linear states and
- /// computes the marginal likelihood p(z | position) which is used to
- /// update the particle weight.
- pub fn update(
- &mut self,
- position: &Vector3,
- measurement: &M,
- ) -> f64 {
- // 1. Generate measurement sigma points
- // 2. Compute predicted measurement and innovation covariance
- // 3. Compute Kalman gain
- // 4. Update mean and covariance
- // 5. Compute marginal likelihood:
- // log p(z|position) = -0.5 * (innovation^T * S^-1 * innovation + log|S| + k*log(2π))
- // where S is the innovation covariance
-
- // ... (Standard UKF update equations)
-
- // Return log-likelihood for particle weighting
- let log_likelihood = -0.5 * (
- innovation.dot(&s_inv_innovation) +
- s.determinant().ln() +
- innovation.len() as f64 * (2.0 * std::f64::consts::PI).ln()
- );
-
- log_likelihood
- }
-}
-```
-
-### Step 4: Extend sim.rs with initialization helper
-
-**Location:** `core/src/sim.rs`
-
-```rust
-/// Initialize a Rao-Blackwellized particle filter for simulation.
-///
-/// This function creates and initializes a `RaoBlackwellizedParticleFilter` with the
-/// given parameters, using UKF for per-particle linear state estimation.
-///
-/// # Arguments
-///
-/// * `initial_pose` - A `TestDataRecord` containing the initial pose information.
-/// * `num_particles` - Number of particles in the ensemble (recommend 50-200 for RBPF).
-/// * `vertical_mode` - Vertical channel mode (Simplified for 2.5D).
-/// * `attitude_covariance` - Optional initial attitude covariance.
-/// * `imu_biases` - Optional initial IMU biases.
-/// * `imu_biases_covariance` - Optional IMU bias covariance.
-/// * `process_noise` - Optional `RBProcessNoise` struct.
-/// * `resampling_strategy` - Resampling algorithm (default: Systematic).
-/// * `ukf_alpha` - UKF spread parameter (default: 1e-3).
-/// * `ukf_beta` - UKF distribution parameter (default: 2.0).
-/// * `ukf_kappa` - UKF secondary scaling (default: 0.0).
-/// * `seed` - Optional random seed for reproducibility.
-///
-/// # Returns
-///
-/// * `RaoBlackwellizedParticleFilter` - Initialized RBPF instance.
-#[allow(clippy::too_many_arguments)]
-pub fn initialize_rbpf(
- initial_pose: &TestDataRecord,
- num_particles: usize,
- vertical_mode: VerticalChannelMode,
- attitude_covariance: Option>,
- imu_biases: Option>,
- imu_biases_covariance: Option>,
- process_noise: Option,
- resampling_strategy: Option,
- ukf_alpha: Option,
- ukf_beta: Option,
- ukf_kappa: Option,
- seed: Option,
-) -> RaoBlackwellizedParticleFilter {
- // Implementation parallel to initialize_particle_filter
- // but using RBProcessNoise and RBPF constructor
- // ...
-}
-```
-
-### Step 5: Add integration tests
-
-**Location:** `core/tests/integration_tests.rs`
-
-#### 5.1 Basic closed-loop test
-
-```rust
-#[test]
-fn test_rbpf_closed_loop_on_real_data() {
- // Load test data
- let manifest_dir = env!("CARGO_MANIFEST_DIR");
- let test_data_path = Path::new(manifest_dir).join("tests/test_data.csv");
- let records = load_test_data(&test_data_path);
- assert!(!records.is_empty());
-
- // Initialize RBPF with 100 particles (fewer than standard PF)
- let mut rbpf = initialize_rbpf(
- &records[0],
- 100, // Reduced particle count vs standard PF
- VerticalChannelMode::Simplified,
- None,
- None,
- None,
- None,
- Some(ResamplingStrategy::Systematic),
- Some(1e-3), // UKF alpha
- Some(2.0), // UKF beta
- Some(0.0), // UKF kappa
- Some(42), // Seed
- );
-
- // Build event stream with passthrough GNSS.
- //
- // `AidingConfig` is `#[non_exhaustive]`, so it is built from `default()` rather than
- // written as a struct literal; everything not set keeps its default, including the
- // barometer and magnetometer schedules. The fault field is `fault`, and
- // `build_event_stream` takes the navigation frame explicitly -- `false` is NED.
- let mut cfg = AidingConfig::default();
- cfg.scheduler = MeasurementScheduler::PassThrough;
- cfg.fault = GnssFaultModel::None;
- let stream =
- build_event_stream(&records, &cfg, false).expect("records must not be empty");
-
- // Run closed-loop
- let results = run_closed_loop(&mut rbpf, stream, None, None)
- .expect("RBPF closed-loop should complete");
-
- // Compute error metrics
- let stats = compute_error_metrics(&results, &records);
-
- // Print statistics
- println!("\n=== RBPF Closed-Loop Error Statistics ===");
- println!("Horizontal Error: mean={:.2}m, max={:.2}m, rms={:.2}m",
- stats.mean_horizontal_error,
- stats.max_horizontal_error,
- stats.rms_horizontal_error
- );
-
- // Assert reasonable error bounds (should match or beat UKF)
- assert!(
- stats.rms_horizontal_error < 50.0,
- "RBPF RMS horizontal error too large: {:.2}m",
- stats.rms_horizontal_error
- );
-}
-```
-
-#### 5.2 GNSS dropout test
-
-```rust
-#[test]
-fn test_rbpf_with_gnss_dropout() {
- // Similar to particle filter dropout test
- // Use periodic scheduler with 60s on / 30s off
- // Verify particle diversity maintained during outages
- // ...
-}
-```
-
-#### 5.3 Comparison test
-
-```rust
-#[test]
-fn test_rbpf_vs_standard_pf() {
- // Load same data
- // Run RBPF with 100 particles
- // Run standard PF with 500 particles
- // Compare:
- // - Accuracy (RBPF should match or beat)
- // - Bias estimation (RBPF should be better)
- // - Computation time (not directly tested, but note particle count)
- // ...
-}
-```
-
-### Step 6: Documentation
-
-#### 6.1 Design document
-
-**Location:** `docs/PARTICLE_FILTER_DESIGN.md`
-
-Add new section:
-
-```markdown
-## Rao-Blackwellized Particle Filter (RBPF)
-
-### Overview
-
-The RBPF exploits the conditional linear structure of the INS equations to reduce
-computational burden while maintaining or improving estimation performance. It
-partitions the 15-state vector into:
-
-- **Nonlinear states (3)**: Position [lat, lon, alt] → represented by particles
-- **Linear states (12)**: Velocity, attitude, biases → per-particle UKF
-
-### Key Advantage
-
-By marginalizing the linear states analytically (via Kalman filter), the RBPF
-requires significantly fewer particles than a standard PF:
-
-- Standard PF: 500-1000 particles typical
-- RBPF: 50-200 particles sufficient
-
-This 5-10× reduction in particles translates directly to computational savings
-while often improving bias estimation quality.
-
-### State Partitioning Rationale
-
-**Why position as nonlinear?**
-- Coupled with Earth model (geodetic coordinates)
-- Subject to GPS outages → multimodal posteriors
-- Nonlinear transformation from body to navigation frame
-
-**Why velocity/attitude/biases as linear?**
-- Conditionally Gaussian given position
-- Biases evolve as random walks (Gaussian)
-- Attitude dynamics approximately linear over short timesteps
-- UKF handles residual nonlinearity efficiently
-
-### 2.5D Integration
-
-The RBPF maintains the 2.5D vertical channel approach:
-- Vertical velocity in per-particle UKF with large process noise
-- Position altitude propagated via simple integration
-- Horizontal dynamics use full strapdown mechanization
-
-### Algorithm Summary
-
-**Predict:**
-```
-For each particle i:
- 1. Get velocity, attitude from particle_i.ukf
- 2. Propagate position using forward_2_5d_rbpf(position, velocity, attitude, dt)
- 3. Add position process noise ~ N(0, Q_position)
- 4. UKF predict for linear states: ukf.predict(new_position, imu, Q_linear, dt)
-```
-
-**Update:**
-```
-For each particle i:
- 1. Compute marginal likelihood: p(z | position_i) from UKF innovation
- 2. Update particle weight: w_i *= p(z | position_i)
- 3. UKF update linear states: ukf.update(position_i, z)
-
-Normalize weights
-If ESS < threshold: resample particles
-```
-
-**Estimate:**
-```
-position_estimate = Σ(w_i * position_i)
-linear_estimate = Σ(w_i * ukf_i.mean)
-covariance = particle_cov(position) + Σ(w_i * ukf_i.cov) + cross_terms
-```
-
-### When to Use RBPF vs Standard PF
-
-**Use RBPF when:**
-- Computational resources limited (EKF version is 3-5x faster than UKF)
-- Bias estimation critical (e.g., low-cost IMU)
-- GNSS intermittent but not completely denied
-- Need real-time performance
-- The conditionally-linear states have moderate nonlinearity
-
-**Use Standard PF when:**
-- Highly nonlinear dynamics (aggressive maneuvers)
-- Extreme non-Gaussian posteriors expected
-- Computational cost not a concern
-- Research/benchmarking (simpler algorithm)
-
-### Performance Characteristics (EKF Implementation)
-
-The current EKF-based RBPF implementation offers:
-- **3-5x faster** than the previous UKF version
-- **5-10x fewer particles needed** compared to standard PF for similar accuracy
-- Suitable for real-time applications on embedded systems
-- Maintains good accuracy for typical navigation scenarios
-
-**Computational Complexity:**
-- EKF linearization: O(n²) for n-state system
-- UKF sigma points: O(n³) for n-state system
-- For 12-state linear subspace: EKF ~144 operations vs UKF ~1728 operations per particle
-```
-
-#### 6.2 User guide
-
-**Location:** `docs/USER_GUIDE.md`
-
-Add RBPF example:
-
-```markdown
-### Rao-Blackwellized Particle Filter (EKF-based)
-
-For improved efficiency with similar accuracy:
-
-```rust
-use strapdown::particle::{RaoBlackwellizedParticleFilter, RBProcessNoise, VerticalChannelMode, ResamplingStrategy};
-use strapdown::kalman::InitialState;
-
-let initial_state = InitialState { /* ... */ };
-let process_noise = RBProcessNoise::default();
-
-let rbpf = RaoBlackwellizedParticleFilter::new(
- initial_state,
- vec![0.0; 6], // IMU biases
- vec![1e-3; 15], // Initial covariance diagonal
- process_noise,
- 100, // Fewer particles than standard PF (uses EKF internally)
- VerticalChannelMode::Simplified,
- ResamplingStrategy::Systematic,
- Some(42), // Random seed
-);
-```
-
-The RBPF uses per-particle EKF for velocity, attitude, and biases, requiring
-only ~100 particles compared to 500-1000 for standard PF. The EKF implementation
-provides 3-5x faster performance than the previous UKF version.
-```
-
-## Implementation Notes
-
-### Measurement Routing
-
-Different measurements update different components:
-
-- **GPS Position** → Updates particle weights via marginal likelihood, UKF updates velocity correlation
-- **GPS Velocity** → UKF update only (linear in velocity space)
-- **GPS Position+Velocity** → Combined: position for weights, velocity for UKF
-- **Barometric Altitude** → Updates particle altitude weights, UKF vertical velocity
-
-### Numerical Stability
-
-1. **Log-likelihood computation**: Use log-space for particle weights to avoid underflow
-2. **Covariance symmetrization**: Apply `symmetrize()` to UKF covariance matrices
-3. **Robust SPD solve**: Use `robust_spd_solve()` for Kalman gain computation
-4. **Weight normalization**: Subtract max log-weight before exp() to prevent overflow
-
-### Performance Considerations
-
-**Expected particle counts:**
-- Continuous GNSS: 50 particles sufficient
-- Intermittent GNSS (5-10s updates): 100 particles
-- Long outages (>30s): 200 particles
-- Extreme scenarios: 500 particles (but standard PF may be better)
-
-**Computational complexity per timestep:**
-- RBPF: O(N_particles × [position_prop + UKF_prop + UKF_update])
-- Standard PF: O(N_particles × full_state_prop)
-- UKF speedup: ~2-3× per particle, but RBPF UKF is 9-state vs 15-state
-- Overall: RBPF with 100 particles ≈ Standard PF with 200-300 particles in cost
-
-### Compatibility
-
-The RBPF implements the `NavigationFilter` trait, making it a drop-in replacement for UKF or standard PF in:
-- `run_closed_loop()` simulation
-- `dead_reckoning()` comparison
-- Event stream processing
-- All measurement models
-
-## Future Enhancements
-
-1. **Adaptive particle count**: Increase/decrease N based on ESS or GPS availability
-2. **Regularization**: Add roughening/jitter to prevent particle collapse
-3. **Parallel UKF**: Use Rayon to parallelize per-particle UKF operations
-4. **Alternative partitioning**: Position+Attitude as nonlinear (4D particles, 6D UKF)
-5. **Auxiliary particle filter**: Use auxiliary variable for improved proposal
-
-## References
-
-1. Doucet, A., et al. "Rao-Blackwellised Particle Filtering for Dynamic Bayesian Networks." UAI 2000.
-2. Schön, T., et al. "Marginalized Particle Filters for Mixed Linear/Nonlinear State-Space Models." IEEE Trans. Signal Processing, 2005.
-3. Gustafsson, F., et al. "Particle filters for positioning, navigation, and tracking." IEEE Trans. Signal Processing, 2002.
diff --git a/book/book.toml b/book/book.toml
index 6a11c960..156b8ac0 100644
--- a/book/book.toml
+++ b/book/book.toml
@@ -13,8 +13,7 @@ create-missing = true
mathjax-support = true
git-repository-url = "https://github.com/jbrodovsky/strapdown-rs"
edit-url-template = "https://github.com/jbrodovsky/strapdown-rs/edit/main/book/{path}"
-#site-url = "/strapdown-rs/"
-#cname = "www.strapdown.rs"
+site-url = "/strapdown-rs/"
default-theme = "light"
preferred-dark-theme = "navy"
no-section-label = false
diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md
index ec2987e4..4d66343d 100644
--- a/book/src/SUMMARY.md
+++ b/book/src/SUMMARY.md
@@ -6,66 +6,56 @@
- [Installation](./installation/installation.md)
- [System Requirements](./installation/requirements.md)
- - [Installing from Crates.io](./installation/crates-io.md)
- - [Building from Source](./installation/building.md)
- [Quick Start](./quick-start.md)
# User Guide
- [Overview](./user-guide/overview.md)
-- [Core Concepts](./user-guide/concepts.md)
- - [Strapdown Mechanization](./user-guide/strapdown-mechanization.md)
+- [The Navigation Model](./user-guide/concepts.md)
- [Coordinate Frames](./user-guide/coordinate-frames.md)
- [State Representation](./user-guide/state-representation.md)
- [Running Simulations](./user-guide/simulations.md)
- - [Open-Loop (Dead Reckoning)](./user-guide/open-loop.md)
- - [Closed-Loop (UKF/EKF)](./user-guide/closed-loop.md)
+ - [Dead Reckoning](./user-guide/dead-reckoning.md)
+ - [Closed Loop (Kalman Filters)](./user-guide/closed-loop.md)
- [Particle Filter](./user-guide/particle-filter.md)
+ - [Synthetic Trajectories](./user-guide/synthetic.md)
- [Input Data Format](./user-guide/data-format.md)
+- [Output Format](./user-guide/output-format.md)
- [Configuration Files](./user-guide/configuration.md)
- [Logging](./user-guide/logging.md)
+- [Using the Library](./user-guide/library.md)
# Navigation Filters
- [Kalman Filters](./filters/kalman.md)
+ - [Error-State Kalman Filter (ESKF)](./filters/eskf.md)
- [Extended Kalman Filter (EKF)](./filters/ekf.md)
- [Unscented Kalman Filter (UKF)](./filters/ukf.md)
- - [Comparison: EKF vs UKF](./filters/comparison.md)
-- [Particle Filters](./filters/particle-filter.md)
- - [Rao-Blackwellized Particle Filter](./filters/rbpf.md)
-- [Measurement Models](./filters/measurements.md)
+ - [Comparison](./filters/comparison.md)
+- [Rao-Blackwellized Particle Filter](./filters/rbpf.md)
+ - [Particle Building Blocks](./filters/particle-filter.md)
+- [Measurement Models and Integrity](./filters/measurements.md)
-# Geophysical Navigation
+# GNSS Degradation
-- [Overview](./geonav/overview.md)
-- [Gravity Anomaly Navigation](./geonav/gravity.md)
-- [Magnetic Anomaly Navigation](./geonav/magnetic.md)
-- [Data Sources and Maps](./geonav/data-sources.md)
+- [Fault Simulation](./gnss/fault-simulation.md)
+- [Schedulers and Faults Reference](./gnss/scenarios.md)
-# GNSS Degradation Scenarios
+# Geophysical Navigation (Experimental)
-- [Fault Simulation](./gnss/fault-simulation.md)
-- [Dropout Scenarios](./gnss/dropouts.md)
-- [Reduced Update Rates](./gnss/reduced-rates.md)
-- [Measurement Corruption](./gnss/corruption.md)
+- [Overview](./geonav/overview.md)
+- [Maps and Measurement Models](./geonav/maps.md)
-# API Reference
+# Reference
-- [strapdown-core](./api/core.md)
- - [earth Module](./api/earth.md)
- - [kalman Module](./api/kalman.md)
- - [measurements Module](./api/measurements.md)
- - [particles Module](./api/particles.md)
- - [sim Module](./api/sim.md)
-- [strapdown-sim](./api/sim-binary.md)
-- [strapdown-geonav](./api/geonav.md)
+- [API Documentation](./api/index.md)
# Examples and Tutorials
- [Example Configurations](./examples/configurations.md)
-- [Tutorial: Basic INS Simulation](./examples/tutorial-basic.md)
-- [Tutorial: GPS Degradation](./examples/tutorial-gps-degradation.md)
-- [Tutorial: Using the Particle Filter](./examples/tutorial-particle-filter.md)
+- [Tutorial: Basic INS](./examples/tutorial-basic.md)
+- [Tutorial: GNSS Degradation](./examples/tutorial-gps-degradation.md)
+- [Tutorial: Particle Filter](./examples/tutorial-particle-filter.md)
# Development
@@ -73,14 +63,13 @@
- [Building and Testing](./development/building.md)
- [Performance Baselines](./development/performance.md)
- [Architecture](./development/architecture.md)
-- [Project Structure](./development/structure.md)
+- [Python Analysis Tooling](./development/analysis.md)
# FAQ
- [Frequently Asked Questions](./faq.md)
-# Additional Resources
+# Resources
-- [Publications](./resources/publications.md)
-- [External Links](./resources/links.md)
+- [Publications and Links](./resources/publications.md)
- [Glossary](./resources/glossary.md)
diff --git a/book/src/api/core.md b/book/src/api/core.md
deleted file mode 100644
index b0d5c88f..00000000
--- a/book/src/api/core.md
+++ /dev/null
@@ -1 +0,0 @@
-# API Reference
diff --git a/book/src/api/earth.md b/book/src/api/earth.md
deleted file mode 100644
index 554be786..00000000
--- a/book/src/api/earth.md
+++ /dev/null
@@ -1 +0,0 @@
-# earth Module
diff --git a/book/src/api/geonav.md b/book/src/api/geonav.md
deleted file mode 100644
index 64a140fd..00000000
--- a/book/src/api/geonav.md
+++ /dev/null
@@ -1 +0,0 @@
-# strapdown-geonav
diff --git a/book/src/api/index.md b/book/src/api/index.md
new file mode 100644
index 00000000..7a3a9c0f
--- /dev/null
+++ b/book/src/api/index.md
@@ -0,0 +1,88 @@
+# API Documentation
+
+The complete API reference is the rustdoc generated from the source. This page maps the
+workspace so you know which crate and module to open.
+
+## Where to read it
+
+| crate | imported as | rustdoc in this book | docs.rs |
+|---|---|---|---|
+| `strapdown-core` | `strapdown` | [api/strapdown](strapdown/index.html) | [docs.rs/strapdown-core](https://docs.rs/strapdown-core) |
+| `strapdown-sim` | (binary) | [api/strapdown_sim](strapdown_sim/index.html) | -- |
+| `strapdown-geonav` (experimental) | `geonav` | [api/geonav](geonav/index.html) | [docs.rs/strapdown-geonav](https://docs.rs/strapdown-geonav) |
+
+The copy under `api/` is generated by `cargo doc` and published with this book, so it matches
+the book's version of the code. The docs.rs pages appear once the crates are published to
+crates.io with the v1.0.0 release; until then use the copy here or build your own.
+
+To build and open the documentation locally:
+
+```bash
+cargo doc --workspace --no-deps --open # all three crates (alias: cargo docs)
+cargo doc -p strapdown-core --all-features --no-deps --open # include the hdf5/netcdf/mcap/clap items
+```
+
+Items behind a cargo feature only appear when that feature is enabled, which is why the second
+command exists. Output goes to `target/doc/`, one directory per crate under its library name:
+`strapdown`, `strapdown_sim` and `geonav`.
+
+## `strapdown-core`
+
+The library. Every module is public; `lib.rs` itself holds the 9-state strapdown mechanization
+(`StrapdownState`, `forward`, the IMU input type) and the `NavigationFilter` trait.
+
+| module | purpose |
+|---|---|
+| `alignment` | coarse alignment (Groves §5.6.3): roll and pitch by levelling, heading by gyrocompassing or from velocity |
+| `calibration` | deterministic IMU calibration, removing systematic sensor errors ahead of the mechanization |
+| `earth` | WGS84 ellipsoid constants, radii of curvature, normal gravity, Earth rate, transport rate, Eötvös correction, gravity anomaly |
+| `engine` | `InsEngine`: a high-level, builder-configured navigation engine for feeding samples in one at a time |
+| `error` | `StrapdownError`, the single error type every fallible function returns |
+| `gating` | innovation gating (chi-squared outlier rejection) and its recovery policies |
+| `kalman` | the Kalman-family filters: ESKF, EKF and UKF |
+| `linalg` | linear-algebra helpers, chiefly robust covariance square roots |
+| `linearize` | analytic Jacobians of the mechanization for the EKF and ESKF |
+| `measurements` | the `MeasurementModel` trait and its models: GNSS position, velocity and both together, barometric relative altitude, magnetometer yaw, ZUPT and ZARU |
+| `messages` | event-stream construction: GNSS, barometer and magnetometer scheduling and GNSS fault injection |
+| `metrics` | navigation-accuracy metrics (RMSE, CEP, NEES, containment) for scoring a solution against a reference |
+| `particle` | particle-filter building blocks: the `Particle` trait, resampling and averaging strategies |
+| `rbpf` | the Rao-Blackwellized particle filter after Canciani & Raquet (2017) |
+| `sim` | input records (`TestDataRecord`), output rows (`NavigationResult`), dead reckoning, the closed-loop runner, synthetic trajectories, configuration types and health monitoring |
+| `stationary` | variance-based detection of stationary periods, for zero-velocity and zero-angular-rate aiding |
+
+The crate root also re-exports `InsEngine` and its configuration types, `StrapdownError`, and
+the gating types `InnovationGate`, `GateRecovery` and `UpdateOutcome`.
+
+Its cargo features are all off by default, so `strapdown-core` alone needs nothing but a Rust
+toolchain:
+
+| feature | enables |
+|---|---|
+| `clap` | `clap` derives on the configuration enums, used by `strapdown-sim` |
+| `hdf5` | `to_hdf5` / `from_hdf5` on `TestDataRecord` and `NavigationResult` (builds libhdf5 from source) |
+| `netcdf` | `to_netcdf` / `from_netcdf` on the same two types (builds libnetcdf from source) |
+| `mcap` | `to_mcap` / `from_mcap` on the same two types |
+| `full` | all of the above |
+
+## `strapdown-sim`
+
+The command-line tool. It is a binary crate, so its rustdoc documents the program's internals
+rather than an API to depend on; the user-facing reference is `strapdown-sim --help` and
+[Running Simulations](../user-guide/simulations.md).
+
+| module | purpose |
+|---|---|
+| `main` | argument parsing, the `dr`/`cl`/`pf`/`syn`/`ol`/`config` subcommands, and configuration-file runs |
+| `common` | logging setup, input and output path validation (CSV output only), file discovery, interactive prompts |
+| `plotting` | the optional `--plot` performance figure (feature `plotting`, on by default) |
+
+Its `geonav` feature adds the `--geo` flags and depends on `strapdown-geonav`.
+
+## `strapdown-geonav`
+
+The experimental geophysical-navigation crate, a single module. Its main items are `GeoMap`
+(NetCDF anomaly grids with interpolation and gradients), the measurement models
+`GravityMeasurement`, `MagneticAnomalyMeasurement` and `CombinedGeophysicalMeasurement`, the
+bias-state bookkeeping `GeoBiasLayout` and `BiasState`, and `build_event_stream`, which adds
+geophysical measurements to core's event stream. See [Geophysical Navigation](../geonav/overview.md)
+and [Maps and Measurement Models](../geonav/maps.md).
diff --git a/book/src/api/kalman.md b/book/src/api/kalman.md
deleted file mode 100644
index 775bb7a1..00000000
--- a/book/src/api/kalman.md
+++ /dev/null
@@ -1 +0,0 @@
-# kalman Module
diff --git a/book/src/api/measurements.md b/book/src/api/measurements.md
deleted file mode 100644
index 902e0d50..00000000
--- a/book/src/api/measurements.md
+++ /dev/null
@@ -1 +0,0 @@
-# measurements Module
diff --git a/book/src/api/particles.md b/book/src/api/particles.md
deleted file mode 100644
index c6526136..00000000
--- a/book/src/api/particles.md
+++ /dev/null
@@ -1 +0,0 @@
-# particles Module
diff --git a/book/src/api/sim-binary.md b/book/src/api/sim-binary.md
deleted file mode 100644
index 77a4627d..00000000
--- a/book/src/api/sim-binary.md
+++ /dev/null
@@ -1 +0,0 @@
-# strapdown-sim Binary
diff --git a/book/src/api/sim.md b/book/src/api/sim.md
deleted file mode 100644
index a22a9db4..00000000
--- a/book/src/api/sim.md
+++ /dev/null
@@ -1 +0,0 @@
-# sim Module
diff --git a/book/src/chapter_1.md b/book/src/chapter_1.md
deleted file mode 100644
index b743fda3..00000000
--- a/book/src/chapter_1.md
+++ /dev/null
@@ -1 +0,0 @@
-# Chapter 1
diff --git a/book/src/development/analysis.md b/book/src/development/analysis.md
new file mode 100644
index 00000000..499cb8dd
--- /dev/null
+++ b/book/src/development/analysis.md
@@ -0,0 +1,80 @@
+# Python Analysis Tooling
+
+> **Experimental research tooling.** The `analysis` package is what the project's own
+> experiments run on. It is tested in CI, but its interface is not covered by the 1.0 API
+> commitments the Rust crates make.
+
+The repository is a two-language monorepo. Beside the Cargo workspace sits `analysis/`, a
+Python package (Python 3.13 or newer) that preprocesses recordings into simulator input and
+scores simulator output. It is a member of a **uv** workspace declared by the root
+`pyproject.toml`; it is not a Cargo member, and nothing in the Rust crates depends on it.
+
+## Setup
+
+From the repository root:
+
+```bash
+uv sync # creates .venv and installs analysis with its dependencies
+uv run analyze --help # the CLI, through the `analyze` entry point
+```
+
+`just setup` runs `cargo fetch` and `uv sync` together.
+
+**GMT is optional.** PyGMT loads the GMT C library when it is imported, so every import of it
+is inside the function that uses it, and the package, its CLI and its tests all work without
+GMT installed (CI's `python.yml` deliberately installs none). GMT and network access are only
+needed to download maps with `analyze preprocess --getmaps`.
+
+## The `analyze` command
+
+| subcommand | module | what it does |
+|---|---|---|
+| `preprocess` | `preprocess.py` | rebuilds simulator input from Sensor Logger exports: resampling to a fixed rate (`-f`), splitting recordings at IMU dropouts, and with `--getmaps` downloading each trajectory's `_gravity.nc`, `_magnetic.nc` and `_relief.nc` maps; `--synthetic` replaces the phone's gravity and magnetometer readings with simulated dedicated sensors (`synthetic.py`) |
+| `dataset-summary` | `__init__.py` | distance travelled and duration of each trajectory |
+| `performance` | `compare.py`, `plotting.py` | error statistics, LaTeX tables and plots for a directory of results against the GNSS reference |
+| `geoperformance` | `compare.py`, `plotting.py` | the same for geophysically aided runs, against a degraded unaided baseline |
+| `compare-filters` | `compare.py` | side-by-side comparison of several result directories |
+| `geostats` | `geostats.py` | bias, noise, signal-to-noise and de-correlation length of the geophysical readings against their maps; `--apply-to conf` writes the measured values into the configs |
+
+`uv run analyze --help` lists each one's options. `geostats` mirrors the
+anomaly computations in `core/src/earth.rs` and `geonav/src/lib.rs` term for term and checks
+that it agrees with them before computing anything; see
+[Maps and Measurement Models](../geonav/maps.md#the-python-mirror-of-these-models).
+
+## The `justfile` recipes
+
+The experiment pipeline is a set of [`just`](https://github.com/casey/just) recipes at the
+repository root:
+
+| recipe | does |
+|---|---|
+| `setup` | `cargo fetch` and `uv sync` |
+| `build` | `cargo build --release --workspace --all-features` |
+| `check-python` | `ruff check`, `ruff format --check` and `pytest`, as CI runs them |
+| `preprocess` | rebuilds `data/input` from `data/raw` at 10 Hz, with maps and synthetic geophysical sensors |
+| `preprocess-1hz` | the same at 1 Hz |
+| `geo-stats` | `analyze geostats` over `data/input`; writes a report and leaves `conf/` alone |
+| `geo-adopt` | `analyze geostats --apply-to conf`: rewrites the geophysical configs with measured values |
+| `truth`, `degraded`, `ukf-geo`, `ekf-geo`, `rbpf-sim` | run the `conf/` recipes through `strapdown-sim --config` |
+| `postprocess` | `dataset-summary` and `performance` over every result directory |
+| `geoperf-all`, `geoperf-rbpf` | `geoperformance` for each geophysically aided run against its baseline |
+| `clean` | deletes `data/input`, `data/output` and `log` |
+| `pipeline` | `clean build preprocess geo-stats truth degraded ukf-geo ekf-geo rbpf-sim postprocess geoperf-all`, in order |
+
+**`data/raw` is not distributed.** The recordings the pipeline starts from are not in the
+repository (`data/` is ignored by git), so `just preprocess` and `just pipeline` only run where
+those recordings exist. The other subcommands take any directory of simulator input and
+output: `performance` and `dataset-summary` were run for this page on a trajectory from
+`strapdown-sim syn` and its closed-loop result, matched by file name. `geostats` also needs
+the `_gravity.nc` and `_magnetic.nc` maps beside each trajectory.
+
+## Checks
+
+```bash
+uv run ruff check
+uv run ruff format --check
+uv run pytest -q
+```
+
+These are what `.github/workflows/python.yml` runs, and what `just check-python` wraps. Ruff
+is configured in the root `pyproject.toml`.
diff --git a/book/src/development/architecture.md b/book/src/development/architecture.md
index c79bec1a..2fe59165 100644
--- a/book/src/development/architecture.md
+++ b/book/src/development/architecture.md
@@ -1 +1,174 @@
# Architecture
+
+This page describes how the workspace is put together: which crate depends on which, how a
+simulation's data moves from a CSV file to a CSV file, and the rules every crate follows for
+errors, determinism and optional features. For a module-by-module list, see
+[API Documentation](../api/index.md).
+
+## Crates
+
+The repository is a Cargo workspace of three crates, plus a separate Python package.
+
+| crate | kind | imported as | version | role |
+|---|---|---|---|---|
+| `strapdown-core` | library | `strapdown` | 1.0.0 | mechanization, filters, measurement models, event streams, simulation framework |
+| `strapdown-sim` | binary | -- | 1.0.0 | the `strapdown-sim` command-line tool |
+| `strapdown-geonav` | library | `geonav` | 0.1.0, experimental | geophysical map aiding |
+| `analysis` | Python package | `analyze` CLI | -- | preprocessing and post-processing; not a Cargo member ([Python Analysis Tooling](./analysis.md)) |
+
+```text
+ +--------------------+
+ | strapdown-sim | binary: CLI, config files, CSV output,
+ | (bin) | parallel runs (rayon), plots (plotters)
+ +----+----------+----+
+ | | optional, feature "geonav"
+ | v
+ | +------------------+
+ | | strapdown-geonav | maps (netcdf), WMM,
+ | | (lib "geonav") | gravity / magnetic models
+ | +--------+---------+
+ | |
+ v v
+ +--------------------+
+ | strapdown-core | nalgebra, serde, rand, csv, WMM;
+ | (lib "strapdown") | optional hdf5 / netcdf / mcap / clap
+ +--------------------+
+```
+
+`strapdown-core` depends on no other workspace crate and needs no C toolchain in its default
+configuration. `strapdown-sim` enables core's `clap` feature for its argument enums.
+`strapdown-geonav` always links libnetcdf (built from source), which is why `strapdown-sim`
+only pulls it in behind the `geonav` feature.
+
+## Layers inside `strapdown-core`
+
+| layer | modules | what lives there |
+|---|---|---|
+| foundations | `earth`, `linalg`, `error` | WGS84 geometry and gravity, covariance square roots, `StrapdownError` |
+| mechanization | crate root (`lib.rs`) | `StrapdownState`, `IMUData`, `forward`: the 9-state strapdown equations of Groves §5.4–5.5 |
+| initialisation | `alignment`, `calibration`, `stationary` | coarse alignment, IMU calibration, stationary detection for ZUPT/ZARU |
+| measurements | `measurements`, `gating` | the `MeasurementModel` trait and its models; innovation gating |
+| estimation | `kalman`, `linearize`, `particle`, `rbpf` | ESKF, EKF, UKF, the RBPF, and the Jacobians they share |
+| framework | `messages`, `sim`, `metrics`, `engine` | event streams, records and results, runners, scoring, the `InsEngine` facade |
+
+Lower layers do not know about higher ones: the mechanization knows nothing about filters, and
+the filters know nothing about files or schedules.
+
+## Data flow
+
+Every simulation mode is the same pipeline with a different estimator in the middle:
+
+```text
+ input.csv
+ | TestDataRecord::from_csv (sim)
+ v
+ Vec one row per sample: IMU, GNSS, barometer, magnetometer, ...
+ | check_declared_frame(records, is_enu) (sim; rejects a wrong NED/ENU declaration)
+ |
+ | build_event_stream(records, &AidingConfig, is_enu) (messages)
+ | - MeasurementScheduler per channel: GNSS, barometer, magnetometer -> *when*
+ | - GnssFaultModel on each delivered GNSS fix -> *what*
+ | - seeded RNG from AidingConfig::seed
+ | geonav::build_event_stream adds gravity/magnetic events on top (geonav, optional)
+ v
+ EventStream { start_time, events: Vec }
+ | Event::Imu { dt_s, imu, elapsed_s }
+ | Event::Measurement { meas: Box, elapsed_s }
+ |
+ | run_closed_loop(&mut filter, stream, health_limits, execution_limits) (sim)
+ | for each event: Imu -> filter.predict(imu, dt)
+ | Measurement -> filter.update(meas) (gated, NIS reported)
+ | HealthMonitor and ExecutionMonitor can stop a diverging or stalled run
+ v
+ Vec one row per timestamp: state, IMU and map biases, covariance
+ | NavigationResult::to_csv (sim; to_hdf5 / to_netcdf / to_mcap in the library)
+ v
+ output.csv
+```
+
+The variations are:
+
+- **Dead reckoning** (`dr`) skips the event stream:
+ `sim::dead_reckoning_with_limits(records, is_enu, health_limits, execution_limits)`
+ mechanizes the IMU rows directly, checks whichever limits it is given after each step, and
+ reports no covariance. `strapdown-sim` passes only the wall-clock limits, because an unaided
+ arc is expected to leave the health bounds. `sim::dead_reckoning(records, is_enu)` is the
+ same with no limits.
+- **Closed loop** (`cl`) builds one of the Kalman filters and calls `run_closed_loop`;
+ with geophysical maps it calls `run_closed_loop_with_geo`, which also reports the map biases.
+- **Particle filter** (`pf`) consumes the same `EventStream` through an event loop in
+ `strapdown-sim` that drives the RBPF.
+- **Synthetic** (`syn`) runs the other way: `sim::generate_synthetic` produces both a truth
+ trajectory and the sensor records a vehicle on it would have logged, and writes the records
+ as a CSV that the other modes can read.
+- **Online use** from Rust does not need a stream at all: `InsEngine` wraps any
+ `NavigationFilter` and accepts IMU samples and GNSS fixes one at a time. See
+ [Using the Library](../user-guide/library.md).
+
+### Where degradation sits
+
+Scheduling and fault injection happen **once, in `build_event_stream`**, before any filter
+runs. The filter never knows a fix was dropped or corrupted; it sees only the events it is
+given. That is what makes comparisons fair: every filter run on the same records with the same
+`AidingConfig` sees an identical stream, and swapping the filter changes nothing upstream. It
+is also why `strapdown-geonav` delegates to core's builder rather than reimplementing it, and
+why `geonav/tests/builder_equivalence.rs` checks that the two produce the same non-geophysical
+events. See [Schedulers and Faults Reference](../gnss/scenarios.md).
+
+## Trait boundaries
+
+| trait | defined in | implemented by | contract |
+|---|---|---|---|
+| `NavigationFilter` | crate root | ESKF, EKF, UKF, RBPF | `predict(&dyn InputModel, dt)`, `update(&dyn MeasurementModel)` returning an `UpdateOutcome`, `get_estimate`, `get_certainty`, and optional gating hooks |
+| `InputModel` | crate root | `IMUData`, `ImuSample`, `VelocityData` | the control input to `predict`, taken as a trait object so that `NavigationFilter` is object-safe |
+| `MeasurementModel` | `measurements` | GNSS, barometer, magnetometer, ZUPT, ZARU; geonav's gravity and magnetic models | the measurement, its prediction from a state, its noise and its Jacobian |
+| `Particle` | `particle` | nothing in the workspace; it is for user-built particle filters | the hooks the generic resampling and averaging strategies in `particle` need |
+
+Adding a sensor means implementing `MeasurementModel` and emitting events for it; adding an
+estimator means implementing `NavigationFilter`. Neither requires touching the other, the
+event stream, or the runner.
+
+## Errors
+
+Library code never panics. `unwrap_used`, `expect_used` and `panic` are denied for library code
+(tests are exempt), and every fallible function returns `Result<_, StrapdownError>`, documented
+with an `# Errors` section. `StrapdownError` is one enum with variants for shape errors,
+non-finite values, invalid configuration, map loading, divergence, sensor gaps and timeouts.
+
+`StrapdownError::is_recoverable` separates the conditions a run should skip from the ones that
+should stop it. An estimate off a geophysical map, a measurement that cannot be evaluated, and
+an external model (the World Magnetic Model) refusing a query are recoverable: the runner
+skips that measurement and counts it. Everything else ends the run with the error.
+
+The lints that enforce this are workspace-wide and at `deny`, including `clippy::pedantic`,
+`clippy::nursery` and `missing_docs`; see [Building and Testing](./building.md#linting-and-formatting).
+
+## Determinism
+
+A run is a function of its inputs and its seeds. There are no wall-clock or thread-dependent
+inputs to the navigation solution:
+
+- the GNSS fault model draws from a `StdRng` seeded from `AidingConfig::seed` (`[aiding] seed`
+ in a config file, falling back to the top-level `seed` through
+ `SimulationConfig::resolved_aiding`; `--seed` on the command line; 42 when nothing sets it);
+- the RBPF seeds its own `StdRng` from its configuration's seed;
+- `generate_synthetic` takes the seeded RNG it draws from.
+
+`core/tests/integration_tests.rs` checks that repeated runs are identical, and the
+[performance baseline](./performance.md) is gated on all three CI platforms, which catches
+results that depend on the platform. `--parallel` processes *files* concurrently; each file's
+run is still sequential.
+
+## Feature gating
+
+| crate | feature | default | adds |
+|---|---|---|---|
+| `strapdown-core` | `clap` | off | `clap` derives on configuration enums |
+| `strapdown-core` | `hdf5`, `netcdf`, `mcap` | off | binary I/O on `TestDataRecord` and `NavigationResult` |
+| `strapdown-core` | `full` | off | all four |
+| `strapdown-sim` | `plotting` | **on** | the `--plot` figure; loads libfontconfig at run time |
+| `strapdown-sim` | `geonav` | off | `--geo` and the `[geophysical]` section |
+
+Because an item used only behind a feature is dead code without it, CI lints and tests both
+`--all-features` and core's `--no-default-features`; see
+[Building and Testing](./building.md#linting-and-formatting).
diff --git a/book/src/development/baseline-tables.md b/book/src/development/baseline-tables.md
index b73c8d7a..4df5b3fa 100644
--- a/book/src/development/baseline-tables.md
+++ b/book/src/development/baseline-tables.md
@@ -13,12 +13,12 @@ overwrites this file, and the gate fails if it is stale. See #380. -->
| `real_outage_60s__eskf` | 5,366 | 257.380 | 4.618 | 645.701 | 2,166.400 | 1.834 | -0.236 | 10.750 | 0.604 |
| `real_degraded__ukf` | 5,366 | 50.700 | 40.636 | 88.053 | 140.311 | 13.878 | 0.438 | 2.487 | 0.787 |
| `real_degraded__eskf` | 5,366 | 50.702 | 40.635 | 88.051 | 140.315 | 13.864 | 0.433 | 2.469 | 0.794 |
-| `syn_cruise_1hz__ukf` | 15,000 | 2.600 | 2.214 | 4.354 | 6.784 | 2.279 | -0.685 | 0.581 | 0.304 |
-| `syn_cruise_1hz__ekf` | 15,000 | 2.600 | 2.213 | 4.355 | 6.785 | 2.279 | -0.686 | 0.581 | 0.304 |
-| `syn_cruise_1hz__eskf` | 15,000 | 2.600 | 2.179 | 4.397 | 6.785 | 2.154 | -0.549 | 0.559 | 0.262 |
-| `syn_outage_60s__ukf` | 15,000 | 24.024 | 1.379 | 48.123 | 125.428 | 2.045 | -0.039 | 1.290 | 0.284 |
-| `syn_outage_60s__eskf` | 15,000 | 23.444 | 1.406 | 55.373 | 112.796 | 1.872 | -0.229 | 1.346 | 0.234 |
-| `syn_dead_reckoning` | 6,000 | 316.860 | 110.128 | 715.856 | 835.634 | 86.591 | -64.255 | 9.363 | 1.896 |
+| `syn_cruise_1hz__ukf` | 15,000 | 1.717 | 1.334 | 3.043 | 4.377 | 1.518 | -0.781 | 0.358 | 0.179 |
+| `syn_cruise_1hz__ekf` | 15,000 | 1.717 | 1.334 | 3.043 | 4.377 | 1.518 | -0.781 | 0.358 | 0.179 |
+| `syn_cruise_1hz__eskf` | 15,000 | 1.734 | 1.343 | 3.034 | 5.588 | 1.450 | -0.724 | 0.358 | 0.163 |
+| `syn_outage_60s__ukf` | 15,000 | 24.797 | 3.392 | 55.798 | 80.304 | 1.116 | -0.281 | 1.257 | 0.177 |
+| `syn_outage_60s__eskf` | 15,000 | 28.656 | 3.390 | 66.482 | 95.768 | 1.104 | -0.396 | 1.453 | 0.139 |
+| `syn_dead_reckoning` | 6,000 | 302.347 | 104.578 | 685.614 | 802.620 | 86.505 | -64.190 | 9.161 | 1.894 |
| `real_rbpf_slice__rbpf` | 1,200 | 3.235 | 0.579 | 6.004 | 27.672 | 0.795 | -0.131 | 1.231 | 0.388 |
### Attitude
@@ -33,11 +33,11 @@ overwrites this file, and the gate fails if it is stale. See #380. -->
| `real_outage_60s__eskf` | 5,366 | 3.561 | 3.264 | 21.704 | 22.219 |
| `real_degraded__ukf` | 5,366 | 3.497 | 3.005 | 24.300 | 24.725 |
| `real_degraded__eskf` | 5,366 | 3.417 | 3.107 | 24.167 | 24.593 |
-| `syn_cruise_1hz__ukf` | 15,000 | 0.298 | 0.251 | 0.156 | 0.420 |
-| `syn_cruise_1hz__ekf` | 15,000 | 0.298 | 0.251 | 0.155 | 0.420 |
-| `syn_cruise_1hz__eskf` | 15,000 | 0.291 | 0.254 | 0.155 | 0.416 |
-| `syn_outage_60s__ukf` | 15,000 | 0.231 | 0.206 | 0.189 | 0.363 |
-| `syn_outage_60s__eskf` | 15,000 | 0.222 | 0.249 | 0.248 | 0.416 |
+| `syn_cruise_1hz__ukf` | 15,000 | 0.230 | 0.258 | 0.216 | 0.407 |
+| `syn_cruise_1hz__ekf` | 15,000 | 0.230 | 0.258 | 0.233 | 0.417 |
+| `syn_cruise_1hz__eskf` | 15,000 | 0.476 | 0.335 | 0.293 | 0.651 |
+| `syn_outage_60s__ukf` | 15,000 | 0.184 | 0.289 | 0.395 | 0.523 |
+| `syn_outage_60s__eskf` | 15,000 | 0.196 | 0.319 | 0.444 | 0.581 |
| `syn_dead_reckoning` | 6,000 | 0.468 | 1.106 | 0.494 | 1.301 |
| `real_rbpf_slice__rbpf` | 1,200 | 3.080 | 3.107 | 21.847 | 22.252 |
@@ -53,10 +53,10 @@ overwrites this file, and the gate fails if it is stale. See #380. -->
| `real_outage_60s__eskf` | 5,366 | 42.922 | 40.595 | 0.614 | 0.853 |
| `real_degraded__ukf` | 5,366 | 5,474.700 | 5,473.870 | 0.074 | 0.093 |
| `real_degraded__eskf` | 5,366 | 5,474.380 | 5,473.580 | 0.074 | 0.094 |
-| `syn_cruise_1hz__ukf` | 15,000 | 4.774 | 4.776 | 1.000 | 0.913 |
-| `syn_cruise_1hz__ekf` | 15,000 | 4.774 | 4.776 | 1.000 | 0.913 |
-| `syn_cruise_1hz__eskf` | 15,000 | 4.573 | 4.575 | 1.000 | 0.928 |
-| `syn_outage_60s__ukf` | 15,000 | 2.341 | 2.341 | 0.999 | 0.966 |
-| `syn_outage_60s__eskf` | 15,000 | 2.228 | 2.229 | 0.999 | 0.963 |
+| `syn_cruise_1hz__ukf` | 15,000 | 3.272 | 3.272 | 1.000 | 1.000 |
+| `syn_cruise_1hz__ekf` | 15,000 | 3.272 | 3.272 | 1.000 | 1.000 |
+| `syn_cruise_1hz__eskf` | 15,000 | 3.170 | 3.171 | 1.000 | 1.000 |
+| `syn_outage_60s__ukf` | 15,000 | 1.426 | 1.431 | 1.000 | 0.998 |
+| `syn_outage_60s__eskf` | 15,000 | 1.346 | 1.350 | 1.000 | 1.000 |
| `syn_dead_reckoning` | 6,000 | -- | -- | -- | -- |
| `real_rbpf_slice__rbpf` | 1,200 | 18.121 | 10.327 | 0.951 | 0.951 |
diff --git a/book/src/development/building.md b/book/src/development/building.md
index de5868f8..60ee6887 100644
--- a/book/src/development/building.md
+++ b/book/src/development/building.md
@@ -1,323 +1,255 @@
# Building and Testing
-## Building the Project
+## Building the project
-### Build Dependencies
+### Build dependencies
There are no system libraries to install. libhdf5, libnetcdf, zlib and freetype are compiled
from vendored sources that ship as cargo dependencies, so the only requirement beyond Rust is
a toolchain to build them with:
+
- a C/C++ compiler
-- **cmake 3.26 or newer** (more than Ubuntu 22.04 or Debian 12 ship -- see
+- **cmake 3.26 or newer** (newer than Ubuntu 22.04 or Debian 12 ship; see
[System Requirements](../installation/requirements.md))
-On Ubuntu/Debian systems:
+On Ubuntu/Debian systems with a recent enough release:
+
```bash
sudo apt update
sudo apt install -y build-essential cmake
```
Neither is needed for `cargo build -p strapdown-core`, which uses no C library by default.
+Keep `HDF5_DIR` unset: when it is set, the HDF5 build looks for a system library even though a
+vendored one was requested, and the netCDF build then fails against the wrong headers.
-### Rust Toolchain
-- Pinned to 1.91 by `rust-toolchain.toml`; rustup fetches it on the first cargo command
-- Required components: `clippy`, `rustfmt` (also declared in `rust-toolchain.toml`)
+### Rust toolchain
-### Building
+`rust-toolchain.toml` pins Rust 1.91 with the `clippy`, `rustfmt`, `rust-src` and
+`rust-analyzer` components; rustup fetches it on the first cargo command. The pin matters for
+linting, because `clippy::pedantic` and `clippy::nursery` gain lints with every release.
-Build the entire workspace:
-```bash
-cargo build --workspace --all-features
-```
-
-Build a specific crate:
-```bash
-cargo build -p strapdown-core
-cargo build -p strapdown-sim
-cargo build -p strapdown-geonav
-```
+### Building
-Build with optimizations (release mode):
```bash
-cargo build --workspace --all-features --release
+cargo build --workspace --all-features # everything
+cargo build -p strapdown-core # the library alone, no C toolchain needed
+cargo build --release -p strapdown-sim # the CLI
+cargo build --release -p strapdown-sim --features geonav # the CLI with --geo
```
-### Installing Binaries
+### Installing the binary
-Install the simulation binaries to your system:
```bash
-# Install strapdown-sim
-cargo install --path sim
-
-# ...with geophysical navigation. This is what pulls in libnetcdf, so it needs cmake.
-cargo install --path sim --features geonav
+cargo install --path sim # from a checkout
+cargo install --path sim --features geonav # with geophysical navigation
```
## Testing
-### Overview
-
-The strapdown-rs project includes comprehensive unit tests, integration tests, and module-specific tests to validate the correctness of the navigation algorithms.
-
-### Running Tests
-
-Run all tests in the workspace:
```bash
-cargo test --workspace --all-features --verbose
+cargo test --workspace --all-features # the whole suite, as CI's `full` job runs it
+cargo test-min # strapdown-core with no default features, as CI's `minimal` job runs it
+cargo test -p strapdown-core # one crate
```
-Run tests for a specific crate:
-```bash
-cargo test -p strapdown-core
-cargo test -p strapdown-sim
-cargo test -p strapdown-geonav
-```
+Both of the first two are gates in CI, and they test different code: an item used only behind
+a feature is live in one configuration and dead in the other.
-Run with output visible:
-```bash
-cargo test -- --nocapture
-```
-
-Run tests sequentially (single-threaded):
-```bash
-cargo test -- --test-threads=1
-```
+### Where the tests are
-### Test Organization
+Unit tests sit beside the code in `#[cfg(test)]` modules in every crate. The integration tests
+are:
-Tests are organized into:
-- **Unit tests**: Inline in source files using `#[cfg(test)]` modules
-- **Integration tests**: Located in `core/tests/integration_tests.rs`
-- **Module tests**: Specific to individual modules
+| file | what it checks |
+|---|---|
+| `core/tests/integration_tests.rs` | every filter end to end on the real recording `test_data.csv` (see below) |
+| `core/tests/filter_comparison.rs` | the ESKF, EKF, UKF and RBPF driven through the same `NavigationFilter` interface on one shared scenario |
+| `core/tests/perf_baseline.rs` | the navigation-accuracy regression gate against `perf_baseline.json`; see [Performance Baselines](./performance.md) |
+| `core/tests/aiding.rs` | innovation gating and ZUPT/ZARU aiding over whole runs |
+| `core/tests/baro_bias.rs` | that the barometric bias state is actually estimated, in all three Kalman filters |
+| `core/tests/engine_lever_arm.rs` | `InsEngine` and antenna lever-arm compensation, on synthetic and real data |
+| `core/tests/jacobian_agreement.rs` | that the analytic transition Jacobians agree with the mechanization they linearize |
+| `core/tests/ukf_conditioning.rs` | that a one-ulp change to the UKF's input cannot move its answer by a metre |
+| `core/tests/rbpf_depletion.rs` | that the RBPF's particle cloud does not collapse to a point when its weights degenerate |
+| `core/tests/example_configs.rs` | that every config in `examples/configs/` and `conf/` deserializes into the scenario it describes, and that paired `conf/` recipes agree |
+| `core/tests/config_serde_defaults.rs` | that each configuration type's `Default` and its serde defaults agree |
+| `geonav/tests/geo_closed_loop.rs` | geophysically aided closed-loop runs |
+| `geonav/tests/builder_equivalence.rs` | that `geonav::build_event_stream` produces the same non-geophysical events as core's |
-### Integration Tests for INS Filters
+`core/tests/` also holds the two data files, `test_data.csv` and `perf_baseline.json`. The
+Python package has its own tests, run with `uv run pytest -q` (see
+[Python Analysis Tooling](./analysis.md)).
-The integration tests validate the entire INS filter pipeline using real sensor data. These tests are comprehensive and take longer to run than unit tests.
+### The real-data integration tests
-#### Test Data
+#### Test data
-The integration tests use real data collected from the Sensor Logger mobile application:
-- IMU measurements (accelerometer and gyroscope) at ~100 Hz
-- GNSS position and velocity measurements at ~1 Hz
-- Approximately 90 minutes of data with ~5366 samples
-- Dataset location: `core/tests/test_data.csv`
+`core/tests/test_data.csv` is a Sensor Logger recording from a consumer phone:
+**5,366 records at 1 Hz**, spanning about 89 minutes, with IMU, GNSS, barometer, magnetometer
+and orientation columns in the ENU convention. IMU and GNSS share the 1 Hz rows.
-#### Error Metrics
+#### Error metrics
-##### Horizontal Position Error
-- **Metric**: Haversine distance between estimated and GNSS positions (meters)
-- **Formula**: Great-circle distance on Earth's surface
-- **Purpose**: Measures planar navigation accuracy
+`compute_error_metrics` in the test file matches each navigation result to the GNSS fix at
+the same timestamp, skips rows without a valid fix, and reports mean, maximum and RMS of:
-##### Altitude Error
-- **Metric**: Simple absolute difference (meters)
-- **Purpose**: Measures vertical navigation accuracy
+- horizontal error: the haversine distance between estimate and fix, in metres;
+- altitude error: the absolute difference, in metres;
+- velocity error: per component, in m/s.
-##### Velocity Error
-- **Metric**: Component-wise absolute differences for north, east, and down velocities (m/s)
-- **Purpose**: Measures velocity estimation accuracy
+Note that the reference here is the GNSS fix, which is also what the filters are aided by; see
+the first caveat in [Performance Baselines](./performance.md) for what that does and does not
+measure.
-#### Test Suite
+#### The suite
-`core/tests/integration_tests.rs` holds 23 tests, not the handful this page used to walk
-through one by one. That walkthrough transcribed each test's thresholds into prose, and the
-prose then drifted from the constants -- it was still quoting a 30 m horizontal limit long after
-the code moved to 40 m. So this section names the groups and the constants and points at the
-source, rather than copying numbers that nothing keeps honest.
+`core/tests/integration_tests.rs` holds 23 tests at the time of writing;
+`cargo test -p strapdown-core --test integration_tests -- --list` prints the current set. This
+section names the groups and points at the source rather than transcribing thresholds, which
+is how an earlier version of this page came to quote a limit the code had long since changed.
-**Per-filter closed-loop suites.** Each of the four filters gets the same three scenarios:
+**Per-filter closed-loop tests:**
-| | full-rate GNSS | degraded GNSS (5 s) | beats dead reckoning |
+| | full-rate GNSS | reduced-rate GNSS | beats dead reckoning |
|---|---|---|---|
-| UKF | `test_ukf_closed_loop_on_real_data` | `test_ukf_with_degraded_gnss` | `test_ukf_outperforms_dead_reckoning` |
-| EKF | `test_ekf_closed_loop_on_real_data` | `test_ekf_with_degraded_gnss` | `test_ekf_outperforms_dead_reckoning` |
-| ESKF | `test_eskf_closed_loop_on_real_data` | `test_eskf_with_degraded_gnss` | `test_eskf_outperforms_dead_reckoning` |
-| RBPF | `test_rbpf_closed_loop_on_real_data` | `test_rbpf_with_degraded_gnss` | -- |
+| UKF | `test_ukf_closed_loop_on_real_data` | `test_ukf_with_degraded_gnss` (5 s) | `test_ukf_outperforms_dead_reckoning` |
+| EKF | `test_ekf_closed_loop_on_real_data` | `test_ekf_with_degraded_gnss` (5 s) | `test_ekf_outperforms_dead_reckoning` |
+| ESKF | `test_eskf_closed_loop_on_real_data` | `test_eskf_with_degraded_gnss` (2 s) | `test_eskf_outperforms_dead_reckoning` |
+| RBPF | `test_rbpf_closed_loop_on_real_data` | `test_rbpf_with_degraded_gnss` (5 s) | -- |
-**Plus**: `test_dead_reckoning_on_real_data` (the unaided baseline),
+**Others:** `test_dead_reckoning_on_real_data` (the unaided baseline),
+`test_filter_comparison` (UKF, EKF and ESKF on the same data),
`test_eskf_output_stays_valid_across_full_run`, `test_eskf_default_initialization_on_real_data`,
`test_eskf_auto_covariance_initialization_on_real_data`, `test_eskf_recovers_from_gnss_outage`,
`test_filter_output_length_matches_input`, `test_filters_are_deterministic_across_runs`,
`test_rmse_benchmark_across_filters`, `test_full_lifecycle_through_ins_engine`,
-`magnetometer_yaw_aiding_source_error_matches_derivation`, and
-`gating_through_the_closed_loop_no_longer_cascades`.
+`magnetometer_yaw_aiding_source_error_matches_derivation` and
+`gating_through_the_closed_loop_no_longer_cascades`. The last is marked `#[ignore]`, with the
+reason in its attribute and doc comment, so a plain run reports 22 passed and 1 ignored; add
+`-- --ignored` to run it.
#### Thresholds
-The limits live in `core/tests/integration_tests.rs` as named constants, each with its
+The limits are named constants at the top of `core/tests/integration_tests.rs`, each with its
derivation in a doc comment. Read those rather than any number on this page:
| constant | what bounds it |
|---|---|
| `MAX_HORIZONTAL_RMSE_M` | empirical, with headroom over the observed run |
| `MAX_VERTICAL_RMSE_M` | empirical |
-| `MAX_LEVEL_ATTITUDE_RMSE_RAD` | **derived** -- gravity observability |
-| `MAX_YAW_RMSE_RAD` | **derived** -- a multiple of `MAG_YAW_SOURCE_RMSE_RAD`, the magnetometer's own measured error |
-| `DEAD_RECKONING_BASELINE_SAMPLES` | **derived** -- see below |
-| `DEAD_RECKONING_BEAT_FACTOR` | **derived** -- how far a filter must beat the baseline for the comparison to be live |
+| `MAX_LEVEL_ATTITUDE_RMSE_RAD` | **derived**: gravity observability |
+| `MAX_YAW_RMSE_RAD` | **derived**: a multiple of `MAG_YAW_SOURCE_RMSE_RAD`, the magnetometer's own measured error |
+| `DEAD_RECKONING_BASELINE_SAMPLES` | **derived**: see below |
+| `DEAD_RECKONING_BEAT_FACTOR` | **derived**: how far a filter must beat the baseline for the comparison to mean anything |
The distinction matters. An empirical guard answers "is this worse than yesterday?"; a derived
-one answers "is this physically possible?". **Do not tighten a derived bound to match a measured
-number** -- if a filter beats it, the bound was wrong, and the derivation is what changes. See
-`AGENTS.md` for the policy.
+one answers "is this physically possible?". **Do not tighten a derived bound to match a
+measured number**: if a filter beats it, the derivation is what changes. `AGENTS.md` has the
+policy.
#### The dead-reckoning baseline is a window, not the whole run
-The `*_outperforms_dead_reckoning` tests score the comparison over
-`DEAD_RECKONING_BASELINE_SAMPLES` records, not the full 90-minute recording. This page
-previously advertised the full-run version -- "dead reckoning RMS error ~7,100 km, improvement
->99.99%" -- and that headline is exactly what the truncation exists to kill.
-
-Unaided dead reckoning over the whole log ends millions of metres out. A test asserting
-`filter_error < dead_reckoning_error` against that is vacuous: it passes for any filter that
-does not itself diverge, including a badly broken one. Truncating to a window where the baseline
-drift is comparable to the filter's error makes the comparison discriminating again, and
-`DEAD_RECKONING_BEAT_FACTOR` then requires a real margin rather than any margin. See #307 and
-#299, and the derivation in the module header.
+The `*_outperforms_dead_reckoning` tests compare over the first
+`DEAD_RECKONING_BASELINE_SAMPLES` records, not the whole recording. Unaided dead reckoning over
+the full 89 minutes ends millions of metres out, and a test asserting
+`filter_error < dead_reckoning_error` against that passes for any filter that does not itself
+diverge, including a badly broken one. Truncating to a window where the baseline drift is
+comparable to the filter's error makes the comparison discriminating, and
+`DEAD_RECKONING_BEAT_FACTOR` then requires a real margin. See #307 and #299.
-#### Running Integration Tests
+#### Running them
```bash
-cargo test -p strapdown-core --test integration_tests # all of them
-cargo test -p strapdown-core --test integration_tests -- --nocapture # with printed output
+cargo test -p strapdown-core --test integration_tests # all of them
+cargo test -p strapdown-core --test integration_tests -- --nocapture # with printed output
cargo test -p strapdown-core --test integration_tests test_ukf_closed_loop_on_real_data -- --nocapture
-cargo test -p strapdown-core --test integration_tests -- --test-threads=1 # sequential
```
-#### Expected Runtime
-
-Deliberately not itemised here. The previous figures covered four tests where there are now 22,
-and predated the baseline truncation above, so they were wrong in both directions and nothing
-noticed. Nothing in CI measures wall clock today -- that is the open half of #377 -- so treat
-any runtime number as an observation you made, not a contract. What *is* bounded is CI itself:
-every job sets `timeout-minutes` (#379).
-
-
-#### Implementation Details
-
-##### Error Metric Calculation
+No runtime is given here because none is measured: nothing in CI tracks wall-clock time (the
+open half of #377). What is bounded is CI itself: every job sets `timeout-minutes`.
-The `compute_error_metrics()` function:
-1. Matches navigation results to GNSS measurements by timestamp
-2. Skips invalid GNSS data (NaN values)
-3. Computes error for each matched sample
-4. Filters out non-finite errors
-5. Calculates mean, max, and RMS statistics
+## Linting and formatting
-##### Filter Initialization
+The lints are enforced at `deny`, and CI lints two feature configurations. `.cargo/config.toml`
+defines an alias for each command CI runs:
-Tests use realistic initialization based on first GNSS measurement:
-- Position: First GNSS lat/lon/alt
-- Velocity: Computed from GNSS speed and bearing
-- Attitude: From phone orientation sensors
-- Covariances: Conservative initial uncertainties
-- Process noise: Tuned for MEMS IMU characteristics
+| alias | expands to | CI job |
+|---|---|---|
+| `cargo fmt-check` | `cargo fmt --all -- --check` | `full` |
+| `cargo lint` | `cargo clippy --workspace --all-targets --all-features -- -D warnings` | `full` |
+| `cargo lint-min` | `cargo clippy -p strapdown-core --all-targets --no-default-features -- -D warnings` | `minimal` |
+| `cargo test-min` | `cargo test -p strapdown-core --no-default-features` | `minimal` |
-##### Event Stream Generation
+Run all four, plus `cargo test --workspace --all-features`, before pushing. `cargo lint` alone
+is not enough: an import used only under `--all-features` is dead under
+`--no-default-features`, and only `cargo lint-min` sees it. `cargo lint-fix` applies the fixes
+clippy can make itself, and `cargo fmt --all` formats.
-Tests use the `build_event_stream()` function to create a sequence of IMU propagation and GNSS update events from the raw data, with configurable scheduling and fault injection.
+`clippy::pedantic`, `clippy::nursery`, `missing_docs` and the zero-panic lints
+(`unwrap_used`, `expect_used`, `panic`, in library code) are all denied. Relax a lint once, in
+`[workspace.lints.clippy]` in the root `Cargo.toml` with a reason, rather than with a call-site
+`#[allow]`. `AGENTS.md` lists the existing exceptions and why.
-### Future Test Enhancements
+The Python half has its own gate: `just check-python` runs `uv run ruff check`,
+`uv run ruff format --check` and `uv run pytest -q`.
-Potential improvements for the test suite:
-
-1. ~~**Additional test scenarios**~~ -- **done.** `core/tests/perf_baseline.rs` covers GNSS
- outages (`real_outage_60s`, `syn_outage_60s`, both `DutyCycle`), measurement corruption
- (`real_degraded`, an AR(1) fault model) and a synthetic cruise profile alongside the real
- recording.
-
-2. ~~**More filters**~~ -- **done.** The EKF is implemented (`core/src/kalman.rs`) and has the
- same three-scenario integration suite as the others; the RBPF has
- `test_rbpf_closed_loop_on_real_data` and `test_rbpf_with_degraded_gnss`, and its own row in
- the performance baseline.
-
-3. **Performance benchmarks**: *accuracy* regression is done -- `core/tests/perf_baseline.rs`
- gates every filter against a checked-in baseline in both directions, and
- [Performance Baselines](./performance.md) has the current numbers. What remains is the
- *wall-clock* half, which the accuracy gate deliberately does not measure:
- - Execution time metrics
- - Memory usage tracking
- - Scalability tests
-
-4. **Shorter test datasets**:
- - Create focused test datasets for faster CI/CD
- - Keep full dataset for comprehensive validation
-
-## Linting and Formatting
+## Documentation
-### Running Clippy
+### API documentation
-Clippy provides lint checks for Rust code:
```bash
-cargo clippy --workspace --all-features
+cargo docs # alias for cargo doc --workspace --no-deps
+cargo doc --workspace --no-deps --open # and open it in a browser
```
-Address warnings and errors before committing.
+See [API Documentation](../api/index.md) for what each crate contains and where the published
+copy lives.
-### Running rustfmt
+### Building the book
-Format code with rustfmt:
-```bash
-cargo fmt --all
-```
+The book is built with mdBook. CI pins version 0.4.40, so install that one:
-Check formatting without making changes:
```bash
-cargo fmt --all -- --check
+cargo install mdbook --version 0.4.40 --locked
+mdbook build book # output in book/book/
+mdbook serve book # live-reloading server on http://localhost:3000
```
-## Documentation
+Run them from the repository root. Pages under `book/src/` include files from elsewhere in the
+repository (Rust examples by anchor, `CONTRIBUTING.md`, the generated
+`development/baseline-tables.md`), so an edit to those files changes the book too.
-### Building API Documentation
+### Publishing the book
-Generate documentation for all crates:
-```bash
-cargo doc --workspace --all-features --no-deps
-```
+Publishing is automatic. `.github/workflows/deploy-book.yml` builds the book on every push to
+`main` (and on pull requests that touch the book or the crates, without deploying), adds the
+workspace rustdoc under `api/`, checks the links, and deploys the result to GitHub Pages at
+.
-Open the documentation in a browser:
-```bash
-cargo doc --workspace --all-features --no-deps --open
-```
+For that to work, the repository's **Settings → Pages → Build and deployment → Source** must be
+set to **GitHub Actions**; that is a one-time setting. There is no custom domain: the `cname`
+line in `book/book.toml` is commented out, so the site is served from the default
+`github.io` address.
-### Building the Book
+## Continuous integration
-This user guide is built using mdBook. Install mdBook:
-```bash
-cargo install mdbook
-```
-
-Build the book:
-```bash
-cd book
-mdbook build
-```
-
-Serve the book locally for development:
-```bash
-cd book
-mdbook serve
-```
-
-Then open http://localhost:3000 in your browser.
+The workflows in `.github/workflows/`:
-## Continuous Integration
-
-The project uses GitHub Actions for continuous integration. See `.github/workflows/` for workflow definitions:
-
-- `rust.yml`: the blocking gate. Three jobs -- `minimal` (`strapdown-core`, no default
- features, on Linux/macOS/Windows), `full` (fmt, clippy `-D warnings`, and the whole suite
- with all features, Linux), and `vendored` (the macOS/Windows canary for the source builds of
- netCDF and HDF5)
-- `deploy-book.yml`: builds and deploys this documentation to GitHub Pages
-- `publish.yml`: verifies, then publishes the crates to crates.io. Takes a `dry_run` input
-- `draft-pdf.yml`: renders the JOSS paper, on the `joss` branch
-- `copilot-setup-steps.yml`: toolchain provisioning only
+| workflow | what it does |
+|---|---|
+| `rust.yml` | the blocking Rust gate. `minimal`: `strapdown-core` with no default features (build, `clippy -D warnings`, test) on Linux, macOS and Windows. `full`: format check, `clippy -D warnings` and the whole test suite with all features, on Linux. `vendored`: builds the vendored netCDF/HDF5 on macOS and Windows. Two advisory jobs: `platform-spread`, which reports how far the accuracy metrics differ across the three platforms, and `semver`, which runs `cargo semver-checks` against the last release |
+| `python.yml` | lints and tests the `analysis` package (`ruff check`, `ruff format --check`, `pytest`), deliberately without GMT installed |
+| `deploy-book.yml` | builds this book and the rustdoc, checks links, and deploys to GitHub Pages |
+| `publish.yml` | verifies, then publishes the crates to crates.io on a release; a manual run takes a `dry_run` input |
+| `draft-pdf.yml` | renders the JOSS paper in `papers/joss/` when it changes |
+| `copilot-setup-steps.yml` | toolchain provisioning for the Copilot coding agent only |
-Every job sets `timeout-minutes` (#379), so a hang fails rather than running to GitHub's
-360-minute default.
+Every job sets `timeout-minutes`, so a hang fails instead of running to GitHub's 360-minute
+default.
## References
-- Groves, P. D. (2013). *Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems*, 2nd ed.
-- Sensor Logger app: https://www.tszheichoi.com/sensorlogger
+- Groves, P. D. (2013). *Principles of GNSS, Inertial, and Multisensor Integrated Navigation
+ Systems*, 2nd ed. Artech House.
+- Sensor Logger app:
diff --git a/book/src/development/contributing.md b/book/src/development/contributing.md
index 854139a3..d759ebfc 100644
--- a/book/src/development/contributing.md
+++ b/book/src/development/contributing.md
@@ -1 +1,9 @@
-# Contributing
+{{#include ../../../CONTRIBUTING.md}}
+
+---
+
+*This page is the repository's
+[`CONTRIBUTING.md`](https://github.com/jbrodovsky/strapdown-rs/blob/main/CONTRIBUTING.md),
+included verbatim so the two cannot drift. [Building and Testing](./building.md) covers the
+build, the test suites and the full set of lint commands, including the no-default-features
+configuration (`cargo lint-min`, `cargo test-min`) that CI also gates on.*
diff --git a/book/src/development/performance.md b/book/src/development/performance.md
index 3fd218fa..eaae4c12 100644
--- a/book/src/development/performance.md
+++ b/book/src/development/performance.md
@@ -1,12 +1,11 @@
# Performance Baselines
-"Performance" on this page means **navigation accuracy**, not wall-clock speed. How far the
+"Performance" on this page means **navigation accuracy**, not wall-clock speed: how far the
solution was from truth, and whether the filter's covariance knew it. Execution time, memory
-and scalability are tracked nowhere yet; see [Building and Testing](./building.md) for what
-remains.
+and scalability are not measured anywhere yet.
-Every number below is recorded in `core/tests/perf_baseline.json` and checked on every CI run
-by `core/tests/perf_baseline.rs`. The check fails in **both** directions:
+Every number here is recorded in `core/tests/perf_baseline.json` and checked on every CI run by
+`core/tests/perf_baseline.rs`. The check fails in **both** directions:
- a metric more than **10%** worse than its baseline is a regression, and CI goes red;
- a metric more than **25%** better is *also* a failure, and the message asks for the baseline
@@ -14,452 +13,163 @@ by `core/tests/perf_baseline.rs`. The check fails in **both** directions:
Each scenario also records the number of aligned samples it was scored over and the number of
channel-samples dropped as non-finite, both compared for exact equality before any metric is.
-The second is zero everywhere and is recorded because dropping a sample does not lower the
+The second is zero everywhere. It is recorded because dropping a sample does not lower the
first, but does make the metric it was dropped from look better.
-Re-bless with `UPDATE_PERF_BASELINE=1 cargo test -p strapdown-core --test perf_baseline`, then
-commit the diff; `cargo perf` runs the suite and prints the table without writing anything.
-[CONTRIBUTING.md](https://github.com/jbrodovsky/strapdown-rs/blob/main/CONTRIBUTING.md) has the
-workflow.
+## Running and re-blessing
-## Read these seven caveats first
+```bash
+cargo perf # run the suite and print the table; writes nothing
+UPDATE_PERF_BASELINE=1 cargo test -p strapdown-core --test perf_baseline # re-bless
+```
-The numbers are meaningless without them. All but the fifth and seventh are properties of the
-measurement rather than defects in the harness; the fifth is a defect in the gate, and the
-seventh was a defect in the UKF that is now fixed.
+In PowerShell the second is `$env:UPDATE_PERF_BASELINE=1; cargo test -p strapdown-core --test
+perf_baseline`. Re-blessing rewrites `core/tests/perf_baseline.json` *and* regenerates
+`book/src/development/baseline-tables.md`, which this page includes below, and the gate fails if
+the two disagree, so there is no second step to forget. It preserves the per-metric `note`,
+`gated` and tolerance overrides already in the file. Review the diff before committing it:
+every changed number is a claim about the navigation solution, and the pull request should
+say which change produced it. [Contributing](./contributing.md) has the workflow.
-1. **On the real-data scenarios, "truth" is the GNSS fix -- which is also the filters' aiding
- source.** They measure agreement with the aid, not independent accuracy, and cannot fall
- below the receiver's own 3.81 m horizontal noise however good the filter is. The `syn_*`
- scenarios are scored against an exact synthetic trajectory and have no such floor, which is
- why their horizontal figures are five times smaller.
-2. **On a full-rate real-data row, the filter is scored against a fix it has already been
- given.** This used to read differently: every horizontal figure carried a one-step
- propagation offset, because `sim::run_closed_loop` pushed each row *after* applying the
- next event, so the row labelled $t_k$ held a state already propagated to $t_{k+1}$. At
- 1 Hz and 21.19 m/s that was 21.2 m of along-track error -- very nearly the whole of the
- ~23.5 m the `real_clean` rows then showed, and the reason all three filters landed within
- 0.2 m of each other. [#367](https://github.com/jbrodovsky/strapdown-rs/issues/367) fixed
- it, and every horizontal metric improved at once.
-
- What that uncovered is caveat 1 with nothing left diluting it. A row at $t_k$ now contains
- $t_k$'s GNSS update, so on a `PassThrough` schedule these columns measure how completely a
- filter absorbs its own aiding.
-
- That absorption used to be total: `real_clean__ukf` read 0.014 m and `real_clean__ekf`
- 0.0001 m, far below the receiver's own 3.81 m. Not accuracy — a Kalman gain of about 1,
- caused by an absolute covariance floor applied to a latitude variance in radians².
- [#373](https://github.com/jbrodovsky/strapdown-rs/issues/373) **fixed it**, and the three
- filters now read **4.78, 5.22 and 5.12 m** — above the receiver's own noise rather than
- reproducing it, and in agreement with the ESKF, which had floored its covariance relatively
- since #266.
-
- **The real-data rows that still measure navigation are the ones where the filter has to
- predict between fixes** -- `real_sparse_5s`, `real_outage_60s`, `real_degraded` -- together
- with the `syn_*` scenarios and their exact independent truth.
-3. **The synthetic scenarios now carry a real magnetic field, and the yaw column says which
- filters can use it.** `generate_synthetic` evaluates the World Magnetic Model at each
- epoch's position and date and rotates it into the body frame through the truth attitude
- ([#369](https://github.com/jbrodovsky/strapdown-rs/issues/369)); before that it wrote
- nothing, and heading was observable only through the GNSS velocity fix. With a 1 Hz heading
- aid all three filters now hold a fraction of a degree of yaw on `syn_cruise_1hz` -- the EKF
- 0.28, the ESKF 0.18, the UKF 0.16, the last down from 108.3 deg without a magnetometer at
- all.
-
- **`syn_outage_60s__ukf` used to be where that stopped, and the stated reason was wrong.**
- With the field added that row read 72.68 deg of yaw, 809 m horizontal and a NEES of 44.67,
- against the ESKF's 0.255 deg and 24.0 m on the identical stream, and this page cited that
- pair as evidence for [#371](https://github.com/jbrodovsky/strapdown-rs/issues/371). It was
- not evidence for anything: the three filter constructors shipped initial gyro-bias variances
- five orders of magnitude apart -- `1e-3` for the UKF and the EKF against `1e-8` for the
- ESKF -- so the two filters were never handed the same prior. `1e-3` is a gyro-bias sigma of
- 1.81 deg/s against the 0.028 deg/s a consumer-grade part actually has.
-
- Sizing all three from the IMU grade takes that row to **0.222 deg of yaw, 27.4 m
- horizontal, NEES 4.21 and 3-sigma horizontal containment 0.997** against an ideal of 0.9973
- -- past the ESKF's own numbers on the same stream, so the UKF is not incapable of carrying
- an attitude through a coast. `syn_outage_60s__eskf` moved the other way and for the same
- reason: its `1e-8` was about 5x *tighter* than the truth it was modelling, and correcting it
- costs 24.0 -> 26.3 m of position and 0.255 -> 0.292 deg of yaw while taking its NEES
- 4.64 -> 3.87 and its vertical containment 0.866 -> 0.925. Less accurate, more honest.
-
- #371 was a real defect -- a linear mean over sigma-point Euler triples sends 31 rotations
- inside a 0.24 deg cone to a point 34 deg outside it -- but it is not what this row was
- measuring. Fixing it, so the UKF perturbs, averages, correlates and injects attitude on
- SO(3), moved `syn_outage_60s__ukf` yaw by **0.007 deg** (0.222 to 0.230) and improved its
- position (27.39 to 27.17 m). That near-nil result on the rows with exact truth is the
- finding. The two `__ekf` rows did not move at all for the prior change either, which is
- also a finding rather than a null result: the EKF's bias states are structurally inert
- ([#394](https://github.com/jbrodovsky/strapdown-rs/issues/394)), so its prior cannot be
- falsified by any measurement.
-
- **The `real_*` UKF rows are the exception, and the yaw column there cannot adjudicate it.**
- `real_clean__ukf` yaw went 22.72 to 25.83 deg and `real_degraded__ukf` 22.18 to 26.01 when
- the chart was fixed, which reads as a 14-17% regression. Three measurements say what it
- actually is. The UKF's disagreement with the **ESKF** -- the other filter here that does its
- attitude arithmetic on a manifold, and which this change does not touch -- fell from 8.40 to
- 2.57 deg RMS on the same recording. The recording's own magnetometer, levelled by its own
- roll and pitch, disagrees with its yaw column by **16.8 deg RMS after removing every
- constant offset**, which is the floor for any filter aided by it, so the 3 deg the UKF moved
- is inside what that column can resolve. And on the synthetic rows, where truth is exact, the
- change is neutral. Caveat 1 again, in the attitude channel.
-4. **The consistency columns mean different things on the two sources.** On the synthetic
- scenarios `npes` lands between 3.9 and 12.1 against an ideal of 3.0, which is a real
- measurement of whether a filter believes the right thing. On the real-data scenarios it reaches the
- hundreds, because caveat 2's offset enters the numerator while the covariance in the
- denominator models none of it. Those values are kept as a drift detector, not read as a
- consistency verdict.
-
- The synthetic figures roughly doubled when
- [#375](https://github.com/jbrodovsky/strapdown-rs/issues/375) scheduled the barometer, and
- the vertical columns say why: what a normalised statistic now sees is a systematic altitude
- bias of -0.6 to -2.0 m that nothing models. That is
- [#372](https://github.com/jbrodovsky/strapdown-rs/issues/372), measured rather than masked.
-
-5. **The baseline is blessed on one platform and gated on three.** `rust.yml` runs this suite
- on Linux, macOS and Windows, and nothing in the gate knows that -- there is no
- cross-platform tolerance floor. For most rows it does not matter: the same commit agrees to
- about 1% across platforms. It matters where a metric is a *tail* statistic of something
- unstable. `real_rbpf_slice__rbpf`'s `horizontal_cep95_m` measured 34.02 m on Linux against
- 24.33 m on Windows -- a 28.5% spread against a 25% improve band -- so a Linux bless failed
- the Windows leg of a run that was behaving identically. That metric is ungated with the
- numbers recorded in its note; the general problem is
- [#386](https://github.com/jbrodovsky/strapdown-rs/issues/386).
-
-**The spread is now measured, on all three legs of one run** (at the old `ukf_alpha`), by
- the advisory `Cross-platform accuracy spread` job. The largest entries:
-
- | spread | scenario / metric | macOS | Linux | Windows |
- |---:|---|---:|---:|---:|
- | 10.79% | `real_rbpf_slice__rbpf/horizontal_cep50_m` | 1.82705 | 1.82705 | 1.64916 |
- | 8.61% | `real_rbpf_slice__rbpf/horizontal_cep95_m` | 29.2597 | 29.2597 | 26.9394 |
- | 4.70% | `syn_outage_60s__ukf/horizontal_cep50_m` | 1.64422 | 1.62557 | 1.57045 |
- | 2.87% | `syn_outage_60s__ukf/roll_rmse_deg` | 0.27204 | 0.27475 | 0.26708 |
- | 2.39% | `syn_outage_60s__ukf/yaw_rmse_deg` | 0.22314 | 0.22687 | 0.22158 |
-
- Two readings fall out. The 28.5% this caveat quotes above is now **8.61%**, so #385's fix
- did shrink the spread it was blamed for -- that was the missing measurement. And it is
- **Windows against the other two**, not three-way scatter: macOS and Linux agree to eleven
- significant figures on the RBPF rows, which is what a libm differing by an ulp looks like
- rather than anything about the navigation.
-
- The UKF rows there are caveat 7 seen a second way -- same rows, same order, about half the
- magnitude of the one-ulp response recorded there. So caveat 7's fix predicted those rows
- would collapse and the RBPF rows would not.
-
- **That prediction was recorded before the run, and the run confirmed it.** Same job, same
- three platforms, on the commit that raised `ukf_alpha`:
-
- | scenario / metric | before | after |
- |---|---:|---:|
- | `syn_outage_60s__ukf/horizontal_cep50_m` | 4.70% | **0%** |
- | `syn_outage_60s__ukf/roll_rmse_deg` | 2.87% | **0%** |
- | `syn_outage_60s__ukf/yaw_rmse_deg` | 2.39% | **0%** |
- | `syn_outage_60s__ukf/attitude_geodesic_rmse_deg` | 2.06% | **0%** |
- | `syn_outage_60s__ukf/velocity_horizontal_rmse_mps` | 1.76% | **0%** |
- | `real_rbpf_slice__rbpf/horizontal_cep50_m` | 10.79% | 10.79% |
- | `real_rbpf_slice__rbpf/horizontal_cep95_m` | 8.61% | 8.61% |
-
- Every `syn_*__ukf` row now agrees across all three platforms to seven or eight significant
- figures, and every RBPF row is unchanged to the digit.
-
- **So what is left of #386 is a single scenario — and it is not floating-point noise.**
- `real_rbpf_slice__rbpf` holds every entry above 0%, and nothing else in the suite exceeds
- it. The obvious next move is a tolerance, global or per-metric. **Both are wrong, because
- the number is not understood.**
-
- Three one-ulp perturbations, each applied on *every* call — which is what a libm differing
- in its last bit actually is:
-
- | perturbation | worst of 236 metrics |
- |---|---:|
- | every Gaussian draw in the RBPF | 1.28e-6 % |
- | every particle weight, after `exp` | 3.09e-7 % |
- | one WGS84 constant (caveat 7's ensemble) | 1.0e-6 % |
-
- The RBPF moves by about one part in 10⁸ under any of them, and `horizontal_cep50_m` — the
- metric carrying the 10.79% spread — is the most responsive at 1.28e-6 %. **The RBPF is not
- an amplifier**, the opposite of the UKF in caveat 7, so the residual spread cannot be a
- last-bit effect.
-
- The platform pattern agrees. macOS and Linux match to **eight significant figures** on that
- metric, across *different CPU architectures*, while Windows — same architecture as Linux —
- sits 10% away. That rules out CPU architecture, SIMD width and runtime feature dispatch,
- all of which would separate ARM from x86 rather than Windows from everyone.
-
- A 10% discrepancy on one platform and one scenario, demonstrably larger than an ulp, is a
- **defect to diagnose rather than a band to widen**; fitting a tolerance to it would be
- [#288](https://github.com/jbrodovsky/strapdown-rs/issues/288) again. Diagnose it by emitting
- the sorted error series behind `horizontal_cep50_m` from each leg — the `PERF_EMIT_MEASURED`
- plumbing is most of the way there — and by checking that `test_data.csv` parses identically
- on Windows before blaming the filter.
-
- **Two parts of that are now closed.** The baseline records the operating system it was
- blessed on (`blessed_on`), and the improve-side failure no longer tells a contributor their
- baseline is stale when the run is simply on a different platform -- it names both platforms
- and says to check the blessing one first. Re-blessing on the wrong leg was the specific
- damage the old message caused.
-
- **The tolerance floor is deliberately not set yet, because nobody has measured it.** Every
- matrix leg now writes its raw numbers with `PERF_EMIT_MEASURED` and uploads them, and the
- advisory `Cross-platform accuracy spread` job prints the per-metric spread across all three.
- Setting a floor before reading that output would be gating on a guess, which is the mistake
- #386 exists to correct. Read the job's table, then set the floor from it.
-
- Note also that the 28.5% figure above predates
- [#385](https://github.com/jbrodovsky/strapdown-rs/issues/385). That row's tail *was* the
- epochs where the particle cloud collapsed, and it no longer collapses, so the spread may
- already be much smaller. It has not been re-measured. Until then, **check a Windows run
- before calling a re-bless done.**
-7. **A one-ulp change to anything upstream used to move these numbers by percents.** This is
- [#399](https://github.com/jbrodovsky/strapdown-rs/issues/399), and both halves of its
- recorded diagnosis turned out to be wrong, which is worth keeping.
-
- The issue's experiment was to add a `pub fn` to `linearize.rs` that nothing calls and
- re-bless: 59 metrics moved, one by 4.86%. Its proposed mechanism was the innovation gate --
- a continuous statistic turned into a discrete accept/reject, one flipped decision in 15,000
- steps separating two trajectories.
-
- **The gate was refuted by counting.** Gating is opt-in and this suite never installs one, so
- across a full run all **137,876** calls to `GatePolicy::decide` took the "no gate" branch.
- There was no accept/reject decision to flip. Nor was there any other discrete branch: all
- 98,786 sigma-point factorizations took plain Cholesky with no jitter and no eigenvalue
- fallback, no IMU-bias clamp bound in 394,740 opportunities, and the Euler-rate inverse was
- admitted on all 106,518.
-
- **The codegen story did not reproduce either.** The dead `pub fn`, with its symbol confirmed
- present in the compiled rlib, leaves all 236 metrics bit-identical. Rust emits IEEE-754
- semantics without fast-math, so LLVM may not reassociate or contract floating-point;
- changing what surrounds a function cannot change what it computes.
+## Scenarios
- **What does reproduce is the amplification, from the data side, and it was the UKF's.**
- Perturbing `earth::EQUATORIAL_RADIUS` by one ulp moved 170 of 236 metrics, the worst by
- **9.77%** against a 10% band. Over six independent one-ulp perturbations of WGS84 constants:
+`real` is `core/tests/test_data.csv`: 5,366 records at 1 Hz over 89 minutes, ENU, from a
+consumer phone. `syn` is `sim::generate_synthetic`: 300 s at 50 Hz, NED, a 50 m/s
+constant-velocity cruise (40 m/s north, 30 m/s east) from 40° N, 75° W with a consumer-grade
+IMU, seed 42, scored against its own exact truth.
- | estimator | worst response to one ulp |
- |---|---:|
- | **UKF** | **9.77%** |
- | RBPF | 1.0e-6 % |
- | dead reckoning | 1.7e-10 % |
- | EKF | 3.8e-11 % |
- | ESKF | 3.3e-11 % |
+| id | data | GNSS | estimators |
+|---|---|---|---|
+| `real_clean` | real | every epoch | UKF, EKF, ESKF |
+| `real_sparse_5s` | real | every 5 s | UKF, ESKF |
+| `real_outage_60s` | real | duty cycle: 60 s off, 120 s on, repeating | ESKF |
+| `real_degraded` | real | every epoch, AR(1) position and velocity fault ($\rho$ 0.98, $\sigma$ 3 m and 0.3 m/s, `r_scale` 1) | UKF, ESKF |
+| `syn_cruise_1hz` | syn | every 1 s | UKF, EKF, ESKF |
+| `syn_outage_60s` | syn | duty cycle: 60 s off, 60 s on, repeating | UKF, ESKF |
+| `syn_dead_reckoning` | syn, first 120 s | none | unaided mechanization |
+| `real_rbpf_slice` | real, first 1,200 records | every epoch | RBPF, 500 particles |
- Eleven orders of magnitude on the same scenarios, which rules out "a 60 s coast compounds a
- last bit": `syn_outage_60s__eskf` coasts identically and sits at 3.3e-11 %. The UKF is the
- only estimator here that forms a weighted sigma-point mean, and at the `alpha = 1e-3` this
- crate shipped, a 16-state filter formed it as `-999,999 x_0 + sum 31,250 x_i` -- six of
- `f64`'s sixteen significant digits spent on cancellation, every step. End to end, one ulp of
- initial latitude moved a 180 s solution's final position by **1.76 m**.
+The two outage scenarios use `start_phase_s = 0`, so each begins with its OFF window (see
+[`DutyCycle`](../gnss/scenarios.md#dutycycle)). The barometer and magnetometer are scheduled at
+their 1 Hz default in every scenario, so the synthetic vertical and yaw columns are those of a
+1 Hz barometer and magnetometer even though the IMU runs at 50 Hz.
- **Fixed by raising `ukf_alpha` to `0.1`**, which takes that to 0.18 mm and the worst metric
- response to 0.0003%, and improves accuracy slightly on the way. An equilibrated Cholesky
- landed with it and is worth a further factor of two. `core/tests/ukf_conditioning.rs` guards
- both ends, and the numbers above are in that file and in `ClosedLoopConfig::ukf_alpha`.
+Two scenarios are deliberately absent. **Full-run dead reckoning** ends millions of metres out,
+at altitudes where floating-point results have already been seen to differ between platforms;
+the 120 s synthetic window is the safe version of the same measurement. **A second
+particle-filter scenario** is left out to keep the suite's CI time down.
- **Use a control build when a bless surprises you.** If a re-bless moves rows the change
- cannot reach, compile the new code *without calling it*, bless that, and diff the real
- change against the control rather than against the parent commit. On
- [#394](https://github.com/jbrodovsky/strapdown-rs/issues/394) that reduced "seven scenarios
- moved" to the two the change can actually touch. It is only valid if it neutralises **every**
- call site -- a first attempt at #398's control missed the UKF's transport and reported half
- the moved metrics. This is now insurance rather than a necessity, but it is the habit that
- found every mis-attribution on this project so far.
-6. **The `syn_*` rows run at 50 Hz and the `real_*` rows at 1 Hz, and the aiding sensors no
- longer follow that.** Until
- [#375](https://github.com/jbrodovsky/strapdown-rs/issues/375) the barometer and the
- magnetometer were emitted once per record, outside the scheduler, so their update rate was
- the log's: 1 Hz on `test_data.csv` and 50 Hz on the synthetic trajectories, where fifty
- pressure readings a second each entered the filter as an independent fix. Both channels are
- now scheduled at 1 Hz by default. Every `real_*` row came through bit-identical -- they were
- already at 1 Hz -- and all five aided `syn_*` rows moved, almost entirely in the vertical
- channel: horizontal RMSE on `syn_cruise_1hz` moved by under half a percent. Read the
- synthetic vertical columns as a 1 Hz barometer's, not a 50 Hz one's, and the yaw
- columns as a 1 Hz magnetometer's.
+The suite is not behind a feature or `#[ignore]`, so it runs on all three CI platforms. That is
+deliberate: the three legs double as a portability check on the accuracy numbers themselves.
## The metrics
| metric | unit | definition | ideal |
|---|---|---|---|
| `horizontal_rmse_m` | m | RMS great-circle distance from truth | 0 |
-| `horizontal_cep50_m` | m | median radial error -- the empirical, non-parametric CEP, *not* the Rayleigh form. Nearest-rank, so it is a value some epoch actually had | 0 |
-| `horizontal_cep95_m` | m | 95th percentile radial error, same convention | 0 |
+| `horizontal_cep50_m` | m | median radial error: the empirical, nearest-rank CEP, *not* the Rayleigh form | 0 |
+| `horizontal_cep95_m` | m | 95th-percentile radial error, same convention | 0 |
| `horizontal_max_m` | m | largest single-sample radial error | 0 |
| `vertical_rmse_m` | m | RMS altitude error | 0 |
-| `vertical_bias_m` | m | **signed** mean altitude error -- catches a slow one-sided drift while it is still small | 0 |
+| `vertical_bias_m` | m | **signed** mean altitude error; catches a slow one-sided drift while it is still small | 0 |
| `velocity_horizontal_rmse_mps` | m/s | RMS north/east velocity error | 0 |
| `velocity_vertical_rmse_mps` | m/s | RMS vertical velocity error | 0 |
| `roll_rmse_deg`, `pitch_rmse_deg` | deg | RMS per-axis error, wrapped onto $[-\pi, \pi]$ | 0 |
| `yaw_rmse_deg` | deg | RMS heading error, wrapped | 0 |
-| `attitude_geodesic_rmse_deg` | deg | RMS rotation angle of $R_{est}^{-1} R_{true}$ -- the only attitude error independent of the Euler sequence | 0 |
-| `nees_position` | -- | mean normalized estimation error squared over the full 3x3 position block, $\frac{1}{N}\sum_k e_k^\top P_k^{-1} e_k$ | 3.0 |
-| `npes_position` | -- | the same, computed as though $P$ were diagonal: $\overline{\epsilon} = \frac{1}{N}\sum_k \left(\frac{e_{lat}^2}{P_{lat}} + \frac{e_{lon}^2}{P_{lon}} + \frac{e_{alt}^2}{P_{alt}}\right)$ | 3.0 |
+| `attitude_geodesic_rmse_deg` | deg | RMS rotation angle of $R_{est}^{-1} R_{true}$: the only attitude error independent of the Euler sequence | 0 |
+| `nees_position` | -- | mean normalized estimation error squared over the full 3×3 position block, $\frac{1}{N}\sum_k e_k^\top P_k^{-1} e_k$ | 3.0 |
+| `npes_position` | -- | the same, computed as though $P$ were diagonal: $\frac{1}{N}\sum_k \left(\frac{e_{lat}^2}{P_{lat}} + \frac{e_{lon}^2}{P_{lon}} + \frac{e_{alt}^2}{P_{alt}}\right)$ | 3.0 |
| `containment_3sigma_horizontal` | fraction | share of latitude and longitude samples inside $\pm 3\sigma$ | 0.9973 |
| `containment_3sigma_vertical` | fraction | share of altitude samples inside $\pm 3\sigma$ | 0.9973 |
-`nees_position` is the real statistic. It became computable in
-[#376](https://github.com/jbrodovsky/strapdown-rs/issues/376), which stopped `NavigationResult`
-discarding the position block's off-diagonal terms; before that the crate could only report the
-diagonal-only `npes_position`, which equals the NEES when the position states are uncorrelated
-and is **optimistic** when they are not.
-
-Both are kept. `npes_position` stays so the baseline it has accumulated remains comparable
-across that change, not as a claim about consistency.
-
-**How much did the diagonal-only form actually understate?** Less than #376 feared, and
-precisely where you would expect:
-
-| scenario | `npes` | `nees` | ratio |
-|---|---:|---:|---:|
-| every row with GNSS every epoch | — | — | **1.00–1.01** |
-| `real_outage_60s__eskf` | 73.43 | 83.04 | **1.13** |
-| `syn_outage_60s__ukf` | 6.54 | 6.82 | **1.04** |
+`nees_position` is the real consistency statistic; it became computable when
+`NavigationResult` started keeping the position block's off-diagonal terms
+([#376](https://github.com/jbrodovsky/strapdown-rs/issues/376)). `npes_position` is kept so its
+history stays comparable. It equals the NEES when the position states are uncorrelated and is
+optimistic when they are not, which is during a free-inertial coast: compare the two columns on
+the outage rows.
-Where the filter is aided every epoch the two agree to within 1%, so the historical `npes`
-numbers were not misleading. The gap opens on the **outage** rows -- `syn_outage_60s__ukf` read
-15.12 against 18.45, a ratio of 1.22, until #375 brought that coast back under control -- and the mechanism is the
-obvious one: during a free-inertial coast the position error accumulates along a correlated
-direction with no fix to break it up, and a diagonal-only statistic cannot see that. The
-contrived worst case is far larger — at a latitude-longitude correlation of 0.9 the two read
-2.0 and 20.0 — so the modest ratios here are a measurement about these trajectories, not a
-general reassurance.
-
-Read either beside the containment row, never alone -- together they separate the two failure
-modes either one alone hides:
+Read either beside the containment columns, never alone. Together they separate the two
+failure modes either one hides:
| containment | `nees_position` | diagnosis |
|---|---|---|
| ~1.0 | far below 3 | over-conservative: the filter is right but does not believe it |
-| below 0.99 | far above 3 | over-confident -- the dangerous one |
+| below 0.99 | far above 3 | over-confident, the dangerous one |
| ~0.9973 | ~3 | consistent |
-There is no Wasserstein-2 metric, though the original issue floated one. Against a Dirac at
-truth it reduces to squared error plus total variance, which is strictly less information than
-reporting the error and the consistency separately. Against the empirical error distribution it
-is not a distance between samples of anything, because errors along one trajectory are strongly
-autocorrelated. The CEP columns carry the "the shape of the error distribution moved" signal
-instead, and a human reading a failure message can interpret them. The reasoning is recorded in
-full in the `strapdown::metrics` module documentation.
-
-## Scenarios
-
-`real` is `core/tests/test_data.csv`: 5,366 samples at 1 Hz over 89 minutes, ENU, from a
-consumer MEMS IMU. `syn` is `sim::generate_synthetic`: 300 s at 50 Hz, NED, 50 m/s off-axis
-cruise, consumer-grade IMU, seed 42, scored against its own exact truth.
-
-| id | data | GNSS | estimators |
-|---|---|---|---|
-| `real_clean` | real | every epoch | UKF, EKF, ESKF |
-| `real_sparse_5s` | real | every 5 s | UKF, ESKF |
-| `real_outage_60s` | real | 120 s on, 60 s off | ESKF |
-| `real_degraded` | real | every epoch, AR(1) position and velocity fault | UKF, ESKF |
-| `syn_cruise_1hz` | syn | every 1 s | UKF, EKF, ESKF |
-| `syn_outage_60s` | syn | 60 s on, 60 s off | UKF, ESKF |
-| `syn_dead_reckoning` | syn, first 120 s | none | unaided mechanization |
-| `real_rbpf_slice` | real, first 1,200 samples | every epoch | RBPF, 500 particles |
-
-Two scenarios are deliberately absent. **Full-run dead reckoning** ends millions of metres out
-by way of an altitude at which the `r_e + altitude` denominator in `earth::transport_rate` is
-within a few percent of zero, where finiteness is a floating-point accident that has already
-differed between Windows and Linux; the 120 s synthetic window is the safe version of the same
-measurement. **A second particle-filter scenario** is affordable in principle and not in CI
-time: the RBPF is the only estimator here whose cost is measured in seconds.
-
-The whole suite runs in about 5.5 seconds on Linux and is not gated behind a feature or an
-`#[ignore]`, so it runs on all three CI platforms. That is deliberate: the three legs are a
-free portability canary for the accuracy numbers themselves, which this project has been bitten
-by before.
+There is deliberately no Wasserstein metric; the reasoning is in the `strapdown::metrics`
+module documentation.
+
+## Read these caveats first
+
+The numbers mean little without them.
+
+1. **On the real-data scenarios, "truth" is the GNSS fix, which is also the filters' aiding
+ source.** They measure agreement with the aid, not independent accuracy, and they cannot
+ fall below the receiver's own error. The receiver advertises a 3.81 m horizontal 1σ on
+ average over this recording (`GNSS_REPORTED_HORIZONTAL_ACCURACY_M` in
+ `core/tests/integration_tests.rs`, checked against the data on every run). The `syn_*`
+ scenarios are scored against an exact synthetic trajectory and have no such floor.
+2. **On a full-rate real-data row, the filter is scored against a fix it has just been
+ given.** The row at $t_k$ contains $t_k$'s GNSS update, so on `real_clean` the horizontal
+ columns measure how a filter weighs its own aiding against its prediction. The real-data
+ rows that measure navigation are the ones where the filter has to predict between or
+ without fixes (`real_sparse_5s`, `real_outage_60s`, `real_degraded`), together with the
+ `syn_*` rows and their exact truth.
+3. **The consistency columns mean different things on the two sources.** On the synthetic
+ rows they are a real measurement of whether a filter believes the right thing. On the
+ real-data rows the reference is itself noisy and the filters' models of the phone are
+ approximate, so read them as a drift detector rather than a verdict.
+4. **`real_degraded` tells the filter nothing about the fault.** Its fault uses
+ `r_scale = 1`, so the filter's measurement noise is not inflated while each fix carries an
+ AR(1) error with a steady-state σ of $3/\sqrt{1-0.98^2} \approx 15$ m. Its NEES and
+ containment columns are what a filter looks like when its $R$ is wrong, which is the
+ point of the scenario. Under that fault the GNSS altitude is itself biased, so the
+ barometric bias state cannot be separated from it, and the vertical columns suffer.
+5. **The baseline is blessed on one platform and gated on three.** The JSON records the
+ platform it was blessed on (`blessed_on`). Most metrics agree across Linux, macOS and Windows
+ to well inside the tolerance; the advisory `Cross-platform accuracy spread` job in
+ `rust.yml` measures the spread on every run. `real_rbpf_slice__rbpf` is the exception: its
+ `horizontal_cep95_m`, `nees_position` and `npes_position` are recorded but **not gated**,
+ with the reasons in each metric's `note`, until a cross-platform tolerance exists
+ ([#386](https://github.com/jbrodovsky/strapdown-rs/issues/386)). Check a Windows run before
+ calling a re-bless done.
+6. **A one-ulp change upstream used to move the UKF rows by percents.** At the old
+ `ukf_alpha = 1e-3` the weighted sigma-point mean lost about six significant digits to
+ cancellation every step ([#399](https://github.com/jbrodovsky/strapdown-rs/issues/399)).
+ `ukf_alpha` is now 0.1, and `core/tests/ukf_conditioning.rs` guards the result. If a
+ re-bless moves rows the change cannot reach, compile the new code without calling it, bless
+ that as a control, and diff the real change against the control.
## Current values
-Measured on `ubuntu-latest`, rustc 1.91. Read-only with `cargo perf`; re-blessed with
-`UPDATE_PERF_BASELINE=1 cargo test -p strapdown-core --test perf_baseline`.
-
-The three tables below are **generated** from `core/tests/perf_baseline.json` by the same test
-that gates it, and the gate fails if they drift from it. They used to be maintained here by
-hand, which meant every re-bless was a command plus 45 transcribed rows, with nothing checking
-the transcription -- and a wrong number on this page is harder to notice than a wrong number in
-the gated file, because nothing asserts it (#380). Edit `baseline-tables.md` and the next run
-will tell you off; change the numbers by re-blessing.
+These tables are **generated** from `core/tests/perf_baseline.json` by the test that gates it,
+and the gate fails if they drift from it. Do not edit them; change them by re-blessing.
{{#include ./baseline-tables.md}}
-## What the table is saying
-
-- **The `real_clean` horizontal column measures agreement with the aid, not accuracy.** All
- three filters now read 4.78, 5.22 and 5.12 m against a reference whose own noise is 3.81 m,
- so none of them is below its own reference any more — #373 fixed the absolute covariance
- floor that had the UKF and EKF reproducing the fix they were handed (0.014 m and 0.0001 m).
- What remains is caveat 1's circularity, which no fix to the filters can remove: the score is
- against the aiding source itself.
-- **`syn_cruise_1hz` is where the filters actually separate**, and no one of them wins. The
- ESKF leads on vertical error, the EKF on horizontal, and all three now hold a fraction of a
- degree of yaw — the UKF's, once the worst column in the table at 108.3 deg with no
- magnetometer and 2.01 deg with one but a mis-sized bias prior, is now the best of the three.
- These rows are scored against exact truth, so nothing here is circular.
-- **The outage rows are dominated by attitude, not by position.** 60 s of free inertial turns a
- fraction of a degree of tilt error into tens of metres. Both filters now hold about a quarter
- of a degree of yaw through the coast and land within a couple of metres of each other, around
- 26–27 m. The UKF used to reach 809 m on this row; that was its initial gyro-bias prior, not
- its attitude algebra, and the story is in caveat 3.
-- **The two consistency columns disagree with each other on real data, and that is the
- finding.** Horizontal three-sigma containment sits near 0.50 across the three filters and
- vertical near 0.40, where better than half the altitude errors fall outside three sigma.
- Neither is the old flat 1.000 — [#373](https://github.com/jbrodovsky/strapdown-rs/issues/373)
- removed the absolute covariance floor that made the horizontal figure unfalsifiable, so what
- is left in both columns is a real measurement of over-confidence rather than an artefact. The
- vertical half is [#372](https://github.com/jbrodovsky/strapdown-rs/issues/372).
-- **The ESKF's numbers moved furthest when #367 landed**, and in the right direction:
- horizontal containment 0.161 to 0.497, `npes` 1,249 to 68. That is the offset leaving the
- numerator. It is still not consistent -- 0.497 against an ideal of 0.9973 -- and what
- remains is a real finding rather than an artefact.
-- **`real_rbpf_slice__rbpf`'s consistency metrics are not gated.** When this was written `npes`
- read 5.7e25 and the real `nees` larger still, because the particle cloud collapsed to a
- horizontal sigma of nanometres on 17 of 1,200 epochs, which a mean of $e^2/P$ cannot survive
- ([#385](https://github.com/jbrodovsky/strapdown-rs/issues/385)). Roughening removed the
- collapse, and the restructure after Canciani & Raquet (2026-09-25) took `npes` to 10.3 and
- both channels' 3-sigma containment to 0.95: the filter is now close to consistent. The metrics stay ungated until the gate has a
- cross-platform tolerance ([#386](https://github.com/jbrodovsky/strapdown-rs/issues/386)).
-- **Several numbers here therefore record known defects rather than good behaviour**, which is
- what a two-sided gate is for. Each is annotated in the baseline file. When one is fixed the
+## What the tables are saying
+
+Read the rows rather than any summary here; these are the comparisons worth making.
+
+- **`real_clean` measures agreement with the aid.** Compare its `horiz RMSE` column with the
+ receiver's 3.81 m advertised accuracy (caveat 1). The three Kalman filters land within a few
+ centimetres of each other there, because on this row they are all mostly reporting the fix
+ they were just handed (caveat 2).
+- **`syn_cruise_1hz` is where the filters can actually separate**, because it is scored against
+ exact truth. Compare its three rows column by column; the attitude table shows what a 1 Hz
+ magnetometer and GNSS velocity make of yaw on a synthetic trajectory.
+- **The outage rows are dominated by the outages.** On `real_outage_60s__eskf` and both
+ `syn_outage_60s` rows, CEP50 stays within a few metres of the full-rate rows while RMSE, CEP95
+ and the maximum, an order of magnitude larger, are set by the coasts. That is the shape free-inertial drift gives: most
+ epochs are aided and accurate, and the error concentrates at the ends of the outages.
+- **`syn_dead_reckoning` is the unaided reference.** It is only 120 s long, and its
+ consistency columns are empty because dead reckoning reports no covariance.
+- **The real-data consistency columns say the filters are over-confident.** Their horizontal
+ and vertical containment sit well below 0.9973 and their NEES well above 3, while the
+ synthetic rows sit much closer to ideal. That is caveat 3 in numbers; `real_degraded` is the
+ extreme case for the reason in caveat 4.
+- **Several numbers record known defects rather than good behaviour**, which is what a two-sided
+ gate is for. Each is annotated with a `note` in `perf_baseline.json`. When one is fixed the
improvement side trips and asks for the diff that records it.
-
-## The vertical process-noise retune
-
-These numbers already include one deliberate change the gate was built to catch, and it is
-worth reading as a worked example of the workflow.
-
-`DEFAULT_PROCESS_NOISE_DENSITY`'s altitude entry was `1e-4` -- a 1 cm standard deviation,
-a tenth of the horizontal channel's 0.1 m, an asymmetry nothing ever justified. Issue #308 had
-fixed the *units* of the horizontal entries and deliberately left this one alone, recording
-that whether `1e-4` was the right *tuning* was a separate question. The consistency columns
-answered it: at `1e-4` three-sigma altitude containment was 0.88 on the synthetic trajectory
-and 0.44 on the recording, against an ideal of 0.9973. More than half the altitude errors on
-real data fell outside the uncertainty the filter reported for them.
-
-Three entries could have been blamed. Sweeping each alone over four decades, only the altitude
-position entry moves containment the right way -- the vertical-velocity entry is flat and costs
-a vertical-velocity RMSE growing from 0.34 to 4.37 m/s, and the accelerometer-bias entry makes
-containment *worse* while taking the real 60 s-outage horizontal RMSE from 291 m to 443 m. The
-entry is now `POSITION_PROCESS_NOISE_M_PER_ROOT_S²`, which makes the position block isotropic in
-standard deviation and lands on the knee of the measured curve.
-
-What it bought, and what it cost:
-
-| | before | after |
-|---|---:|---:|
-| `syn_cruise_1hz__eskf` 3-sigma vertical | 0.880 | **0.933** |
-| `syn_cruise_1hz__eskf` `npes` (ideal 3.0) | 5.653 | **4.795** |
-| `syn_outage_60s__eskf` horizontal RMSE | 137.66 m | **20.22 m** |
-| `syn_outage_60s__eskf` pitch RMSE | 1.500 deg | **0.205 deg** |
-| `syn_cruise_1hz__eskf` vertical RMSE | **0.665 m** | 0.836 m |
-| `syn_outage_60s__ukf` horizontal RMSE | **221.67 m** | 266.68 m |
-
-The vertical RMSE cost is the honest price: the old value bought that number by under-reporting
-its own error, and on the reference recording it is not paid at all -- vertical RMSE there
-improved slightly. (These synthetic figures have since moved again, and further, under #375 --
-see caveat 6. The numbers in this table are the ones that change measured, kept as its
-record.) The `syn_outage_60s__ukf` row is recorded but not endorsed: across the sweep
-its horizontal RMSE runs 222, 174, 267, 344 m while its yaw runs 105, 98, 21, 34 deg, so
-position degrades exactly where attitude improves fivefold. That row is
-[#371](https://github.com/jbrodovsky/strapdown-rs/issues/371) coasting an outage, and it does
-not respond monotonically to this or any other knob.
diff --git a/book/src/development/structure.md b/book/src/development/structure.md
deleted file mode 100644
index 782fdf4d..00000000
--- a/book/src/development/structure.md
+++ /dev/null
@@ -1 +0,0 @@
-# Project Structure
diff --git a/book/src/examples/configurations.md b/book/src/examples/configurations.md
index 2a9db591..24fdf571 100644
--- a/book/src/examples/configurations.md
+++ b/book/src/examples/configurations.md
@@ -2,73 +2,112 @@
Ready-to-run scenario files live in
[`examples/configs/`](https://github.com/jbrodovsky/strapdown-rs/tree/main/examples/configs).
-For the schema itself — every field, and the naming pitfall that silently disables a scenario
-— see [Configuration Files](../user-guide/configuration.md).
-
-`--config` supplies the whole run, so the subcommand's `-i`/`-o` are ignored alongside it —
-set `input:` and `output:` inside the file instead:
-
-```bash
-strapdown-sim --config examples/configs/simple_dropout.yaml
-```
-
-## Baseline
-
-| File | What it does |
+Each is a complete `SimulationConfig`; for the schema itself see
+[Configuration Files](../user-guide/configuration.md), and for every scheduler and fault field
+see [Schedulers and Faults Reference](../gnss/scenarios.md).
+
+Three things apply to all of them:
+
+- **`--config` supplies the whole run.** The subcommand's `-i`, `-o` and `--seed` are ignored
+ alongside it, so set `input` and `output` inside the file. Most of these files omit both, and
+ then read `input.csv` and write `output.csv` in the working directory.
+- **They declare the NED frame** by not setting `is_enu`. That is right for `strapdown-sim syn`
+ output. Sensor Logger exports are ENU, so add `is_enu: true` (or `is_enu = true`) to run one
+ against a phone recording; a wrong declaration is rejected before the run starts.
+- **Duty cycles start with their OFF window** unless `start_phase_s` gives an initial ON
+ window (see [`DutyCycle`](../gnss/scenarios.md#dutycycle)). Several files below set
+ `start_phase_s: 0.0`, so their runs begin in an outage.
+
+Every file in the tables below was run against a 600 s trajectory from
+`strapdown-sim syn -o synthetic.csv --duration-s 600 --seed 42`, with `input` and `output`
+added, and completed. `geonav_example.toml` needs a binary built with `--features geonav` and
+map files beside the input.
+
+## Scenario files
+
+All of these are `mode: closed-loop` with the default filter (the ESKF), unless noted.
+
+### Baseline
+
+| File | Scheduler | Fault | What it models |
+|---|---|---|---|
+| `baseline.yaml` | `pass_through` | `none` | no degradation; the reference to compare the others against |
+
+### Availability
+
+| File | Scheduler | Fault | What it models |
+|---|---|---|---|
+| `sched_10s.yaml` | `fixed_interval`, 10 s | `none` | a reduced update rate |
+| `duty_10on_2off.yaml` | `duty_cycle`, 10 s on / 2 s off, initial 1 s on | `none` | brief periodic outages |
+| `simple_dropout.yaml` | `duty_cycle`, 120 s on / 30 s off, no initial on | `none` | bridges and tall buildings; starts with a 30 s outage |
+| `extended_gnss_denied.yaml` | `duty_cycle`, 60 s on / 300 s off, no initial on | `none` | tunnels and sustained jamming; starts with a 300 s outage |
+
+`extended_gnss_denied.yaml` shows dead-reckoning quality most clearly: five minutes is long
+enough for consumer-MEMS drift to dominate. Because it sets no initial ON window, the first
+five minutes are an outage before the filter has seen any fix; set `start_phase_s` if you want
+the filter to converge first. See [Tutorial: GNSS Degradation](./tutorial-gps-degradation.md).
+
+### Accuracy
+
+| File | Scheduler | Fault | What it models |
+|---|---|---|---|
+| `degraded_fullrate.yaml` | `pass_through` | `degraded` (ρ 0.99, σ 3 m; ρ 0.95, σ 0.3 m/s; `r_scale` 5) | AR(1)-correlated error at full rate |
+| `degraded_5s.yaml` | `fixed_interval`, 5 s | `degraded`, same values | reduced rate and corruption together |
+| `gnss_degradation.yaml` | `fixed_interval`, 10 s | `degraded`, same values | the same idea at 10 s |
+| `gnss_degradation.toml` | as above | as above | the same scenario in TOML |
+| `gnss_degradation.json` | as above | as above | the same scenario in JSON |
+| `combo.yaml` | `fixed_interval`, 5 s | `degraded` (ρ 0.995, σ 4 m; ρ 0.97, σ 0.35 m/s; `r_scale` 5) | reduced rate plus degraded accuracy |
+| `particle_filter_comparison.yaml` | `fixed_interval`, 5 s | `degraded` (σ 5 m, 0.5 m/s) | the closed-loop half of a filter comparison; see below |
+
+None of these sets `tau_pos_s` or `tau_vel_s`, so their `sigma_*` values are per-fix
+innovations and their correlation times depend on the fix interval; see
+[Fault Simulation](../gnss/fault-simulation.md#correlation-time-and-the-fix-interval).
+
+`combo.yaml` combines a scheduler with a fault. It is **not** the `combo` fault kind, which
+chains several fault models on the same fix; no shipped example uses that kind, and
+[Schedulers and Faults Reference](../gnss/scenarios.md#combo) shows its syntax.
+
+`particle_filter_comparison.yaml` is, despite its name, a closed-loop file. Its comments
+describe the comparison: copy it, change the copy's `mode` to `particle-filter` and both
+files' `output`, and run each with `--config`.
+
+### Spoofing
+
+| File | Scheduler | Fault | What it models |
+|---|---|---|---|
+| `slowbias.yaml` | `pass_through` | `slow_bias`, 0.02 m/s north, `q_bias` 1e-6 | soft spoofing: each fix looks plausible |
+| `slowbias_rot.yaml` | `pass_through` | `slow_bias`, as above with `q_bias` 5e-6 and the direction rotating at 1e-3 rad/s | the same, drifting in a turning direction |
+| `hijack.yaml` | `pass_through` | `hijack`, 50 m north from 120 s for 60 s | hard spoofing: an abrupt offset |
+| `combo_duty_hijack.yaml` | `duty_cycle`, 10 s on / 3 s off, no initial on | `hijack`, 10 m north and 10 m east from 150 s for 120 s | duty-cycled availability plus hard spoofing |
+
+Spoofing scenarios are worth pairing with an innovation gate (`--gate-confidence` on the
+command line). A `hijack` produces a large normalized innovation squared the moment it starts,
+which a chi-squared gate can reject, while a `slow_bias` is designed to stay under that
+threshold.
+
+### Filter, I/O and geophysical settings
+
+| File | What it shows |
|---|---|
-| `baseline.yaml` | No degradation. The reference every other scenario is compared against. |
+| `closed-loop-ukf.toml` | selecting the UKF in `[closed_loop]`, with `[logging]` and an undegraded `[aiding]` section |
+| `parallel_example.toml` | a directory as `input` and `output`, `parallel = true` to process its files concurrently, and a log file |
+| `geonav_example.toml` | a `[geophysical]` section with gravity and magnetic aiding on the UKF; see [Geophysical Navigation](../geonav/overview.md) |
-## Availability
-
-| File | What it does |
-|---|---|
-| `sched_10s.yaml` | One fix every 10 s, uncorrupted. A reduced update rate. |
-| `duty_10on_2off.yaml` | 10 s available, 2 s denied, repeating. Brief periodic outages. |
-| `simple_dropout.yaml` | 2 minutes available, 30 s denied. Bridges and tall buildings. |
-| `extended_gnss_denied.yaml` | 1 minute available, 5 minutes denied. Tunnels and sustained jamming. |
-
-`extended_gnss_denied.yaml` is the one that shows dead-reckoning quality most clearly: five
-minutes is long enough for consumer-MEMS drift to dominate completely. Expect errors in the
-hundreds of metres to kilometres, and see
-[Tutorial: GPS Degradation](./tutorial-gps-degradation.md) for why the figure is usually
-smaller than double-integrating the sensor's bias would predict.
-
-## Accuracy
-
-| File | What it does |
-|---|---|
-| `degraded_fullrate.yaml` | Full rate, AR(1)-correlated position and velocity error. |
-| `degraded_5s.yaml` | Every 5 s *and* degraded. Scheduling and corruption together. |
+## Other files
-## Spoofing
-
-| File | What it does |
-|---|---|
-| `slowbias.yaml` | A slowly drifting offset. Soft spoofing — each fix looks plausible. |
-| `slowbias_rot.yaml` | The same, with the drift direction rotating. |
-| `hijack.yaml` | An abrupt offset during a fixed window. Hard spoofing. |
-
-Spoofing scenarios are the ones worth pairing with an innovation gate: a `hijack` produces a
-large normalized innovation squared the moment it starts, which a chi-squared gate rejects,
-while a `slow_bias` is specifically designed to stay under that threshold.
-
-## Combined
-
-| File | What it does |
-|---|---|
-| `combo.yaml` | Reduced rate plus degraded accuracy. |
-| `combo_duty_hijack.yaml` | Duty-cycled availability plus hard spoofing. |
-
-## Other formats
-
-`gnss_degradation.json` and `gnss_degradation.toml` are the same schema in the other two
-supported formats. The `json/` subdirectory is a different thing: those files are
-`{name, args}` CLI-invocation presets, not scenario configs, and they use the command line's
-vocabulary rather than the config schema's.
+- `README.md` in the directory repeats this catalogue with each scheduler and fault option
+ written out.
+- `json/` holds ten `{"name", "args"}` files (`baseline`, `combo`, `combo_duty_hijack`,
+ `degraded_5s`, `degraded_fullrate`, `duty_10on_2off`, `hijack`, `sched_10s`, `slowbias`,
+ `slowbias_rot`). They are **not** configuration files: each is a list of command-line
+ arguments for the same scenario, in the command line's vocabulary (`--sched fixed`,
+ `--fault slowbias`) rather than the configuration file's (`fixed_interval`, `slow_bias`).
+ Nothing in the repository reads them, and `--config` would reject them.
## Running the set
-Because `--config` ignores `-i`/`-o`, a batch varies the paths *in the file*:
+Because `--config` ignores `-i`/`-o`, a batch varies the paths *in the file*. This writes a
+copy of each YAML scenario pointed at one input and a separate output, then runs it:
```bash
mkdir -p results .scenarios
@@ -81,3 +120,17 @@ for config in examples/configs/*.yaml; do
strapdown-sim --config ".scenarios/${name}.yaml"
done
```
+
+Passing `-o "results/${name}.csv"` instead would be silently ignored, and every scenario would
+write to the same `output.csv`.
+
+## The experiment recipes in `conf/`
+
+`conf/` holds the fifteen configurations the project's own experiments run through the
+`justfile`: `{ukf,ekf,rbpf}_{truth,degraded,grav,mag,both}.toml`, plus the same fifteen under
+`conf/real/` for the frozen real-sensor arm. They read a directory of preprocessed recordings
+(`data/input`, which is not distributed), declare `is_enu = true`, and carry long comments
+explaining every value. `*_truth` is undegraded, `*_degraded` is the single interference
+profile described in [Fault Simulation](../gnss/fault-simulation.md), and
+`*_{grav,mag,both}` add geophysical aiding to that profile. They are worth reading as worked
+examples even without the data.
diff --git a/book/src/examples/tutorial-basic.md b/book/src/examples/tutorial-basic.md
index c922e424..09ed4392 100644
--- a/book/src/examples/tutorial-basic.md
+++ b/book/src/examples/tutorial-basic.md
@@ -49,9 +49,9 @@ without a recovery path the next fix disagrees by *more*, is rejected harder, an
rejection quietly turns into dead reckoning for the rest of the run. `GateRecovery` is what
prevents that: every rejection inflates the filter's uncertainty in the directions that
measurement observed -- so the next fix of the same kind is judged against a covariance that
-grew -- and after five consecutive rejections a measurement is applied regardless, on the
-reasoning that a belief contradicted five times running is likelier to be wrong than the sensor
-contradicting it. `set_gate_recovery`
+grew -- and when five measurements in a row fail the gate, the fifth is applied regardless
+(four rejections, then a forced update), on the reasoning that a belief contradicted five times
+running is likelier to be wrong than the sensor contradicting it. `set_gate_recovery`
tunes it, `GateRecovery::none()` switches it off, and `UpdateOutcome::forced` says whether an
accepted fix was accepted on its merits or by that escape.
@@ -80,13 +80,17 @@ altitude fixed. If a first integration produces those two symptoms together, che
```text
start: NavSolution(t: 0.000 s, 39.9500000 deg, -75.1600000 deg, 12.00 m, ...)
-after 60 s: NavSolution(t: 60.000 s, 39.9553996 deg, -75.1600000 deg, 12.14 m, ...)
-travelled 600.0 m north; expected 600.0 m (difference 0.00 m)
-position uncertainty (1-sigma): 3.01 m north, 2.32 m east, 1.08 m vertical
+after 60 s: NavSolution(t: 60.000 s, 39.9554004 deg, -75.1600000 deg, 12.11 m, ...)
+travelled 600.1 m north; expected 600.0 m (difference 0.10 m)
+position uncertainty (1-sigma): 0.80 m north, 0.78 m east, 1.04 m vertical
```
-600 m in 60 s at 10 m/s, and the reported north uncertainty settles near the 3 m accuracy the
-synthetic fixes advertise, which is what a correctly-tuned filter should do: with no vehicle
-dynamics to exploit it cannot do better than its aiding source.
+600 m in 60 s at 10 m/s, to a tenth of a metre. The reported uncertainty is well inside the 3 m
+horizontal and 5 m vertical the fixes advertise, and that is correct rather than optimistic: the
+filter has fused sixty position fixes and sixty 0.2 m/s velocity fixes through a motion model
+that lets the vehicle wander very little between them, and the combination is tighter than any
+single fix. (This page used to show about 3 m here and read it as the filter being unable to do
+better than its aiding source; the current code prints the numbers above, and a filter that
+averages repeated fixes is expected to beat each one.)
Next: [Tutorial: GPS Degradation](./tutorial-gps-degradation.md).
diff --git a/book/src/examples/tutorial-gps-degradation.md b/book/src/examples/tutorial-gps-degradation.md
index c0c386f3..89ff59b8 100644
--- a/book/src/examples/tutorial-gps-degradation.md
+++ b/book/src/examples/tutorial-gps-degradation.md
@@ -15,15 +15,16 @@ consumer MEMS part after turn-on.
```text
t (s) error (m) GNSS
- 60 0.0 ok
- 70 0.2 denied
- 100 2.0 denied
- 140 14.9 denied
- 180 49.4 denied
- 190 0.0 ok
+ 60 0.2 ok
+ 70 0.4 denied
+ 100 2.6 denied
+ 140 16.8 denied
+ 180 54.0 denied
+ 190 0.1 ok
```
-Flat while aided, growing while coasting, and back to zero within a single fix of recovery.
+Flat while aided, growing while coasting, and back to a decimetre within a single fix of
+recovery. (The example prints every 10 s; these are a selection of its rows.)
The growth is quadratic because a constant acceleration error integrates twice into position.
## Why the drift is smaller than the textbook figure
@@ -34,19 +35,19 @@ Double-integrating the bias over the outage predicts 360 m:
0.5 × 0.05 m/s² × (120 s)² = 360 m
```
-The observed error is 49.4 m, seven times smaller. The reason is worth reading off the filter
+The observed error is 54.0 m, nearly seven times smaller. The reason is worth reading off the filter
state rather than guessing at, and the example prints it:
```text
accelerometer bias present: 0.0500 m/s^2 (forward axis)
bias the filter estimated: 0.0001 m/s^2 <- it barely moved
-pitch error at outage start: 0.2987 deg
-gravity that tilt leaks forward: 0.0511 m/s^2 <- nearly cancels the bias
+pitch error at outage start: 0.2879 deg
+gravity that tilt leaks forward: 0.0493 m/s^2 <- nearly cancels the bias
```
The filter did **not** estimate the bias. It absorbed it into *attitude* instead: it believes
-the vehicle is pitched nose-up by three tenths of a degree, and the gravity that tilt leaks
-into the forward axis very nearly cancels the bias.
+the vehicle is pitched by just under three tenths of a degree, and the gravity that tilt leaks
+into the forward axis, 0.0493 m/s², very nearly cancels the 0.05 m/s² bias.
That is not a defect. A constant forward specific-force bias and a small pitch error produce
the same horizontal acceleration signature, so position and velocity aiding cannot separate
diff --git a/book/src/examples/tutorial-particle-filter.md b/book/src/examples/tutorial-particle-filter.md
index 3c26e977..5c954fb4 100644
--- a/book/src/examples/tutorial-particle-filter.md
+++ b/book/src/examples/tutorial-particle-filter.md
@@ -1 +1,251 @@
# Tutorial: Particle Filter
+
+This tutorial runs the [Rao-Blackwellized particle filter](../filters/rbpf.md) end to end with
+`strapdown-sim pf`: generate a synthetic drive and its exact truth, run the filter from flags and
+then from a configuration file adapted from the `conf/rbpf_*` recipes, score both against truth,
+and see why the simulator does not use the paper's horizontal process noise. Every command and
+every block of output below was produced by the `strapdown-sim` 1.0.0 binary and the examples in
+`core/examples/`; your timestamps will differ.
+
+## A trajectory and its truth
+
+`syn` with the same flags and seed writes the noisy sensor log and, with `--no-noise`, the exact
+trajectory it was derived from. This one starts in Philadelphia and drives due north at 15 m/s
+for ten minutes with a consumer-grade IMU sampled at 10 Hz (the `syn` defaults). A negative
+value has to be attached with `=`, or the parser reads it as a flag.
+
+```bash
+strapdown-sim syn -o drive.csv --duration-s 600 --seed 42 \
+ --latitude-deg 39.95 --longitude-deg=-75.16 --altitude-m 50 --velocity-north-mps 15
+strapdown-sim syn -o drive_truth.csv --duration-s 600 --seed 42 \
+ --latitude-deg 39.95 --longitude-deg=-75.16 --altitude-m 50 --velocity-north-mps 15 --no-noise
+```
+
+```text
+2026-10-01 21:44:03.088 [INFO] - Generated 6000 synthetic records (600.0 s at 10 Hz)
+2026-10-01 21:44:03.097 [INFO] - Sensor records written to drive.csv
+2026-10-01 21:44:03.155 [INFO] - Generated 6000 synthetic records (600.0 s at 10 Hz)
+2026-10-01 21:44:03.160 [INFO] - Truth trajectory written to drive_truth.csv
+```
+
+`syn` output is NED, which is the default for every subcommand, so no `--enu` is needed. (The
+`conf/` recipes set `is_enu = true` because they read ENU Sensor Logger exports.)
+
+## Run `pf` with its defaults
+
+```bash
+strapdown-sim pf -i drive.csv -o pf_out.csv
+```
+
+```text
+2026-10-01 21:44:03.164 [INFO] - Processing file: drive.csv
+2026-10-01 21:44:03.185 [INFO] - Read 6000 records from drive.csv
+2026-10-01 21:44:03.186 [INFO] - Mechanizing input as NED: mean vertical specific force over the first 10 record(s) is -9.775 m/s^2 against a local gravity of 9.801 m/s^2
+2026-10-01 21:44:04.269 [INFO] - Results written to pf_out.csv
+2026-10-01 21:44:04.269 [INFO] - Particle filter simulation complete
+```
+
+The "Mechanizing input as NED" line is the frame check: the mean vertical specific force has the
+sign NED predicts, so the declared frame is accepted.
+
+With no flags the filter runs 100 particles, uses a horizontal process noise of `[1, 1]` m/√s and
+takes every GNSS fix in the file, here one per record (10 Hz). `pf_out.csv` has the same columns
+as a `cl` run (see [Output Format](../user-guide/output-format.md)), one row per IMU sample. The
+six IMU-bias columns are zero: the RBPF carries no bias states.
+
+## Comparing against truth
+
+`core/examples/score_run.rs` loads an output CSV and a truth CSV and scores them with
+`metrics::evaluate`, the reduction the accuracy baseline is gated on:
+
+```rust,ignore
+{{#include ../../../core/examples/score_run.rs:score}}
+```
+
+```bash
+cargo run -p strapdown-core --example score_run -- pf_out.csv drive_truth.csv
+```
+
+```text
+aligned samples 5990
+horizontal RMSE 0.920 m
+horizontal CEP50 0.758 m
+horizontal CEP95 1.619 m
+horizontal max 2.706 m
+vertical RMSE 0.888 m
+horizontal velocity RMSE 0.193 m/s
+yaw RMSE 0.404 deg
+position NEES (consistent at 3) 3.534
+3-sigma horizontal containment 1.000
+```
+
+Rows are matched by timestamp, which works because `syn` always starts at
+2025-01-01T00:00:00Z; the first ten aligned samples (one second) are skipped as initialization.
+Read the two consistency lines together, as
+[metrics](../user-guide/library.md#scoring-a-run-against-truth) explains: the NEES compares the
+error with the full position covariance, and containment counts how often the error lies inside
+three sigma.
+
+## A configuration adapted from `conf/rbpf_truth.toml`
+
+The recipes under `conf/` describe the repository's own experiments: ENU phone recordings in
+`data/input`, logs written to `log/`, map biases in `[geophysical]`. For a `syn` trajectory, keep
+their `[particle_filter]` section and change the rest: the input and output paths, `is_enu =
+false`, no `[geophysical]` section, and an `[aiding]` scheduler that thins the 10 Hz synthetic
+fixes to 1 Hz, the rate the recordings' receivers actually deliver. `[aiding]` is the section's
+name; the recipes' `[gnss_degradation]` is accepted as an alias.
+
+```toml
+# rbpf_syn.toml: particle filter on a synthetic NED trajectory, adapted from conf/rbpf_truth.toml.
+input = "drive.csv"
+output = "pf_config_out.csv"
+mode = "particle-filter"
+is_enu = false # `syn` writes NED; the conf/ recipes read ENU Sensor Logger exports
+seed = 42
+
+[particle_filter]
+num_particles = 1000
+position_init_std_m = [10.0, 10.0, 5.0]
+velocity_init_std_mps = 1.0
+attitude_init_std_rad = 0.1
+velocity_process_noise_std_mps = 1e-3
+attitude_process_noise_std_rad = 0.01
+horizontal_process_noise_std_m = [1.0, 1.0]
+baro_loop_time_constant_s = 10.0
+baro_error_std_m = 8.3
+baro_error_time_constant_s = 3600.0
+vertical_accel_error_init_std_mps2 = 0.1
+effective_sample_threshold = 1.0
+roughening_factor = 0.2
+
+[aiding]
+seed = 42
+
+[aiding.scheduler]
+kind = "fixed_interval"
+interval_s = 1.0
+phase_s = 0.0
+
+[aiding.fault]
+kind = "none"
+```
+
+A configuration file supplies the whole run, so it is passed on its own:
+
+```bash
+strapdown-sim --config rbpf_syn.toml
+cargo run -p strapdown-core --example score_run -- pf_config_out.csv drive_truth.csv
+```
+
+```text
+2026-10-01 21:44:12.099 [INFO] - Loading configuration from rbpf_syn.toml
+2026-10-01 21:44:12.099 [INFO] - Configuration loaded successfully
+2026-10-01 21:44:12.099 [INFO] - Mode: ParticleFilter
+...
+2026-10-01 21:44:12.117 [INFO] - Running particle filter simulation
+2026-10-01 21:44:16.836 [INFO] - Results written to pf_config_out.csv
+```
+
+```text
+aligned samples 5990
+horizontal RMSE 1.845 m
+horizontal CEP50 1.613 m
+horizontal CEP95 3.007 m
+horizontal max 4.470 m
+vertical RMSE 1.415 m
+horizontal velocity RMSE 0.479 m/s
+yaw RMSE 0.418 deg
+position NEES (consistent at 3) 3.056
+3-sigma horizontal containment 1.000
+```
+
+The [RBPF configuration table](../filters/rbpf.md#configuration) explains every key. Three are
+worth knowing before changing anything:
+
+- `horizontal_process_noise_std_m`: see the next section.
+- `effective_sample_threshold = 1.0` resamples after every update, as Canciani and Raquet do.
+- `roughening_factor = 0.2` jitters the cloud after resampling so it cannot collapse onto copies
+ of one particle; `0.0` reproduces the paper.
+
+The `[geophysical]` section and the `*_variation_*` keys only matter for map-aided runs, which
+need gravity or magnetic anomaly maps; see [Geophysical Navigation](../geonav/overview.md).
+
+## Why not the paper's zero horizontal noise
+
+Canciani and Raquet put no process noise on the sampled horizontal position (their eq. 19). The
+library's `RbpfConfig` keeps that default; `strapdown-sim` does not. On the same trajectory with
+1 Hz fixes:
+
+```bash
+strapdown-sim pf -i drive.csv -o pf_zero.csv --sched fixed --interval-s 1 \
+ --horizontal-process-noise-std-m 0 0
+cargo run -p strapdown-core --example score_run -- pf_zero.csv drive_truth.csv
+```
+
+```text
+aligned samples 5990
+horizontal RMSE 2.025 m
+horizontal CEP50 1.624 m
+horizontal CEP95 3.550 m
+horizontal max 6.068 m
+vertical RMSE 1.409 m
+horizontal velocity RMSE 0.509 m/s
+yaw RMSE 0.603 deg
+position NEES (consistent at 3) 9.786
+3-sigma horizontal containment 0.929
+```
+
+The same command with the default `1 1` (drop the last flag) scores a horizontal RMSE of
+1.870 m, a NEES of 3.141 and a containment of 1.000. On this short, clean synthetic drive the
+zero-noise run finishes and its error is only slightly larger, but its covariance is no longer
+honest: a NEES three times the ideal and 93% three-sigma containment mean the filter claims more
+certainty than it has. With zero noise each epoch's time update is a noiseless observation of
+the velocity and tilt errors, which moves their uncertainty out of the shared covariance and
+into the particles' spread, and resampling on metre-level fixes then destroys that spread. On
+the reference recording that overconfidence grows until the solution runs kilometres off;
+[RBPF](../filters/rbpf.md#horizontal-process-noise-why-the-default-is-1-ms) gives the full
+account.
+
+## The same trajectory through the ESKF
+
+For a reference point, run the default Kalman filter on the same input with the same 1 Hz
+schedule and score it the same way:
+
+```bash
+strapdown-sim cl -i drive.csv -o cl_out.csv --sched fixed --interval-s 1
+cargo run -p strapdown-core --example score_run -- cl_out.csv drive_truth.csv
+```
+
+```text
+aligned samples 5990
+horizontal RMSE 1.574 m
+horizontal CEP50 1.380 m
+horizontal CEP95 2.653 m
+horizontal max 3.994 m
+vertical RMSE 1.183 m
+horizontal velocity RMSE 0.371 m/s
+yaw RMSE 0.498 deg
+position NEES (consistent at 3) 2.879
+3-sigma horizontal containment 0.999
+```
+
+One synthetic straight-line drive is not a ranking of the two filters. The RBPF exists for
+map-aided navigation, where the measurement is a nonlinear, often multimodal function of
+position; with GNSS fixes alone, as here, it has nothing to exploit that a Kalman filter cannot.
+The gated comparison across scenarios, including the RBPF's own row, is on
+[Performance Baselines](../development/performance.md), and
+[RBPF](../filters/rbpf.md#sparse-gnss-what-this-structure-cannot-recover-from) documents a regime
+(one fix a minute) in which it diverges where the EKF does not.
+
+For the unaided baseline, run
+`strapdown-sim dr -i drive.csv -o dr_out.csv`. Scored the same way, it reports no consistency metrics (a
+dead-reckoning run has no covariance) and a horizontal error that reaches 108.8 km by the end, a
+horizontal RMSE of 41.3 km, on this consumer-grade IMU.
+
+## Where next
+
+- [RBPF](../filters/rbpf.md): structure, configuration keys and departures from the paper.
+- [Particle Filter](../user-guide/particle-filter.md) in the user guide: the `pf` subcommand's
+ flags.
+- [Schedulers and Faults](../gnss/scenarios.md): outages, reduced rates and spoofing for any of
+ the runs above.
diff --git a/book/src/faq.md b/book/src/faq.md
index bb6eb971..67f244e7 100644
--- a/book/src/faq.md
+++ b/book/src/faq.md
@@ -1,132 +1,177 @@
# Frequently Asked Questions
-## General Questions
+## General
-### What is Strapdown-rs?
+### What is strapdown-rs?
-Strapdown-rs is a Rust library for implementing strapdown inertial navigation systems (INS). It provides core functionality for processing IMU data to estimate position, velocity, and orientation.
+A Rust implementation of strapdown inertial navigation and of the tools to study it under GNSS
+degradation. It is three crates: `strapdown-core` (the library, imported as `strapdown`), the
+`strapdown-sim` command-line simulator, and the experimental `strapdown-geonav` for gravity
+and magnetic map aiding. See the [Introduction](./introduction.md).
-### Who should use Strapdown-rs?
+### Who is it for?
-Strapdown-rs is designed for:
-- Researchers working on navigation systems
-- Engineers developing autonomous systems
-- Students learning about inertial navigation
-- Anyone needing a high-performance INS implementation in Rust
+Researchers, students and engineers who want reproducible inertial-navigation experiments:
+the same input, configuration and seed give the same output, and the GNSS outages, noise and
+spoofing are configured rather than hand-edited into the data.
### What coordinate frames are supported?
-The library primarily uses the North-East-Down (NED) local-level frame. The 9-state vector includes:
-- Position: latitude, longitude, altitude
-- Velocity: northward, eastward, downward
-- Attitude: roll, pitch, yaw
+North-East-Down (NED) is the default local-level frame, as in Groves. East-North-Up (ENU) is an
+explicit opt-in: `--enu` on the command line or `is_enu = true` in a config file. The 9-state
+navigation vector is:
+
+- position: latitude, longitude, altitude (height above the ellipsoid, positive up in both
+ frames);
+- velocity: north, east and vertical, where vertical is positive **down** in NED and positive
+ **up** in ENU (the output column is `velocity_vertical`);
+- attitude: roll, pitch, yaw.
+
+See [Coordinate Frames](./user-guide/coordinate-frames.md).
### Is this production-ready?
-Strapdown-rs is primarily intended for research and development. While the code is well-tested and prioritizes correctness, it is still under active development as part of ongoing PhD research.
+It is research software. It is tested and prioritises correctness, but it is developed as part
+of ongoing PhD research, and `strapdown-geonav` in particular is experimental.
-## Installation and Setup
+## Installation and setup
### What are the system requirements?
-See the [System Requirements](./installation/requirements.md) page for detailed information. In summary:
-- Rust 1.91 or later
-- A C/C++ compiler and cmake 3.26+, but only for features that use a C library
-- No system libraries to install at build time
-- libfontconfig at *run* time, if you use `strapdown-sim`'s plotting (a default feature).
- It is loaded on demand, so a machine without it builds fine and fails at the first plot
-- Supported on Linux, macOS, and Windows
+See [System Requirements](./installation/requirements.md). In summary:
+
+- Rust 1.91 or later (`rust-toolchain.toml` fetches it);
+- a C compiler for features that bundle a C library (`strapdown-sim`'s default `plotting`,
+ `mcap`), and a C/C++ compiler with cmake 3.26 or newer for HDF5, netCDF and `geonav`;
+ `cargo build -p strapdown-core` needs neither;
+- no system libraries at build time;
+- libfontconfig at *run* time, for `strapdown-sim`'s `--plot` (the `plotting` feature, on by
+ default). It is loaded on demand, so a machine without it builds fine and fails at the
+ first plot;
+- Linux, macOS or Windows.
### Do I need to install HDF5 and NetCDF?
No. They are compiled from vendored sources that ship as ordinary cargo dependencies, along
with zlib and freetype, so nothing is searched for on your machine. What you need instead is a
-C/C++ compiler and cmake 3.26 or newer to build them with.
-
-They are used for:
-- HDF5: binary data storage for `TestDataRecord` and `NavigationResult`
-- NetCDF: geophysical map data for the geonav features
-
-Neither is on by default in `strapdown-core`, so if you only need the core INS functionality
-you need no C toolchain either: `cargo build -p strapdown-core` uses none.
+C/C++ compiler and cmake 3.26 or newer to build them with. HDF5 and NetCDF back the optional
+`hdf5`/`netcdf` output methods on `NavigationResult` and `TestDataRecord`, and NetCDF also
+reads the geophysical maps.
### How do I install on Windows?
Install the MSVC toolchain from Visual Studio Build Tools plus
-[cmake](https://cmake.org/download/). vcpkg is no longer needed, since nothing is looked up on
-the system. WSL2 also works if you prefer a Linux environment.
+[cmake](https://cmake.org/download/). vcpkg is not needed, since nothing is looked up on the
+system. WSL2 also works. See [Installation](./installation/installation.md).
-See [Installation](./installation/installation.md) for details.
-
-## Usage Questions
+## Usage
### What data format does strapdown-sim accept?
-The simulation expects CSV files with IMU and GNSS data following the Sensor Logger app format. See [Input Data Format](./user-guide/data-format.md) for details.
+CSV files in the Sensor Logger app's format: timestamped IMU, GNSS and optional barometer and
+magnetometer columns. `strapdown-sim syn` writes the same format from a synthetic trajectory.
+See [Input Data Format](./user-guide/data-format.md).
+
+### What does it write?
+
+CSV. Every path through `strapdown-sim` ends in `NavigationResult::to_csv`. An `-o` value ending
+in `.csv` is a file; one ending in another data format's extension (`.h5`, `.nc`, `.mcap`,
+`.parquet` and so on) is refused; any other value is a directory to write `.csv`
+into. HDF5, NetCDF and MCAP writers exist as library methods on `NavigationResult` behind cargo
+features, not as CLI options. See [Output Format](./user-guide/output-format.md).
+
+### My run stops with `InvalidConfiguration { field: "is_enu", ... }`
+
+The data's frame does not match the one you declared. Sensor Logger exports are ENU, so pass
+`--enu` (or set `is_enu = true` in the config file); `syn` output is NED, so leave it off. The
+check compares the leading records' vertical specific force with what the declared frame
+expects at rest, and the message says which way round it is.
-### Which filter should I use: EKF, UKF, or Particle Filter?
+### Which filter should I use?
-- **EKF**: Fastest, works well for mildly nonlinear systems
-- **UKF**: Better accuracy for highly nonlinear systems, 2-3x slower than EKF
-- **Particle Filter**: Best for non-Gaussian distributions and multimodal scenarios
+- **ESKF** (`cl`, the default): the error-state Kalman filter. Start here.
+- **EKF** (`cl --filter ekf`) and **UKF** (`cl --filter ukf`): the full-state alternatives,
+ and the two Kalman filters that accept geophysical aiding.
+- **Particle filter** (`pf`): the Rao-Blackwellized particle filter, the only particle filter
+ in the crate. It is built for map-aided navigation, where the measurement is a nonlinear,
+ possibly ambiguous function of position.
-See [Filter Comparison](./filters/comparison.md) for detailed analysis.
+No speed comparison is published, because none has been measured. For accuracy, see
+[Filter Comparison](./filters/comparison.md) and [Performance Baselines](./development/performance.md).
### Can I use my own sensor data?
-Yes! You'll need to convert your data to the expected CSV format. The library is designed to work with standard IMU (gyroscope and accelerometer) and GNSS (position) measurements.
+Yes: convert it to the input CSV format above. Any IMU (accelerometer and gyroscope) with GNSS
+position and velocity will do; barometer and magnetometer columns are optional.
### How do I simulate GNSS outages?
-Use the GNSS fault simulation features in the configuration file:
+With a scheduler. On the command line, a duty cycle of 100 s available and 50 s denied:
-```toml
-[gnss]
-dropout_probability = 0.1 # 10% chance of dropout
-reduced_update_rate = 0.5 # Half the normal rate
+```bash
+strapdown-sim cl -i input.csv -o output.csv --sched duty --on-s 100 --off-s 50
```
-See [GNSS Degradation Scenarios](./gnss/fault-simulation.md) for more options.
+or one fix a minute with `--sched fixed --interval-s 60`. In a config file the same goes in the
+`[aiding]` section:
-## Performance Questions
+```toml
+[aiding.scheduler]
+kind = "duty_cycle"
+on_s = 100.0
+off_s = 50.0
+start_phase_s = 0.0
+```
-### How fast is Strapdown-rs?
+Note that a duty cycle starts with its OFF window unless `start_phase_s` (`--duty-phase-s`)
+gives an initial ON window. Noise, bias and spoofing are fault models (`--fault`). See
+[Schedulers and Faults Reference](./gnss/scenarios.md) for every option.
-Performance varies by filter type and configuration:
-- **EKF**: ~10,000-20,000 updates/second
-- **UKF**: ~3,000-5,000 updates/second
-- **Particle Filter**: Depends on particle count (100 particles: ~500 updates/second)
+## Performance
-These are approximate figures on modern hardware and will vary based on your system.
+### How fast is it?
+
+There are no published throughput figures, because none have been measured; nothing in CI
+tracks wall-clock time yet. What is measured and gated is navigation *accuracy*: see
+[Performance Baselines](./development/performance.md).
### Can I run simulations in parallel?
-The current implementation processes data sequentially as navigation is inherently a sequential process. However, the particle filter implementation can utilize multiple cores for particle processing.
+Across files, yes. Point the input at a directory and pass `--parallel`
+(`strapdown-sim --parallel cl -i dir/ -o out/`), or set `parallel = true` in a config file, and
+the files are processed concurrently on a thread pool. `--parallel` works the same way with
+`dr`, `cl`, `pf` and `--config`; `syn`, `config` and `ol` refuse it. Each file's run is itself
+sequential, as navigation is.
-### How much memory does it use?
+### The particle filter is slow
-Memory usage is modest:
-- Core library: ~10-50 MB
-- Simulations: Depends on data size and filter configuration
-- Particle filters: Linear with particle count
+Its cost grows with the number of particles, so reduce `--num-particles` (or `num_particles` in
+`[particle_filter]`). If you do not need map aiding, a Kalman filter (`cl`) is the usual
+choice.
-## Development Questions
+## Development
### How can I contribute?
-We welcome contributions! Please see the [Contributing Guide](./development/contributing.md) and reach out to the project maintainer before starting major work.
+See [Contributing](./development/contributing.md), and contact the maintainer before starting
+major work.
### Where is the API documentation?
-Full API documentation is available at [docs.rs/strapdown-core](https://docs.rs/strapdown-core). This book focuses on high-level concepts and usage patterns.
+The rustdoc is published with this book; [API Documentation](./api/index.md) links it and maps
+the modules. It will also be on docs.rs once the crates are published with v1.0.0.
-### Can I use this in my commercial project?
+### Can I use this in a commercial project?
-Yes! Strapdown-rs is licensed under the MIT License, which allows commercial use. See the [LICENSE](https://github.com/jbrodovsky/strapdown-rs/blob/main/LICENSE) file for details.
+The code is MIT licensed, which allows commercial use. See the
+[LICENSE](https://github.com/jbrodovsky/strapdown-rs/blob/main/LICENSE) file.
### How do I cite this work?
-If you use Strapdown-rs in your research, please cite the JOSS paper:
+The JOSS paper is under review
+([openjournals/joss-reviews#11377](https://github.com/openjournals/joss-reviews/issues/11377)).
+Until it is published, cite the software with the repository's `CITATION.cff` (GitHub's "Cite
+this repository" button). See [Publications and Links](./resources/publications.md).
[](https://joss.theoj.org/papers/5079592cc860d1435482a4a7764edcd4)
@@ -137,40 +182,22 @@ If you use Strapdown-rs in your research, please cite the JOSS paper:
These are built from source, so failures are cmake or compiler errors rather than linker
errors. The two common ones:
-1. **`CMake 3.26 or higher is required`** -- your cmake is older than the bundled HDF5 needs.
+1. **`CMake 3.26 or higher is required`**: your cmake is older than the bundled HDF5 needs.
Ubuntu 22.04 (3.22) and Debian 12 (3.25) both hit this.
-2. **A confusing cmake failure inside the netCDF build** -- check `echo "${HDF5_DIR:-unset}"`.
+2. **A confusing cmake failure inside the netCDF build**: check `echo "${HDF5_DIR:-unset}"`.
If it is set, the HDF5 build switches to looking for a *system* library even though a
- vendored build was requested, and netCDF is then given the wrong headers.
-
-See [Installation Troubleshooting](./installation/installation.md#troubleshooting) for more help.
+ vendored build was requested, and netCDF is then given the wrong headers. Unset it.
-### My simulation produces NaN values
+See [Installation](./installation/installation.md) for more.
-Common causes:
-- Invalid initial conditions
-- IMU data with unrealistic values
-- Numerical instability in filter
+### My simulation produces NaN values or stops on a health check
-Check your input data and initial state. Enable debug logging with `--log-level debug` to investigate.
-
-### The particle filter is very slow
-
-This is expected with high particle counts. Consider:
-- Reducing the number of particles
-- Using the RBPF (Rao-Blackwellized) variant
-- Using EKF/UKF instead if appropriate
+Common causes are a wrong frame declaration (see above), unrealistic IMU values, or a filter
+that has diverged. The run's health monitor stops a run whose state leaves configured bounds;
+`--log-level debug` shows what happened before it did.
### Where can I get help?
-- Check this FAQ and the user guide
-- Search existing [GitHub Issues](https://github.com/jbrodovsky/strapdown-rs/issues)
-- Open a new issue if you've found a bug
-- Contact the maintainer for research collaborations
-
-## Additional Questions?
-
-If your question isn't answered here, please:
-1. Check the [User Guide](./user-guide/overview.md)
-2. Review the [API Reference](./api/core.md)
-3. Open an issue on [GitHub](https://github.com/jbrodovsky/strapdown-rs/issues)
+- this FAQ and the [User Guide](./user-guide/overview.md);
+- existing [GitHub Issues](https://github.com/jbrodovsky/strapdown-rs/issues);
+- a new issue, if you have found a bug.
diff --git a/book/src/filters/comparison.md b/book/src/filters/comparison.md
index e80b64ff..d7bdad6d 100644
--- a/book/src/filters/comparison.md
+++ b/book/src/filters/comparison.md
@@ -1 +1,67 @@
-# EKF vs UKF Comparison
+# Comparison
+
+The three Kalman filters share the mechanization, the measurement models, the gating and the
+initialization helpers (see [Kalman Filters](./kalman.md)). They differ in what they carry as
+state and how they handle the nonlinearity.
+
+| | [ESKF](./eskf.md) | [EKF](./ekf.md) | [UKF](./ukf.md) |
+| --- | --- | --- | --- |
+| `cl --filter` | `eskf` (default) | `ekf` | `ukf` |
+| estimates | the error in a nominal trajectory | the full state | the full state |
+| attitude | quaternion nominal, rotation-vector error, multiplicative correction | Euler angles, additive correction | Euler angles, perturbed, averaged and corrected on the rotation group |
+| IMU biases | always (15 error states) | with `use_biases` (the default) | always through `initialize_ukf` |
+| extra states | barometric bias only | map biases and barometric bias | map biases and barometric bias |
+| nonlinearity | linearized about a nominal that is reset after every update | linearized about the current estimate (analytic Jacobians) | sigma points; no Jacobians in the filter |
+| covariance update | Joseph form, then reset transport | Joseph form | $P - KSK^\top$, then reset transport |
+| tuning beyond $P_0$, $q$ | none | none | $\alpha$, $\beta$, $\kappa$ |
+| used by default in | `strapdown-sim cl`, `InsEngine` | | |
+
+## When to use which
+
+- **Start with the ESKF.** It is the default for structural reasons, not tuning: biases are
+ always estimated, attitude is never linearized about Euler angles, and the error the filter
+ linearizes is small by construction. It is the only filter `InsEngine` builds on its own. It has
+ no geophysical implementation: `cl --geo` refuses it, and because it is the default, a
+ geophysical run has to name `--filter ekf` or `--filter ukf`.
+- **Use the EKF** for map-aided runs (the geophysical path runs the EKF or the UKF), when you need a
+ nine-state filter, or when you want the textbook full-state formulation for comparison with
+ published work. Its Jacobians are analytic and checked against the mechanization by
+ `core/tests/jacobian_agreement.rs`.
+- **Use the UKF** to study whether linearization matters for your scenario: it needs no
+ Jacobians, so it is the reference against which a linearized filter's approximation shows
+ up. Keep $\alpha$ at its 0.1 default unless you have measured otherwise
+ ([why](./ukf.md#why-not-the-textbook-alpha-of-0001)).
+- **Use the [RBPF](./rbpf.md)** when the measurement is a highly nonlinear or multimodal
+ function of position, which is the map-matching case it was built for. It is a particle
+ filter, run with `strapdown-sim pf`, and its configuration is separate.
+
+## Accuracy
+
+Accuracy is not asserted on this page. The numbers below are generated by
+`core/tests/perf_baseline.rs`, which scores every filter over a fixed scenario matrix and fails
+CI when a metric moves; `real_*` rows are a phone recording scored against its own GNSS track,
+`syn_*` rows are synthetic and scored against exact truth. Read the
+caveats on [Performance Baselines](../development/performance.md)
+before drawing a conclusion from any row: on full-rate real-data rows, for example, every filter
+is scored against fixes it has already been given.
+
+{{#include ../development/baseline-tables.md}}
+
+No wall-clock comparison of the filters is published; nothing in the repository measures
+runtime.
+
+## Running all three on the same input
+
+Every filter reads the same input and writes the same CSV columns, so a comparison is three runs
+of `cl` that differ only in `--filter` (run here on a `syn` trajectory):
+
+```bash
+strapdown-sim syn -o synthetic.csv --duration-s 600 --seed 42
+strapdown-sim cl -i synthetic.csv -o cl_eskf.csv --filter eskf
+strapdown-sim cl -i synthetic.csv -o cl_ekf.csv --filter ekf
+strapdown-sim cl -i synthetic.csv -o cl_ukf.csv --filter ukf
+```
+
+`strapdown-sim syn --no-noise` with the same flags writes the exact trajectory, and
+[Tutorial: Particle Filter](../examples/tutorial-particle-filter.md#comparing-against-truth)
+shows how to score an output CSV against it.
diff --git a/book/src/filters/ekf.md b/book/src/filters/ekf.md
index cae6020b..3e59153f 100644
--- a/book/src/filters/ekf.md
+++ b/book/src/filters/ekf.md
@@ -1,174 +1,83 @@
# Extended Kalman Filter (EKF)
-The Extended Kalman Filter (EKF) is one of the primary navigation filters available in Strapdown-rs. It provides efficient state estimation for the INS through linearization of nonlinear system and measurement models.
-
-## Overview
-
-The EKF linearizes the nonlinear navigation equations using Jacobian matrices (first-order Taylor series expansion). While this approximation is less accurate than the UKF's unscented transform for highly nonlinear systems, it is computationally more efficient and works well for most practical navigation scenarios.
-
-## Mathematical Foundation
-
-### State Vector
-
-The EKF supports two state configurations:
-
-**9-State Model (Navigation Only)**:
-- Latitude, longitude, altitude
-- North, east, down velocities
-- Roll, pitch, yaw angles
-
-**15-State Model (Navigation + Biases)**:
-- 9 navigation states (as above)
-- Accelerometer biases (3)
-- Gyroscope biases (3)
-
-### Prediction Step
-
-The prediction step propagates the state and covariance forward using IMU measurements using the strapdown mechanization and computed Jacobian matrices.
-
-### Update Step
-
-When GNSS or other measurements are available, the Kalman gain is computed and the state is updated with the measurement innovation.
-
-## Features
-
-### Advantages
-
-1. **Computational Efficiency**: 3-5x faster than UKF
-2. **Memory Efficient**: Stores only mean and covariance
-3. **Well-Understood**: Extensive literature and proven track record
-4. **Analytic Jacobians**: Uses pre-computed derivatives for accuracy
-
-### Limitations
-
-1. **Linearization Error**: Less accurate for highly nonlinear systems
-2. **First-Order Approximation**: May miss higher-order effects
-3. **Gaussian Assumption**: Cannot handle multimodal distributions
-
-## Usage
-
-### Basic Initialization
-
-```rust
-use strapdown::kalman::{ExtendedKalmanFilter, InitialState, NavigationFilter};
-use nalgebra::{DMatrix, DVector};
-
-// Define initial state
-let initial_state = InitialState {
- latitude: 45.0,
- longitude: -122.0,
- altitude: 100.0,
- northward_velocity: 0.0,
- eastward_velocity: 0.0,
- vertical_velocity: 0.0,
- roll: 0.0,
- pitch: 0.0,
- yaw: 0.0,
- in_degrees: true,
- is_enu: false, // NED, the crate default; set true for ENU data
-};
-
-// Initial covariance diagonal.
-//
-// Latitude and longitude are held in RADIANS and altitude in metres, so the three position
-// entries are not the same unit and cannot come from one literal. `vec![1e-6; 9]` -- what
-// this example used to show -- reads as a 6.4 km initial horizontal uncertainty rather than
-// as a small number, and `1e-9` as a process-noise density is a 201 m one. Both are issue
-// #308; see **Units on the covariance diagonals** below. Write the metres once, convert where
-// they are used.
-let horizontal_std_rad = 10.0 * strapdown::earth::METERS_TO_RADIANS; // a 10 m GNSS fix
-let mut initial_covariance = vec![
- horizontal_std_rad.powi(2), // latitude, rad^2
- horizontal_std_rad.powi(2), // longitude, rad^2
- 10.0_f64.powi(2), // altitude, m^2
-];
-initial_covariance.extend([0.25; 3]); // velocity, (m/s)^2 -- a 0.5 m/s fix
-initial_covariance.extend([1e-4; 3]); // attitude, rad^2 -- ~0.6 deg
-
-// Initialize 9-state EKF (no biases)
-let mut ekf = ExtendedKalmanFilter::new(
- initial_state,
- vec![], // No biases for 9-state
- initial_covariance,
- // The crate's own default, which is built the same way: one metric constant, converted
- // once. Nine-state filters take its leading nine entries.
- DMatrix::from_diagonal(&DVector::from_vec(
- strapdown::sim::DEFAULT_PROCESS_NOISE_DENSITY[0..9].to_vec(),
- )),
- false, // use_biases = false for 9-state
-);
+`kalman::ExtendedKalmanFilter` is a full-state EKF: position, velocity and attitude (as roll,
+pitch and yaw) are the state vector itself, and the filter linearizes the mechanization about
+its current estimate with analytic Jacobians (Groves Chapter 14.2). Run it from the command line
+with `strapdown-sim cl --filter ekf`. For when to prefer it over the default
+[ESKF](./eskf.md), see [Comparison](./comparison.md).
+
+## State
+
+| configuration | states |
+| --- | --- |
+| 9-state (`use_biases: false`) | latitude, longitude, altitude, velocity (3), roll, pitch, yaw |
+| 15-state (`use_biases: true`, the `EkfConfig` default) | the nine above, then accelerometer bias (3) and gyroscope bias (3) |
+| extended | the fifteen, then any `other_states` (geophysical map biases), then the barometric bias if `estimate_baro_bias` is set |
+
+Units and order are the [shared layout](./kalman.md#state-layout-and-units): latitude and
+longitude in radians, attitude in radians on the principal branch. Extra states and the
+barometric bias require `use_biases`; `initialize_ekf` refuses them otherwise.
+
+## Predict
+
+1. Bias-correct the increments with the current bias estimate, as the ESKF does:
+ $\Delta v^b = \Delta\tilde v^b - b_a\Delta t$, $\Delta\theta^b = \Delta\tilde\theta^b - b_g\Delta t$.
+2. Compute the transition Jacobian $F$ at the **pre-propagation** state with
+ `linearize::euler_state_transition_jacobian`, from the bias-corrected average rates.
+3. For the 15-state filter, widen $F$ with `linearize::widen_with_imu_bias_coupling`: the
+ blocks through which the accelerometer bias reaches velocity (and position, through the
+ trapezoidal half-step) and the gyroscope bias reaches attitude. Without them the bias states
+ exist but never correlate with anything a measurement observes, and the filter estimates nine
+ states while carrying fifteen; that was the EKF until #394. Extra states get an identity
+ (random-walk) diagonal.
+4. Mechanize the state with `mechanize`.
+5. $P \leftarrow F P F^\top + q\ \Delta t$, then regularize. There is no separate noise-input
+ matrix $G$: $q$ is taken to be the process-noise density already expressed in state space.
+
+### The Jacobian is in the Euler chart
+
+The EKF's attitude states are Euler angles, so its Jacobian differentiates with respect to
+roll, pitch and yaw. That is a different matrix from the rotation-vector form an error-state
+filter uses: the two differ by the Euler-rate matrix $E(\Phi)$, and the difference is as large
+as the terms themselves. `linearize` names the choice through `AttitudeParametrization`
+(`Euler` for this filter, `RotationVector` for the error-state form) rather than leaving it
+implied by which function is called. Using the rotation-vector form in the EKF was #307.
+
+## Update
+
+1. Evaluate the measurement Jacobian $H$ from the model's `get_jacobian` first: a geophysical
+ model whose estimate has left its map reports that as an error there, before any NaN reaches
+ the innovation. Every model writes its attitude columns as $\partial h/\partial$(roll, pitch,
+ yaw), which is exactly this filter's chart, so no conversion is needed. A nine-column
+ Jacobian is padded with zeros to the state width.
+2. $S = HPH^\top + R$, innovation $\nu = z - h(x)$, wrapped by the model for angles.
+3. Gate, if a gate is installed ([gating](./measurements.md#innovation-gating)).
+4. $K = PH^\top S^{-1}$ (through an SPD solve), $x \leftarrow x + K\nu$, then wrap the Euler
+ angles back onto the principal branch.
+5. Joseph-form covariance update, $P \leftarrow (I-KH)P(I-KH)^\top + KRK^\top$, then
+ regularize.
+
+## Construction
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:ekf_new}}
```
-### 15-State with Bias Estimation
-
-```rust
-// The nine-state diagonal built above, extended with the bias states. The same unit
-// caveat applies to its position block, and for the same reason.
-let mut initial_covariance_15 = initial_covariance.clone();
-initial_covariance_15.extend([1e-3; 3]); // accel bias, (m/s^2)^2
-initial_covariance_15.extend([1e-8; 3]); // gyro bias, (rad/s)^2
-
-// Initialize 15-state EKF with bias estimation
-let mut ekf = ExtendedKalmanFilter::new(
- initial_state,
- vec![0.0; 6], // Initial bias estimates (3 accel + 3 gyro)
- initial_covariance_15,
- DMatrix::from_diagonal(&DVector::from_vec(
- strapdown::sim::DEFAULT_PROCESS_NOISE_DENSITY.to_vec(),
- )), // Process noise
- true, // use_biases = true for 15-state
-);
-```
-
-### Prediction with IMU Data
-
-```rust
-use strapdown::IMUData;
-
-let imu_data = IMUData {
- timestamp: 1234567890.0,
- gyro: [0.01, -0.02, 0.03], // rad/s
- accel: [0.5, -0.2, 9.81], // m/s²
-};
-
-let dt = 0.01; // Time step in seconds
-ekf.predict(&imu_data, dt);
-```
-
-### Update with GNSS
-
-```rust
-use strapdown::measurements::GPSPositionMeasurement;
-
-let gps_measurement = GPSPositionMeasurement {
- latitude: 45.00012,
- longitude: -122.00015,
- altitude: 101.5,
- std_dev: [5.0, 5.0, 10.0], // Measurement uncertainty
-};
-
-ekf.update(&gps_measurement);
-```
-
-## Performance
-
-### Computational Complexity
-
-- Typical update rate: 10,000-20,000 updates/second on modern hardware
-- 3-5x faster than UKF
-- Memory usage: ~2 KB for 15-state
-
-## Comparison with UKF
+The arguments are an `InitialState`, a slice of initial bias estimates (used only when
+`use_biases` is `true`, with any further entries seeding extra states), the covariance
+diagonal, the process-noise density $q$ as a matrix, and `use_biases`. The state's width is the
+length of the covariance diagonal; states beyond the nine navigation states and the supplied
+seeds start at zero. `kalman_filters.rs` builds the diagonal with
+`IMUQuality::auto_covariance`; see [Kalman Filters](./kalman.md#the-constructors-with-p0-from-the-imu-grade).
-| Aspect | EKF | UKF |
-|--------|-----|-----|
-| **Speed** | Faster (3-5x) | Slower |
-| **Accuracy** | Good for mildly nonlinear | Better for highly nonlinear |
-| **Implementation** | Requires Jacobians | No Jacobians needed |
-| **Memory** | Lower | Higher |
-| **Best For** | Real-time systems | Research/offline processing |
+`sim::initialize_ekf(&record, EkfConfig)` builds the same filter from a `TestDataRecord`, which
+is what `strapdown-sim` does; [Kalman Filters](./kalman.md#the-siminitialize_-helpers) lists
+the `EkfConfig` fields and the $P_0$ it derives. `EkfConfig::default()` is the 15-state filter;
+its `Default` is written by hand precisely so that it does not silently become the 9-state one.
-See [EKF vs UKF Comparison](./comparison.md) for detailed analysis.
+Driving it is the same as any filter: `predict` with an `ImuSample` or `IMUData`, `update` with
+a [measurement model](./measurements.md), each returning a `Result`
+([Driving a filter](./kalman.md#driving-a-filter)).
## Units on the covariance diagonals
@@ -184,10 +93,10 @@ It is worth knowing what the round numbers mean once the conversion is skipped:
|---|---|
| `1e-6` rad² | 6367 m |
| `1e-9` rad² | 201 m |
-| `(5 m × METERS_TO_DEGREES)²` | 286 m (degrees, not radians -- 57.3x too large) |
+| `(5 m × METERS_TO_DEGREES)²` | 286 m (degrees, not radians: 57.3x too large) |
All three shipped in this crate, in $Q$ and in $P_0$, and are what issue #308 fixed. The
-symptom is characteristic: with $Q$ that large the innovation covariance $S = HPH^T + R$ is
+symptom is characteristic: with $Q$ that large the innovation covariance $S = HPH^\top + R$ is
dominated by the filter's own prediction, so the update discards it and lands on each fix,
the solution tracks the fix noise one-for-one instead of averaging it down, and innovation
gating cannot function because a genuinely bad fix is still inside what the filter believes
@@ -195,20 +104,60 @@ possible.
`sim::DEFAULT_PROCESS_NOISE_DENSITY`, `sim::DEFAULT_INITIAL_POSITION_UNCERTAINTY_M` and the
`sim::initialize_*` helpers all do the conversion for you; `IMUQuality::auto_covariance`
-derives a whole $P_0$ diagonal from an IMU grade and a reported fix accuracy.
+derives a whole $P_0$ diagonal from an IMU grade and a reported fix accuracy. Remember too that
+the diagonal of $Q$ is a density: the filter multiplies it by $\Delta t$
+([Process noise](./kalman.md#process-noise-is-a-spectral-density)).
+
+## Analytic Jacobians, and how they are checked
+
+The EKF's correctness rests on its Jacobians matching the function they linearize, and a wrong
+block does not crash: it makes the gain wrong, and the filter degrades in a way that looks like
+bad tuning. `core/tests/jacobian_agreement.rs` therefore checks the analytic transition
+Jacobians directly against central finite differences of the mechanization, rather than
+inferring their correctness from whether a filter converges:
+
+- `euler_jacobian_matches_the_mechanization_in_both_frames` bounds every entry of the Euler
+ Jacobian against the finite difference, in NED and ENU, at a derived tolerance of $2\times10^{-5}$.
+- `altitude_row_follows_the_frame` pins the one entry whose sign the frame decides:
+ $\partial\ \text{alt}/\partial v_\text{vertical}$ is $-\Delta t$ in NED, where vertical velocity is
+ positive down, and $+\Delta t$ in ENU. A wrong sign turns the altitude/vertical-velocity pair
+ into positive feedback.
+- `the_two_parametrisations_differ_in_every_block_that_touches_attitude` checks that the Euler
+ and rotation-vector forms really are different matrices.
+
+```bash
+cargo test -p strapdown-core --test jacobian_agreement
+```
+
+The measurement Jacobians live beside them in `core/src/linearize.rs` (`gps_position_jacobian`,
+`gps_velocity_jacobian`, `relative_altitude_jacobian`, `magnetometer_yaw_jacobian`, `zupt_jacobian`,
+`zaru_jacobian` and others).
+
+## Troubleshooting
+
+**The solution copies every fix, and gating never rejects anything.** Check the units of $P_0$
+and $Q$ against the table above. A horizontal variance written as if it were m² is thousands of
+metres in radians.
+
+**The vertical channel runs away, or roll converges to 180°.** The data's frame disagrees with
+the declared one. In NED a level IMU reads $-g$ on its down axis; Sensor Logger exports are ENU
+and need `is_enu = true` (`--enu`). `sim::check_declared_frame` catches a wrong declaration
+before propagation, and `strapdown-sim` calls it on every run.
-## Best Practices
+**Bias estimates do not move.** A 9-state filter has nowhere to put them; use `use_biases:
+true`. On a 15-state filter, position and velocity fixes observe the biases only through the
+coupling blocks, and an accelerometer bias and a small tilt produce the same horizontal
+signature, so they are not separately observable from position and velocity alone
+([Tutorial: GNSS Degradation](../examples/tutorial-gps-degradation.md) shows this). A ZARU
+pseudo-measurement observes the gyro bias directly
+([Measurement Models](./measurements.md#zero-velocity-and-zero-angular-rate-updates)).
-1. **Start with 9-state** unless you need bias estimation
-2. **Tune conservatively**: Start with larger uncertainties and reduce
-3. **Monitor innovation**: Check measurement residuals for divergence
-4. **Use 15-state** for long-duration missions or low-quality IMUs
-5. **Validate with dead reckoning**: Compare against the `dr` subcommand's results
-6. **Write position uncertainties in metres** and convert once -- see
- [Units on the covariance diagonals](#units-on-the-covariance-diagonals)
+**An update returns an error.** `StrapdownError::is_recoverable` distinguishes a measurement
+that could not be evaluated (skip it) from a filter that can no longer continue.
-## Next Steps
+## References
-- Try the [UKF](./ukf.md) for comparison
-- Learn about [Measurement Models](./measurements.md)
-- See [Example: Closed-Loop Simulation](../examples/tutorial-basic.md)
+- Groves, P. D., *Principles of GNSS, Inertial, and Multisensor Integrated Navigation
+ Systems*, 2nd ed., Chapter 14.2.
+- Bar-Shalom, Y., Li, X.-R. and Kirubarajan, T., *Estimation with Applications to Tracking and
+ Navigation*, Chapter 5.
diff --git a/book/src/filters/eskf.md b/book/src/filters/eskf.md
new file mode 100644
index 00000000..9afdff8b
--- /dev/null
+++ b/book/src/filters/eskf.md
@@ -0,0 +1,199 @@
+# Error-State Kalman Filter (ESKF)
+
+`kalman::ErrorStateKalmanFilter` is the default filter: `strapdown-sim cl` runs it unless told
+otherwise (`FilterType::default()` is `Eskf`), and `InsEngine::builder().build()` constructs
+one. It is the indirect, error-state formulation of Groves Chapter 14 and Solà (2017): a
+nonlinear **nominal** trajectory is mechanized at full fidelity, and a linear Kalman filter
+estimates the small **error** in it.
+
+## Why it is the default
+
+The ESKF became the default in #258 for reasons that are structural rather than tuning:
+
+- **It estimates the IMU biases.** The fifteen-element error state always carries
+ accelerometer and gyroscope bias, coupled to velocity and attitude in the transition matrix,
+ so a turn-on bias is estimated online instead of integrated as motion. A nine-state EKF has no
+ bias states to put it in.
+- **Attitude is a quaternion, corrected multiplicatively.** The nominal attitude is a unit
+ quaternion; the error is a three-element rotation vector. Nothing is linearized about Euler
+ angles, so there is no Euler-chart singularity in the propagation and no Euler addition in the
+ correction.
+- **The linearization point is good by construction.** The error is reset to zero after every
+ update, so the linear model only ever has to describe a small perturbation.
+
+The EKF and UKF remain selectable and are unchanged by this default. For measured accuracy of
+all three on the same scenarios see [Comparison](./comparison.md).
+
+## Nominal and error states
+
+The **nominal** state is held as typed quantities, not a vector: latitude and longitude
+(radians), altitude (m), north/east/vertical velocity (m/s), a unit quaternion for the
+body-to-navigation attitude, the two bias vectors and, when carried, a barometric bias.
+
+The **error** state $\delta x$ is
+
+| index | error in | unit |
+| --- | --- | --- |
+| 0, 1 | latitude, longitude | rad |
+| 2 | altitude | m |
+| 3, 4, 5 | north, east, vertical velocity | m/s |
+| 6, 7, 8 | attitude, as a body-frame rotation vector $\delta\theta$ | rad |
+| 9, 10, 11 | accelerometer bias | m/s² |
+| 12, 13, 14 | gyroscope bias | rad/s |
+| 15 (optional) | barometric bias | m |
+
+The position errors are in the filter's own units (radians for latitude and longitude), not
+metres. The error-state transition matrix and the GNSS position Jacobian are both written in
+those units, so the correction is added to the nominal latitude without conversion; dividing
+by the radii of curvature there was #266.
+
+The filter's width is the length of the covariance diagonal it is constructed with: fifteen,
+or sixteen when the last entry is a barometric bias. `get_estimate` returns the *nominal* state
+in the [shared layout](./kalman.md#state-layout-and-units), converting the quaternion to Euler
+angles; `get_certainty` returns the *error-state* covariance.
+
+## Predict
+
+1. **Bias-correct the increments.** Biases are rates and the increments are their integrals:
+ $$
+ \Delta v^b = \Delta \tilde v^b - b_a \Delta t, \qquad
+ \Delta\theta^b = \Delta\tilde\theta^b - b_g \Delta t .
+ $$
+2. **Mechanize the nominal** with `mechanize`, the same strapdown equations every filter
+ uses, and renormalize the quaternion.
+3. **Propagate the error covariance** with the error-state transition matrix from
+ `linearize::error_state_transition_jacobian` (Groves 14.2.4, Solà 2017 Section 6.3),
+ evaluated at the propagated nominal with the bias-corrected average rates:
+ $$
+ P \leftarrow F_{\delta x}\ P\ F_{\delta x}^\top + q\ \Delta t .
+ $$
+ $F_{\delta x}$ couples the accelerometer bias into velocity and the gyroscope bias into
+ attitude, which is what makes the biases observable from position and velocity fixes. A
+ barometric bias is a random walk with no coupling: it reaches the navigation states only
+ through the barometer's measurement Jacobian.
+
+## Update, injection and reset
+
+1. **Predict the measurement** from the nominal state, assembled into the
+ [shared layout](./kalman.md#state-layout-and-units) including the bias entries (ZARU reads
+ them).
+2. **Form $H$.** Every measurement model writes its attitude columns as $\partial h /
+ \partial(\text{roll, pitch, yaw})$. The ESKF's attitude error is a body-frame rotation
+ vector, so those columns are converted by the chain rule,
+ $$
+ \frac{\partial h}{\partial \delta\theta^b} =
+ \frac{\partial h}{\partial \Phi}\ \frac{\partial \Phi}{\partial \delta\theta^b},
+ $$
+ with the second factor from `linearize::body_rotation_vector_to_euler_jacobian`. It is the
+ identity only at zero roll. Near gimbal lock (about 89.45° of pitch) no finite matrix is
+ right, and the attitude columns are zeroed: the update declines to correct attitude from
+ that measurement rather than apply an enormous row.
+3. **Gate**, if a gate is installed (see [gating](./measurements.md#innovation-gating)). A
+ rejection inflates the covariance in the observed directions and returns before anything
+ is injected; there is no undo after injection starts.
+4. **Solve** $\delta x = K\nu$ with $K = P H^\top (H P H^\top + R)^{-1}$.
+5. **Inject** the error into the nominal:
+ - position, velocity and biases are added;
+ - attitude is composed, $q \leftarrow q \otimes \operatorname{Exp}(\delta\theta)$, using the
+ exact exponential map rather than the first-order quaternion $[1, \tfrac12\delta\theta]$;
+ - the barometric bias, when carried, is added.
+6. **Clamp the IMU biases** (anti-windup): each accelerometer bias to ±2.0 m/s² and each gyro
+ bias to ±0.05 rad/s. These are orders of magnitude above a consumer MEMS turn-on bias and
+ exist so that a persistently faulty aiding source cannot drag the biases to physically
+ impossible values (#286). The barometric bias is not clamped: it does not feed the
+ mechanization.
+7. **Reset** $\delta x \leftarrow 0$.
+8. **Update the covariance** in Joseph form, using the same prior $P$ the gain was computed
+ from: $P \leftarrow (I-KH)P(I-KH)^\top + KRK^\top$.
+9. **Transport the covariance** onto the tangent space of the attitude just composed on:
+ $P \leftarrow G P G^\top$, where $G$ is the identity except for the attitude block, which
+ is the right Jacobian $J_r(\delta\theta)$ from `linearize::attitude_reset_jacobian`. The
+ whole covariance is transformed, so attitude's correlations with the other states move with
+ it (#398).
+10. **Regularize**: symmetrize and add the relative jitter described on
+ [Kalman Filters](./kalman.md#the-update-and-keeping-the-covariance-healthy).
+
+## Construction
+
+The direct constructor takes an `InitialState`, six initial bias estimates, the covariance
+diagonal and the process-noise density $q$:
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:eskf_new}}
+```
+
+`initialize_eskf` builds the same filter from a `TestDataRecord` and an `EskfConfig`; its
+default $P_0$ is tabulated on [Kalman Filters](./kalman.md#the-siminitialize_-helpers). For the
+sixteen-state form pass a sixteen-element diagonal and $q$, and tell the barometer model where
+the bias is through `AidingConfig::baro_bias_index`; `EskfConfig::estimate_baro_bias` does the
+first half for you, and `EskfConfig::baro_bias_index()` returns the index (always 15) for the
+second.
+
+## Running it end to end
+
+[`core/examples/eskf.rs`](https://github.com/jbrodovsky/strapdown-rs/blob/main/core/examples/eskf.rs)
+is the library route to what `strapdown-sim cl` does: a five-minute synthetic drive due north at
+15 m/s from a consumer-grade IMU, GNSS for 120 s, a 60 s outage, then GNSS again, scored against
+the exact trajectory.
+
+```bash
+cargo run -p strapdown-core --example eskf
+```
+
+Build the filter with the barometric-bias state `strapdown-sim` turns on by default:
+
+```rust,ignore
+{{#include ../../../core/examples/eskf.rs:build}}
+```
+
+Build the event stream. A `DutyCycle` scheduler starts with `start_phase_s` of availability,
+then alternates `off_s` of outage and `on_s` of availability; with a zero phase the run would
+start in an outage.
+
+```rust,ignore
+{{#include ../../../core/examples/eskf.rs:stream}}
+```
+
+Run the closed loop and score it with `metrics::evaluate`:
+
+```rust,ignore
+{{#include ../../../core/examples/eskf.rs:run}}
+```
+
+```rust,ignore
+{{#include ../../../core/examples/eskf.rs:score}}
+```
+
+Read the bias estimates back off the state vector:
+
+```rust,ignore
+{{#include ../../../core/examples/eskf.rs:biases}}
+```
+
+It printed:
+
+```text
+scored 3000 samples against truth
+horizontal error: RMSE 20.65 m, max 105.72 m
+end of outage: error 105.72 m, filter 1-sigma 336.56 m north, 341.87 m east
+final accelerometer bias estimate: [0.0599, 0.0160, -0.0716] m/s^2
+final gyroscope bias estimate: [0.00023, -0.00028, 0.00041] rad/s
+final barometric bias estimate: 4.012 m
+```
+
+The "end of outage" line is the last sample before GNSS returns. On this run the filter's own
+horizontal uncertainty at that point is about three times its actual error: it is conservative,
+not over-confident, while coasting. Whether that holds in general is what the consistency
+metrics on [Performance Baselines](../development/performance.md) measure: the NEES and the
+three-sigma containment columns, read together.
+
+## References
+
+- Groves, P. D., *Principles of GNSS, Inertial, and Multisensor Integrated Navigation
+ Systems*, 2nd ed., Chapter 14 (14.2.4 for the error-state transition matrix).
+- Solà, J., "Quaternion kinematics for the error-state Kalman filter", 2017.
+- Trawny, N. and Roumeliotis, S., "Indirect Kalman Filter for 3D Attitude Estimation", 2005.
+
+The implementation, with the reasoning behind each step in its comments, is
+`ErrorStateKalmanFilter` in `core/src/kalman.rs` and `error_state_transition_jacobian` in
+`core/src/linearize.rs`.
diff --git a/book/src/filters/kalman.md b/book/src/filters/kalman.md
index 6381b881..23dc4b1f 100644
--- a/book/src/filters/kalman.md
+++ b/book/src/filters/kalman.md
@@ -1 +1,272 @@
# Kalman Filters
+
+`strapdown-core` ships three Kalman-family filters in `core/src/kalman.rs`. All three are
+loosely coupled: they take GNSS position and velocity fixes (and the other aiding sources on
+[Measurement Models and Integrity](./measurements.md)), not pseudoranges or carrier phase. They
+share one interface, one set of measurement models and one propagation core: the strapdown
+mechanization of Groves Chapter 5.4-5.5 described in
+[The Navigation Model](../user-guide/concepts.md).
+
+| filter | type | state | attitude carried as | `cl --filter` |
+| --- | --- | --- | --- | --- |
+| [Error-State Kalman Filter](./eskf.md) | `kalman::ErrorStateKalmanFilter` | 15-element error state, 16 with a barometric bias | unit quaternion, corrected multiplicatively | `eskf` (the default) |
+| [Extended Kalman Filter](./ekf.md) | `kalman::ExtendedKalmanFilter` | 9 or 15 full states, plus optional extra states | Euler angles in the state vector | `ekf` |
+| [Unscented Kalman Filter](./ukf.md) | `kalman::UnscentedKalmanFilter` | 15 full states through `initialize_ukf` (9 is possible from the constructor), plus optional extra states | Euler angles, perturbed and averaged on the rotation group | `ukf` |
+
+The [Comparison](./comparison.md) page says when to reach for which. The
+[Rao-Blackwellized particle filter](./rbpf.md) implements the same trait and is documented
+separately.
+
+## The `NavigationFilter` trait
+
+Every filter implements `strapdown::NavigationFilter`, which lives at the crate root
+(`core/src/lib.rs`), not in `kalman`. The trait is object-safe, so a
+`Box` can hold any of them; that is what lets the
+[`InsEngine`](../user-guide/library.md) drive a filter it did not construct.
+
+| method | returns | what it does |
+| --- | --- | --- |
+| `predict(&mut self, control_input: &dyn InputModel, dt: f64)` | `Result<(), StrapdownError>` | Propagate by one inertial sample. |
+| `update(&mut self, measurement: &dyn MeasurementModel)` | `Result` | Correct with one measurement. |
+| `get_estimate(&self)` | `DVector` | The current state, in the filter's native units. |
+| `get_certainty(&self)` | `DMatrix` | The current covariance. For the ESKF this is the *error-state* covariance. |
+| `set_innovation_gate(&mut self, gate: Option)` | `bool` | Install or clear an innovation gate; `true` if the filter honours it. |
+| `set_gate_recovery(&mut self, recovery: GateRecovery)` | `bool` | Tune how a rejection is recovered from; `true` if honoured. |
+| `baro_bias_index(&self)` | `Option` | Where the barometric bias lives in `get_estimate`, if the filter carries one. |
+
+The last three have default bodies (`false`, `false`, `None`). All three Kalman filters and the
+RBPF override the two gating methods.
+
+### Inputs: `InputModel`
+
+`predict` takes a `&dyn InputModel` and accepts the two inertial forms:
+
+- `ImuSample`: integrated increments ($\Delta v$, $\Delta\theta$) over its own `dt`. This is
+ what an IMU emits and what `mechanize` consumes. Its `dt` must agree with the `dt` argument
+ to a relative tolerance of $10^{-9}$, or `predict` returns
+ `StrapdownError::InconsistentTimestep` rather than silently preferring one of the two.
+- `IMUData`: instantaneous specific force (m/s²) and angular rate (rad/s), which the filter
+ integrates over `dt` with `ImuSample::from_rates`.
+
+Anything else that implements `InputModel` (`VelocityData`, for example) is refused with
+`StrapdownError::UnsupportedInput`. Accelerometer readings are raw specific force, gravity
+included: in NED a level, stationary IMU reads $-g$ on its down axis. See
+[Tutorial: Basic INS](../examples/tutorial-basic.md#the-sign-convention-that-catches-everyone).
+
+### Outputs: `UpdateOutcome`
+
+`update` returns an `UpdateOutcome` (defined in `gating`, re-exported at the crate root) rather
+than `()`, because three cases have to be told apart and only one of them is an error:
+
+| field | meaning |
+| --- | --- |
+| `nis` | normalized innovation squared, $\nu^\top S^{-1}\nu$ with $S = HPH^\top + R$ |
+| `dof` | the measurement's dimension, the degrees of freedom of the test |
+| `accepted` | whether the correction was applied |
+| `forced` | applied *despite* failing the gate, because the recovery policy forced it |
+
+A filter with no gate installed (the default) accepts every measurement and still reports the
+NIS. A gated-out measurement is `Ok` with `accepted == false`: the state is unchanged apart from
+the covariance inflation described under [gating](./measurements.md#innovation-gating). An
+`Err` means the measurement could not be evaluated at all, and
+`StrapdownError::is_recoverable` says whether to skip it and carry on (see
+[Using the Library](../user-guide/library.md#errors)).
+
+### Driving a filter
+
+[`core/examples/kalman_filters.rs`](https://github.com/jbrodovsky/strapdown-rs/blob/main/core/examples/kalman_filters.rs)
+builds all three filters two ways, puts the six behind the trait, and runs one loop over a
+two-minute synthetic drive with a GNSS position fix once a second:
+
+```bash
+cargo run -p strapdown-core --example kalman_filters
+```
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:trait_objects}}
+```
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:loop}}
+```
+
+It printed:
+
+```text
+ESKF, initialize_eskf: 15 states, 2.757 m from truth at the end, last update NIS 3.535 (3 dof, accepted: true)
+EKF, initialize_ekf: 15 states, 2.760 m from truth at the end, last update NIS 3.531 (3 dof, accepted: true)
+UKF, initialize_ukf: 15 states, 2.758 m from truth at the end, last update NIS 3.534 (3 dof, accepted: true)
+ESKF, constructor: 15 states, 2.759 m from truth at the end, last update NIS 3.532 (3 dof, accepted: true)
+EKF, constructor: 15 states, 2.760 m from truth at the end, last update NIS 3.531 (3 dof, accepted: true)
+UKF, constructor: 15 states, 2.757 m from truth at the end, last update NIS 3.534 (3 dof, accepted: true)
+```
+
+On a short straight drive with a 2.5 m fix every second, all six end up where the fixes put
+them. That is a property of this easy scenario, not a ranking; the gated comparison is on
+[Comparison](./comparison.md).
+
+## State layout and units
+
+All three filters report the same layout from `get_estimate`:
+
+| index | state | unit |
+| --- | --- | --- |
+| 0, 1 | latitude, longitude | **radians** |
+| 2 | altitude above the WGS84 ellipsoid, positive up in both frames | m |
+| 3, 4, 5 | north, east, vertical velocity (vertical is positive down in NED, up in ENU) | m/s |
+| 6, 7, 8 | roll, pitch, yaw (XYZ Euler sequence, body to navigation) | rad |
+| 9, 10, 11 | accelerometer bias, body frame | m/s² |
+| 12, 13, 14 | gyroscope bias, body frame | rad/s |
+| 15 onward | extra states: geophysical map biases, then the barometric bias | their own units |
+
+A nine-state EKF stops at index 8. Latitude and longitude are radians and altitude is metres,
+so no covariance diagonal, $P_0$ or $Q$, can be filled with one number for all three position
+entries. [Units on the covariance diagonals](./ekf.md#units-on-the-covariance-diagonals) shows
+what goes wrong when it is.
+
+The frame is a property of the data. Every filter is NED unless its `InitialState` or config
+sets `is_enu`; see [Coordinate Frames](../user-guide/coordinate-frames.md).
+
+## Process noise is a spectral density
+
+Every filter forms the per-step process noise as
+
+$$
+Q_k = q \ \Delta t
+$$
+
+from a diagonal $q$ of **variances per second**, and adds it to the propagated covariance. The
+noise a run accumulates therefore depends on elapsed time, not on how often the IMU was sampled.
+Before #374 the same numbers were added once per sample, which made the effective noise
+proportional to the sample rate. The `process_noise` argument of every constructor, and every
+`process_noise_diagonal` config field, is $q$, not $Q_k$.
+
+The default is `sim::DEFAULT_PROCESS_NOISE_DENSITY`, fifteen entries in the state order above:
+
+| states | density $q$ |
+| --- | --- |
+| latitude, longitude | $(0.1\ \text{m} \cdot \texttt{METERS\\_TO\\_RADIANS})^2$ rad²/s, i.e. 0.1 m/√s |
+| altitude | $10^{-2}$ m²/s, i.e. 0.1 m/√s |
+| velocity (3) | $10^{-3}$ (m/s)²/s |
+| attitude (3) | $10^{-5}$ rad²/s |
+| accelerometer bias (3) | $10^{-6}$ (m/s²)²/s |
+| gyroscope bias (3) | $10^{-8}$ (rad/s)²/s |
+
+The position entries come from one constant, `sim::POSITION_PROCESS_NOISE_M_PER_ROOT_S`
+(0.1 m/√s), converted to radians for the horizontal pair. The rest are hand-tuned values, not
+derived from a sensor model. A nine-state EKF takes the leading nine entries. A barometric bias
+state walks at `sim::BARO_BIAS_PROCESS_NOISE_M2_PER_S`, derived from 8.3 m (about one
+hectopascal) of reference drift per hour.
+
+## The update, and keeping the covariance healthy
+
+The measurement update is the standard one (Groves Chapter 3):
+$K = P H^\top (H P H^\top + R)^{-1}$, with the gain solved through a symmetric
+positive-definite solver rather than an explicit inverse. Angular innovations (magnetometer
+yaw) are wrapped onto $[-\pi, \pi)$ by the model's `wrap_residual` before they are used.
+
+- The **EKF and ESKF** update the covariance in **Joseph form**,
+ $P^+ = (I - KH) P (I - KH)^\top + K R K^\top$, which stays symmetric and positive
+ semi-definite under rounding where $(I - KH)P$ does not.
+- The **UKF** subtracts $K S K^\top$, its sigma-point equivalent.
+
+After every predict and update each filter symmetrizes $P$ and adds a jitter proportional to
+each diagonal entry's own scale: a relative $10^{-9}$, with the process-noise diagonal as a
+floor. An absolute jitter cannot work on a state whose units span twelve orders of magnitude.
+The absolute $10^{-9}$ the UKF and EKF used to add was about 200 m of horizontal standard
+deviation on a radian-valued latitude (#373).
+
+## Initialization
+
+A filter needs an initial state, an initial covariance $P_0$ and a process-noise density $q$.
+There are two routes.
+
+### The `sim::initialize_*` helpers
+
+`initialize_eskf`, `initialize_ekf` and `initialize_ukf` (in `core/src/sim.rs`) build a filter
+from one `TestDataRecord`, which is how `strapdown-sim cl` starts every run:
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:helpers}}
+```
+
+The record supplies the initial state through `TestDataRecord::initial_state(is_enu)`: position
+from its GNSS columns, attitude from its quaternion, horizontal velocity from its `speed` and
+`bearing`, and zero vertical velocity. Each helper takes a config struct. All three are
+`#[non_exhaustive]`, so outside the crate you start from `default()` and assign fields.
+
+| field | `EskfConfig` | `EkfConfig` | `UkfConfig` | meaning |
+| --- | :-: | :-: | :-: | --- |
+| `is_enu` | yes | yes | yes | frame of the records; `false` (NED) by default |
+| `imu_quality` | yes | yes | yes | IMU grade the bias prior is derived from; `Consumer` by default |
+| `imu_biases` | yes | yes | yes | initial bias **estimate**, 6 values; zero by default |
+| `imu_biases_covariance` | yes | yes | yes | initial bias variances, 6 values; default `imu_quality.initial_bias_covariance()` |
+| `attitude_covariance` | yes | yes | yes | initial attitude variances, 3 values, rad² |
+| `process_noise_diagonal` | yes | yes | yes | $q$, one entry per state; default `DEFAULT_PROCESS_NOISE_DENSITY` |
+| `estimate_baro_bias` | yes | yes | yes | add a barometric-bias state; `false` by default |
+| `use_biases` | | yes | | 15 states (`true`, the default) or 9 |
+| `other_states`, `other_states_covariance` | | yes | yes | extra states appended after the fifteen |
+| `ukf_alpha`, `ukf_beta`, `ukf_kappa` | | | yes | sigma-point parameters; see [UKF](./ukf.md) |
+
+The helpers do not derive $P_0$ identically:
+
+| $P_0$ block | `initialize_eskf` | `initialize_ekf`, `initialize_ukf` |
+| --- | --- | --- |
+| horizontal position | `DEFAULT_INITIAL_POSITION_UNCERTAINTY_M` (10 m), as rad² | the record's `horizontal_accuracy`, as rad² |
+| altitude | (10 m)² | the record's `vertical_accuracy`, squared |
+| velocity | $10^{-3}$ (m/s)² | the record's `speed_accuracy`, squared |
+| attitude | $10^{-5}$ rad² | $10^{-9}$ rad² |
+| IMU biases | `imu_quality.initial_bias_covariance()` | the same |
+
+`estimate_baro_bias` defaults to `false` on the three library configs but to `true` in
+`strapdown-sim` (`ClosedLoopConfig`; `--no-estimate-baro-bias` turns it off). A filter that
+carries the bias state must also have it *named* to the barometer model, through
+`AidingConfig::baro_bias_index`, or nothing observes it. Read the index from the config's
+`baro_bias_index()` method; [ESKF](./eskf.md#running-it-end-to-end) shows the pair.
+
+The helpers do not check the declared frame against the data, because one record cannot tell a
+frame error from a manoeuvre. Call `sim::check_declared_frame` over the whole record slice, as
+`strapdown-sim` does.
+
+### The constructors, with P0 from the IMU grade
+
+Each filter can also be built directly from a `kalman::InitialState`. `InitialState` holds its
+latitude, longitude and Euler angles in whatever unit its `in_degrees` flag names, and the
+constructors convert exactly when that flag is set.
+
+`IMUQuality::auto_covariance` derives a fifteen-element $P_0$ from two things known at start-up:
+the IMU grade, and how well the first fix placed the vehicle (an `InitialUncertainty` holding
+one-sigma horizontal and vertical position in metres and velocity in m/s). Each block comes back
+in the filter's own units:
+
+| states | derived from |
+| --- | --- |
+| position | the uncertainty, converted to rad² through the WGS84 radii at the given latitude (Groves Eq. 2.105-2.106) |
+| velocity | the uncertainty, plus the grade's velocity random walk over a one-minute alignment |
+| attitude | the grade's angle random walk over the same minute, plus the levelling error a bias-instability-sized accelerometer bias causes (Groves 5.6.3) |
+| accelerometer bias | the grade's bias instability, squared |
+| gyroscope bias | the grade's bias instability, converted from rad/h to rad/s, squared |
+
+It treats heading like roll and pitch, so widen entry 8 when the initial yaw came from a
+magnetometer or a gyrocompass, as
+[Using the Library](../user-guide/library.md#coarse-alignment) does.
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:initial_covariance}}
+```
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:constructors}}
+```
+
+The constructors are infallible and take the filter's width from the length of the covariance
+diagonal; they do not check it. The `initialize_*` helpers do, and return
+`StrapdownError::InvalidConfiguration` on a mismatch.
+
+## Where next
+
+- [ESKF](./eskf.md): the default filter, its error state and its reset.
+- [EKF](./ekf.md): analytic Jacobians, and the units traps on $P_0$ and $Q$.
+- [UKF](./ukf.md): sigma points, and why $\alpha = 0.1$.
+- [Measurement Models and Integrity](./measurements.md): what `update` accepts, and gating.
+- [Closed Loop](../user-guide/closed-loop.md): running these filters from the command line.
diff --git a/book/src/filters/measurements.md b/book/src/filters/measurements.md
index 66462436..80022994 100644
--- a/book/src/filters/measurements.md
+++ b/book/src/filters/measurements.md
@@ -1 +1,229 @@
-# Measurement Models
+# Measurement Models and Integrity
+
+Every filter's `update` takes a `&dyn MeasurementModel`, so any model below can be applied to
+the ESKF, EKF, UKF or RBPF, and a new aiding source is a new type implementing the trait, with no
+change to the filters. The models live in `core/src/measurements.rs`; the stationary detector
+in `core/src/stationary.rs`; innovation gating in `core/src/gating.rs`.
+
+The integration is **loosely coupled**: GNSS enters as a position (and velocity) solution
+produced by the receiver. There are no pseudorange or carrier-phase models in this crate.
+
+## The `MeasurementModel` trait
+
+| method | returns | meaning |
+| --- | --- | --- |
+| `get_dimension()` | `usize` | length of the measurement vector |
+| `get_measurement(&state)` | `Result, StrapdownError>` | the observed $z$; `state` is passed so a model can use it (the magnetometer levels itself with the estimated roll and pitch) |
+| `get_expected_measurement(&state)` | `DVector` | the prediction $h(x)$ |
+| `get_noise()` | `DMatrix` | the measurement covariance $R$, a **variance** |
+| `get_jacobian(&state)` | `Result, StrapdownError>` | $H = \partial h/\partial x$ |
+| `wrap_residual(&mut residual)` | | wraps angular innovations; the default does nothing |
+
+Three conventions hold for every model:
+
+- `state` is the [shared layout](./kalman.md#state-layout-and-units): latitude and longitude in
+ radians, attitude as roll, pitch and yaw.
+- The attitude columns of $H$ are derivatives with respect to **roll, pitch and yaw**. The EKF
+ uses them directly; the ESKF converts them to its body-frame rotation-vector error
+ ([ESKF](./eskf.md#update-injection-and-reset)) and the RBPF to its nav-frame tilt.
+- Every `*_noise_std` field is a one-sigma standard deviation; the model squares it to form
+ $R$.
+
+`get_measurement` and `get_jacobian` return `Result` because some models can legitimately fail
+to produce a value; a geophysical model queried off its map is the main case, and its error is
+*recoverable* (skip the measurement, carry on).
+
+## The models
+
+| model | dim | $z$ | noise fields | observes |
+| --- | :-: | --- | --- | --- |
+| `GPSPositionMeasurement` | 3 | latitude, longitude (given in degrees, converted to radians), altitude | `horizontal_noise_std`, `vertical_noise_std` (m) | position |
+| `GPSVelocityMeasurement` | 3 | north, east, vertical velocity (vertical in the state's frame convention) | `horizontal_noise_std`, `vertical_noise_std` (m/s) | velocity |
+| `GPSPositionAndVelocityMeasurement` | 5 | latitude, longitude, altitude, north and east velocity; **no vertical velocity** | `horizontal_noise_std`, `vertical_noise_std` (m), `velocity_noise_std` (m/s) | position, horizontal velocity |
+| `RelativeAltitudeMeasurement` | 1 | `relative_altitude + reference_altitude` | `noise_std` (m) | altitude, and a barometric bias if `bias_index` names one |
+| `MagnetometerYawMeasurement` | 1 | tilt-compensated heading from a body-frame field, optionally corrected by WMM declination | `noise_std` (rad) | yaw |
+| `ZuptMeasurement` | 3 | zero velocity | `velocity_noise_std` (m/s) | velocity |
+| `ZaruMeasurement` | 3 | the raw body-frame gyro reading | `angular_rate_noise_std` (rad/s) | gyroscope bias |
+
+The GNSS position noise is a ground distance in metres. It is converted to latitude and
+longitude variances through the WGS84 radii of curvature at the fix, separately for each axis,
+because a metre of easting is a larger angle of longitude than a metre of northing is of
+latitude.
+
+### What `strapdown-sim` feeds the filter
+
+`messages::build_event_stream` turns each input record into events, and the simulator's filters
+see three measurement types:
+
+| source | model | rate | noise |
+| --- | --- | --- | --- |
+| GNSS | `GPSPositionAndVelocityMeasurement` | every record with a fix, then thinned by the `[aiding]` scheduler and corrupted by its fault model | the record's `horizontalAccuracy`, `verticalAccuracy`, `speedAccuracy` |
+| barometer | `RelativeAltitudeMeasurement` | `baro_scheduler`, 1 Hz by default | `baro_noise_std_m`, default $\sqrt{5}$ m |
+| magnetometer | `MagnetometerYawMeasurement`, declination on | `magnetometer_scheduler`, 1 Hz by default | `MAG_YAW_NOISE`, 0.2 rad, fixed |
+
+[Schedulers and Faults](../gnss/scenarios.md) covers the scheduler and fault options. ZUPT and
+ZARU are not applied by the simulator; they are library building blocks.
+
+### Barometric altitude
+
+`RelativeAltitudeMeasurement` predicts `altitude + bias`, where the bias is `state[bias_index]`
+when `bias_index` is `Some` and zero otherwise. An index that falls inside the fifteen
+navigation and IMU-bias states, or past the end of the state, is refused with an error rather
+than read as a bias. The default noise, `BAROMETRIC_ALTITUDE_NOISE_M`, is $\sqrt5 \approx 2.24$
+m: it keeps the variance the model used before the field existed, which was 5 m².
+
+### Magnetometer yaw
+
+`MagnetometerYawMeasurement` levels the body-frame field with the state's roll and pitch (never
+its yaw, which would make the measurement depend on the quantity it measures), takes the
+heading with the `atan2` appropriate to the frame, and, with `apply_declination`, adds the World
+Magnetic Model declination at the state's position for `year` and `day_of_year`. Declination
+enters with opposite signs in NED and ENU, and the `is_enu` field **must** match the state's
+frame: a mismatch reflects the heading rather than degrading it. `get_declination(lat_deg,
+lon_deg, alt_m)` returns the declination in radians, positive east.
+
+```rust,ignore
+{{#include ../../../core/examples/aiding.rs:magnetometer}}
+```
+
+### Zero-velocity and zero-angular-rate updates
+
+A stationary vehicle is free information. `ZuptMeasurement` asserts the velocity is zero
+(Groves 15.2.1); because velocity error is correlated with accelerometer bias error, the
+correction reaches the bias too. `ZaruMeasurement` asserts that a stationary gyro reads only its
+own bias plus the Earth's rotation, which makes it a direct observation of the gyro bias (Groves
+15.2.2). It predicts $b_g + C_n^b\ \omega_{ie}^n$ (`set_earth_rate_compensation(false)` drops
+the Earth-rate term), and it **requires** a filter with gyro-bias states: on a nine-state filter
+it returns `StrapdownError::DimensionMismatch` instead of silently correcting nothing.
+
+Neither model decides whether the vehicle is still. That is `stationary::StationaryDetector`'s
+job: it keeps a sliding window of IMU samples and declares the platform stationary when all four
+hold across the window:
+
+1. specific-force variance (trace) below `accel_variance_threshold`, (m/s²)²;
+2. mean specific-force magnitude within `gravity_tolerance_mps2` of 9.807 m/s²;
+3. angular-rate variance (trace) below `gyro_variance_threshold`, (rad/s)²;
+4. mean angular-rate magnitude below `gyro_mean_threshold`, rad/s. This separates a stop from a
+ steady turn, which has small gyro *variance* and a large mean.
+
+It latches only after `min_stationary_samples` consecutive stationary windows and releases on
+the first sample that fails. `StationaryConfig::default()` (a 100-sample window, latching after
+50 more) is tuned for a consumer MEMS IMU at about 100 Hz. Constant-velocity cruise on a smooth
+road can pass all four tests; prefer conservative thresholds, since a false stop injects a hard
+zero-velocity constraint into a moving solution.
+
+[`core/examples/aiding.rs`](https://github.com/jbrodovsky/strapdown-rs/blob/main/core/examples/aiding.rs)
+parks an ESKF-backed `InsEngine` for 30 s with a gyro bias the filter has not been told about:
+
+```bash
+cargo run -p strapdown-core --example aiding
+```
+
+```rust,ignore
+{{#include ../../../core/examples/aiding.rs:stationary}}
+```
+
+### Geophysical models
+
+The experimental `strapdown-geonav` crate adds gravity-anomaly, magnetic-anomaly and combined
+models (`GravityMeasurement`, `MagneticAnomalyMeasurement`, `CombinedGeophysicalMeasurement`)
+that implement the same trait against a loaded map. See
+[Maps and Measurement Models](../geonav/maps.md).
+
+## Innovation gating
+
+A Kalman update trusts its measurement unconditionally. Under the filter's own model the
+innovation is $\nu \sim \mathcal N(0, S)$ with $S = HPH^\top + R$, so the normalized innovation
+squared
+
+$$
+d^2 = \nu^\top S^{-1} \nu
+$$
+
+is $\chi^2$-distributed with as many degrees of freedom as the measurement has components
+(Bar-Shalom, Li and Kirubarajan, Section 5.4). Rejecting an update whose NIS exceeds a $\chi^2$
+quantile discards what the model says should almost never happen. Every filter reports the NIS
+in its [`UpdateOutcome`](./kalman.md#outputs-updateoutcome) whether or not a gate is installed.
+
+`gating::InnovationGate` has two variants:
+
+| variant | threshold | constructor |
+| --- | --- | --- |
+| `ChiSquared { confidence }` | the `confidence` quantile of $\chi^2$ at the measurement's own dimension | `InnovationGate::chi_squared(confidence)`, refusing values outside $(0, 1)$ |
+| `Fixed { threshold }` | the same number for every measurement | `InnovationGate::fixed(threshold)` |
+
+Prefer the $\chi^2$ form: a filter mixing 1-D barometer, 3-D position and 5-D position and
+velocity updates needs a different threshold for each. `gating::chi_squared_quantile(p, dof)`
+and `chi_squared_cdf(x, dof)` are public. Gating is **off** by default everywhere: in the
+library, in `ClosedLoopConfig` and on the command line.
+
+### A gate needs a way back
+
+Rejecting a fix leaves the state where it was, but the filter keeps propagating and keeps
+accumulating error, while the covariance the next fix is judged against does not grow. The next
+innovation is larger, fails by more, and one rejection can become permanent dead reckoning
+(#340). `gating::GateRecovery` is the way back, and it is on by default once a gate is
+installed:
+
+| field | default | effect |
+| --- | --- | --- |
+| `rejection_inflation` | 2.0 | each rejection multiplies the filter's uncertainty in the directions that measurement observes, so $HPH^\top$ grows by this factor; 1.0 disables it |
+| `forced_update_after` | `Some(5)` | when this many consecutive measurements in a row fail the gate, the last of them is applied anyway and reported with `forced: true`; `None` disables it, and values below 2 are refused by `GateRecovery::new` |
+
+The streak counts every sensor and resets on any accepted update. `GateRecovery::none()` turns
+both mechanisms off.
+
+The third scene of `aiding.rs` installs a 0.999 gate on a vehicle driving north at 10 m/s, then
+from t = 61 s feeds fixes 200 m east of the truth:
+
+```rust,ignore
+{{#include ../../../core/examples/aiding.rs:gate}}
+```
+
+```rust,ignore
+{{#include ../../../core/examples/aiding.rs:outcome}}
+```
+
+### Configuring the gate in `strapdown-sim`
+
+| `cl` flag | config key in `[closed_loop]` | meaning |
+| --- | --- | --- |
+| `--gate-confidence
` | `innovation_gate = { chi_squared = { confidence = P } }` | install a $\chi^2$ gate |
+| `--gate-inflation ` | `gate_recovery = { rejection_inflation = F }` | inflation per rejection, default 2 |
+| `--gate-force-after ` | `gate_recovery = { forced_update_after = N }` | forced-update streak, default 5 |
+
+`innovation_gate = { fixed = { threshold = T } }` selects the fixed variant in a file. Gating
+rejects individual measurements; a filter that has genuinely diverged produces a large NIS on
+every fix, and the run's health monitor (`--nis-pos-max`, `--nis-pos-consec-fail`) is what stops
+it rather than letting it degrade silently to dead reckoning.
+
+## Output of `aiding.rs`
+
+```text
+parked for 30 s, 286 ZUPT/ZARU pairs
+ gyro bias estimate z: 0.00200 rad/s (injected 0.00200)
+ speed: 0.0000 m/s, altitude 12.00 m
+magnetometer: declination -11.85 deg, true heading 30.00 deg, measured 30.00 deg
+chi-squared 0.999 threshold, 1 dof: 10.83
+chi-squared 0.999 threshold, 3 dof: 16.27
+chi-squared 0.999 threshold, 5 dof: 20.52
+t = 59 s NIS 0.0 accepted true forced false
+t = 60 s NIS 0.0 accepted true forced false
+t = 61 s NIS 2805.9 accepted false forced false
+t = 62 s NIS 1564.2 accepted false forced false
+t = 63 s NIS 674.9 accepted false forced false
+t = 64 s NIS 256.0 accepted false forced false
+t = 65 s NIS 93.6 accepted true forced true
+t = 66 s NIS 43.5 accepted false forced false
+t = 67 s NIS 107.0 accepted false forced false
+t = 68 s NIS 114.9 accepted false forced false
+t = 69 s NIS 88.9 accepted false forced false
+t = 70 s NIS 58.8 accepted true forced true
+```
+
+The ZARU updates recover the injected gyro bias; the magnetometer model returns the heading the
+field was built for; and the gate rejects the spoofed fixes while each rejection inflates the
+covariance, so the NIS falls, until the fifth consecutive failure is forced through. Against a
+constant 200 m offset the forced updates pull the solution toward the spoofed track a step at a
+time: a gate bounds how long the filter disagrees with its sensor, it does not detect a
+spoofer.
diff --git a/book/src/filters/particle-filter.md b/book/src/filters/particle-filter.md
index c2a27a10..5fd6bd0b 100644
--- a/book/src/filters/particle-filter.md
+++ b/book/src/filters/particle-filter.md
@@ -1,531 +1,65 @@
-# Particle Filters
-
-## Overview
-
-This document outlines the design for a particle filter-based Inertial Navigation System (INS) following the architecture established in the UKF implementation (`kalman.rs`). The design addresses vertical channel instability through two alternative approaches: third-order damping and 2.5D navigation.
-
-## Executive Summary: Key Architectural Decisions
-
-### 1. Custom Forward Propagation Function Required
-
-**Critical insight**: For 2.5D navigation, we **cannot reuse** the standard `forward()` function from `lib.rs`. A new `forward_2_5d()` function must be implemented in `particle.rs`.
-
-**Why?**
-- Standard strapdown mechanization (Groves Eq 5.54) fully integrates vertical acceleration into vertical velocity
-- This creates deterministic coupling: `v_v(t+dt) = v_v(t) + ∫[a_z + g - Coriolis] dt`
-- In 2.5D navigation, we want vertical velocity to be a **random walk** constrained by measurements, not deterministically coupled to accelerometer readings
-
-**Solution**: `forward_2_5d()` implements:
-- **Full strapdown** for: attitude, horizontal velocities (v_n, v_e), horizontal position (lat, lon)
-- **Simplified** for: vertical velocity (random walk), altitude (integration of v_v only)
-
-### 2. Vertical Channel Treatment
-
-Two approaches are provided:
-
-| Approach | States | Vertical Velocity | Complexity | Recommended |
-|----------|--------|-------------------|------------|-------------|
-| **2.5D Simplified** | 15 | Random walk with large process noise | Low | **Yes** - Start here |
-| Third-Order Damping | 17 | Damped feedback control | High | Optional - if 2.5D insufficient |
-
-### 3. Implementation Priority
-
-1. First: Implement `forward_2_5d()` - this is the foundation
-2. Second: Implement particle filter with 2.5D mode
-3. Later: Optionally add third-order damping if needed
-
-## State Representation
-
-### Standard 15-State Model
-
-Following the UKF implementation, the baseline particle filter uses a 15-state model:
-
-**Navigation states (9):**
-- Position: `[latitude, longitude, altitude]` (rad, rad, m)
-- Velocity: `[v_north, v_east, v_vertical]` (m/s)
-- Attitude: `[roll, pitch, yaw]` (rad) - represented internally as DCM
-
-**Bias states (6):**
-- Accelerometer biases: `[b_ax, b_ay, b_az]` (m/s²)
-- Gyroscope biases: `[b_gx, b_gy, b_gz]` (rad/s)
-
-### Extended State for Vertical Channel Damping
-
-For third-order vertical channel damping, add **optional states**:
-- Altitude error estimate: `δh` (m)
-- Altitude error rate: `δh_dot` (m/s)
-
-Total state dimension: **15 + 2 = 17 states** (when using damping)
-
-**Implementation note**: Use `Particle.other_states: Option>` for the damping states.
-
-## Vertical Channel Approaches
-
-### Approach A: Third-Order Vertical Channel Damping
-
-**Motivation**: The vertical channel in INS is inherently unstable due to coupling between altitude and vertical velocity errors. Third-order damping provides feedback to stabilize this channel.
-
-**State augmentation:**
-```
-x = [lat, lon, h, v_n, v_e, v_v, φ, θ, ψ, b_a, b_g, δh, δh_dot]
- └─────────────────────────────────────┘ └─────┘ └────────┘
- 15 standard states biases damping
-```
-
-**Dynamics model:**
-- Altitude error dynamics: `δh_dot = δv_v`
-- Altitude error rate dynamics: `δh_ddot = -k₁·δh - k₂·δh_dot + w_h`
- - `k₁`, `k₂`: Damping coefficients (tunable)
- - `w_h`: Process noise on altitude error
-
-**Feedback mechanism:**
-During propagation (`predict` step):
-1. Propagate particles through standard strapdown equations
-2. Update altitude using damping feedback:
- ```
- h_corrected = h_propagated - k_fb · δh
- v_v_corrected = v_v_propagated - k_fb · δh_dot
- ```
-3. During measurement update with GPS altitude:
- - Innovation: `z - h_expected` updates both `h` and `δh`
- - Damping states receive weighted update based on particle importance
-
-**Pros:**
-- Theoretically rigorous approach based on observability analysis
-- Provides smooth vertical channel behavior
-- Well-suited for long GNSS outages
-
-**Cons:**
-- Additional states increase computational cost
-- Requires careful tuning of damping coefficients
-- Increased complexity in implementation
-
-### Approach B: 2.5D Navigation (Simplified Vertical Treatment)
-
-**Motivation**: Treat vertical acceleration as primarily noise-driven rather than deterministic, simplifying the vertical channel dynamics. This is the recommended approach based on past success.
-
-**State representation:**
-```
-x = [lat, lon, h, v_n, v_e, v_v, φ, θ, ψ, b_a, b_g]
- └────────────────────────────────────────────┘
- Standard 15 states only
-```
-
-**Modified dynamics:**
-- **Horizontal navigation**: Full 6-DOF strapdown mechanization for position, velocity, and attitude
-- **Vertical channel**: Simplified treatment:
- - Altitude propagation: `h(t+dt) = h(t) + v_v(t)·dt`
- - Vertical velocity: Integrate vertical acceleration with **high process noise**
- - Vertical acceleration noise: Model as white noise with large variance
- ```
- Q_vertical = [Q_h, Q_v_v] where Q_v_v >> Q_v_n, Q_v_e
- ```
-
-**Process noise tuning:**
-- Position (lat/lon): `1e-6` (tight)
-- Altitude: `1e-3` to `1e-2` (loose, allows drift)
-- Horizontal velocity: `1e-3`
-- Vertical velocity: `1e-2` to `1e-1` (very loose, absorbs vertical uncertainty)
-- Biases: `1e-6` to `1e-8` (standard)
-
-**Measurement handling:**
-- GPS altitude measurements directly constrain `h` with measurement noise
-- Barometric altitude (if available) provides additional vertical constraint
-- Vertical velocity measurements (if available) constrain `v_v`
-- During GNSS outages: Altitude drifts according to high process noise
-
-**Pros:**
-- Simpler implementation (no additional states)
-- Computationally efficient
-- Leverages particle filter's ability to handle non-Gaussian distributions
-- Works well with intermittent GPS
-- Avoids complex tuning of damping coefficients
-
-**Cons:**
-- Less theoretically rigorous
-- Vertical channel accumulates uncertainty faster during outages
-- Requires careful process noise tuning to balance stability and responsiveness
-
-## Particle Filter Architecture
-
-### Core Components
-
-#### Particle struct (already defined in `particle.rs`)
-```rust
-pub struct Particle {
- pub nav_state: StrapdownState, // 9 nav states
- pub accel_bias: DVector, // 3 accel biases
- pub gyro_bias: DVector, // 3 gyro biases
- pub other_states: Option>, // Optional: damping states
- pub state_size: usize, // Total dimension
- pub weight: f64, // Importance weight
-}
-```
-
-#### ParticleFilter struct
-```rust
-pub struct ParticleFilter {
- particles: Vec,
- num_particles: usize,
- process_noise: ProcessNoise,
- resampling_strategy: ResamplingStrategy,
- averaging_strategy: AveragingStrategy,
- effective_particle_threshold: f64, // e.g., 0.5 * num_particles
- rng: StdRng, // Seeded RNG for reproducibility
- is_enu: bool,
-
- // Vertical channel specific
- vertical_channel_mode: VerticalChannelMode, // ThirdOrder or Simplified
- damping_coefficients: Option<(f64, f64)>, // (k1, k2) if using damping
-}
-```
-
-#### ProcessNoise struct
-```rust
-pub struct ProcessNoise {
- pub position_std: Vector3, // [σ_lat, σ_lon, σ_h]
- pub velocity_std: Vector3, // [σ_vn, σ_ve, σ_vv]
- pub attitude_std: Vector3, // [σ_φ, σ_θ, σ_ψ]
- pub accel_bias_std: Vector3, // [σ_ba_x, σ_ba_y, σ_ba_z]
- pub gyro_bias_std: Vector3, // [σ_bg_x, σ_bg_y, σ_bg_z]
- pub damping_states_std: Option>, // [σ_δh, σ_δh_dot]
-}
-```
-
-#### Enums
-```rust
-pub enum VerticalChannelMode {
- ThirdOrderDamping { k1: f64, k2: f64 },
- Simplified, // 2.5D navigation
-}
-
-pub enum ResamplingStrategy {
- Systematic,
- Stratified,
- Residual,
- Multinomial,
-}
-
-pub enum AveragingStrategy {
- WeightedMean, // Standard weighted average
- MaximumWeight, // Use highest weight particle
- MeanWithTrimming, // Remove outliers then average
-}
-```
-
-### Core Algorithm
-
-#### Initialization
-```rust
-impl ParticleFilter {
- pub fn new(
- initial_state: InitialState,
- imu_biases: Vec,
- covariance_diagonal: Vec,
- process_noise: ProcessNoise,
- num_particles: usize,
- vertical_mode: VerticalChannelMode,
- seed: Option,
- ) -> Self;
-}
-```
-
-**Initialization steps:**
-1. Create `num_particles` particles from initial state
-2. Sample each particle's state from `N(μ₀, P₀)` where:
- - `μ₀` = initial mean state
- - `P₀` = diag(covariance_diagonal)
-3. Initialize all weights to `1.0 / num_particles`
-4. Seed RNG for reproducibility
-
-#### Predict Step
-
-**Key architectural decision**: For 2.5D navigation, we **cannot** use the standard `forward()` function from `lib.rs`. The standard strapdown mechanization fully integrates vertical acceleration to update vertical velocity (Equation 5.54 from Groves), which creates deterministic coupling we want to avoid in 2.5D.
-
-**Why a new forward function is needed:**
-
-The standard `forward()` computes vertical velocity as:
-```rust
-// velocity_update() in lib.rs, line 532
-velocity + (specific_force + gravity - r * (transport_rate + 2.0 * rotation_rate) * velocity) * dt
-```
-
-This tightly couples vertical acceleration to vertical velocity. In 2.5D navigation, we want:
-- **Horizontal dynamics**: Full strapdown (deterministic acceleration → velocity → position)
-- **Vertical dynamics**: Decoupled or weakly coupled (vertical velocity as random walk, altitude from velocity integration only)
-
-**Solution**: Implement `forward_2_5d()` that modifies vertical channel propagation.
-
-#### Update Step
-```rust
-impl NavigationFilter for ParticleFilter {
- fn update(&mut self, measurement: &M) {
- // 1. Compute weights based on measurement likelihood
- for particle in &mut self.particles {
- let predicted_meas = measurement.get_expected_measurement(
- &particle.to_state_vector()
- );
- let innovation = measurement.get_vector() - predicted_meas;
- let meas_cov = measurement.get_noise();
-
- // Likelihood: p(z|x) ∝ exp(-0.5 * innovation^T * R^-1 * innovation)
- let likelihood = self.compute_likelihood(&innovation, &meas_cov);
- particle.weight *= likelihood;
- }
-
- // 2. Normalize weights
- self.normalize_weights();
-
- // 3. Check effective particle count
- let n_eff = self.effective_particle_count();
-
- // 4. Resample if needed
- if n_eff < self.effective_particle_threshold {
- self.resample();
- }
- }
-}
-```
-
-#### Resampling
-
-Systematic resampling is the recommended strategy:
-
-```rust
-fn systematic_resample(&mut self) {
- let n = self.num_particles;
- let mut new_particles = Vec::with_capacity(n);
-
- // Cumulative sum of weights
- let cumsum: Vec = self.particles.iter()
- .scan(0.0, |sum, p| { *sum += p.weight; Some(*sum) })
- .collect();
-
- // Systematic sampling
- let step = 1.0 / n as f64;
- let start = self.rng.gen_range(0.0..step);
-
- for i in 0..n {
- let u = start + i as f64 * step;
- let idx = cumsum.iter().position(|&cs| cs >= u).unwrap_or(n - 1);
- let mut new_particle = self.particles[idx].clone();
- new_particle.weight = 1.0 / n as f64;
- new_particles.push(new_particle);
- }
-
- self.particles = new_particles;
-}
-```
-
-#### State Estimation
-
-```rust
-fn weighted_mean_estimate(&self) -> DVector {
- let mut mean_state = DVector::zeros(self.particles[0].state_size);
-
- for particle in &self.particles {
- let state_vec = particle.to_state_vector();
- mean_state += particle.weight * state_vec;
- }
-
- // Special handling for circular quantities (angles)
- self.wrap_angles(&mut mean_state);
-
- mean_state
-}
-```
-
-## The forward_2_5d() Function
-
-This function implements modified strapdown mechanization for 2.5D navigation. It should be added to `particle.rs` as a module-level function.
-
-### Mathematical Formulation
-
-**Full strapdown components (unchanged from Groves Ch 5.4-5.5):**
-1. **Attitude update** (Equation 5.46):
- ```
- C(t+dt) = C(t) * [I + Ω_ib * dt] - [Ω_ie + Ω_el] * C(t) * dt
- ```
- - Full implementation using gyros, transport rate, Earth rate
-
-2. **Horizontal velocity update** (Equation 5.54, horizontal components only):
- ```
- v_n(t+dt) = v_n(t) + [f_n + g_n - Coriolis_n - transport_n] * dt
- v_e(t+dt) = v_e(t) + [f_e + g_e - Coriolis_e - transport_e] * dt
- ```
- - Full mechanization for northward and eastward velocities
-
-3. **Horizontal position update** (Equation 5.56, lat/lon only):
- ```
- lat(t+dt) = lat(t) + [v_n / (R_N + h)] * dt
- lon(t+dt) = lon(t) + [v_e / ((R_E + h) * cos(lat))] * dt
- ```
-
-**Simplified vertical components (2.5D modification):**
-
-4. **Vertical velocity**: Random walk model (NOT integrated from acceleration)
- ```
- v_v(t+dt) = v_v(t) + w_v * sqrt(dt)
- ```
- - `w_v ~ N(0, σ_vv²)` - large process noise
- - **No deterministic integration of vertical specific force**
- - Vertical velocity drifts according to process noise only
-
-5. **Altitude update**: Simple integration of vertical velocity
- ```
- h(t+dt) = h(t) + v_v(t) * dt
- ```
- - Uses trapezoidal rule: `h(t+dt) = h(t) + 0.5 * [v_v(t) + v_v(t+dt)] * dt`
-
-### Implementation Details
-
-```rust
-/// Modified forward propagation for 2.5D navigation.
-///
-/// Implements full strapdown mechanization for horizontal navigation (position,
-/// velocity, attitude) while treating the vertical channel with simplified dynamics.
-/// Vertical acceleration is NOT integrated into vertical velocity; instead, vertical
-/// velocity follows a random walk model constrained by measurements and process noise.
-///
-/// # Arguments
-/// * `state` - Mutable reference to the navigation state
-/// * `imu_data` - Bias-corrected IMU measurements
-/// * `dt` - Time step in seconds
-///
-/// # Mathematical Basis
-/// - Horizontal: Full Groves Equations 5.46, 5.54, 5.56
-/// - Vertical: Simplified dynamics, vertical velocity as random walk
-pub fn forward_2_5d(state: &mut StrapdownState, imu_data: IMUData, dt: f64) {
- // See full implementation in source code
-}
-```
-
-### Key Differences from Standard forward()
-
-| Component | Standard `forward()` | `forward_2_5d()` |
-|-----------|---------------------|------------------|
-| Attitude | Full mechanization (Eq 5.46) | **Same** - Full mechanization |
-| Specific force transform | Full (Eq 5.47) | **Same** - Full transform |
-| Horizontal velocity | Full mechanization (Eq 5.54) | **Same** - Full mechanization |
-| **Vertical velocity** | **Integrated from vertical accel** | **NOT integrated - random walk** |
-| Horizontal position | Full mechanization (Eq 5.56) | **Same** - Full mechanization |
-| Altitude | Integrated from vertical velocity | **Same** - Simple integration |
-
-**Critical insight**: The ONLY difference is that `v_v(t+dt) ≈ v_v(t)` in the propagation step. Changes to vertical velocity come entirely from:
-1. Process noise injection (large `σ_vv`)
-2. Measurement updates (GPS altitude/velocity)
-
-This makes vertical velocity behave like a "free parameter" that is constrained by measurements rather than deterministic dynamics.
-
-## Integration with Existing Codebase
-
-### Mirroring UKF Structure
-
-The particle filter implements the same `NavigationFilter` trait as UKF:
-```rust
-pub trait NavigationFilter {
- fn predict(&mut self, imu_data: IMUData, dt: f64);
- fn update(&mut self, measurement: &M);
- fn get_estimate(&self) -> DVector;
- fn get_certainty(&self) -> DMatrix; // Empirical covariance from particles
-}
-```
-
-### Simulation Integration
-
-In `sim.rs`, add particle filter option to `closed_loop` function:
-```rust
-pub enum FilterType {
- UKF { alpha: f64, beta: f64, kappa: f64 },
- ParticleFilter {
- num_particles: usize,
- vertical_mode: VerticalChannelMode,
- resampling: ResamplingStrategy,
- },
-}
-```
-
-## Testing Strategy
-
-### Unit Tests
-- Test particle initialization from `InitialState`
-- Test process noise injection
-- Test resampling algorithms (verify particle diversity)
-- Test weight computation and normalization
-- Test vertical channel damping (if used)
-- Test state estimation with different averaging strategies
-
-### Integration Tests
-- Compare PF vs UKF on same trajectory
-- Test with GNSS dropout scenarios
-- Test vertical channel stability (hover, climb, descent scenarios)
-- Verify deterministic results with seeded RNG
-
-### Vertical Channel Tests
-Create tests similar to UKF tests in `kalman.rs`:
-- `pf_free_fall_motion()` - vertical dynamics with no support
-- `pf_hover_motion()` - stationary altitude
-- `pf_climb_descent()` - vertical motion profile
-- `pf_altitude_drift_during_outage()` - verify controlled drift with 2.5D
-
-## Recommended Implementation Order
-
-1. ✅ Define `Particle` struct (already done)
-2. **Implement `forward_2_5d()` function in `particle.rs`**
- - Copy `attitude_update()` from `lib.rs` or make it public
- - Implement `velocity_update_horizontal()` helper
- - Reuse `position_update()` from `lib.rs` (make public if needed)
-3. Implement `ProcessNoise` struct
-4. Implement `ParticleFilter` struct with basic initialization
-5. Implement `predict()` using `forward_2_5d()`
-6. Implement `update()` with systematic resampling
-7. Implement `get_estimate()` with weighted mean
-8. Write unit tests for each component
-9. Integration with `sim.rs`
-10. Test on real datasets
-11. (Optional) Implement third-order damping if 2.5D is insufficient
-
-## Tuning Guidance
-
-### Number of Particles
-- Start with **500-1000** particles for smartphone IMU
-- Increase to **2000-5000** for high-precision applications
-- Monitor computational cost vs. accuracy tradeoff
-
-### Process Noise (2.5D)
-**Conservative (high uncertainty, smooth vertical):**
-- `σ_h = 0.1 m`, `σ_vv = 0.2 m/s`
-
-**Aggressive (low uncertainty, responsive vertical):**
-- `σ_h = 0.01 m`, `σ_vv = 0.05 m/s`
-
-**Recommended starting point:**
-- `σ_h = 0.05 m`, `σ_vv = 0.1 m/s`
-
-### Resampling Threshold
-- Effective particle threshold: `0.5 * num_particles`
-- Resample more frequently if seeing particle degeneracy
-- Monitor `n_eff` over time to diagnose issues
-
-## Expected Performance
-
-### Advantages over UKF
-- Better handling of non-Gaussian distributions
-- More robust to outliers in measurements
-- Can represent multimodal posteriors (e.g., during ambiguous scenarios)
-- 2.5D approach naturally handles vertical channel uncertainty
-
-### Computational Cost
-- PF with N=1000 particles ≈ 10-50× slower than UKF
-- Use Rayon for parallel particle propagation if needed
-- Profile and optimize hot paths (propagation, resampling)
-
-### Memory Requirements
-- Each particle: ~200 bytes (15 states × 8 bytes + overhead)
-- 1000 particles ≈ 200 KB (negligible for modern systems)
-
-## References
-
-- Groves, P. D. (2013). *Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, 2nd Edition*. Chapters 14-15 (INS error models, vertical channel instability).
-- Gustafsson, F., et al. (2002). "Particle filters for positioning, navigation, and tracking." *IEEE Transactions on Signal Processing*.
-- Existing `kalman.rs` implementation for architectural patterns.
+# Particle Building Blocks
+
+`core/src/particle.rs` is not a particle filter. There is no canonical particle-filter INS, so
+the module provides pieces for assembling one: a trait for a particle, strategy enums, and four
+resampling algorithms. The one concrete particle filter in the crate is the
+[Rao-Blackwellized particle filter](./rbpf.md) in `core/src/rbpf.rs`, and it uses only the
+resampling half of this module.
+
+## What the module provides
+
+| item | kind | purpose |
+| --- | --- | --- |
+| `Particle` | trait | a weighted state hypothesis: `new(&DVector, weight)`, `state()`, `set_state(..)`, `weight()`, `set_weight(..)`, plus `as_any` downcasting helpers |
+| `ParticleFilter` | trait | one method, `resample(&mut self)`, for a filter built from these parts |
+| `ParticleResamplingStrategy` | enum | `Multinomial`, `Systematic` (the default), `Stratified`, `Residual` |
+| `ParticleAveragingStrategy` | enum | `Mean` (ignores weights), `WeightedMean` (the default), `HighestWeight` (the maximum-a-posteriori particle) |
+| `multinomial_resample`, `systematic_resample`, `stratified_resample`, `residual_resample` | functions | draw ancestor indices from a weight vector |
+
+Each resampling function takes `(weights: &[f64], num_samples: usize, rng: &mut R)` for any
+`R: rand::Rng` and returns a `Vec` of indices into the original particles; a particle
+whose index appears $k$ times is copied $k$ times. The weights must already be normalized to sum
+to one, and that is the caller's job.
+
+| algorithm | how it draws | variance |
+| --- | --- | --- |
+| multinomial | $N$ independent draws from the weight distribution | highest |
+| systematic | one random offset, then $N$ evenly spaced points through the cumulative weights | lower |
+| stratified | one random point in each of $N$ equal strata of $[0, 1)$ | lower than multinomial |
+| residual | $\lfloor N w_i \rfloor$ copies of each particle deterministically, the remainder systematically from the fractional parts | lower than multinomial |
+
+The algorithms are deterministic given the RNG state, so a seeded `StdRng` makes resampling
+reproducible.
+
+## How the RBPF uses them
+
+The RBPF does not implement `Particle` or `ParticleFilter`, and it does not use
+`ParticleAveragingStrategy`. Its particles (`rbpf::RbpfParticle`) carry a two-element horizontal
+position error, the conditional mean of the linear states and a weight, which is a different
+shape from a `Particle`'s single state vector; its estimate is a weighted mean with the linear
+states' covariance added by the law of total covariance (see [RBPF](./rbpf.md)).
+
+What it does use is the resampling:
+
+- `RbpfConfig::resampling_strategy` is a `ParticleResamplingStrategy`, defaulting to
+ `Systematic`.
+- After each measurement update the filter computes the effective sample size,
+ $N_\text{eff} = 1 / \sum_i w_i^2$ (`RaoBlackwellizedParticleFilter::effective_sample_size`),
+ and resamples when it falls below `effective_sample_threshold` times the particle count.
+ The default threshold, 1.0, resamples after every update, as Canciani and Raquet do.
+- The selected strategy's function draws the indices; the survivors are copied with uniform
+ weights and then roughened by `roughening_factor` (see [RBPF](./rbpf.md#configuration)).
+- The draws come from the filter's own `StdRng`, seeded by `RbpfConfig::seed`, so a run is
+ reproducible.
+
+`resampling_strategy` is a field of the library's `RbpfConfig` only. The simulator's
+`[particle_filter]` section and the `pf` subcommand do not expose it, so `strapdown-sim pf`
+always resamples systematically.
+
+## Building your own
+
+A filter assembled from these parts implements `Particle` for its state type, keeps its own
+weights normalized, calls one of the resampling functions inside its `ParticleFilter::resample`,
+and implements [`NavigationFilter`](./kalman.md#the-navigationfilter-trait) so it can be driven
+by `sim::run_closed_loop` or [`InsEngine`](../user-guide/library.md). The RBPF is the worked
+example of the last two steps; `core/src/rbpf.rs` documents the rest.
diff --git a/book/src/filters/rbpf.md b/book/src/filters/rbpf.md
index 132c163a..3a1ab6f9 100644
--- a/book/src/filters/rbpf.md
+++ b/book/src/filters/rbpf.md
@@ -124,6 +124,19 @@ The paper's setting never tests this: a navigation-grade INS, map fixes every ep
6. **Process noise across an epoch.** The accumulated process noise carries each state's own
decay across the epoch, so a Gauss-Markov state stays stationary over long gaps between
sparse fixes.
-7. **Configurable horizontal process noise.** The default is the paper's zero.
+7. **Configurable horizontal process noise.** The library's `RbpfConfig` defaults to the paper's
+ zero; `strapdown-sim` and its `[particle_filter]` section default to `[1, 1]` m/√s, for the
+ reason [above](#horizontal-process-noise-why-the-default-is-1-ms).
The implementation, with equation references throughout, is `core/src/rbpf.rs`.
+
+## See also
+
+- [Tutorial: Particle Filter](../examples/tutorial-particle-filter.md) runs `strapdown-sim pf`
+ end to end on a synthetic trajectory and scores it against truth.
+- [Particle Building Blocks](./particle-filter.md): the resampling algorithms this filter uses.
+ It resamples systematically; `RbpfConfig::resampling_strategy` selects another algorithm from
+ the library, and the simulator does not expose it.
+- [Measurement Models and Integrity](./measurements.md): the models it is updated with, and the
+ innovation gate it honours like the Kalman filters.
+- [Particle Filter](../user-guide/particle-filter.md) in the user guide: the `pf` subcommand.
diff --git a/book/src/filters/ukf.md b/book/src/filters/ukf.md
index 0092ade7..17a524b3 100644
--- a/book/src/filters/ukf.md
+++ b/book/src/filters/ukf.md
@@ -1 +1,150 @@
# Unscented Kalman Filter (UKF)
+
+`kalman::UnscentedKalmanFilter` propagates a deterministic set of **sigma points** through the
+nonlinear mechanization and the measurement models instead of linearizing them (Julier and
+Uhlmann). It needs no transition Jacobian, and its update uses only each model's
+`get_expected_measurement`. Run it with `strapdown-sim cl --filter ukf`.
+
+## State
+
+The full state vector of the [shared layout](./kalman.md#state-layout-and-units): nine
+navigation states, the six IMU biases, then any extra states (`UkfConfig::other_states`, such as
+geophysical map biases) and, last, the barometric bias when `estimate_baro_bias` is set.
+`initialize_ukf` always builds the fifteen-state core; the constructor accepts an empty bias
+slice for a nine-state filter, in which case no bias correction is applied.
+
+## Sigma points and weights
+
+For an $n$-element state the scaled unscented transform uses $2n+1$ points and
+
+$$
+\lambda = \alpha^2 (n + \kappa) - n ,
+$$
+
+$$
+w^{(m)}_0 = \frac{\lambda}{n+\lambda}, \qquad
+w^{(c)}_0 = \frac{\lambda}{n+\lambda} + (1 - \alpha^2 + \beta), \qquad
+w^{(m)}_i = w^{(c)}_i = \frac{1}{2(n+\lambda)} .
+$$
+
+Point 0 is the mean; points $i$ and $i+n$ are the mean plus and minus column $i$ of a matrix
+square root of $(n+\lambda)P$ (`linalg::matrix_square_root`: an equilibrated Cholesky, with
+plain, jittered and eigenvalue fallbacks for a matrix that is not positive definite).
+
+The attitude rows are not treated as a vector. Adding a rotation vector to an Euler triple is
+not the same rotation as composing it, so for attitude each point is
+$R_\text{mean}\operatorname{Exp}(\pm\text{column})$, re-expressed on the mean's branch of the
+Euler angles. The same idea runs through the rest of the filter (#371):
+
+- **Predict.** Each sigma point is bias-corrected with *its own* bias hypothesis
+ ($\Delta v - b_a\Delta t$, $\Delta\theta - b_g\Delta t$) and mechanized. The mean of every
+ non-attitude row is the weighted sum. The mean attitude is formed in the tangent space at
+ propagated sigma point 0: the residuals $\operatorname{Log}(R_0^\top R_i)$ are summed with the
+ mean weights and mapped back. The covariance uses tangent-space attitude residuals, and
+ $q\ \Delta t$ is added to it.
+- **Update.** Every sigma point is passed through `get_expected_measurement`, giving
+ $\hat z$, $S$ and the state-measurement cross covariance (again with tangent-space attitude
+ residuals). After the gate, $K = P_{xz} S^{-1}$; the attitude part of $K\nu$ is a rotation
+ vector and is composed onto the mean attitude, the rest is added. The covariance becomes
+ $P - K S K^\top$ and is then transported onto the new attitude's tangent space with the same
+ right Jacobian the [ESKF](./eskf.md#update-injection-and-reset) uses (#398).
+
+## Defaults: $\alpha = 0.1$, $\beta = 2$, $\kappa = 0$
+
+| parameter | default | role |
+| --- | --- | --- |
+| `alpha` | `0.1` (`sim::DEFAULT_UKF_ALPHA`) | spread of the points about the mean |
+| `beta` | `2.0` | prior knowledge of the distribution; 2 is optimal for a Gaussian |
+| `kappa` | `0.0` | secondary spread |
+
+They are set by `UkfConfig::{ukf_alpha, ukf_beta, ukf_kappa}` (each an `Option`, `None` taking
+the default), by `[closed_loop]`'s `ukf_alpha`, `ukf_beta` and `ukf_kappa` in a configuration
+file, or by `--ukf-alpha`, `--ukf-beta` and `--ukf-kappa` on `strapdown-sim cl`. All three routes
+default to the same values.
+
+### Why not the textbook alpha of 0.001
+
+With $\kappa = 0$ the weights are $w_0 = 1 - \alpha^{-2}$ and $w_i = 1/(2n\alpha^2)$. They sum to
+exactly 1 for any $\alpha$, but they cancel only in exact arithmetic. At $\alpha = 10^{-3}$ and
+$n = 16$ the mean is formed as $-999{,}999\ x_0 + \sum 31{,}250\ x_i$: every term is about
+$10^6$ times the answer, so six of `f64`'s sixteen significant digits go to cancellation on
+every propagation step. At $\alpha = 0.1$, $w_0 = -99$ and the cancellation costs two digits.
+
+That was the cause of #399, where the accuracy baseline moved under source changes that should
+have been invisible. The investigation recorded in `ClosedLoopConfig::ukf_alpha`'s
+documentation perturbed a single WGS84 constant by one unit in the last place and took the
+worst response over the gated metrics:
+
+| configuration | worst response to one ulp |
+| --- | ---: |
+| `alpha = 1e-3`, plain Cholesky (before #399) | 9.77% |
+| `alpha = 1e-3`, equilibrated Cholesky | 3.57% |
+| `alpha = 0.1`, plain Cholesky | 0.000297% |
+| `alpha = 0.1`, equilibrated Cholesky (shipped) | 0.000140% |
+
+`alpha` accounts for almost all of it; the equilibrated Cholesky that landed in the same change
+for a further factor of two. Over the same perturbations the EKF, ESKF and RBPF, none of which
+forms a weighted sigma-point mean, moved by less than $10^{-6}$%. The value is 0.1 rather than
+1.0 because $\alpha$ still has a job: it keeps the points near the mean (0.4 sigma at 0.1), so
+the transform samples the local nonlinearity rather than a shell several sigma out.
+
+### The conditioning tests
+
+`core/tests/ukf_conditioning.rs` holds both ends of that:
+
+- `one_ulp_of_input_cannot_move_the_solution_by_a_centimetre` runs the UKF twice through a
+ 180 s, 50 Hz synthetic scenario with GNSS duty-cycled 60 s off and 60 s on (no start phase,
+ so it opens with the outage), the second time with the initial latitude moved by one ulp, and requires the final positions to agree within 1 cm. The test's
+ own documentation records 1.76 m at the old $\alpha$ and 0.18 mm at 0.1.
+- `the_shipped_sigma_point_weights_do_not_cancel_away_the_mantissa` checks that the default
+ weights spend no more than 2.5 of `f64`'s digits on cancellation, so lowering $\alpha$ again
+ fails a test that names its own cause.
+
+```bash
+cargo test -p strapdown-core --test ukf_conditioning
+```
+
+## Construction
+
+```rust,ignore
+{{#include ../../../core/examples/kalman_filters.rs:ukf_new}}
+```
+
+The arguments are an `InitialState`, the six initial bias estimates, optional extra states, the
+covariance diagonal (one entry per state, in the units of the
+[shared layout](./kalman.md#state-layout-and-units)), the process-noise density $q$ as a
+matrix, and $\alpha$, $\beta$, $\kappa$. `sim::initialize_ukf(&record, UkfConfig)` builds the
+same filter from a `TestDataRecord`; [Kalman Filters](./kalman.md#the-siminitialize_-helpers)
+lists the config fields and the $P_0$ it derives.
+
+The same run as a configuration file (verified with `strapdown-sim --config` on a `syn`
+trajectory):
+
+```toml
+input = "synthetic.csv"
+output = "cl_ukf_config.csv"
+mode = "closed-loop"
+
+[closed_loop]
+filter = "ukf"
+ukf_alpha = 0.1
+ukf_beta = 2.0
+ukf_kappa = 0.0
+```
+
+## Things to know
+
+- The update calls `get_expected_measurement` on all $2n+1$ points and never `get_jacobian`,
+ so a model's Jacobian does not affect this filter. `MeasurementModel` still requires one,
+ because the other filters use it.
+- Each predict and each update factorizes the covariance once and evaluates the mechanization
+ or the measurement model at all $2n+1$ points. No timing comparison is published for this
+ crate.
+- The reported Euler angles are on the principal branch after both predict and update.
+
+## References
+
+- Julier, S. J. and Uhlmann, J. K., "Unscented Filtering and Nonlinear Estimation",
+ *Proceedings of the IEEE* 92(3), 2004.
+- `UnscentedKalmanFilter` in `core/src/kalman.rs`, and `ClosedLoopConfig::ukf_alpha` in
+ `core/src/sim.rs` for the full #399 record.
diff --git a/book/src/geonav/data-sources.md b/book/src/geonav/data-sources.md
deleted file mode 100644
index 570d8c3a..00000000
--- a/book/src/geonav/data-sources.md
+++ /dev/null
@@ -1 +0,0 @@
-# Data Sources and Maps
diff --git a/book/src/geonav/gravity.md b/book/src/geonav/gravity.md
deleted file mode 100644
index 27f4d4cf..00000000
--- a/book/src/geonav/gravity.md
+++ /dev/null
@@ -1 +0,0 @@
-# Gravity Anomaly Navigation
diff --git a/book/src/geonav/magnetic.md b/book/src/geonav/magnetic.md
deleted file mode 100644
index fbc2b683..00000000
--- a/book/src/geonav/magnetic.md
+++ /dev/null
@@ -1 +0,0 @@
-# Magnetic Anomaly Navigation
diff --git a/book/src/geonav/maps.md b/book/src/geonav/maps.md
new file mode 100644
index 00000000..679d148d
--- /dev/null
+++ b/book/src/geonav/maps.md
@@ -0,0 +1,221 @@
+# Maps and Measurement Models
+
+> **Experimental.** This page documents `strapdown-geonav` 0.1 (imported as `geonav`). See
+> [Geophysical Navigation Overview](./overview.md) for how to run it.
+
+A geophysical measurement compares two numbers: an **anomaly computed from a sensor reading**,
+and the **anomaly read off a map** at the filter's estimated position. Everything below is
+about how each of those is formed, and how the map's own error is absorbed by a bias state.
+
+## Maps: `GeoMap`
+
+`GeoMap` holds one regular latitude/longitude grid: a vector of latitudes, a vector of
+longitudes (both in degrees, ascending), a matrix of values with one row per latitude and one
+column per longitude, and a `GeophysicalMeasurementType` saying what the values are.
+
+`GeoMap::load_geomap(path, map_type)` reads a NetCDF file with three variables:
+
+| variable | shape | contents |
+|---|---|---|
+| `lat` | 1-D | latitudes, degrees |
+| `lon` | 1-D | longitudes, degrees |
+| `z` | `lat` × `lon` | anomaly: milligal for gravity, nanotesla for magnetic |
+
+This is the layout GMT writes for its gridded datasets. The file does not say what kind of map
+it is, so the caller supplies the type. A file that cannot be opened, lacks one of the three
+variables, or whose `z` does not have `len(lat) × len(lon)` values is rejected with
+`StrapdownError::MapLoad`.
+
+### Map types and resolutions
+
+`GeophysicalMeasurementType` is `Relief`, `Gravity` or `Magnetic`, each carrying a resolution
+enum. The resolutions are the grid spacings GMT publishes its remote datasets at, and each
+formats as GMT's code for it (`01d`, `30m`, ... `01m`):
+
+| type | resolutions |
+|---|---|
+| `GravityResolution` | one degree; 30, 20, 15, 10, 6, 5, 4, 3, 2 and 1 arc-minutes |
+| `MagneticResolution` | one degree; 30, 20, 15, 10, 6, 5, 4, 3 and 2 arc-minutes |
+| `ReliefResolution` | also includes arc-second spacings; no measurement model uses relief |
+
+The resolution is metadata. Interpolation uses the grid actually stored in the file, so a label
+that disagrees with the file changes nothing numerically.
+
+### Reading a value: bilinear interpolation
+
+`GeoMap::get_point(lat, lon)` interpolates bilinearly between the four surrounding grid nodes
+$(\varphi_1, \lambda_1)$, $(\varphi_2, \lambda_2)$:
+
+$$
+m(\varphi, \lambda) = \frac{
+ q_{11}(\lambda_2-\lambda)(\varphi_2-\varphi) + q_{12}(\lambda_2-\lambda)(\varphi-\varphi_1) +
+ q_{21}(\lambda-\lambda_1)(\varphi_2-\varphi) + q_{22}(\lambda-\lambda_1)(\varphi-\varphi_1)
+}{(\lambda_2-\lambda_1)(\varphi_2-\varphi_1)}
+$$
+
+with $q_{ij}$ the value at $(\varphi_i, \lambda_j)$, and linear interpolation along an edge. A
+non-finite coordinate is `StrapdownError::NonFinite`; a point outside the grid is
+`StrapdownError::OutOfMapBounds`.
+
+What happens when the estimate leaves the grid depends on the filter:
+
+- **EKF and particle filter:** `OutOfMapBounds` is classed as recoverable, so the measurement is
+ skipped with a warning naming the map bounds, and the run continues unaided by the map.
+- **UKF:** the predicted measurement is evaluated at each sigma point through a method that
+ cannot return an error, and an off-map point yields `NaN` there. The UKF checks for that before
+ it touches the state: if any sigma point has no finite prediction, the update returns the
+ recoverable `MeasurementUnavailable`, and the measurement is skipped with a warning as on the
+ other filters. This happens a little sooner than on the EKF, since a sigma point can leave the
+ map while the estimate itself is still on it.
+
+Either way, size the map with room to spare around the track.
+
+### The map gradient
+
+The EKF and the particle filter's Kalman part need $\partial m / \partial \varphi$ and
+$\partial m / \partial \lambda$. `GeoMap::get_gradient` takes central differences with a step of
+$\epsilon = 10^{-6}$ degrees, falling back to a one-sided difference at the edge of the grid:
+
+$$
+\frac{\partial m}{\partial \varphi} \approx \frac{m(\varphi+\epsilon, \lambda) - m(\varphi-\epsilon, \lambda)}{2\epsilon},
+\qquad
+\frac{\partial m}{\partial \lambda} \approx \frac{m(\varphi, \lambda+\epsilon) - m(\varphi, \lambda-\epsilon)}{2\epsilon}.
+$$
+
+The result is per degree and is converted to per radian, the unit of the state. Because the
+interpolant is piecewise bilinear, this is the slope of the cell the estimate is in.
+
+## Measurement models
+
+Both models implement core's `MeasurementModel` trait and are one-dimensional. Each predicts the
+map value plus a bias, $h(\mathbf{x}) = m(\varphi, \lambda) + b$, and has
+$R = \sigma^2$ from its `noise_std`. The Jacobian row is
+
+$$
+H = \begin{bmatrix} \dfrac{\partial m}{\partial \varphi} & \dfrac{\partial m}{\partial \lambda} & 0 & \cdots & 0 & 1 & 0 & \cdots \end{bmatrix}
+$$
+
+with the 1 in the column of that channel's bias state, if the filter carries one.
+
+What makes them unusual is the *observation*. The sensor does not measure an anomaly; it
+measures a total field. Turning that into an anomaly needs the vehicle's position, altitude,
+velocity and the date, and those are only known once a filter is running. So the observation
+is computed from the state the filter hands the model, at update time, not when the event
+stream is built.
+
+### Gravity: `GravityMeasurement`
+
+The observed specific-force magnitude $g_\text{obs}$ is the norm of the record's
+`grav_x`, `grav_y`, `grav_z` columns (m/s²). The anomaly, in milligal, is
+
+$$
+\Delta g = \left[\ g_\text{obs} - \gamma(\varphi, h) + E \ \right] \times 10^{5}
+$$
+
+where:
+
+- $\gamma(\varphi, h) = \gamma_e \dfrac{1 + k \sin^2\varphi}{\sqrt{1 - e^2 \sin^2\varphi}} - 3.08\times10^{-6}\ h$
+ is Somigliana normal gravity on the WGS84 ellipsoid with the free-air gradient
+ (`earth::gravity`), evaluated at the observation height;
+- $E = 2\Omega v_E \cos\varphi + \dfrac{v_N^2}{R_N + h} + \dfrac{v_E^2}{R_E + h}$ is the Eötvös
+ correction (`earth::eotvos`): the down component of the Coriolis and transport-rate term of
+ Groves eq. 5.54, with the transport rate of eq. 5.44. A gravimeter on a moving platform reads
+ low by $E$, so it is added back;
+- $10^5$ converts m/s² to milligal (`earth::MGAL_PER_M_PER_S2`).
+
+Because $h$ is height above the ellipsoid, this is strictly the gravity disturbance rather than
+the classical free-air anomaly, which is referred to the geoid. The two differ by about
+$0.3086\ N$ mGal for a geoid undulation of $N$ metres: near-constant over a trajectory, and
+absorbed by the bias state. This is `earth::gravity_anomaly`.
+
+### Magnetic: `MagneticAnomalyMeasurement`
+
+The observed total field $|\mathbf{B}_\text{obs}|$ is the norm of `mag_x`, `mag_y`, `mag_z`,
+which are microtesla, scaled by 1000 into nanotesla. The anomaly is
+
+$$
+\Delta F = |\mathbf{B}\_\text{obs}| - F\_\text{WMM}(\varphi, \lambda, h, t)
+$$
+
+where $F_\text{WMM}$ is the World Magnetic Model's total intensity at the estimated position and
+the record's date, from the `world_magnetic_model` crate, in nanotesla. Altitude is clamped to
+the model's valid band of −1 km to 850 km. A position or date the model cannot serve is
+`StrapdownError::ExternalModel`, which is recoverable: the measurement is skipped.
+
+The total-field magnitude is used because it does not depend on the sensor's orientation, so
+attitude error does not enter the observation.
+
+### Both: `CombinedGeophysicalMeasurement`
+
+When a run loads both maps and a record carries both readings, the two are emitted as a single
+two-dimensional measurement, $[\Delta g, \Delta F]$, with a diagonal $R$: the two channels'
+noises are taken as independent. For the filters that use the Jacobian, either half falling
+off its map fails the whole measurement rather than applying the other half alone.
+
+## Bias states
+
+The map is not the truth. Grids are smoothed, referenced to a different datum or epoch, and a
+magnetometer in a vehicle also sees the vehicle. Each channel therefore has a bias state $b$
+in the map's unit, and $h(\mathbf{x}) = m + b$.
+
+**UKF and EKF.** The biases are appended after the 15 navigation and IMU-bias states, gravity
+first, then magnetic, then the barometric bias if it is estimated (the default; see
+`--no-estimate-baro-bias`). Each is a random walk: initial value `gravity_bias` /
+`magnetic_bias`, initial variance `*_bias_init_std`², and process-noise density
+`*_bias_process_noise_std`² (a variance per second, so $Q = q\ \Delta t$). The
+initial standard deviation defaults to the measurement noise; the random-walk rate defaults to
+that prior spread over an hour, $\sigma_0/\sqrt{3600\ \text{s}}$.
+
+`GeoBiasLayout` records where these states sit and how wide the filter's state is. Each
+measurement carries a `BiasState` with both numbers and checks them against the state vector
+it is handed, so a measurement built for one filter layout and given to another fails with
+`StrapdownError::DimensionMismatch` instead of reading an IMU bias as a map bias.
+
+**Particle filter.** Following Canciani & Raquet, each channel's bias is split into a
+first-order Gauss-Markov temporal variation $V$ and a constant $c$, both linear states of the
+filter's shared Kalman part, and the measurement selects $V + c$. See
+[Rao-Blackwellized Particle Filter](../filters/rbpf.md).
+
+## When measurements are emitted
+
+`geonav::build_event_stream` builds the ordinary event stream with
+`strapdown::messages::build_event_stream` (IMU, GNSS, barometer and magnetometer heading, with
+their schedules and GNSS faults) and merges the geophysical events into it. Its geophysical
+settings come in a `GeophysicalAiding` struct: the maps, the two noise values, the interval
+between measurements, and the bias layout.
+
+- With `geo_interval_s` unset, every record that carries the reading produces a measurement;
+ with it set, one is produced at most every `geo_interval_s` seconds.
+- A record with any `NaN` among `grav_*` (or `mag_*`) produces no measurement on that channel.
+- At equal timestamps the geophysical measurement comes after the others.
+- Geophysical measurements continue through a GNSS outage; that is the point of them.
+
+## Where the maps come from
+
+The Python tooling downloads them. `analyze preprocess --getmaps` (see
+[Python Analysis Tooling](../development/analysis.md)) calls PyGMT for each trajectory, over its
+bounding box padded by a fraction (`--buffer`, default 0.1) and a fixed margin
+(`--margin-km`, default 5 km):
+
+| file | PyGMT call | grid |
+|---|---|---|
+| `_gravity.nc` | `load_earth_free_air_anomaly(resolution="01m")` | 1 arc-minute free-air anomaly, mGal |
+| `_magnetic.nc` | `load_earth_magnetic_anomaly(resolution="03m", data_source="wdmam")` | 3 arc-minute World Digital Magnetic Anomaly Map, nT |
+| `_relief.nc` | `load_earth_relief(resolution="15s")` | 15 arc-second relief, for plotting only |
+
+These names are what `strapdown-sim` looks for beside each input CSV. Note that the shipped
+recipes label the magnetic map `two_minutes` while the file holds a 3 arc-minute grid; as above,
+the label has no numerical effect. When preprocessing splits a recording into segments without
+`--getmaps`, each segment is given a copy of its parent recording's maps, which necessarily
+cover it. Downloading needs the GMT C library and network access; nothing else in the toolchain
+does.
+
+## The Python mirror of these models
+
+`analysis/src/analysis/geostats.py` (`analyze geostats`) characterises a data set's geophysical
+readings against its maps: per-channel bias, measurement noise, signal-to-noise ratio and the
+de-correlation length along track. For those statistics to describe the quantity the filter
+actually sees, its anomaly functions (`normal_gravity`, `eotvos`, `gravity_anomaly_mgal`,
+`observed_field_nt`, `wmm_total_field_nt`) mirror `core/src/earth.rs` and `geonav/src/lib.rs`
+term for term, and its `self_check()` asserts that the two implementations agree on known cases
+before any statistic is computed.
diff --git a/book/src/geonav/overview.md b/book/src/geonav/overview.md
index d2e33d5e..8bcfcb28 100644
--- a/book/src/geonav/overview.md
+++ b/book/src/geonav/overview.md
@@ -1 +1,199 @@
# Geophysical Navigation Overview
+
+> **Experimental.** The `strapdown-geonav` crate is held at version 0.1 so that its API can
+> still change, and its results are research results, not a validated product. Everything on
+> this page describes what the code does today.
+
+Geophysical navigation aids an inertial solution with a quantity the Earth itself provides: the
+local **gravity anomaly** or the local **magnetic anomaly**. Both vary with position and are
+published as global grids. A sensor on the vehicle measures the anomaly, the filter reads the
+same quantity off a map at its estimated position, and the difference corrects the position
+estimate. Unlike GNSS, nothing has to be received, so there is nothing to jam or spoof. The
+price is that a map measurement is a highly nonlinear, often ambiguous function of position,
+and that the signal (tens of milligal, tens to hundreds of nanotesla) is small against the
+sensor errors of anything cheap.
+
+The work this module supports is described in two Institute of Navigation papers, one using the
+UKF and one the particle filter (see [Publications and Links](../resources/publications.md)):
+
+- J. Brodovsky and P. Dames, "Navigation in GNSS-denied environments using MEMS-grade sensors
+ and geophysical anomalies: A UKF approach," *ION ITM 2026*, pp. 155–164,
+ [doi:10.33012/2026.20508](https://doi.org/10.33012/2026.20508).
+- J. Brodovsky and P. Dames, "Navigation in GNSS-Denied Environments Using MEMS-Grade Sensors
+ and Geophysical Anomalies: A Particle Filter Approach," *ION Pacific PNT 2026*, pp. 399–410,
+ [doi:10.33012/2026.20618](https://doi.org/10.33012/2026.20618).
+
+[Maps and Measurement Models](./maps.md) has the measurement equations, the bias states and
+where the maps come from.
+
+## Building
+
+Geophysical aiding is a feature of `strapdown-sim`, off by default because it compiles libnetcdf
+(and with it HDF5) from source, which needs a C compiler and cmake 3.26 or newer:
+
+```bash
+cargo build --release -p strapdown-sim --features geonav
+# or, to install the binary
+cargo install --git https://github.com/jbrodovsky/strapdown-rs strapdown-sim --features geonav
+```
+
+A binary built without the feature has no `--geo` flag at all. (There used to be a separate
+`geonav-sim` binary; it was folded into `strapdown-sim`.)
+
+## Which filters
+
+| mode | filter | geophysical aiding |
+|---|---|---|
+| `cl --filter ukf` | UKF | yes |
+| `cl --filter ekf` | EKF | yes |
+| `cl` (default `--filter eskf`) | ESKF | **no**: the run stops with "ESKF is not yet implemented for geophysical navigation" |
+| `pf` | Rao-Blackwellized particle filter | yes |
+| `dr` | dead reckoning | no |
+
+Because the ESKF is the closed-loop default, `cl --geo` must name `--filter ukf` or
+`--filter ekf`, and a config file must set `filter` in `[closed_loop]`.
+
+## Command-line flags
+
+All of these require `--geo`, and at least one of `--gravity-resolution` or
+`--magnetic-resolution` must be given; a run with `--geo` and neither stops with "geophysical
+navigation needs at least one map". The same flags are available on `cl` and `pf`.
+
+| flag | unit | default | meaning |
+|---|---|---|---|
+| `--geo` | -- | off | enable geophysical aiding |
+| `--gravity-resolution` | -- | unset | enable gravity aiding; one of `one-degree` ... `one-second` (see below) |
+| `--gravity-map-file` | path | `_gravity.nc` | gravity anomaly map |
+| `--gravity-noise-std` | mGal | 100 | gravity measurement noise σ |
+| `--gravity-bias` | mGal | 0 | initial value of the gravity map-bias state |
+| `--gravity-bias-init-std` | mGal | `--gravity-noise-std` | initial σ of the gravity map-bias state |
+| `--gravity-bias-process-noise-std` | mGal/√s | init σ / √3600 | random-walk rate of the gravity map bias |
+| `--magnetic-resolution` | -- | unset | enable magnetic aiding; same choices |
+| `--magnetic-map-file` | path | `_magnetic.nc` | magnetic anomaly map |
+| `--magnetic-noise-std` | nT | 150 | magnetic measurement noise σ |
+| `--magnetic-bias` | nT | 0 | initial value of the magnetic map-bias state |
+| `--magnetic-bias-init-std` | nT | `--magnetic-noise-std` | initial σ of the magnetic map-bias state |
+| `--magnetic-bias-process-noise-std` | nT/√s | init σ / √3600 | random-walk rate of the magnetic map bias |
+| `--geo-interval-s` | s | every record | seconds **between** geophysical measurements (alias `--geo-frequency-s`) |
+
+The particle filter adds four more, for the temporal-variation part of its map-bias model (see
+[Rao-Blackwellized Particle Filter](../filters/rbpf.md)): `--gravity-variation-std`,
+`--gravity-variation-time-constant-s` (default 300 s), `--magnetic-variation-std` and
+`--magnetic-variation-time-constant-s` (default 300 s). The two standard deviations default to
+values derived from the corresponding `--*-bias-process-noise-std`.
+
+The 100 mGal and 150 nT noise defaults are placeholders; nothing has measured them against
+these maps. Set the noise and the bias prior for your sensor. `--magnetic-bias-init-std` in
+particular wants to be large for a magnetometer inside a vehicle, whose own field the bias
+state exists to absorb.
+
+**The resolution flags are labels, not selectors.** The grid used is whatever the map file
+contains; the resolution is recorded with the map but changes nothing numerically. Gravity
+labels stop at `one-minute` and magnetic labels at `two-minutes`. A finer choice is refused
+before the run starts, with an error listing the supported labels, on the command line and in a
+configuration file alike.
+
+## Configuration file
+
+The same settings, in snake case, go in a `[geophysical]` section. This file ran as written
+against a synthetic trajectory with map files beside it:
+
+```toml
+input = "synthetic.csv"
+output = "results/geo_cfg.csv"
+mode = "closed-loop"
+
+[closed_loop]
+filter = "ekf"
+
+[geophysical]
+gravity_resolution = "one_minute"
+gravity_noise_std = 50.0
+gravity_bias_init_std = 100.0
+magnetic_resolution = "two_minutes"
+magnetic_noise_std = 20.0
+magnetic_bias_init_std = 500.0
+geo_interval_s = 5.0
+
+[aiding.scheduler]
+kind = "duty_cycle"
+on_s = 100.0
+off_s = 200.0
+start_phase_s = 0.0
+```
+
+| key | CLI counterpart |
+|---|---|
+| `gravity_resolution`, `magnetic_resolution` | `--gravity-resolution`, `--magnetic-resolution` (in the file the values are snake case, `one_minute`, `two_minutes`, ...; on the command line, kebab case) |
+| `gravity_map_file`, `magnetic_map_file` | `--gravity-map-file`, `--magnetic-map-file` |
+| `gravity_noise_std`, `magnetic_noise_std` | `--gravity-noise-std`, `--magnetic-noise-std` |
+| `gravity_bias`, `magnetic_bias` | `--gravity-bias`, `--magnetic-bias` |
+| `gravity_bias_init_std`, `magnetic_bias_init_std` | `--gravity-bias-init-std`, `--magnetic-bias-init-std` |
+| `gravity_bias_process_noise_std`, `magnetic_bias_process_noise_std` | `--gravity-bias-process-noise-std`, `--magnetic-bias-process-noise-std` |
+| `geo_interval_s` (alias `geo_frequency_s`) | `--geo-interval-s` |
+
+The particle filter's variation settings go in `[particle_filter]` as
+`gravity_variation_std`, `gravity_variation_time_constant_s`, `magnetic_variation_std` and
+`magnetic_variation_time_constant_s`. The recipes `conf/{ukf,ekf,rbpf}_{grav,mag,both}.toml`
+are complete worked examples, with the source of every number in their comments.
+
+## How maps are found
+
+Unless a map file is given explicitly, `strapdown-sim` looks for it **beside the input CSV,
+named after it**: for `data/input/drive.csv` it opens `data/input/drive_gravity.nc` and
+`data/input/drive_magnetic.nc`. A directory input is processed file by file, so every
+trajectory needs its own pair. A missing map stops the run with
+`Gravity map file not found: ` (or the magnetic equivalent).
+
+A map is a NetCDF grid with one-dimensional `lat` and `lon` variables in degrees and a
+two-dimensional `z` variable of anomaly values, gravity in milligal and magnetic in nanotesla,
+which is the layout GMT writes. `analyze preprocess --getmaps` in the Python tooling downloads
+both maps for each trajectory and writes them under exactly these names; see
+[Maps and Measurement Models](./maps.md#where-the-maps-come-from).
+
+## Output
+
+The output CSV always carries `gravity_bias`, `gravity_bias_cov`, `magnetic_bias` and
+`magnetic_bias_cov` columns (see [Output Format](../user-guide/output-format.md)). For each
+channel a geophysically aided run uses, they hold the filter's estimate of the map bias, in
+the map's unit, and its variance; for a channel the run does not use, they are empty (a
+gravity-only `pf --geo` run leaves both `magnetic_bias` cells blank).
+
+## Example
+
+The command below ran against `strapdown-sim syn -o synthetic.csv --duration-s 600 --seed 42`,
+with `synthetic_gravity.nc` and `synthetic_magnetic.nc` beside it. Those two maps were written
+by a short Python script as a smooth artificial field covering the track: `syn` does not
+produce maps, and its `grav_*` and `mag_*` columns are not sampled from any map, so this shows
+the mechanics of a run, not geophysical navigation performance.
+
+```bash
+strapdown-sim cl -i synthetic.csv -o geo_both.csv --filter ekf \
+ --geo --gravity-resolution one-minute --magnetic-resolution two-minutes \
+ --gravity-noise-std 50 --magnetic-noise-std 20 --magnetic-bias-init-std 500
+
+strapdown-sim pf -i synthetic.csv -o geo_pf.csv \
+ --geo --gravity-resolution one-minute --geo-interval-s 5 --num-particles 200
+```
+
+## Status and limitations
+
+- **Experimental API.** `strapdown-geonav` is 0.1 and may change in any release.
+- **No ESKF.** Only the UKF, the EKF and the particle filter accept geophysical measurements.
+- **Leaving the map.** A measurement whose estimate is off the map tile is skipped with a
+ warning, so a map that is too small quietly stops aiding. The UKF skips one as soon as any of
+ its sigma points is off the map. A run that skips more than 100 measurements in a row fails
+ with `FilterDiverged`. Pad the map well beyond the track; see
+ [Maps and Measurement Models](./maps.md#reading-a-value-bilinear-interpolation).
+- **The sensor matters more than the filter.** The gravity observation is the magnitude of the
+ record's `grav_x/y/z` columns and the magnetic observation the magnitude of `mag_x/y/z`.
+ Phone recordings from Sensor Logger are poor sources for both: the magnitude of the `grav_*`
+ channel is pinned to a device constant, so it carries no gravity information, and the
+ magnetometer is dominated by the vehicle's own field. The project's own experiments therefore
+ replace those two channels with simulated readings of dedicated low-cost sensors
+ (`analyze preprocess --synthetic`, documented in `analysis/src/analysis/synthetic.py`).
+- **The noise defaults are not measurements.** `analyze geostats` in the
+ [Python tooling](../development/analysis.md) measures bias, noise and signal-to-noise for a
+ data set against its maps.
+- **Relief maps are not used.** `GeoMap` can represent a terrain-relief grid, and the
+ preprocessing downloads one for plotting, but no measurement model consumes it.
diff --git a/book/src/gnss/corruption.md b/book/src/gnss/corruption.md
deleted file mode 100644
index 959d4542..00000000
--- a/book/src/gnss/corruption.md
+++ /dev/null
@@ -1 +0,0 @@
-# Measurement Corruption
diff --git a/book/src/gnss/dropouts.md b/book/src/gnss/dropouts.md
deleted file mode 100644
index 9a75f8aa..00000000
--- a/book/src/gnss/dropouts.md
+++ /dev/null
@@ -1 +0,0 @@
-# Dropout Scenarios
diff --git a/book/src/gnss/fault-simulation.md b/book/src/gnss/fault-simulation.md
index 66d0fd8a..e4eb4c5d 100644
--- a/book/src/gnss/fault-simulation.md
+++ b/book/src/gnss/fault-simulation.md
@@ -1,110 +1,152 @@
# Fault Simulation
-This chapter is the experiment-design rationale behind `conf/`: which GNSS conditions are
-worth simulating, what the published measurements say those conditions look like, and which
-knobs in `GnssFaultModel` correspond to which.
+This chapter is the experiment-design rationale behind the recipes in `conf/`: which GNSS
+conditions are worth simulating, what the published measurements say those conditions look
+like, and which knobs in `GnssFaultModel` correspond to which. Every variant, field, default
+and flag is listed in [Schedulers and Faults Reference](./scenarios.md); this page explains why
+the recipes use the values they do.
+
+Two pieces of the library are involved, and they are deliberately separate:
+
+- a **scheduler** (`MeasurementScheduler`) decides *when* a GNSS fix reaches the filter;
+- a **fault model** (`GnssFaultModel`) decides *what* is wrong with each fix that does.
+
+Both live in the `[aiding]` section of a configuration file. That section was called
+`[gnss_degradation]` before the v1.0 freeze, and the old name is still accepted as an alias,
+which is why the recipes under `conf/` still spell it that way.
## What jamming actually does
The dominant, repeatedly measured effect of jamming is **loss of fix**, not graceful
-degradation. At Jammertest — the open field trial run annually at Andøya by the Norwegian
-Public Roads Administration, Communications Authority, Defence Research Establishment,
-Metrology Service and Space Agency — the jamming signal was in most runs strong enough to
-cause complete GNSS signal loss, and a smartphone roughly ten metres from a jammer lost lock
-on benign signals entirely. Receivers reacquired when terrain or buildings shadowed them from
-the jammer and lost lock again on returning to line of sight.
+degradation. At Jammertest, the open field trial run annually at Andøya by Norwegian public
+agencies, the jamming signal was in most runs strong enough to cause complete GNSS signal
+loss, and a smartphone roughly ten metres from a jammer lost lock on benign signals entirely.
+Receivers reacquired when terrain or buildings shadowed them from the jammer and lost lock
+again on returning to line of sight.
That matters for how a scenario is built. A receiver inside the jammed area does not report a
noisier position; it reports nothing. A model that keeps delivering fixes with more error on
-them describes the *fringe* of the jammed area, not the inside of it — and it is the inside
-that an inertial system, or a geophysical aid, exists to carry you through.
+them describes the *fringe* of the jammed area, not the inside of it. The inside is what an
+inertial system, or a geophysical aid, exists to carry you through.
The scale is not marginal. IATA recorded a 220% rise in GPS signal-loss events between 2021
and 2024; European flights encountering GNSS interference rose from roughly 200 per day in Q1
2024 to around 900 per day in Q2, and EUROCONTROL logged more than 2,500 jamming events in
-2024 alone.
+2024 alone (see the sources at the end of this page).
-## The interference tier
+## The interference tiers
-| Tier | What it models | Scheduler | Fault | Configs |
+| Tier | What it models | Scheduler | Fault | Recipes |
|---|---|---|---|---|
+| **Denial** | inside a jammed area: no fix at all | `duty_cycle` | `none` | none shipped; use `--sched duty` |
| **Degraded** | the fringe of a jammed area | `fixed_interval` | `degraded` | `conf/*_degraded.toml` |
-| **Spoof** | a deceptive signal | either | `slow_bias` / `hijack` | — |
+| **Spoof** | a deceptive signal | either | `slow_bias` / `hijack` | none shipped; use `--fault slowbias` or `hijack` |
-An earlier version of this experiment matrix also carried a **Denial** tier
-(`duty_cycle`/`none`, modeling total loss of fix inside a jammed area) as a config separate
-from Degraded. It was consolidated into the single Degraded tier below: keeping one
-interference profile, used identically everywhere a geo-aided run is scored, was worth more
-than covering both regimes at the cost of doubling the config matrix and the pairing logic
-that keeps it honest (see "Choosing a baseline" below).
+The experiment matrix in `conf/` carries one interference profile, Degraded. Keeping one
+profile, used identically everywhere a geophysically aided run is scored, was worth more than
+covering both regimes at the cost of doubling the config matrix and the pairing logic that
+keeps it honest (see [Choosing a baseline](#choosing-a-baseline-to-compare-against) below).
+
+The Denial tier is still one command away. This gives 30 s of fixes in every 150 s, with
+availability as the only variable:
+
+```bash
+strapdown-sim cl -i input.csv -o denial.csv \
+ --sched duty --on-s 30 --off-s 120 --duty-phase-s 30 --fault none
+```
+
+`--duty-phase-s` is the length of an initial ON window. Without it the cycle starts with its
+OFF window, so the filter would begin with a 120 s outage before it had seen a single fix; see
+[the duty-cycle timeline](./scenarios.md#dutycycle).
### Degraded
-`conf/*_degraded.toml`: fixes every 5 s, with AR(1)-correlated error on position and velocity
-and the advertised accuracies inflated.
+`conf/*_degraded.toml` keeps **one fix every 60 s** (`fixed_interval`, `interval_s = 60.0`)
+from a roughly 1 Hz receiver, and puts AR(1)-correlated error on each one, with the advertised
+accuracies inflated:
-Anchoring the magnitude to measurement rather than to a round number: smartphone GNSS is 3–5 m
-under good multipath and over 10 m in harsh multipath, with semi-urban CEP95 around 10–12 m.
-Under jamming the tracked satellite count falls and GDOP rises, so true error and advertised
-accuracy inflate together. `sigma_pos_m = 35.0` is about 14× this dataset's 2.58 m median
-advertised accuracy — a receiver still producing fixes, but bad ones.
+```toml
+[gnss_degradation.scheduler] # the same as [aiding.scheduler]
+kind = "fixed_interval"
+interval_s = 60.0
+phase_s = 0.0
+
+[gnss_degradation.fault] # the same as [aiding.fault]
+kind = "degraded"
+rho_pos = 0.99 # ignored while tau_pos_s is set
+sigma_pos_m = 35.0 # steady-state wander, metres
+tau_pos_s = 500.0
+rho_vel = 0.95 # ignored while tau_vel_s is set
+sigma_vel_mps = 1.5 # steady-state wander, m/s
+tau_vel_s = 100.0
+r_scale = 5.0 # advertised sigmas x5, so R x25
+```
+
+The magnitude is anchored to measurement rather than to a round number. Smartphone GNSS is
+3–5 m under good multipath and over 10 m in harsh multipath, with semi-urban CEP95 around
+10–12 m. Under jamming the tracked satellite count falls and GDOP rises, so true error and
+advertised accuracy inflate together. 35 m of steady-state wander is roughly an order of
+magnitude above the few metres a phone advertises in open conditions: a receiver still
+producing fixes, but bad ones.
`r_scale` inflates the *advertised 1σ*, which the measurement model then squares, so **R moves
by `r_scale²`**: the standard 5.0 is a 25× R, not a 5× one.
### Spoofing
-`slow_bias` and `hijack` are implemented and unused in the current experiment matrix. They
-differ in detectability by construction: a `hijack` steps the position with no matching
-velocity change, so it produces a large NIS the moment it starts and a chi-squared gate
-rejects it. A `slow_bias` moves position and velocity consistently, which is what keeps it
-under the gate — that is the whole design of a soft spoof.
+`slow_bias` and `hijack` are implemented and not used in the current experiment matrix. They
+differ in detectability by construction. A `hijack` steps the position with no matching
+velocity change, so it produces a large normalized innovation squared (NIS) the moment it
+starts, which an innovation gate (`--gate-confidence`, off by default) can reject. A
+`slow_bias` moves position and velocity consistently, which is what is meant to keep it under
+the gate; that is the whole design of a soft spoof.
## Correlation time and the fix interval
-`rho_pos` and `rho_vel` are applied **once per emitted fix**, with no reference to elapsed
-time. The error's correlation time is therefore `-interval_s / ln(rho)` — a property of the
-*scheduler*, not of the error model. At `rho_pos = 0.99`, a 5 s fix interval is a 498 s
-correlation time and a 30 s interval is 2985 s.
+Without a time constant, `rho_pos` and `rho_vel` are applied **once per emitted fix**, with no
+reference to elapsed time. The error's correlation time is then
-So an experiment that sweeps the fix interval is also sweeping the error timescale, and the
-two cannot be separated in the result.
+$$\tau = -\frac{\Delta t_\text{fix}}{\ln \rho}$$
-`tau_pos_s` and `tau_vel_s` fix this. When set, the coefficient becomes `exp(-dt / tau)` for
-the actual interval between fixes, and `sigma_pos_m` is reinterpreted as the **steady-state**
-standard deviation in metres rather than the per-step innovation:
+which is a property of the *scheduler*, not of the error model. At `rho_pos = 0.99`, a 5 s fix
+interval is a 498 s correlation time and a 30 s interval is 2985 s. An experiment that sweeps
+the fix interval is therefore also sweeping the error timescale, and the two cannot be
+separated in the result.
-```toml
-[gnss_degradation.fault]
-kind = "degraded"
-sigma_pos_m = 35.0 # steady-state wander, metres, whatever the schedule
-tau_pos_s = 500.0 # correlation time in seconds
-```
+`tau_pos_s` and `tau_vel_s` (added in commit `96a47f4`) fix this. When set, the coefficient
+becomes $\rho = e^{-\Delta t/\tau}$ for the actual interval $\Delta t$ between fixes, and
+`sigma_pos_m` is reinterpreted as the **steady-state** standard deviation rather than the
+per-step innovation. This is the first-order Gauss-Markov process, whose autocorrelation is
+$R(\Delta t) = \sigma^2 e^{-|\Delta t|/\tau}$.
They are optional and additive. Omit them and the per-fix form applies exactly as before, so
-every configuration written earlier — and every result recorded from one — still means what it
+every configuration written earlier, and every result recorded from one, still means what it
meant. Prefer them for anything that varies the schedule.
Note also that without a time constant, `sigma_pos_m` is the per-step innovation, not the
-error you get: an AR(1) settles at `sigma / sqrt(1 - rho²)`, so `sigma_pos_m = 3.0` with
+error you get. An AR(1) settles at $\sigma / \sqrt{1 - \rho^2}$, so `sigma_pos_m = 3.0` with
`rho_pos = 0.99` is 21 m of wander, not 3 m.
+The same commit fixed the clock the fault advances on. A fault is applied once per *emitted*
+fix, and its `dt` is now the time since the previous emitted fix rather than the record
+spacing. Before that, a `slow_bias` under a 5 s schedule integrated one second of drift per
+five seconds of run time.
+
## Choosing a baseline to compare against
-`geoperf-all` scores each geophysically-aided run against that filter's unaided run, so the
-two must carry an **identical** GNSS profile. If they differ, the "improvement" reported is
-the difference between two degradations and has nothing to do with the aid. The
-`[gnss_degradation]` and `[health_limits]` sections of `conf/{ukf,ekf,rbpf}_{grav,mag,both}.toml`
-are duplicated from `conf/*_degraded.toml` for exactly this reason, and
-`core/tests/example_configs.rs` covers `conf/` so a drift in them fails a test.
-
-`conf/*_degraded.toml` carries this recalibrated 35 m profile, and it is the only
-interference tier in the config matrix: `conf/{ukf,ekf,rbpf}_{grav,mag,both}.toml` are all
-scored against their own filter's `conf/{ukf,ekf,rbpf}_degraded.toml`, and RBPF's geo-aided
-runs are additionally scored against `conf/ekf_degraded.toml` as the canonical INS baseline
-(`just geoperf-all`/`geoperf-rbpf`). Keeping a single profile, applied identically everywhere,
-is what makes the pairing in `core/tests/example_configs.rs` a simple filename convention
-rather than a per-tier lookup.
+`just geoperf-all` scores each geophysically aided run against that filter's unaided run, so
+the two must carry an **identical** GNSS profile. If they differ, the reported "improvement" is
+the difference between two degradations and has nothing to do with the aid. The aiding
+(`[gnss_degradation]`) and `[health_limits]` sections of
+`conf/{ukf,ekf,rbpf}_{grav,mag,both}.toml` are duplicated from the matching
+`conf/*_degraded.toml` for exactly this reason, and `core/tests/example_configs.rs` loads the
+`conf/` recipes so that a drift between them fails a test.
+
+All nine geophysical recipes are scored against their own filter's
+`conf/{ukf,ekf,rbpf}_degraded.toml`. The RBPF's geo-aided runs are additionally scored against
+`conf/ekf_degraded.toml` as the canonical INS baseline (`just geoperf-all` and
+`just geoperf-rbpf`). Keeping a single profile, applied identically everywhere, is what lets
+that pairing be a filename convention rather than a per-tier lookup.
## Sources
@@ -120,4 +162,4 @@ rather than a per-tier lookup.
- [EUROCONTROL GNSS interference testing guide v2.0](https://www.eurocontrol.int/sites/default/files/2023-03/eurocontrol-gnss-interference-testing-guide-v2-0.pdf)
- [RTCA DO-235C, *Assessment of radio frequency interference relevant to the GNSS L1 frequency band*](https://standards.globalspec.com/std/14557649/do-235c)
- [Overbounding the effect of uncertain Gauss-Markov noise in Kalman filtering, *NAVIGATION* 68(2):259](https://navi.ion.org/content/68/2/259)
-- [GNSS error simulator for farm machinery navigation](https://www.sciencedirect.com/science/article/abs/pii/S0168169915003348) — the first-order Gauss-Markov form `R(Δt) = σ² e^(-|Δt|/τ)` these time constants implement
+- [GNSS error simulator for farm machinery navigation](https://www.sciencedirect.com/science/article/abs/pii/S0168169915003348), the source of the first-order Gauss-Markov form the time constants implement
diff --git a/book/src/gnss/reduced-rates.md b/book/src/gnss/reduced-rates.md
deleted file mode 100644
index e843f1dd..00000000
--- a/book/src/gnss/reduced-rates.md
+++ /dev/null
@@ -1 +0,0 @@
-# Reduced Update Rates
diff --git a/book/src/gnss/scenarios.md b/book/src/gnss/scenarios.md
new file mode 100644
index 00000000..8c07dfe0
--- /dev/null
+++ b/book/src/gnss/scenarios.md
@@ -0,0 +1,274 @@
+# Schedulers and Faults Reference
+
+This page lists every scheduler and fault model in `strapdown::messages`, with each field, its
+unit and default, and how to set it from a configuration file and from the command line. For
+why the shipped recipes use the values they do, see [Fault Simulation](./fault-simulation.md).
+
+The two are orthogonal. A **scheduler** (`MeasurementScheduler`) decides *when* a measurement
+reaches the filter. A **fault model** (`GnssFaultModel`) decides *what* is wrong with each GNSS
+fix that does. Both are applied once, when `build_event_stream` turns the input records into
+the time-ordered stream of IMU and measurement events, so every filter sees exactly the same
+degraded stream.
+
+## Where they are configured
+
+Everything on this page sits in one struct, `AidingConfig`, which is the `[aiding]` section of
+a configuration file. The section was called `[gnss_degradation]` before the v1.0 freeze and
+that spelling is still accepted as an alias; the recipes under `conf/` use it.
+
+| key | type | default | meaning |
+|---|---|---|---|
+| `scheduler` | scheduler | `pass_through` | when GNSS fixes are delivered |
+| `fault` | fault model | `none` | how GNSS fixes are corrupted |
+| `baro_scheduler` | scheduler | `fixed_interval`, 1 s | when barometric altitude is delivered |
+| `magnetometer_scheduler` | scheduler | `fixed_interval`, 1 s | when magnetometer heading is delivered |
+| `baro_noise_std_m` | m (1σ) | 2.236 (√5) | barometric altitude noise standard deviation |
+| `baro_bias_index` | integer or unset | unset | which filter state holds the barometric bias (library use; see below) |
+| `seed` | integer or unset | unset | seed for the fault model's random draws; unset takes the file's top-level `seed`, or `DEFAULT_AIDING_SEED` (42) when an event stream is built from Rust |
+| `max_imu_gap_s` | s | 5.0 | longest inertial gap tolerated before the run is refused; `<= 0` disables |
+
+A complete example that runs as written (`input`/`output` pointed at a synthetic trajectory):
+
+```toml
+mode = "closed-loop"
+input = "synthetic.csv"
+output = "results/baro.csv"
+
+[aiding]
+seed = 7
+baro_noise_std_m = 3.0
+max_imu_gap_s = 5.0
+
+[aiding.scheduler] # GNSS: 100 s available, 50 s denied
+kind = "duty_cycle"
+on_s = 100.0
+off_s = 50.0
+start_phase_s = 0.0
+
+[aiding.baro_scheduler] # an independent barometer outage
+kind = "duty_cycle"
+on_s = 60.0
+off_s = 60.0
+start_phase_s = 0.0
+
+[aiding.magnetometer_scheduler]
+kind = "pass_through"
+```
+
+Three behaviours of the parser are worth knowing:
+
+- **A misspelled `kind` is an error.** `kind = "fixed"` fails with
+ ``unknown variant `fixed`, expected one of `pass_through`, `fixed_interval`, `duty_cycle` ``.
+- **A missing field is an error.** Scheduler and fault fields have no defaults, except the two
+ optional time constants on `degraded`; leave one out and the run stops with
+ ``missing field `...` ``.
+- **A misspelled section name is not.** Unknown top-level keys are ignored, so
+ `[gnss_degredation]` parses, is discarded, and the run proceeds with no degradation at all.
+ `core/tests/example_configs.rs` guards the shipped files against this; your own files are
+ not guarded, so check section names against this page.
+
+**Seeds.** In a configuration file the fault model is seeded by `[aiding] seed` when it is
+given, and otherwise by the top-level `seed`, so two files differing only in the top-level
+`seed` produce two fault realizations. On the command line, `--seed` seeds the fault model.
+
+**`baro_bias_index`** tells the barometer measurement which state of the filter holds a
+barometric bias. `strapdown-sim` overwrites it from the filter it builds (and clears it for the
+particle filter, which carries no barometric bias state), so setting it in a `strapdown-sim`
+config file has no effect. It matters when you call `build_event_stream` from Rust with your
+own filter.
+
+## Schedulers
+
+The configuration file names the variant with `kind` in snake case. The command line uses
+shorter names: `--sched passthrough|fixed|duty`. The GNSS scheduler is the only one with flags;
+the barometer and magnetometer schedulers are set from a configuration file or from Rust, and
+otherwise take their 1 Hz default.
+
+### `PassThrough`
+
+`kind = "pass_through"`, `--sched passthrough` (the CLI default). Every record that carries a
+complete fix delivers it. No fields.
+
+### `FixedInterval`
+
+`kind = "fixed_interval"`, `--sched fixed`.
+
+| field | unit | CLI flag | CLI default | meaning |
+|---|---|---|---|---|
+| `interval_s` | s | `--interval-s` | 1.0 | interval between delivered fixes |
+| `phase_s` | s | `--phase-s` | 0.0 | time of the first tick |
+
+Ticks fall on exact multiples of `interval_s` after `phase_s`, so they do not creep over a long
+run. It is a **rate limit, not a resampler**: it delivers the first record at or after each
+tick, so a log sampled more slowly than `interval_s` delivers every record. After a gap in the
+log the clock jumps past the gap rather than bursting to catch up. A non-positive or non-finite
+`interval_s` behaves as `PassThrough` rather than silently withholding every fix.
+
+### `DutyCycle`
+
+`kind = "duty_cycle"`, `--sched duty`.
+
+| field | unit | CLI flag | CLI default | meaning |
+|---|---|---|---|---|
+| `on_s` | s | `--on-s` | 10.0 | length of each ON (available) window |
+| `off_s` | s | `--off-s` | 10.0 | length of each OFF (denied) window |
+| `start_phase_s` | s | `--duty-phase-s` | 0.0 | length of an initial ON window |
+
+The timeline is `start_phase_s` of ON, then `off_s` OFF and `on_s` ON, repeating. **The cycle
+starts with its OFF window**, so with `start_phase_s = 0` the run begins in an outage:
+
+```text
+start_phase_s = 0: OFF [0, off_s) ON [off_s, off_s+on_s) OFF ...
+start_phase_s = p: ON [0, p) OFF [p, p+off_s) ON [p+off_s, p+off_s+on_s) OFF ...
+```
+
+Set `start_phase_s` (on the command line, `--duty-phase-s`; note it is not `--phase-s`, which
+belongs to `fixed`) to let the filter converge on some fixes before the first outage. Every
+record inside an ON window delivers its fix. A cycle whose `on_s + off_s` is not positive and
+finite behaves as `PassThrough`.
+
+## Fault models
+
+The configuration file names the variant with `kind` in snake case. The command line spells it
+`--fault none|degraded|slowbias|hijack`. Every field is required in a configuration file except
+`tau_pos_s` and `tau_vel_s`; the CLI defaults below apply only on the command line.
+
+Faults apply to GNSS only. Barometer and magnetometer measurements are scheduled but never
+corrupted. Each fault advances once per *delivered* fix, with `dt` the time since the previous
+delivered fix.
+
+### `None`
+
+`kind = "none"`, `--fault none` (the CLI default). Fixes reach the filter unchanged.
+
+### `Degraded`
+
+`kind = "degraded"`, `--fault degraded`. AR(1)-correlated error added to position (north, east
+and up) and to north/east velocity, and the advertised accuracies inflated.
+
+| field | unit | CLI flag | CLI default | meaning |
+|---|---|---|---|---|
+| `rho_pos` | -- | `--rho-pos` | 0.99 | AR(1) coefficient for position error, per fix |
+| `sigma_pos_m` | m | `--sigma-pos-m` | 3.0 | position innovation σ per fix; steady-state σ if `tau_pos_s` is set |
+| `rho_vel` | -- | `--rho-vel` | 0.95 | AR(1) coefficient for velocity error, per fix |
+| `sigma_vel_mps` | m/s | `--sigma-vel-mps` | 0.3 | velocity innovation σ per fix; steady-state σ if `tau_vel_s` is set |
+| `r_scale` | -- | `--r-scale` | 5.0 | multiplies the advertised horizontal and velocity 1σ |
+| `tau_pos_s` | s | `--tau-pos-s` | unset | position correlation time (optional) |
+| `tau_vel_s` | s | `--tau-vel-s` | unset | velocity correlation time (optional) |
+
+Each error state $x$ follows
+
+$$x_k = \rho\ x_{k-1} + w_k, \qquad w_k \sim \mathcal{N}(0, s^2).$$
+
+Without a time constant, $\rho$ is `rho_pos` and $s$ is `sigma_pos_m`, applied per delivered
+fix, so the correlation time depends on the schedule and the error settles at
+$s/\sqrt{1-\rho^2}$, not at $s$. With `tau_pos_s` set, $\rho = e^{-\Delta t/\tau}$ for the
+actual interval $\Delta t$ between fixes and $s = \sigma\sqrt{1-\rho^2}$, which holds the
+steady-state standard deviation at `sigma_pos_m` whatever the schedule. The time constants were
+added in commit `96a47f4` for exactly this reason; [Fault
+Simulation](./fault-simulation.md#correlation-time-and-the-fix-interval) has the argument. A
+non-positive or non-finite `tau` falls back to the per-fix form.
+
+`r_scale` scales the advertised **standard deviations**, which the GNSS measurement model
+squares to build $R$, so $R$ grows by `r_scale²`. The advertised vertical accuracy is not
+scaled, although the altitude does receive the position error.
+
+### `SlowBias`
+
+`kind = "slow_bias"`, `--fault slowbias`. A soft spoof: a north/east position offset that
+drifts at a set rate, with a matching velocity offset so that position and velocity stay
+mutually consistent.
+
+| field | unit | CLI flag | CLI default | meaning |
+|---|---|---|---|---|
+| `drift_n_mps` | m/s | `--drift-n-mps` | 0.02 | northward drift rate of the offset |
+| `drift_e_mps` | m/s | `--drift-e-mps` | 0.0 | eastward drift rate of the offset |
+| `q_bias` | m²/s | `--q-bias` | 1e-6 | random-walk intensity on the offset; 0 disables |
+| `rotate_omega_rps` | rad/s | `--rotate-omega-rps` | 0.0 | rotation rate of the drift direction; 0 keeps it fixed |
+
+At each fix the offset grows by the drift rate times $\Delta t$, plus a zero-mean draw with
+variance `q_bias`$\ \Delta t$ per axis. With `rotate_omega_rps` non-zero, the drift vector is
+rotated by $\omega t$ before it is applied. The reported velocity is offset by the current drift
+rate. The advertised accuracies are unchanged.
+
+### `Hijack`
+
+`kind = "hijack"`, `--fault hijack`. A hard spoof: a constant north/east offset over a fixed
+window, with velocity left alone.
+
+| field | unit | CLI flag | CLI default | meaning |
+|---|---|---|---|---|
+| `offset_n_m` | m | `--hijack-offset-n-m` | 50.0 | northward offset |
+| `offset_e_m` | m | `--hijack-offset-e-m` | 0.0 | eastward offset |
+| `start_s` | s | `--hijack-start-s` | 120.0 | start of the window, from the first record |
+| `duration_s` | s | `--hijack-duration-s` | 60.0 | length of the window |
+
+The offset applies to fixes with elapsed time in $[t_\text{start}, t_\text{start} +
+t_\text{duration}]$, endpoints included, and to none outside it.
+
+### `Combo`
+
+`kind = "combo"`. Several fault models applied in sequence to the same fix, the output of each
+feeding the next. It is available from a configuration file and from Rust; `--fault` has no
+`combo` choice. The members go in a `faults` array, each a complete fault model of its own:
+
+```toml
+[aiding.fault]
+kind = "combo"
+
+[[aiding.fault.faults]]
+kind = "slow_bias"
+drift_n_mps = 0.02
+drift_e_mps = 0.0
+q_bias = 1e-6
+rotate_omega_rps = 0.0
+
+[[aiding.fault.faults]]
+kind = "hijack"
+offset_n_m = 50.0
+offset_e_m = 0.0
+start_s = 120.0
+duration_s = 60.0
+```
+
+The members share one fault state. Combine *different* kinds: two `degraded` members step the
+same AR(1) states twice per fix rather than adding two independent errors.
+
+## Example commands
+
+Each of these was run against a 600 s trajectory from `strapdown-sim syn -o synthetic.csv
+--duration-s 600 --seed 42`:
+
+```bash
+# One fix a minute, otherwise clean
+strapdown-sim cl -i synthetic.csv -o fixed.csv --sched fixed --interval-s 60 --fault none
+
+# 100 s on / 50 s off, with time-constant AR(1) degradation on the fixes that remain
+strapdown-sim cl -i synthetic.csv -o duty.csv --seed 42 \
+ --sched duty --on-s 100 --off-s 50 \
+ --fault degraded --sigma-pos-m 35 --tau-pos-s 500 --sigma-vel-mps 1.5 --tau-vel-s 100
+
+# Soft spoof, drift direction rotating at 1 mrad/s
+strapdown-sim cl -i synthetic.csv -o slowbias.csv \
+ --fault slowbias --drift-n-mps 0.05 --rotate-omega-rps 0.001
+
+# Hard spoof: 50 m north between t = 120 s and t = 180 s
+strapdown-sim cl -i synthetic.csv -o hijack.csv \
+ --fault hijack --hijack-offset-n-m 50 --hijack-start-s 120 --hijack-duration-s 60
+
+# The particle filter takes the same flags
+strapdown-sim pf -i synthetic.csv -o pf.csv --sched fixed --interval-s 10 --num-particles 200
+```
+
+## Shipped recipes
+
+- `examples/configs/*.yaml` covers each scheduler and fault on its own and in pairs; see
+ [Example Configurations](../examples/configurations.md).
+- `conf/{ukf,ekf,rbpf}_degraded.toml` is the experiment matrix's single interference profile:
+ `fixed_interval` at 60 s with `degraded` at 35 m and 1.5 m/s steady state, `tau_pos_s = 500`,
+ `tau_vel_s = 100`, `r_scale = 5`. The `conf/*_truth.toml` recipes are the unscheduled,
+ unfaulted counterparts, and `conf/*_{grav,mag,both}.toml` repeat the degraded profile with
+ geophysical aiding added. `conf/real/` holds the same fifteen recipes for the frozen
+ real-sensor arm of the experiment.
+- No recipe ships for total denial. `--sched duty --on-s 30 --off-s 120 --duty-phase-s 30
+ --fault none` gives 30 s of fixes in every 150 s with availability as the only variable.
diff --git a/book/src/installation/building.md b/book/src/installation/building.md
deleted file mode 100644
index c02da5c3..00000000
--- a/book/src/installation/building.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Building from Source
-
-Detailed instructions for building from source.
-
-*Content coming soon.*
diff --git a/book/src/installation/crates-io.md b/book/src/installation/crates-io.md
deleted file mode 100644
index 94dba775..00000000
--- a/book/src/installation/crates-io.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Installing from Crates.io
-
-Detailed instructions for installing from Crates.io.
-
-*Content coming soon.*
diff --git a/book/src/installation/installation.md b/book/src/installation/installation.md
index 52731fa8..ccf0983d 100644
--- a/book/src/installation/installation.md
+++ b/book/src/installation/installation.md
@@ -1,146 +1,166 @@
# Installation
-This page provides detailed instructions for installing Strapdown-rs on your system.
+There are two things to install, and most readers want only one of them:
-## Prerequisites
+- the **`strapdown-sim` binary**, to run simulations from the command line;
+- the **`strapdown-core` library**, to call the mechanization and filters from your own Rust
+ code. It is imported as `strapdown`.
-Before installing Strapdown-rs, ensure you have the following:
+## Version 1.0 is installed from git
-- **Rust**: Version 1.91 or higher (install from [rustup.rs](https://rustup.rs))
-- **A C/C++ compiler and cmake >= 3.26**, for the features that use a C library
+At the time of writing, crates.io carries only pre-1.0 releases of these crates, whose API
+differs from the one this book documents. Version 1.0.0 is published to crates.io together with
+the JOSS paper. **Until then, install from the GitHub repository**, as below. Once 1.0.0 is on
+crates.io, drop the `--git` argument from every command on this page.
-## Build Dependencies
+## Before you start
-There are **no system libraries to install**. libhdf5, libnetcdf, zlib and freetype are
-compiled from vendored sources that ship as ordinary cargo dependencies, so nothing is looked
-for on your machine. You only need a toolchain to compile them with.
+You need a Rust toolchain, version **1.91 or newer**, from [rustup.rs](https://rustup.rs).
+Whether you need anything else depends on which features you build:
-### Ubuntu/Debian
+| What you build | Needs |
+| --- | --- |
+| `strapdown-core` with default features | Rust only |
+| `strapdown-core` with `mcap`; `strapdown-sim` with its default `plotting` feature | Rust and a C compiler |
+| `strapdown-core` with `hdf5` or `netcdf`; `strapdown-sim` with `geonav`; `strapdown-geonav` | Rust, a C/C++ compiler, and **cmake 3.26 or newer** |
-```bash
-sudo apt update
-sudo apt install -y build-essential cmake
-```
+No system libraries are searched for. libhdf5, libnetcdf, zlib and FreeType are compiled from
+vendored sources that ship as ordinary cargo dependencies, so the compiler and cmake are all
+the build needs. Two details catch people out:
-Check `cmake --version`: the bundled HDF5 needs **3.26 or newer**, which is more than Ubuntu
-22.04 (3.22) or Debian 12 (3.25) ship. On those, install cmake from
-[Kitware's APT repository](https://apt.kitware.com/), or with `pip install cmake`, or with
-`snap install cmake --classic`.
+- **cmake 3.26 is newer than some distributions ship.** Ubuntu 22.04 has 3.22 and Debian 12 has
+ 3.25, and both fail. Install a newer cmake from
+ [Kitware's APT repository](https://apt.kitware.com/), with `pip install cmake`, or with
+ `snap install cmake --classic`. Ubuntu 24.04 and Fedora 40+ are new enough as shipped.
+- **`HDF5_DIR` must be unset.** When it is set, the HDF5 build script looks for a system
+ library instead of building the vendored one, even though a vendored build was requested,
+ and the netCDF build then fails against those headers with an error that does not name the
+ cause. A leftover conda or pixi shell is the usual source.
-### Fedora/RHEL
+[System Requirements](./requirements.md) lists the per-platform commands for the compiler and
+cmake.
+
+## Install the simulator
```bash
-sudo dnf install -y gcc gcc-c++ cmake
+cargo install --git https://github.com/jbrodovsky/strapdown-rs strapdown-sim
```
-### macOS
+With experimental geophysical (gravity and magnetic anomaly) aiding, which adds the `--geo`
+family of flags to `cl` and `pf`:
```bash
-xcode-select --install
-brew install cmake
+cargo install --git https://github.com/jbrodovsky/strapdown-rs strapdown-sim --features geonav
```
-### Windows
-
-Install the MSVC toolchain from Visual Studio Build Tools, plus
-[cmake](https://cmake.org/download/). vcpkg is not needed.
+Check the result:
-> **Note:** `strapdown-core` on its own needs none of this -- `cargo add strapdown-core` and a
-> Rust toolchain are enough unless you turn on its `hdf5` or `netcdf` features.
-
-## Installation Methods
+```console
+$ strapdown-sim --version
+strapdown-sim 1.0.0
+```
-### Method 1: Install from Crates.io (Recommended)
+`cargo install` puts the binary in `~/.cargo/bin`, which rustup adds to your `PATH`.
-The easiest way to use Strapdown-rs is to add it as a dependency in your project:
+## Add the library to a project
```bash
-cargo add strapdown-core
+cargo add strapdown-core --git https://github.com/jbrodovsky/strapdown-rs
```
-Or add manually to your `Cargo.toml`:
+That writes this entry to your `Cargo.toml`:
```toml
[dependencies]
-strapdown-core = "0.1"
+strapdown-core = { git = "https://github.com/jbrodovsky/strapdown-rs", version = "1.0.0" }
```
-To install the simulation binary:
+Add features with `--features`, for example
+`cargo add strapdown-core --git https://github.com/jbrodovsky/strapdown-rs --features mcap`.
+In your code the crate is `strapdown`, not `strapdown_core`. [Using the
+Library](../user-guide/library.md) continues from here.
-```bash
-cargo install strapdown-sim
-```
-
-### Method 2: Build from Source
+## Cargo features
-Clone the repository and build locally:
+### `strapdown-core`
-```bash
-# Clone the repository
-git clone https://github.com/jbrodovsky/strapdown-rs.git
-cd strapdown-rs
+| Feature | Default | What it adds | Build needs |
+| --- | --- | --- | --- |
+| `clap` | no | `clap` `ValueEnum` and `Args` derives on the simulation configuration types in `strapdown::sim`, so a CLI can take them as arguments. `strapdown-sim` turns this on | Rust only |
+| `hdf5` | no | `NavigationResult::to_hdf5` / `from_hdf5` and the matching `TestDataRecord` readers and writers | C/C++ compiler, cmake ≥ 3.26 |
+| `netcdf` | no | `NavigationResult::to_netcdf` / `from_netcdf` and the `TestDataRecord` equivalents | C/C++ compiler, cmake ≥ 3.26 |
+| `mcap` | no | `NavigationResult::to_mcap` / `from_mcap` and the `TestDataRecord` equivalents | C compiler (bundled LZ4 and Zstandard) |
+| `full` | no | All four of the above | as for `hdf5` |
-# Build the entire workspace
-cargo build --workspace --all-features --release
+The default build has none of them and compiles with Rust alone. These writers are library
+methods only. `strapdown-sim` writes CSV whatever features the library was built with, and
+refuses an `-o` path whose extension names another format (`-o out.h5` is an error, not an HDF5
+file); a path with no extension is a directory to write `.csv` files into.
-# Install the simulation binary
-cargo install --path sim
+### `strapdown-sim`
-# Optionally, with geophysical (gravity/magnetic) navigation. This is the variant that
-# compiles libnetcdf from source, so it needs cmake.
-cargo install --path sim --features geonav
-```
+| Feature | Default | What it adds | Build needs |
+| --- | --- | --- | --- |
+| `plotting` | **yes** | Rendering for the global `--plot` flag, a performance plot against the GNSS track. Without the feature `--plot` is refused, and a config file's `generate_plot = true` logs an error and draws nothing | C compiler (bundled FreeType); libfontconfig at **run time** |
+| `geonav` | no | Gravity and magnetic anomaly map aiding: `--geo`, `--gravity-*`, `--magnetic-*` and `--geo-interval-s` on `cl` and `pf`. Without the feature these flags do not exist | C/C++ compiler, cmake ≥ 3.26 |
-> The repository used to ship a `pixi.toml` for environment management. It was removed once
-> the C libraries began building from source, since there was nothing left for it to provide;
-> `cargo build` is now the whole story.
+`plotting` loads libfontconfig when it first draws text rather than linking it at build time.
+A machine without it builds and runs normally, and fails only when a plot is rendered. It is
+present on virtually every desktop Linux install; on a minimal container, `apt install
+libfontconfig1`.
-## Verifying Installation
+## Build from a clone
-After installation, verify everything works:
+Contributors, and anyone who wants the examples and test fixtures, should clone the
+repository:
```bash
-# Check strapdown-sim version
-strapdown-sim --version
-
-# Run a simple test
-cargo test -p strapdown-core
+git clone https://github.com/jbrodovsky/strapdown-rs.git
+cd strapdown-rs
+cargo build --workspace --release
```
-## Troubleshooting
-
-### HDF5/NetCDF Build Issues
+The binary is then at `target/release/strapdown-sim`. Inside the clone, `rust-toolchain.toml`
+pins the toolchain the CI uses (1.91) and rustup fetches it on the first cargo command, so you
+do not choose a version yourself. `.cargo/config.toml` additionally forces the vendored
+FreeType, so a repository build never links a system copy. (`cargo install` from git does not
+read that file and may link a system FreeType if pkg-config reports one; both work.)
-These libraries are compiled from source, so failures look like cmake or compiler errors
-rather than linker errors.
+To put a binary built from your clone on your `PATH`:
-1. **`CMake 3.26 or higher is required`** -- your cmake is too old. See the Build Dependencies
- section above.
+```bash
+cargo install --path sim
+cargo install --path sim --features geonav # with geophysical aiding
+```
-2. **Confusing cmake failures inside the netCDF build** -- check whether `HDF5_DIR` is set:
- ```bash
- echo "${HDF5_DIR:-unset}"
- ```
- If it is, the HDF5 build script quietly switches to looking for a *system* library instead
- of building the vendored one, and the netCDF build is then handed the wrong headers. Unset
- it. A leftover conda or pixi shell is the usual source.
+There is no environment manager to set up; `cargo build` is the whole setup. Running the test
+suite, the lint gate and the performance baselines is covered in
+[Building and Testing](../development/building.md).
-3. **`cargo install` is slow the first time** -- that is the one-off source build of libhdf5
- and libnetcdf, roughly a minute on a modern machine. It is cached afterwards.
+## Troubleshooting
-### Rust Version Issues
+**`CMake 3.26 or higher is required`.** Your cmake is too old for the bundled HDF5. Install a
+newer one as described under [Before you start](#before-you-start).
-Ensure you're using a recent Rust version:
+**Confusing cmake failures inside the netCDF build.** Check for a stale `HDF5_DIR`:
```bash
-rustc --version
+echo "${HDF5_DIR:-unset}"
```
-Inside a clone of the repository, `rust-toolchain.toml` pins the version and rustup fetches it
-for you, so this should already agree with what CI uses.
+If it prints a path, unset it and rebuild.
+
+**The first build of `hdf5`, `netcdf` or `geonav` is slow.** That is the one-off source build
+of libhdf5 and libnetcdf. Cargo caches it, and later builds reuse it.
+
+**A plot fails to render while everything else works.** libfontconfig is missing at run time;
+see the `plotting` row above.
+
+**`cargo add strapdown-core` without `--git` resolved to a 0.x version.** That is the last
+pre-1.0 release on crates.io. Its API is not the one in this book. Use the `--git` form until
+1.0.0 is published.
-## Next Steps
+## Next steps
-- Continue to the [Quick Start](../quick-start.md) guide
-- Learn about [System Requirements](./requirements.md)
-- Explore [Building from Source](./building.md) in detail
+- [Quick Start](../quick-start.md): generate a trajectory and run every simulation mode on it.
+- [System Requirements](./requirements.md): platform-specific setup.
diff --git a/book/src/installation/requirements.md b/book/src/installation/requirements.md
index 04853f2d..c96ef7b8 100644
--- a/book/src/installation/requirements.md
+++ b/book/src/installation/requirements.md
@@ -1,41 +1,24 @@
# System Requirements
-This page outlines the system requirements for running Strapdown-rs.
+This page lists what each part of the project needs to build and run, and how to get it on
+each platform. [Installation](./installation.md) has the install commands themselves.
-## Hardware Requirements
+## Platforms
-### Minimum
+The code is platform-independent Rust plus vendored C libraries. Continuous integration builds
+and tests `strapdown-core` on Linux, macOS and Windows (`ubuntu-latest`, `macos-latest`,
+`windows-latest` GitHub runners), builds `strapdown-geonav` with its vendored netCDF and HDF5
+on macOS and Windows, and builds and tests the whole workspace with every feature on Linux.
-- **CPU**: Any modern 64-bit processor (x86_64 or ARM64)
-- **RAM**: 2 GB
-- **Storage**: 100 MB for binaries, plus space for data files
+There are no special hardware requirements. Memory and run time scale with the length of the
+trajectory and, for the particle filter, with `--num-particles`.
-### Recommended
+## Rust toolchain
-- **CPU**: Multi-core processor (4+ cores) for parallel processing
-- **RAM**: 8 GB or more for large simulations
-- **Storage**: SSD with sufficient space for trajectory data and results
-
-## Software Requirements
-
-### Operating Systems
-
-Strapdown-rs supports all major operating systems:
-
-- **Linux**: Ubuntu 24.04+, Debian 13+, Fedora 40+, or equivalent. Older releases work too,
- but only once a cmake newer than the distribution's own is installed -- see the C toolchain
- note below.
-- **macOS**: 11.0 (Big Sur) or later
-- **Windows**: Windows 10/11 with MSVC or MinGW
-
-### Rust Toolchain
-
-- **Minimum Rust version**: 1.91
-- **Required components**: `rustc`, `cargo`, `clippy`, `rustfmt`
-
-Contributors working in a clone of the repository do not need to choose a version: a
-`rust-toolchain.toml` pins 1.91 and rustup fetches it automatically on the first cargo
-command.
+- **Rust 1.91 or newer** (`rustc` and `cargo`). This is the workspace's declared
+ `rust-version`.
+- `clippy` and `rustfmt` only if you plan to contribute; see
+ [Building and Testing](../development/building.md).
Install via [rustup](https://rustup.rs/):
@@ -43,99 +26,89 @@ Install via [rustup](https://rustup.rs/):
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
-### C Toolchain
-
-There are **no system libraries to install**. libhdf5, libnetcdf, zlib and freetype are all
-compiled from vendored sources shipped as ordinary crates.io dependencies. What you do need is
-a toolchain to compile them with:
+Inside a clone of the repository you do not choose a version: `rust-toolchain.toml` pins 1.91
+and rustup fetches it on the first cargo command.
-- **A C/C++ compiler**: GCC, Clang, or MSVC.
-- **cmake, version 3.26 or later**: required by the bundled HDF5.
+## C toolchain
-Both are needed only when you build something that touches a C library -- `strapdown-geonav`
-always, `strapdown-core`'s `hdf5`/`netcdf` features, and `strapdown-sim`'s `plotting` feature
-(for freetype). `cargo build -p strapdown-core` on its own needs neither.
+There are **no system libraries to install**. libhdf5, libnetcdf, zlib and FreeType are
+compiled from vendored sources that ship as ordinary cargo dependencies. What you may need is a
+toolchain to compile them, depending on the features you build:
-One caveat on "nothing is searched for": inside a clone of this repository that is exactly
-true, because `.cargo/config.toml` sets `FREETYPE2_NO_PKG_CONFIG` and the HDF5/netCDF/zlib
-builds are pinned to their vendored sources by cargo features. `freetype-sys` on its own would
-prefer a system FreeType when pkg-config reports one, so `cargo install strapdown-sim` -- which
-does not see this repository's cargo config -- may link the copy on your machine instead. Both
-work; only the repository build is fully hermetic.
+| Needs | When |
+| --- | --- |
+| Nothing beyond Rust | `strapdown-core` with default features |
+| A C compiler (GCC, Clang or MSVC) | `strapdown-sim` with its default `plotting` feature (FreeType); `strapdown-core` with `mcap` (LZ4, Zstandard) |
+| A C/C++ compiler **and cmake 3.26 or newer** | `strapdown-core` with `hdf5` or `netcdf`; `strapdown-sim` with `geonav`; `strapdown-geonav` always |
> **cmake 3.26 is newer than some distributions ship.** Ubuntu 22.04 LTS has 3.22 and
> Debian 12 has 3.25; both fail. Install a newer cmake from
> [Kitware's APT repository](https://apt.kitware.com/), with `pip install cmake`, or with
> `snap install cmake --classic`. Ubuntu 24.04 and Fedora 40+ are new enough as shipped.
-#### Runtime
+### A variable to keep unset
+
+**`HDF5_DIR`**: if this is set, the HDF5 build script looks for a system library instead of
+building the vendored one, and the netCDF build then fails against those headers with an
+error that does not name the cause. Unset it. A leftover conda or pixi shell is the usual
+source.
-- **libfontconfig**: needed at *run time* by `strapdown-sim`'s `plotting` feature, which loads
- it on demand rather than linking it. A machine without it builds fine and fails only when a
- plot is first rendered. Present by default on virtually every desktop Linux install; on a
- minimal container, `apt install libfontconfig1`.
+### "Nothing is searched for" has one exception
-#### A variable to keep unset
+Inside a clone of the repository the build is fully hermetic: `.cargo/config.toml` sets
+`FREETYPE2_NO_PKG_CONFIG`, and the HDF5, netCDF and zlib builds are pinned to their vendored
+sources by cargo features. `freetype-sys` on its own prefers a system FreeType when pkg-config
+reports one, so `cargo install` from git or crates.io, which does not read the repository's
+cargo configuration, may link the copy on your machine instead. Both work.
-- **`HDF5_DIR`**: if this is set, the HDF5 build script looks for a system library instead of
- building the vendored one, and the netCDF build then fails against those headers with an
- error that does not name the cause. Unset it (a leftover conda or pixi shell is the usual
- source).
+### Runtime
-## Platform-Specific Notes
+**libfontconfig** is needed at *run time* by `strapdown-sim`'s `plotting` feature, which loads
+it on demand rather than linking it. A machine without it builds and runs normally, and fails
+only when a plot is first rendered. It is present on virtually every desktop Linux install; on
+a minimal container, `apt install libfontconfig1`.
+
+## Platform-specific setup
### Linux
-Install a compiler and cmake with your package manager -- for example `apt install build-essential cmake` -- then check `cmake --version` against the 3.26 note above.
+Ubuntu or Debian:
+
+```bash
+sudo apt update
+sudo apt install -y build-essential cmake
+cmake --version # must be 3.26 or newer for hdf5/netcdf/geonav
+```
-**Performance Note**: For best performance, consider building with native CPU optimizations:
+Fedora or RHEL:
```bash
-RUSTFLAGS="-C target-cpu=native" cargo build --release
+sudo dnf install -y gcc gcc-c++ cmake
```
### macOS
-Apple Silicon (M1/M2/M3) is fully supported. The ARM64 architecture provides excellent performance for navigation algorithms.
-
-Xcode Command Line Tools provide the compiler (`xcode-select --install`) and `brew install cmake` provides the rest.
+```bash
+xcode-select --install # the C/C++ compiler
+brew install cmake
+```
### Windows
-The MSVC toolchain from Visual Studio Build Tools, plus cmake, is all that is required. vcpkg is no longer needed: the C libraries are built from source rather than located on the system.
-
-Alternatively, use WSL2 (Windows Subsystem for Linux) for a native Linux environment.
-
-## Development Requirements
+Install the MSVC toolchain from Visual Studio Build Tools, plus
+[cmake](https://cmake.org/download/). vcpkg is not needed: the C libraries are built from
+source rather than located on the system. WSL2 with the Linux instructions above also works.
-If you plan to contribute to Strapdown-rs development:
-
-- **Git**: Version control
-- **clippy**: Rust linter (`rustup component add clippy`)
-- **rustfmt**: Code formatter (`rustup component add rustfmt`)
-- **cargo-edit**: For managing dependencies (`cargo install cargo-edit`)
-
-## Testing Your Environment
-
-After installing dependencies, verify your environment:
+## Checking your environment
```bash
-# Check Rust version
-rustc --version
-
-# Check the C toolchain
-cc --version
-cmake --version # must be 3.26 or newer
-
-# Make sure no stale HDF5 override is in the environment
+rustc --version # 1.91 or newer
+cc --version # any C compiler, if you build plotting/mcap/hdf5/netcdf/geonav
+cmake --version # 3.26 or newer, if you build hdf5/netcdf/geonav
echo "HDF5_DIR=${HDF5_DIR:-(unset, good)}"
-
-# Test compilation. The first run compiles libhdf5 and libnetcdf from source, which takes
-# roughly a minute; later runs reuse them.
-cargo build --workspace
```
-## Next Steps
+## Next steps
-- Proceed to [Installing from Crates.io](./crates-io.md)
-- Or learn about [Building from Source](./building.md)
+- [Installation](./installation.md): install the simulator or add the library.
+- [Quick Start](../quick-start.md): run every simulation mode on a synthetic trajectory.
diff --git a/book/src/introduction.md b/book/src/introduction.md
index 4d6a3032..5a7c39bd 100644
--- a/book/src/introduction.md
+++ b/book/src/introduction.md
@@ -1,56 +1,114 @@
# Introduction
-Welcome to the **Strapdown-rs** documentation! This guide will help you understand and use the Strapdown-rs library, a high-performance Rust implementation of strapdown inertial navigation system (INS) algorithms.
-
-[](https://crates.io/crates/strapdown-rs)
-[](https://docs.rs/strapdown-rs)
-[](https://crates.io/crates/strapdown-rs)
-
-## What is Strapdown-rs?
-
-Strapdown-rs is a straightforward strapdown inertial navigation system (INS) implementation in Rust. It is designed to be simple, performant, and easy to understand, making it an excellent starting point for those interested in learning about or implementing strapdown INS algorithms.
-
-The project provides:
-
-1. **A source library** of strapdown INS algorithms and utilities (`strapdown-core`)
-2. **A simulation program** for simulating INS performance in various GNSS conditions (`strapdown-sim`)
-3. **Experimental geophysical navigation** capabilities for GNSS-denied environments (`strapdown-geonav`)
-
-## Key Features
-
-- **Modern Rust Implementation**: Memory-safe, high-performance code with cross-platform support
-- **Multiple Navigation Filters**: Extended Kalman Filter (EKF), Unscented Kalman Filter (UKF), and Particle Filters
-- **GNSS Degradation Scenarios**: Simulate dropouts, reduced update rates, and measurement corruption
-- **Geophysical Navigation**: Experimental work on gravity and magnetic anomaly navigation
-- **Comprehensive Documentation**: Well-documented code with examples and tutorials
-- **Research-Focused**: Designed for research, teaching, and development purposes
-
-## Target Audience
-
-This library is intended for:
-
-- **Researchers** working on navigation systems and sensor fusion
-- **Engineers** developing autonomous systems, robotics, or aerospace applications
-- **Students** learning about inertial navigation and state estimation
-- **Developers** needing a high-performance INS implementation in Rust
-
-## Project Status
-
-Strapdown-rs is under active development as part of ongoing PhD research. The project prioritizes correctness, numerical stability, and performance while maintaining extensibility for researchers and engineers.
-
-## Getting Help
-
-- **User Guide**: Start with the [Quick Start](./quick-start.md) guide
-- **API Documentation**: See the [API Reference](./api/core.md) for detailed function documentation
-- **Examples**: Check out the [Examples and Tutorials](./examples/configurations.md)
-- **Issues**: Report bugs or request features on [GitHub](https://github.com/jbrodovsky/strapdown-rs/issues)
+[](https://joss.theoj.org/papers/5079592cc860d1435482a4a7764edcd4)
+[](https://github.com/jbrodovsky/strapdown-rs/actions/workflows/rust.yml)
+[](https://crates.io/crates/strapdown-core)
+[](https://docs.rs/strapdown-core)
+[](https://github.com/jbrodovsky/strapdown-rs/blob/main/LICENSE)
+
+`strapdown-rs` is a Rust library and command-line simulator for research on strapdown inertial
+navigation systems (INS), with an emphasis on what happens when GNSS is unavailable or cannot be
+trusted. It mechanizes recorded or synthetic IMU data, fuses it with GNSS and other aiding
+sources through one of four navigation filters, and lets you remove, thin or corrupt the GNSS
+stream according to a seeded, repeatable scenario.
+
+> The crates.io and docs.rs badges show the most recent *published* release, which predates
+> 1.0. Version 1.0.0 is published together with the JOSS paper; until then, install from git
+> as described in [Installation](./installation/installation.md).
+
+## What it provides
+
+The repository is a Cargo workspace of three crates:
+
+| Crate | Imported as | What it is |
+| --- | --- | --- |
+| `strapdown-core` | `strapdown` | Mechanization, Earth model, filters, measurement models, the scenario engine and CSV I/O |
+| `strapdown-sim` | (binary) | The `strapdown-sim` command-line simulator |
+| `strapdown-geonav` | `geonav` | **Experimental** gravity and magnetic anomaly map aiding |
+
+The pieces that matter most:
+
+- **Strapdown mechanization** in the local-level (north, east, vertical) frame, following
+ Groves, *Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems*, 2nd
+ ed., §5.4-5.5. See [The Navigation Model](./user-guide/concepts.md).
+- **Four navigation filters**, all behind the `NavigationFilter` trait:
+ - the error-state Kalman filter (ESKF), the default for closed-loop runs;
+ - the extended Kalman filter (EKF);
+ - the unscented Kalman filter (UKF);
+ - a Rao-Blackwellized particle filter (RBPF) after Canciani & Raquet (2017), the only
+ particle filter in the crate.
+- **Aiding**: GNSS position and velocity, barometric relative altitude (with a barometric
+ bias state, on by default in the simulator) and magnetometer heading. The library adds
+ zero-velocity and zero-angular-rate updates driven by a stationary detector.
+- **GNSS degradation**: schedulers that decide *when* fixes arrive (pass-through, fixed
+ interval, duty-cycled outages) and fault models that decide *what* they contain (AR(1)
+ degradation, slow bias drift, position hijack). See [Fault Simulation](./gnss/fault-simulation.md).
+- **Synthetic trajectories** with IMU error models by sensor grade (`strapdown-sim syn`), so
+ every example in this book runs without a dataset.
+- **Reproducibility**: the random draws are seeded (`--seed`, or `seed` in a configuration
+ file), so the same inputs and seed give a byte-identical result, and a whole run can be
+ described by one TOML, YAML or JSON file.
+
+## What it is not
+
+The boundaries, stated up front:
+
+- **Loosely coupled only.** Aiding enters as position, velocity, altitude or heading
+ measurements. There are no pseudorange or carrier-phase models, no satellite geometry and no
+ raw-signal processing.
+- **Not IMU firmware or a driver.** It reads logged samples (CSV) or samples you hand to the
+ library; it does not talk to hardware.
+- **No coning or sculling compensation.** Each IMU sample is integrated to first order, with
+ the attitude averaged across the interval when the specific force is resolved. That suits
+ the sample rates and dynamics the project targets. It does not suit high-rate,
+ high-vibration, navigation-grade work.
+- **Local-level frame only.** The mechanization is valid from 11 km below to 30 km above the
+ ellipsoid; there is no ECEF or ECI mechanization.
+- **The CLI writes CSV only.** HDF5, NetCDF and MCAP writers exist as library methods on
+ `NavigationResult`, behind cargo features. There is no Parquet support.
+- **One input format.** The simulator reads the
+ [Sensor Logger](https://www.tszheichoi.com/sensorlogger) CSV layout, which `syn` also
+ writes. Other datasets must be converted to that layout first; see
+ [Input Data Format](./user-guide/data-format.md).
+- **Geophysical navigation is experimental.** `strapdown-geonav` is a research tool held at
+ 0.x so its API can change.
+
+## Who it is for
+
+- **Researchers** comparing navigation filters or aiding strategies under identical, repeatable
+ GNSS outages and faults.
+- **Graduate students** learning strapdown navigation. Variables are named after the
+ quantities in Groves rather than after single letters, and every equation can be run.
+- **Engineers** prototyping INS/GNSS integration who want a tested reference implementation to
+ compare their own against.
+
+## How this book is organised
+
+| Part | Read it when |
+| --- | --- |
+| [Installation](./installation/installation.md) and [Quick Start](./quick-start.md) | You want to run something in the next ten minutes |
+| [User Guide](./user-guide/overview.md) | You want the model, the frames, the state vector, and every subcommand |
+| [Navigation Filters](./filters/kalman.md) | You need to know how a particular filter works and how to tune it |
+| [GNSS Degradation](./gnss/fault-simulation.md) | You are designing outage or spoofing scenarios |
+| [Geophysical Navigation](./geonav/overview.md) | You work with gravity or magnetic anomaly maps (experimental) |
+| [API Documentation](./api/index.md) | You are calling the library from Rust |
+| [Examples and Tutorials](./examples/configurations.md) | You learn best from complete worked runs |
+| [Development](./development/contributing.md) | You want to build, test or contribute |
+
+## Getting help
+
+- Questions and bug reports: [GitHub issues](https://github.com/jbrodovsky/strapdown-rs/issues).
+- Frequently asked questions: [FAQ](./faq.md).
+- Every subcommand documents its own flags: `strapdown-sim --help`.
## Citation
-If you use Strapdown-rs in your research, please cite:
-
-[](https://joss.theoj.org/papers/5079592cc860d1435482a4a7764edcd4)
+If you use `strapdown-rs` in research, please cite it using the repository's
+[`CITATION.cff`](https://github.com/jbrodovsky/strapdown-rs/blob/main/CITATION.cff) (GitHub's
+"Cite this repository" button). The JOSS paper is under review
+([openjournals/joss-reviews#11377](https://github.com/openjournals/joss-reviews/issues/11377));
+its DOI will be added on acceptance.
## License
-Strapdown-rs is licensed under the MIT License. See the [LICENSE](https://github.com/jbrodovsky/strapdown-rs/blob/main/LICENSE) file for details.
+MIT. See [LICENSE](https://github.com/jbrodovsky/strapdown-rs/blob/main/LICENSE).
diff --git a/book/src/quick-start.md b/book/src/quick-start.md
index afb057f4..4c6f5be1 100644
--- a/book/src/quick-start.md
+++ b/book/src/quick-start.md
@@ -1,136 +1,269 @@
# Quick Start
-This guide will get you up and running with Strapdown-rs in minutes.
+This page runs every simulation mode on one synthetic trajectory, start to finish, in about
+ten commands. Nothing needs downloading: `strapdown-sim syn` generates the input. Every command
+and every line of output below was produced by `strapdown-sim 1.0.0`.
-## Installation
-
-Add Strapdown-rs to your `Cargo.toml`:
+If you have not installed the simulator yet:
```bash
-cargo add strapdown-core
+cargo install --git https://github.com/jbrodovsky/strapdown-rs strapdown-sim
```
-Or install the simulation binary:
+See [Installation](./installation/installation.md) for the details and the build requirements.
-```bash
-cargo install strapdown-sim
-```
+## 1. Generate a trajectory
-## Running Your First Simulation
+```console
+$ strapdown-sim syn -o synthetic.csv --duration-s 600 --seed 42
+2026-10-01 21:34:29.872 [INFO] - Generated 6000 synthetic records (600.0 s at 10 Hz)
+2026-10-01 21:34:29.880 [INFO] - Sensor records written to synthetic.csv
+```
-### 1. Prepare Input Data
+With no other flags, `syn` writes ten minutes of a **stationary** platform at 0° N, 0° E and
+zero altitude, sampled at 10 Hz, with a consumer-grade IMU error model (`--imu-grade consumer`)
+and a noisy GNSS fix on every row (2.5 m horizontal, 5 m vertical and 0.5 m/s per velocity
+axis, one sigma). The barometer is an independent sensor: `relativeAltitude` is computed from a
+noisy pressure (about 27 Pa, or 2.24 m, one sigma by default). The flags to
+move it, rotate it, change the IMU grade or the sample rate are listed by
+`strapdown-sim syn --help`; see [Synthetic Trajectories](./user-guide/synthetic.md).
-Strapdown-sim expects CSV files with IMU and GNSS data. The format follows the [Sensor Logger](https://github.com/tszheichoi/awesome-sensor-logger) app convention:
+The file has the same 31 columns as a Sensor Logger export, which is the format every
+simulation mode reads:
-```csv
-timestamp,gyro_x,gyro_y,gyro_z,accel_x,accel_y,accel_z,latitude,longitude,altitude
-1234567890.0,0.01,-0.02,0.03,0.5,-0.2,9.81,45.5,-122.6,100.0
-...
+```text
+time,bearingAccuracy,speedAccuracy,verticalAccuracy,horizontalAccuracy,speed,bearing,altitude,longitude,latitude,qz,qy,qx,qw,roll,pitch,yaw,acc_z,acc_y,acc_x,gyro_z,gyro_y,gyro_x,mag_z,mag_y,mag_x,relativeAltitude,pressure,grav_z,grav_y,grav_x
```
-### 2. Declare the frame
+The ones the filters use most:
+
+| Columns | Meaning |
+| --- | --- |
+| `time` | ISO 8601 UTC timestamp, e.g. `2025-01-01T00:00:00.100Z` |
+| `acc_x`, `acc_y`, `acc_z` | Specific force in the body frame, m/s², **including** the reaction to gravity |
+| `gyro_x`, `gyro_y`, `gyro_z` | Angular rate in the body frame, rad/s |
+| `latitude`, `longitude`, `altitude` | GNSS position: degrees, degrees, metres |
+| `speed`, `bearing` | GNSS ground speed (m/s) and course (degrees), turned into a north/east velocity fix |
+| `horizontalAccuracy`, `verticalAccuracy`, `speedAccuracy` | GNSS one-sigma accuracies, used as the measurement noise |
+| `qw`, `qx`, `qy`, `qz` | Attitude quaternion, used for the initial attitude |
+| `relativeAltitude` | Barometric altitude change, m |
+| `mag_x`, `mag_y`, `mag_z` | Magnetometer, µT, used for heading |
+
+A blank or `NaN` cell means "no measurement on this row". [Input Data
+Format](./user-guide/data-format.md) documents every column.
-Every command below assumes **NED** -- north, east, down -- which is the library default and
-what `strapdown-sim syn` emits.
+**This file is in the NED frame**, the library default: at rest its accelerometer reads about
+−9.8 m/s² on `acc_z`, the down axis. Sensor Logger exports from a phone are ENU and need
+`--enu` on every command. Declaring the wrong frame is refused before anything is integrated;
+[Coordinate Frames](./user-guide/coordinate-frames.md) shows the error.
-Sensor Logger exports are **ENU**: at rest the device reports `+g` along its up axis, not
-`-g` along a down axis. For those, add `--enu` (or `is_enu = true` in a config file):
+## 2. Closed loop: the ESKF
```bash
-strapdown-sim cl --enu -i data/sensor_logger.csv -o results/output.csv
+strapdown-sim cl -i synthetic.csv -o eskf.csv
```
-You will not get this wrong silently. The tool checks the declared frame against the leading
-records' sensed specific force and refuses a mismatch, naming the flag to pass -- mechanizing
-ENU records as NED adds the sensed force to the gravity model instead of cancelling it, and
-integrates at 2 g (#296).
+`cl` corrects the inertial solution with GNSS position and velocity, barometric altitude and
+magnetometer heading. Its default filter is the error-state Kalman filter. As `strapdown-sim`
+configures it, that filter carries **16 error states**: the 15 of position, velocity,
+attitude, accelerometer bias and gyroscope bias, plus a barometric altitude bias. The last is
+on by default and `--no-estimate-baro-bias` removes it. [State
+Representation](./user-guide/state-representation.md) lays the states out.
+
+The log begins:
+
+```text
+2026-10-01 21:34:29.887 [INFO] - Running in closed-loop mode with Error-State Kalman Filter (ESKF)
+2026-10-01 21:34:29.887 [INFO] - Processing file: synthetic.csv
+2026-10-01 21:34:29.903 [INFO] - Read 6000 records from synthetic.csv
+2026-10-01 21:34:29.903 [INFO] - Mechanizing input as NED: mean vertical specific force over the first 10 record(s) is -9.754 m/s^2 against a local gravity of 9.780 m/s^2
+2026-10-01 21:34:29.904 [INFO] - Initialized event stream with 13198 events
+2026-10-01 21:34:29.904 [INFO] - Initialized ESKF
+2026-10-01 21:34:29.904 [INFO] - Starting closed-loop navigation filter with 13198 events
+```
-### 3. Run a Simulation
+followed by a progress line every ten events and, at the end, `Results written to eskf.csv`.
+(One line, `Using aiding config: ...`, is omitted above for width.) The progress lines run to
+over a thousand on this file. `--log-level warn` silences them, and the commands below use it:
-**Dead Reckoning** (`dr`; `ol` is a different, unimplemented mode):
```bash
-strapdown-sim dr -i data/input.csv -o results/output.csv
+strapdown-sim --log-level warn cl -i synthetic.csv -o eskf.csv
+```
+
+### What came out
+
+Every mode writes the same CSV layout. The first ten columns are the navigation solution; the
+last row of `eskf.csv` is:
+
+```text
+timestamp,latitude,longitude,altitude,velocity_north,velocity_east,velocity_vertical,roll,pitch,yaw
+2025-01-01T00:09:59.900Z,-1.244253386640393e-6,-1.7581270456255539e-6,-0.42194145354743773,0.015484151883163197,0.0568049993997672,0.038121929489373735,0.009803423792142807,0.006982138212381999,-0.002044723575180731
```
-**Closed-Loop (16-state ESKF, the default)**:
+Latitude and longitude are in degrees, altitude in metres (positive up), velocities in m/s and
+the angles in radians. `velocity_vertical` follows the frame: positive **down** here, because
+the run is NED. The remaining 30 columns are the IMU bias estimates, the covariance, and the
+optional bias states (`gravity_bias`, `magnetic_bias`, `baro_bias` and their variances). The
+map-bias cells are empty on this run because it carried no maps. [Output
+Format](./user-guide/output-format.md) lists them all.
+
+### The same seed gives the same file
+
+Runs are deterministic. Running the same command again produces a byte-identical file:
+
+```console
+$ strapdown-sim --log-level warn cl -i synthetic.csv -o eskf_again.csv
+$ cmp eskf.csv eskf_again.csv && echo identical
+identical
+```
+
+## 3. The other Kalman filters
+
```bash
-strapdown-sim cl -i data/input.csv -o results/output.csv
+strapdown-sim --log-level warn cl -i synthetic.csv -o ekf.csv --filter ekf
+strapdown-sim --log-level warn cl -i synthetic.csv -o ukf.csv --filter ukf
```
-**Closed-Loop with EKF**:
+The EKF and UKF carry the full navigation state rather than an error state, with the same 15
+elements plus the barometric bias. See [Kalman Filters](./filters/kalman.md).
+
+## 4. Dead reckoning
+
```bash
-strapdown-sim cl -i data/input.csv -o results/output.csv --filter ekf
+strapdown-sim --log-level warn dr -i synthetic.csv -o dr.csv
```
-**Closed-Loop with UKF**:
+`dr` propagates the IMU from the first record with no aiding at all, so its error grows without
+bound: on this file the unaided velocity error passes 500 m/s before the ten minutes are up.
+That divergence is the result, so `dr` applies the wall-clock budgets but none of the health
+bounds the filters are held to. (`ol` is a different subcommand, reserved for an open-loop mode that is **not
+implemented**: it writes no output. Use `dr` for dead reckoning.)
+
+## 5. The particle filter
+
```bash
-strapdown-sim cl -i data/input.csv -o results/output.csv --filter ukf
+strapdown-sim --log-level warn pf -i synthetic.csv -o pf.csv
```
-**Particle Filter**:
+`pf` runs the Rao-Blackwellized particle filter (100 particles by default, `--num-particles`
+to change it). Its output has the same columns; its six IMU-bias columns are zero because the
+filter does not estimate IMU biases. See [Rao-Blackwellized Particle Filter](./filters/rbpf.md).
+
+## 6. A GNSS outage
+
```bash
-strapdown-sim pf -i data/input.csv -o results/output.csv --num-particles 100
+strapdown-sim --log-level warn cl -i synthetic.csv -o eskf_outage.csv \
+ --sched duty --on-s 100 --off-s 50
```
-### 4. View Results
+The duty-cycle scheduler withholds GNSS fixes in 50 s windows separated by 100 s of normal
+service. With the default `--duty-phase-s 0` the cycle **starts with an outage**: fixes are
+withheld over 0-50 s, 150-200 s, 300-350 s and 450-500 s. At the default log level the
+difference is visible in the event count: 11199 events here against 13198 for the
+uninterrupted run, which is 200 s of 10 Hz GNSS fixes. The barometer and magnetometer are
+scheduled separately and keep arriving. [Fault Simulation](./gnss/fault-simulation.md) covers
+the other schedulers and the fault models (`--fault degraded|slowbias|hijack`).
+
+## 7. Score the runs
-The output CSV contains the estimated navigation state:
+`syn --no-noise` writes the truth for the same trajectory, in the output format:
-```csv
-timestamp,latitude,longitude,altitude,velocity_north,velocity_east,velocity_down,roll,pitch,yaw
-1234567890.0,45.50001,-122.59999,100.1,1.2,0.5,-0.1,0.01,0.02,90.5
-...
+```bash
+strapdown-sim syn -o truth.csv --duration-s 600 --seed 42 --no-noise
```
-## Using Configuration Files
+This short Python script (standard library only) compares each run's horizontal position with
+the truth, row by row:
+
+```python
+# score.py
+import csv, math, sys
+
+R = 6_371_000.0 # mean Earth radius, m; adequate for metre-level errors
+
-For more complex scenarios, use TOML configuration files:
+def load(path):
+ with open(path) as f:
+ return list(csv.DictReader(f))
+
+
+truth = load("truth.csv")
+for path in sys.argv[1:]:
+ est = load(path)
+ errors = []
+ for t, e in zip(truth, est):
+ d_north = math.radians(float(e["latitude"]) - float(t["latitude"])) * R
+ d_east = (
+ math.radians(float(e["longitude"]) - float(t["longitude"]))
+ * R
+ * math.cos(math.radians(float(t["latitude"])))
+ )
+ errors.append(math.hypot(d_north, d_east))
+ rms = math.sqrt(sum(x * x for x in errors) / len(errors))
+ print(f"{path:16s} horizontal RMS {rms:10.3f} m final {errors[-1]:10.3f} m")
+```
+
+```console
+$ python3 score.py dr.csv eskf.csv ekf.csv ukf.csv pf.csv eskf_outage.csv
+dr.csv horizontal RMS 41364.109 m final 109129.025 m
+eskf.csv horizontal RMS 0.524 m final 0.239 m
+ekf.csv horizontal RMS 0.522 m final 0.239 m
+ukf.csv horizontal RMS 0.522 m final 0.240 m
+pf.csv horizontal RMS 0.921 m final 0.528 m
+eskf_outage.csv horizontal RMS 15.671 m final 0.240 m
+```
+
+Read these as a demonstration of the workflow, not as a comparison of the filters: they come
+from one stationary trajectory and one seed. Unaided, the consumer-grade IMU drifts by about
+110 km in ten minutes. Every aided run stays at the metre level. The outage run's final error
+matches the uninterrupted run's to within a millimetre because the last 100 s have GNSS again,
+while its RMS carries the four outages. The filters' measured accuracy on the reference scenarios is on the
+[Performance Baselines](./development/performance.md) page.
+
+## 8. The same run from a scenario file
+
+Everything above can be written into one TOML, YAML or JSON file, which is the reproducible
+record of an experiment. This is the outage run of step 6:
```toml
-# config.toml -- a whole `SimulationConfig`. `mode` is the only required field.
-mode = "closed-loop" # dead-reckoning | open-loop | closed-loop | particle-filter | synthetic
-input = "data/trajectory.csv"
-output = "results/navigation.csv"
+# outage.toml: the duty-cycle run above, as a scenario file
+mode = "closed-loop"
+input = "synthetic.csv"
+output = "eskf_outage_from_config.csv"
seed = 42
-is_enu = false # NED is the default; Sensor Logger exports need `true`
[logging]
-level = "info"
+level = "warn"
[closed_loop]
-filter = "eskf" # eskf (default) | ukf | ekf
-
-[aiding]
-seed = 42
+filter = "eskf"
-[aiding.scheduler] # when GNSS fixes arrive
-kind = "fixed_interval"
-interval_s = 5.0
-phase_s = 0.0
+[aiding.scheduler]
+kind = "duty_cycle"
+on_s = 100.0
+off_s = 50.0
+start_phase_s = 0.0
-[aiding.fault] # how they are corrupted
+[aiding.fault]
kind = "none"
```
-Run it with the config alone — `--config` supplies the whole run, so a subcommand and its
-`-i`/`-o`/`--filter` arguments are ignored when it is present:
-
-```bash
-strapdown-sim --config config.toml
+```console
+$ strapdown-sim --config outage.toml
+$ cmp eskf_outage.csv eskf_outage_from_config.csv && echo identical
+identical
```
-`core/tests/example_configs.rs` parses every file under `examples/configs/` and asserts it
-deserializes into the scenario it describes, because every field has a default: a misspelled
-section is dropped silently and the run simulates nothing.
-
-Run with:
-```bash
-strapdown-sim --config config.toml
-```
+`--config` supplies the whole run, so no subcommand is given. The `[aiding]` section is also
+accepted under its older name, `[gnss_degradation]`. Every field has a default, so a misspelled
+section name is not an error: it is silently ignored and the run uses defaults. Check a new
+file against the keys in [Configuration Files](./user-guide/configuration.md).
-## Next Steps
+## Next steps
-- Read the [User Guide](./user-guide/overview.md) for detailed usage instructions
-- Explore [Example Configurations](./examples/configurations.md)
-- Learn about [Navigation Filters](./filters/kalman.md)
-- Check the [API Reference](./api/core.md) for programmatic usage
+- [User Guide Overview](./user-guide/overview.md): the crates, subcommands and filters, and
+ where each is documented.
+- [The Navigation Model](./user-guide/concepts.md): what the mechanization computes.
+- [Example Configurations](./examples/configurations.md): scenario files for every scheduler
+ and fault.
+- [Using the Library](./user-guide/library.md): the same machinery from Rust.
diff --git a/book/src/resources/glossary.md b/book/src/resources/glossary.md
index ca3c8276..c1ba3df3 100644
--- a/book/src/resources/glossary.md
+++ b/book/src/resources/glossary.md
@@ -1 +1,76 @@
# Glossary
+
+- **ARW / VRW** (angle / velocity random walk): The integrated effect of white noise on a
+ gyroscope or accelerometer. Integrating white angular-rate noise gives an attitude error whose
+ standard deviation grows with the square root of time; ARW is that growth, in rad/√s (often
+ quoted in deg/√h). VRW is the same for velocity, in m/s/√s. The RBPF's velocity and attitude
+ process noise are VRW and ARW.
+- **CEP** (circular error probable): The radius of a circle, centred on truth, containing a
+ given share of horizontal position errors. CEP50 contains half of them, CEP95 95%.
+ `strapdown::metrics` computes the empirical (nearest-rank) value from the errors, not the
+ Rayleigh approximation.
+- **DCM** (direction cosine matrix): The 3×3 rotation matrix between two frames, here body to
+ navigation frame. The attitude representation the mechanization propagates; roll, pitch and
+ yaw are derived from it.
+- **EKF** (extended Kalman filter): A Kalman filter for a nonlinear system that propagates the
+ full state through the nonlinear model and the covariance through its Jacobians. See
+ [EKF](../filters/ekf.md).
+- **ENU / NED**: The two local-level frame conventions this crate supports. NED
+ (North-East-Down) is the default. "ENU" is opt-in with `--enu` or `is_enu`, and here it is
+ **not** the textbook East-North-Up: it keeps the north-then-east order of the horizontal
+ axes (`velocity_north`, `velocity_east` in both) and flips only the vertical axis to point
+ up, which is what `StrapdownState::to_enu` does. Altitude is positive up in both; vertical
+ velocity is positive down in NED and up in "ENU". See [Coordinate
+ Frames](../user-guide/coordinate-frames.md).
+- **ESKF** (error-state Kalman filter): A Kalman filter that estimates the *error* in a
+ separately propagated nominal solution, folds the estimate back in after each update, and
+ resets. This crate's ESKF carries a multiplicative attitude error and is the closed-loop
+ default. See [ESKF](../filters/eskf.md).
+- **Gauss-Markov process** (first order): A random process whose autocorrelation decays
+ exponentially, $R(\Delta t) = \sigma^2 e^{-|\Delta t|/\tau}$, with steady-state standard
+ deviation $\sigma$ and correlation time $\tau$. In discrete time, an AR(1) process with $\rho
+ = e^{-\Delta t/\tau}$. Used for correlated GNSS errors (`degraded` with `tau_pos_s`) and for
+ map-bias variation.
+- **GNSS** (global navigation satellite system): GPS, Galileo, GLONASS, BeiDou and the like.
+ Here, the source of the position and velocity fixes that aid the INS, and the thing the
+ degradation scenarios take away.
+- **IMU** (inertial measurement unit): An accelerometer triad and a gyroscope triad measuring
+ specific force and angular rate in the body frame.
+- **INS** (inertial navigation system): An IMU plus the computation that integrates its output
+ into position, velocity and attitude.
+- **Lever arm**: The vector from the IMU to another sensor on the same body, typically the GNSS
+ antenna. A rotating vehicle moves the two points differently, so a fix is translated through
+ the lever arm before it is compared with the INS solution. `InsEngine` applies this
+ compensation.
+- **Loosely coupled**: An integration that aids the INS with the GNSS receiver's *solution*
+ (position and velocity) rather than with its raw pseudorange and carrier-phase measurements
+ (tightly coupled). This crate is loosely coupled only.
+- **MEMS** (micro-electro-mechanical systems): The silicon sensor technology of consumer and
+ low-cost IMUs, such as the one in a phone. Cheap and small, with biases and noise far larger
+ than navigation-grade sensors.
+- **NEES / NIS** (normalized estimation error squared / normalized innovation squared):
+ Consistency statistics. NEES is $e^\top P^{-1} e$ for the true estimation error $e$ and the
+ filter's covariance $P$, so it needs truth; its expected value is the dimension of $e$. NIS is
+ $\nu^\top S^{-1} \nu$ for the innovation $\nu$ and its predicted covariance $S$, so it needs
+ no truth and can be computed online; innovation gating thresholds it against a chi-squared
+ quantile.
+- **PNT** (positioning, navigation and timing): The services GNSS provides, and the usual name
+ for the field of providing them by other means when GNSS is unavailable.
+- **RBPF** (Rao-Blackwellized particle filter): A particle filter that samples only the strongly
+ nonlinear part of the state (here, horizontal position) and handles the rest with a Kalman
+ filter conditioned on each sample. The crate's only particle filter. See
+ [RBPF](../filters/rbpf.md).
+- **Specific force**: What an accelerometer measures: the non-gravitational force per unit mass,
+ that is, acceleration minus gravitational acceleration. At rest it points up with magnitude
+ $g$. The mechanization adds the gravity model back.
+- **Strapdown**: An INS whose sensors are fixed ("strapped down") to the vehicle body, so that
+ attitude is computed by integrating the gyroscopes rather than maintained by a gimballed
+ platform.
+- **UKF** (unscented Kalman filter): A Kalman filter that propagates a set of deterministically
+ chosen sigma points through the nonlinear model instead of linearizing it. See
+ [UKF](../filters/ukf.md).
+- **ZUPT / ZARU** (zero-velocity update / zero angular-rate update): Pseudo-measurements applied
+ while the vehicle is known to be stationary: velocity is zero, and the gyroscopes should read
+ only Earth rotation. `strapdown::stationary` detects such periods and
+ `strapdown::measurements` provides both models.
+
diff --git a/book/src/resources/links.md b/book/src/resources/links.md
deleted file mode 100644
index aa7d3db1..00000000
--- a/book/src/resources/links.md
+++ /dev/null
@@ -1 +0,0 @@
-# External Links
diff --git a/book/src/resources/publications.md b/book/src/resources/publications.md
index 5d202aee..7b7f9859 100644
--- a/book/src/resources/publications.md
+++ b/book/src/resources/publications.md
@@ -1 +1,52 @@
-# Publications
+# Publications and Links
+
+## Papers about this software
+
+- **J. Brodovsky**, "strapdown-rs: Strapdown inertial navigation and GNSS-degradation
+ simulation in Rust." Submitted to the *Journal of Open Source Software*; under review at
+ [openjournals/joss-reviews#11377](https://github.com/openjournals/joss-reviews/issues/11377).
+ The source is in `papers/joss/` in the repository. Until it is published, cite the software
+ through the repository's `CITATION.cff`.
+
+## Papers that use it
+
+The geophysical-navigation work that `strapdown-geonav` supports (see
+[Geophysical Navigation](../geonav/overview.md)):
+
+- J. Brodovsky and P. Dames, "Navigation in GNSS-denied environments using MEMS-grade sensors
+ and geophysical anomalies: A UKF approach," in *Proceedings of the 2026 International
+ Technical Meeting of the Institute of Navigation*, Anaheim, California, Jan. 2026,
+ pp. 155–164. [doi:10.33012/2026.20508](https://doi.org/10.33012/2026.20508)
+- J. Brodovsky and P. Dames, "Navigation in GNSS-Denied Environments Using MEMS-Grade Sensors
+ and Geophysical Anomalies: A Particle Filter Approach," in *Proceedings of the ION 2026
+ Pacific PNT Meeting*, Honolulu, Hawaii, Apr. 2026, pp. 399–410.
+ [doi:10.33012/2026.20618](https://doi.org/10.33012/2026.20618)
+
+## References the implementation follows
+
+- P. D. Groves, *Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems*,
+ 2nd ed. Boston: Artech House, 2013. ISBN 978-1-60807-005-3. The mechanization, the Earth
+ model and the filters cite it by section and equation number throughout.
+- A. Canciani and J. Raquet, "Airborne Magnetic Anomaly Navigation," *IEEE Transactions on
+ Aerospace and Electronic Systems*, vol. 53, no. 1, pp. 67–80, 2017.
+ [doi:10.1109/TAES.2017.2649238](https://doi.org/10.1109/TAES.2017.2649238). The design of
+ the Rao-Blackwellized particle filter; see [Rao-Blackwellized Particle Filter](../filters/rbpf.md).
+- National Geospatial-Intelligence Agency, *Department of Defense World Geodetic System 1984:
+ Its Definition and Relationships with Local Geodetic Systems*, NGA.STND.0036_1.0.0_WGS84,
+ 2014. The ellipsoid in `strapdown::earth`.
+- NOAA NCEI Geomagnetic Modeling Team and British Geological Survey, *World Magnetic Model
+ 2025*, 2024. [doi:10.25921/aqfd-sd83](https://doi.org/10.25921/aqfd-sd83). The reference
+ field for magnetometer heading and magnetic anomalies.
+
+## Links
+
+| | |
+|---|---|
+| Source repository | |
+| This book | |
+| API documentation | [published with this book](../api/index.md); on docs.rs as [strapdown-core](https://docs.rs/strapdown-core) and [strapdown-geonav](https://docs.rs/strapdown-geonav) once v1.0.0 is on crates.io |
+| Issue tracker | |
+| Sensor Logger (the app the input format comes from) | |
+| World Magnetic Model | |
+| `world_magnetic_model` crate (the WMM implementation used) | |
+| GMT remote datasets (the source of the gravity and magnetic maps) | |
diff --git a/book/src/user-guide/closed-loop.md b/book/src/user-guide/closed-loop.md
index b7f35bae..b0a337e2 100644
--- a/book/src/user-guide/closed-loop.md
+++ b/book/src/user-guide/closed-loop.md
@@ -1 +1,236 @@
-# Closed-Loop Mode
+# Closed Loop (Kalman Filters)
+
+`strapdown-sim cl` runs the INS with a Kalman filter that corrects it from aiding measurements,
+feeding each correction back into the navigation solution. It is the mode for GNSS-aided
+navigation and for studying what happens when the GNSS is withheld or corrupted.
+
+```bash
+strapdown-sim syn -o synthetic.csv --duration-s 600 --seed 42
+strapdown-sim cl -i synthetic.csv -o results/eskf.csv
+```
+
+```console
+[INFO] - Running in closed-loop mode with Error-State Kalman Filter (ESKF)
+[INFO] - Read 6000 records from synthetic.csv
+[INFO] - Mechanizing input as NED: mean vertical specific force over the first 10 record(s) is -9.754 m/s^2 against a local gravity of 9.780 m/s^2
+[INFO] - Initialized event stream with 13198 events
+[INFO] - Initialized ESKF
+[INFO] - Starting closed-loop navigation filter with 13198 events
+...
+[INFO] - Results written to results/eskf.csv
+```
+
+(Timestamps trimmed; at `info` the filter also logs a progress line every few events, which
+`--log-level warn` silences.) The shared flags -- `-i`, `-o`, `--enu`, the execution and health
+limits -- are described in [Running Simulations](./simulations.md). This page covers the flags
+specific to `cl`.
+
+## Choosing the filter
+
+| Flag | Default | Values |
+|---|---|---|
+| `--filter ` | `eskf` | `eskf`, `ukf`, `ekf` |
+
+- **`eskf`** -- the error-state Kalman filter with a multiplicative attitude error: 15 error
+ states, plus a barometric bias state unless `--no-estimate-baro-bias`. The default. See [ESKF](../filters/eskf.md).
+- **`ekf`** -- the extended Kalman filter. See [EKF](../filters/ekf.md).
+- **`ukf`** -- the unscented Kalman filter. See [UKF](../filters/ukf.md).
+
+All three estimate accelerometer and gyroscope biases (the `acc_bias_*` and `gyro_bias_*` output
+columns are populated for each) and, by default, a barometric bias. How they compare is on the
+[Comparison](../filters/comparison.md) page.
+
+```bash
+strapdown-sim cl -i synthetic.csv -o results/ukf.csv --filter ukf
+strapdown-sim cl -i synthetic.csv -o results/ekf.csv --filter ekf
+```
+
+### UKF sigma-point parameters
+
+Read only with `--filter ukf`.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--ukf-alpha ` | `0.1` | sigma-point spread |
+| `--ukf-beta ` | `2` | prior-distribution parameter; 2 is optimal for a Gaussian |
+| `--ukf-kappa ` | `0` | secondary spread parameter |
+
+`--ukf-alpha` defaults to `0.1`, the same value a configuration file uses, not the textbook
+`1e-3`. At `1e-3` the weighted sigma-point mean is formed from terms about $10^6$ times the
+answer, which costs six significant digits to cancellation on every step; the measurement behind
+the choice is recorded on `ClosedLoopConfig::ukf_alpha` in the API documentation.
+
+## What aids the filter
+
+`cl` builds its measurements from the input records. Which columns feed which measurement is
+covered in [Input Data Format](./data-format.md#which-columns-drive-what); in summary:
+
+| Measurement | Built from | Rate | Noise |
+|---|---|---|---|
+| GNSS position and velocity | `latitude`, `longitude`, `altitude`, `speed`, `bearing` | every record that carries all five, subject to `--sched` | the record's `horizontalAccuracy`, `verticalAccuracy`, `speedAccuracy`, then `--fault` |
+| Barometric altitude | `relativeAltitude`, referenced to the first record's altitude | 1 Hz | 2.236 m one-sigma |
+| Magnetometer heading | `mag_x`, `mag_y`, `mag_z`, with declination from the World Magnetic Model at the record's date | 1 Hz | 0.2 rad one-sigma |
+
+The GNSS channel is the one the command line can degrade. The barometer and magnetometer
+schedules, and the barometer's noise, have **no command-line flags**: they take the defaults
+above, and a configuration file can change them (`aiding.baro_scheduler`,
+`aiding.magnetometer_scheduler`, `aiding.baro_noise_std_m`; see
+[Configuration Files](./configuration.md#the-barometer-and-magnetometer)). Neither is ever
+corrupted; fault models apply to GNSS only.
+
+### The barometric bias state
+
+A barometer converts pressure to altitude against a reference pressure that drifts, and a filter
+that models the reading as unbiased has nowhere to put that drift except into altitude. `cl`
+therefore estimates a barometric bias as an extra filter state, **on by default**, and writes it
+to the `baro_bias` and `baro_bias_cov` output columns.
+
+| Flag | Effect |
+|---|---|
+| `--no-estimate-baro-bias` | do not carry the barometric bias state; the two output columns are left empty |
+
+The flag is spelled negatively because the default is on. The old `--estimate-baro-bias` was
+removed rather than kept as a no-op, so a script still passing it fails with clap's "unexpected
+argument" error instead of silently meaning nothing. The measurements behind the default, and the
+one case where the state hurts (an AR(1)-degraded GNSS fault, issue #410), are on the
+[Configuration Files](./configuration.md#the-barometric-bias) page.
+
+## GNSS scheduling: when fixes arrive
+
+The scheduler decides which GNSS fixes reach the filter at all. A fix the scheduler withholds is
+simply absent; the filter coasts on the IMU, still aided by the barometer and magnetometer.
+
+| Flag | Default | Used by | Meaning |
+|---|---|---|---|
+| `--sched ` | `passthrough` | -- | `passthrough`, `fixed` or `duty` |
+| `--interval-s ` | `1` | `fixed` | seconds between delivered fixes |
+| `--phase-s ` | `0` | `fixed` | offset of the first delivered fix |
+| `--on-s ` | `10` | `duty` | length of each available window |
+| `--off-s ` | `10` | `duty` | length of each denied window |
+| `--duty-phase-s ` | `0` | `duty` | length of an initial available window before the cycle starts |
+
+- **`passthrough`** delivers every fix.
+- **`fixed`** delivers at most one fix per interval: the first usable fix at or after each tick.
+ It models a reduced update rate.
+- **`duty`** alternates denial and availability. The timeline is `--duty-phase-s` of
+ availability, then `--off-s` denied and `--on-s` available, repeating. **With the default
+ phase of 0 the run therefore starts in an outage**: `--sched duty --on-s 100 --off-s 50` denies
+ GNSS for the first 50 s, delivers it from 50 s to 150 s, denies it from 150 s to 200 s, and so
+ on. Set `--duty-phase-s` to start with GNSS available.
+
+```bash
+strapdown-sim cl -i synthetic.csv -o results/fixed.csv --sched fixed --interval-s 5
+strapdown-sim cl -i synthetic.csv -o results/duty.csv --sched duty --on-s 100 --off-s 50
+```
+
+On the 600 s, 10 Hz trajectory above, the pass-through run's event stream holds 13,198 events
+and the duty-cycle run's 11,199 -- the difference is the 1,999 GNSS fixes its four 50 s outages
+(0-50 s, 150-200 s, 300-350 s and 450-500 s) withhold, as `Initialized event stream with ... events` reports at `info` level.
+
+## GNSS faults: what the fixes say
+
+A fault model corrupts the content of each fix the scheduler lets through. Scheduler and fault
+compose: a duty cycle can deliver degraded fixes during its available windows.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--fault ` | `none` | `none`, `degraded`, `slowbias` or `hijack` |
+
+**`degraded`** adds AR(1)-correlated error to position and velocity and inflates the accuracy the
+fix advertises. It models low signal-to-noise or multipath.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--rho-pos` | `0.99` | AR(1) correlation coefficient of the position error, per fix |
+| `--sigma-pos-m` | `3` | position error, metres: the per-fix innovation, or the steady-state sigma with `--tau-pos-s` |
+| `--rho-vel` | `0.95` | AR(1) correlation coefficient of the velocity error, per fix |
+| `--sigma-vel-mps` | `0.3` | velocity error, m/s, read the same way as `--sigma-pos-m` |
+| `--r-scale` | `5` | factor on the advertised one-sigma accuracies, so $R$ grows by its **square** (25 by default) |
+| `--tau-pos-s` | unset | position-error correlation time, seconds |
+| `--tau-vel-s` | unset | velocity-error correlation time, seconds |
+
+Without `--tau-pos-s`, `--rho-pos` is applied once per delivered fix, so the error's correlation
+time is $-\Delta t / \ln \rho$ with $\Delta t$ the fix interval: changing `--interval-s` changes
+the error model too. With `--tau-pos-s`, the coefficient is $e^{-\Delta t/\tau}$ for the actual
+interval between fixes and `--sigma-pos-m` becomes the steady-state standard deviation, so the
+error keeps the same timescale whatever the schedule. `--tau-vel-s` does the same for velocity.
+Leave both unset to reproduce results made before they existed.
+
+**`slowbias`** adds a north/east offset that grows steadily, so each fix looks plausible while
+the trajectory is nudged away. It models a soft spoof.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--drift-n-mps` | `0.02` | northward drift rate of the offset, m/s |
+| `--drift-e-mps` | `0` | eastward drift rate of the offset, m/s |
+| `--q-bias` | `1e-6` | random-walk density of the offset, m²/s: each step adds variance `q_bias * dt` |
+| `--rotate-omega-rps` | `0` | rate at which the drift direction rotates, rad/s |
+
+**`hijack`** applies a constant north/east offset over a fixed window. It models a hard spoof.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--hijack-offset-n-m` | `50` | northward offset, metres |
+| `--hijack-offset-e-m` | `0` | eastward offset, metres |
+| `--hijack-start-s` | `120` | window start, seconds from the first record |
+| `--hijack-duration-s` | `60` | window length, seconds |
+
+```bash
+strapdown-sim cl -i synthetic.csv -o results/degraded.csv \
+ --fault degraded --sigma-pos-m 10 --tau-pos-s 60 --tau-vel-s 30
+strapdown-sim cl -i synthetic.csv -o results/hijack.csv \
+ --fault hijack --hijack-offset-n-m 100 --hijack-start-s 200 --hijack-duration-s 60
+strapdown-sim cl -i synthetic.csv -o results/both.csv \
+ --sched duty --on-s 100 --off-s 50 --fault degraded --sigma-pos-m 10.0 --seed 7
+```
+
+Only one fault can be chosen on the command line. Several applied in sequence -- a slow drift
+followed by a hijack, say -- is the `combo` fault, which exists only in a configuration file; see
+[Configuration Files](./configuration.md#fault-models). Every random draw a fault makes comes from
+`--seed` (default `42`), so the same seed and flags give the same corrupted fixes. The
+[GNSS Degradation](../gnss/fault-simulation.md) chapter describes the models in more depth.
+
+## Innovation gating
+
+By default every measurement is applied. An innovation gate rejects a measurement whose
+normalized innovation squared (NIS) is implausibly large for the filter's own covariance.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--gate-confidence