Skip to content

Estimation filters and analysis

Standalone attitude filters (recurrence blocks, siblings of each other) and the observability / consistency analysis tools.

Attitude filters

manta.Madgwick

Madgwick(beta=0.1, *, name='madgwick')

Bases: RecurrenceBlock

Madgwick gyro+accel AHRS filter as a recurrence block.

Args: beta — filter gain (rad/s): the accelerometer correction rate. Higher trusts the accelerometer more (faster convergence, more noise); lower trusts the gyro. ~0.1 is a typical start. name — codegen basename / default C++ class stem.

Source code in manta/estimation/madgwick.py
def __init__(self, beta: float = 0.1, *, name: str = "madgwick") -> None:
    self.beta = float(beta)
    b = self.beta

    def rec(x, u, dt, t):
        q0, q1, q2, q3 = x["orientation"][0], x["orientation"][1], \
            x["orientation"][2], x["orientation"][3]
        gx, gy, gz = u["gyro"][0], u["gyro"][1], u["gyro"][2]
        ax, ay, az = u["accel"][0], u["accel"][1], u["accel"][2]

        # Rate of change of quaternion from the gyroscope.
        qd0 = 0.5 * (-q1 * gx - q2 * gy - q3 * gz)
        qd1 = 0.5 * (q0 * gx + q2 * gz - q3 * gy)
        qd2 = 0.5 * (q0 * gy - q1 * gz + q3 * gx)
        qd3 = 0.5 * (q0 * gz + q1 * gy - q2 * gx)

        # Normalize the accelerometer (eps-guarded; direction only).
        a_norm = ca.sqrt(ax * ax + ay * ay + az * az + 1e-18)
        ax, ay, az = ax / a_norm, ay / a_norm, az / a_norm

        # Gradient-descent corrective step (Madgwick reference IMU form).
        _2q0, _2q1, _2q2, _2q3 = 2 * q0, 2 * q1, 2 * q2, 2 * q3
        _4q0, _4q1, _4q2 = 4 * q0, 4 * q1, 4 * q2
        _8q1, _8q2 = 8 * q1, 8 * q2
        q0q0, q1q1, q2q2, q3q3 = q0 * q0, q1 * q1, q2 * q2, q3 * q3

        s0 = _4q0 * q2q2 + _2q2 * ax + _4q0 * q1q1 - _2q1 * ay
        s1 = (_4q1 * q3q3 - _2q3 * ax + 4 * q0q0 * q1 - _2q0 * ay
              - _4q1 + _8q1 * q1q1 + _8q1 * q2q2 + _4q1 * az)
        s2 = (4 * q0q0 * q2 + _2q0 * ax + _4q2 * q3q3 - _2q3 * ay
              - _4q2 + _8q2 * q1q1 + _8q2 * q2q2 + _4q2 * az)
        s3 = 4 * q1q1 * q3 - _2q1 * ax + 4 * q2q2 * q3 - _2q2 * ay
        s_norm = ca.sqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3 + 1e-18)

        # Apply the feedback step and integrate.
        q0n = q0 + (qd0 - b * s0 / s_norm) * dt
        q1n = q1 + (qd1 - b * s1 / s_norm) * dt
        q2n = q2 + (qd2 - b * s2 / s_norm) * dt
        q3n = q3 + (qd3 - b * s3 / s_norm) * dt

        qn = ca.vertcat(q0n, q1n, q2n, q3n)
        qn = qn / ca.sqrt(ca.dot(qn, qn) + 1e-18)   # renormalize
        return {"orientation": qn}, {"orientation": qn}

    self._build_recurrence(
        name=name,
        state=[("orientation", SO3Manifold())],
        inputs=[("gyro", 3), ("accel", 3)],
        outputs=[("orientation", 4)],
        x0={"orientation": [1.0, 0.0, 0.0, 0.0]},
        recurrence=rec)

manta.Mahony

Mahony(kp=0.5, ki=0.0, *, name='mahony')

Bases: RecurrenceBlock

Mahony gyro+accel AHRS filter (with bias estimation) as a recurrence block.

Args: kp — proportional gain on the accelerometer error (how hard the accel pulls the attitude). ki — integral gain; the rate at which the gyro-bias estimate learns. 0 disables bias estimation (pure complementary). name — codegen basename / default C++ class stem.

Source code in manta/estimation/mahony.py
def __init__(self, kp: float = 0.5, ki: float = 0.0, *,
             name: str = "mahony") -> None:
    self.kp = float(kp)
    self.ki = float(ki)
    two_kp, two_ki = 2.0 * self.kp, 2.0 * self.ki

    def rec(x, u, dt, t):
        q0, q1, q2, q3 = (x["orientation"][0], x["orientation"][1],
                          x["orientation"][2], x["orientation"][3])
        bx, by, bz = x["gyro_bias"][0], x["gyro_bias"][1], x["gyro_bias"][2]
        gx, gy, gz = u["gyro"][0], u["gyro"][1], u["gyro"][2]
        ax, ay, az = u["accel"][0], u["accel"][1], u["accel"][2]

        # Normalize the accelerometer (eps-guarded; direction only).
        a_norm = ca.sqrt(ax * ax + ay * ay + az * az + 1e-18)
        ax, ay, az = ax / a_norm, ay / a_norm, az / a_norm

        # Estimated direction of gravity (half), and the error = measured
        # × estimated (cross product).
        halfvx = q1 * q3 - q0 * q2
        halfvy = q0 * q1 + q2 * q3
        halfvz = q0 * q0 - 0.5 + q3 * q3
        halfex = ay * halfvz - az * halfvy
        halfey = az * halfvx - ax * halfvz
        halfez = ax * halfvy - ay * halfvx

        # Integral feedback → gyro-bias estimate; corrected rate.
        bx_n = bx + two_ki * halfex * dt
        by_n = by + two_ki * halfey * dt
        bz_n = bz + two_ki * halfez * dt
        gxc = gx + bx_n + two_kp * halfex
        gyc = gy + by_n + two_kp * halfey
        gzc = gz + bz_n + two_kp * halfez

        # First-order quaternion integration (snapshot the old q).
        hx, hy, hz = 0.5 * dt * gxc, 0.5 * dt * gyc, 0.5 * dt * gzc
        q0n = q0 + (-q1 * hx - q2 * hy - q3 * hz)
        q1n = q1 + (q0 * hx + q2 * hz - q3 * hy)
        q2n = q2 + (q0 * hy - q1 * hz + q3 * hx)
        q3n = q3 + (q0 * hz + q1 * hy - q2 * hx)
        qn = ca.vertcat(q0n, q1n, q2n, q3n)
        qn = qn / ca.sqrt(ca.dot(qn, qn) + 1e-18)
        return ({"orientation": qn,
                 "gyro_bias": ca.vertcat(bx_n, by_n, bz_n)},
                {"orientation": qn})

    self._build_recurrence(
        name=name,
        state=[("orientation", SO3Manifold()),
               ("gyro_bias", R3Manifold())],
        inputs=[("gyro", 3), ("accel", 3)],
        outputs=[("orientation", 4)],
        x0={"orientation": [1.0, 0.0, 0.0, 0.0],
            "gyro_bias": [0.0, 0.0, 0.0]},
        recurrence=rec)

manta.IMUIntegrator

IMUIntegrator(*, gravity=(0.0, 0.0, -9.81), p0=(0.0, 0.0, 0.0), v0=(0.0, 0.0, 0.0), q0=(1.0, 0.0, 0.0, 0.0), name='imu_integrator')

Bases: RecurrenceBlock

Strapdown INS dead-reckoner as a recurrence block.

Args: gravity — world-frame gravity vector (default (0, 0, -9.81)). p0, v0 — initial position / velocity (world). Default zero. q0 — initial orientation quaternion (w, x, y, z), body→world. Default identity. name — codegen basename / default C++ class stem.

Source code in manta/estimation/imu_integrator.py
def __init__(self, *, gravity=(0.0, 0.0, -9.81),
             p0=(0.0, 0.0, 0.0), v0=(0.0, 0.0, 0.0),
             q0=(1.0, 0.0, 0.0, 0.0), name: str = "imu_integrator") -> None:
    self.gravity = tuple(float(x) for x in gravity)
    g = ca.DM(list(self.gravity))

    def rec(x, u, dt, t):
        q = x["orientation"]
        v = x["velocity"]
        p = x["position"]
        accel = u["accel"]
        gyro = u["gyro"]

        # Specific force, body → world (quaternion sandwich), + gravity.
        a_body_q = ca.vertcat(0, accel[0], accel[1], accel[2])
        a_world_q = quat_mul(quat_mul(q, a_body_q), quat_conj(q))
        a_world = a_world_q[1:4] + g

        v_next = v + a_world * dt
        p_next = p + v * dt + 0.5 * a_world * dt * dt
        # Exact body-frame attitude increment for the step.
        q_next = quat_mul(q, so3_exp(gyro * dt))

        nxt = {"position": p_next, "velocity": v_next,
               "orientation": q_next}
        return nxt, dict(nxt)

    self._build_recurrence(
        name=name,
        state=[("position", R3Manifold()),
               ("velocity", R3Manifold()),
               ("orientation", SO3Manifold())],
        inputs=[("accel", 3), ("gyro", 3)],
        outputs=[("position", 3), ("velocity", 3), ("orientation", 4)],
        x0={"position": list(map(float, p0)),
            "velocity": list(map(float, v0)),
            "orientation": list(map(float, q0))},
        recurrence=rec)

Observability and consistency

manta.estimation.observability

Observability analysis — does your sensor set actually constrain your state?

A faithful EKF (correct f, correct Jacobians) is still only as good as the observability of the model it filters: whether the measurements, through the dynamics, pin down every state direction. Observability is a property of (dynamics + sensor set + operating point)not of the model alone — so "make the model correct and the EKF follows" silently fails on unobservable modes. They don't error; they drift, and the filter reports tight covariance while doing it. (The canonical example: heading is unobservable from GPS + DVL + gyro — only its rate is measured — so a submarine's yaw estimate wanders until a compass is added. Caveat: that holds on a non-rotating model. On a spinning planet the Earth rate makes heading weakly observable through the dynamics — gyrocompassing — at singular values far below this rank test's threshold; sigma_horizon below is the tool that resolves such slow channels.)

manta is well placed to catch this automatically, because the symbolic state-transition F and per-sensor measurement Jacobians H already exist on the EKF IR (via the shared Linearization). This module builds the discrete observability matrix at an operating point

O = [H; H·F; H·F²; …; H·F^(n-1)]            (n = tangent dimension)

and reports its rank. A rank deficiency means an unobservable subspace; its null space, projected onto the state slots, tells you which states (e.g. sub.orientation) you can't see — turning a silent drift into a setup-time warning.

Usage::

from manta.estimation import observability
rep = observability(EKF(world))
print(rep.summary())
if not rep.observable:
    ...   # add a sensor, or accept the drift on those states

This is local observability at the supplied operating point (the standard linear test, evaluated along the dynamics for n steps). Check a few representative points if your system is strongly nonlinear.

The rank test is binary and short-horizon (n steps ≈ a fraction of a second), so it cannot grade weak observability — information that arrives through slow dynamics over many seconds. For that, use :func:sigma_horizon: it runs the filter's own covariance recursion (no data needed — F, H, Q, R are already baked) along the nominal trajectory and reports how tight each state can get after horizon seconds. A slot this rank test calls unobservable but whose σ shrinks there is weakly observable, with the convergence time read off directly.

ObservabilityReport dataclass

ObservabilityReport(tangent_dim, rank, sensors, unobservable=list(), singular_values=None, basis=None)

Result of :func:observability.

Attributes: tangent_dim — total tangent (error-state) dimension n. rank — rank of the observability matrix (≤ n). observable — True iff rank == tangent_dim. sensors — sensor output names folded into the analysis. unobservable — list of (slot_name, strength) for slots with a component in the unobservable subspace; strength is the Frobenius norm of the null-space basis restricted to that slot (0 ⇒ fully observable). singular_values — singular values of the observability matrix. basis — orthonormal basis of the observable subspace, shape (tangent_dim, rank). Feed to nees(..., observable_basis=...) to check consistency only where the state is actually observable.

SigmaHorizonReport dataclass

SigmaHorizonReport(horizon, dt, sensors, times, sigmas, P_final)

Result of :func:sigma_horizon.

Attributes: horizon, dt — the analyzed window and step. sensors — sensor output names folded into the recursion. times — recorded sample times, shape (k,). sigmas — {slot_name: (k,) array} of the slot's worst-direction σ (√ of the largest eigenvalue of its tangent covariance block) at each recorded time. P_final — full tangent covariance at horizon.

resolve_sensor_set

resolve_sensor_set(ekf, sensors, *, who)

The chosen sensor full-names. sensors=None keeps every registered sensor; otherwise each entry resolves like everywhere else (full name or unique .<suffix>) — an unknown or ambiguous name raises instead of silently dropping a typo. Shared by observability and nees.

Source code in manta/estimation/observability.py
def resolve_sensor_set(ekf, sensors, *, who: str) -> list[str]:
    """The chosen sensor full-names. `sensors=None` keeps every registered
    sensor; otherwise each entry resolves like everywhere else (full name or
    unique `.<suffix>`) — an unknown or ambiguous name raises instead of
    silently dropping a typo. Shared by observability and `nees`."""
    fulls = list(ekf.sys.sensors)
    if sensors is None:
        return fulls
    chosen = {resolve_suffix(s, fulls, label="sensor", who=who)
              for s in sensors}
    return [f for f in fulls if f in chosen]

observability

observability(ekf, *, state=None, inputs=None, sensors=None, dt=0.02, t=0.0, rtol=1e-06)

Local observability of an EKF at an operating point.

Args: ekf — the EKF transform (EKF(world, ...)). state — operating-point state (nested {owner: {slot: v}} or flat), merged over the world's initial state. Defaults to the world's initial state. inputs — operating-point control inputs {name: value}. sensors — restrict the analysis to these sensor outputs (full names or unambiguous suffixes); None ⇒ all registered. Use this to ask "what would I lose without the compass?" dt, t — the step / clock the Jacobians are evaluated at. rtol — relative singular-value threshold for the rank test.

Returns: :class:ObservabilityReport.

Source code in manta/estimation/observability.py
def observability(ekf, *, state=None, inputs=None, sensors=None,
                  dt: float = 0.02, t: float = 0.0,
                  rtol: float = 1e-6) -> ObservabilityReport:
    """Local observability of an `EKF` at an operating point.

    Args:
        ekf      — the `EKF` transform (`EKF(world, ...)`).
        state    — operating-point state (nested `{owner: {slot: v}}` or
                   flat), merged over the world's initial state. Defaults
                   to the world's initial state.
        inputs   — operating-point control inputs `{name: value}`.
        sensors  — restrict the analysis to these sensor outputs (full
                   names or unambiguous suffixes); `None` ⇒ all registered.
                   Use this to ask "what would I lose without the compass?"
        dt, t    — the step / clock the Jacobians are evaluated at.
        rtol     — relative singular-value threshold for the rank test.

    Returns:
        :class:`ObservabilityReport`.
    """
    ir = _resolve_ir(ekf)
    spec = ir.spec
    n = spec.tangent_dim
    x = _operating_point(ir, state)
    u = ir._build_u(inputs)

    pairs = _select_sensors(ir, sensors, who="observability")
    names = [full for _, full in pairs]
    if not pairs:
        return ObservabilityReport(n, 0, [], [(s.name, 1.0) for s in spec.slots],
                                   np.zeros(1), np.zeros((n, 0)))
    return _report_from_O(_local_O(ir, x, u, dt, t, pairs, n), spec, names, rtol)

observability_trajectory

observability_trajectory(world, *, dt, steps, control=None, sensors=None, samples=30, rtol=1e-06)

Observability accumulated over a trajectory, not at one point.

Local observability() is evaluated at a single operating point, where a state can look unobservable that a maneuver would reveal (absolute heading from GPS+DVL is the classic case: unobservable at rest, observable while turning). This rolls out the deterministic nominal trajectory under control, evaluates the local observability matrix at ~samples points along it, and reports the rank / unobservable slots / observable basis of their union — i.e. a direction counts as observable if it is locally observable at any configuration the trajectory visits. (Union of bounded local matrices, so it stays well conditioned — unlike propagating one matrix through the whole run, where the integrators blow the conditioning up.)

Args mirror nees/observability: control is {name: value} or a t -> {name: value} callable; sensors restricts the suite; samples caps how many trajectory points are linearized.

Source code in manta/estimation/observability.py
def observability_trajectory(world, *, dt: float, steps: int,
                             control: "Callable | dict | None" = None,
                             sensors: list[str] | None = None,
                             samples: int = 30,
                             rtol: float = 1e-6) -> ObservabilityReport:
    """Observability accumulated **over a trajectory**, not at one point.

    Local `observability()` is evaluated at a single operating point, where
    a state can look unobservable that a maneuver would reveal (absolute
    heading from GPS+DVL is the classic case: unobservable at rest,
    observable while turning). This rolls out the *deterministic* nominal
    trajectory under `control`, evaluates the local observability matrix at
    ~`samples` points along it, and reports the rank / unobservable slots /
    observable basis of their **union** — i.e. a direction counts as
    observable if it is locally observable at *any* configuration the
    trajectory visits. (Union of bounded local matrices, so it stays well
    conditioned — unlike propagating one matrix through the whole run,
    where the integrators blow the conditioning up.)

    Args mirror `nees`/`observability`: `control` is `{name: value}` or a
    `t -> {name: value}` callable; `sensors` restricts the suite; `samples`
    caps how many trajectory points are linearized.
    """
    from ..codegen.numpy import TargetNumpy
    from ..sim import Sim
    from .ekf import EKF

    sim_ir, ekf_ir = Sim(world), EKF(world)
    spec = ekf_ir.spec
    n = spec.tangent_dim
    sim = TargetNumpy(sim_ir)

    pairs = _select_sensors(ekf_ir, sensors, who="observability_trajectory")
    names = [full for _, full in pairs]
    if not pairs:
        return ObservabilityReport(n, 0, [], [(s.name, 1.0) for s in spec.slots],
                                   np.zeros(1), np.zeros((n, 0)))

    def truth_vec():
        return spec.pack_any(sim.state)

    every = max(1, steps // max(1, samples))
    blocks = []
    for i in range(steps):
        t = i * dt
        u_dict = control(t) if callable(control) else (control or {})
        if i % every == 0:
            blocks.append(_local_O(ekf_ir, truth_vec(),
                                   ekf_ir._build_u(u_dict or None), dt, t, pairs, n))
        sim.step(dt, u=u_dict)
    return _report_from_O(np.vstack(blocks), spec, names, rtol)

sigma_horizon

sigma_horizon(ekf, *, horizon, dt=0.02, state=None, control=None, sensors=None, P0=None, Q=None, t0=0.0, samples=60, record=200)

Per-slot σ attainable after horizon seconds — the covariance recursion run open-loop (no data), i.e. the linear-Gaussian CRLB along the nominal trajectory.

Where :func:observability asks the binary "is this direction in the observable subspace?" over an n-step window, this asks the graded question the rank test cannot: how tight does each state get, and how fast? It propagates the nominal state with the filter's own predict, evaluates F, Q, H, R along it (all already baked on the EKF), and runs

P ← F P Fᵀ + Q;   per due sensor: P ← Joseph(P, H, R)

recording each slot's worst-direction σ. Slow channels the rank test misses — heading from the Earth rate (gyrocompassing), drag-coupled biases — show up as σ trajectories with their convergence time readable directly.

Args: ekf — the EKF transform (EKF(world, ...)). horizon — analysis window (s). dt — filter step (s). state — starting operating point (nested or flat), merged over the world's initial state. control — {name: value} or t -> {name: value} nominal inputs. sensors — restrict to these outputs (full names / suffixes); None ⇒ all registered on the EKF. P0 — initial tangent covariance: full matrix, diagonal vector, or scalar·I. Default 0.1·I (as nees). Use a generous prior on the states in question — σ can only show convergence the prior leaves room for. Q — process-noise override (else the model's auto L Σ Lᵀ). t0 — start time (matters on a time-dependent world, e.g. a rotating planet). samples — how many points along the trajectory F/Q/H/R are re-evaluated at (held constant in between). record — max number of recorded σ samples.

Returns: :class:SigmaHorizonReport.

Source code in manta/estimation/observability.py
def sigma_horizon(ekf, *, horizon: float, dt: float = 0.02,
                  state=None, control: "Callable | dict | None" = None,
                  sensors: list[str] | None = None,
                  P0: "np.ndarray | float | None" = None,
                  Q: np.ndarray | None = None,
                  t0: float = 0.0, samples: int = 60,
                  record: int = 200) -> SigmaHorizonReport:
    """Per-slot σ attainable after `horizon` seconds — the covariance
    recursion run open-loop (no data), i.e. the linear-Gaussian CRLB along
    the nominal trajectory.

    Where :func:`observability` asks the binary "is this direction in the
    observable subspace?" over an `n`-step window, this asks the graded
    question the rank test cannot: *how tight does each state get, and how
    fast?* It propagates the nominal state with the filter's own predict,
    evaluates F, Q, H, R along it (all already baked on the EKF), and runs

        P ← F P Fᵀ + Q;   per due sensor: P ← Joseph(P, H, R)

    recording each slot's worst-direction σ. Slow channels the rank test
    misses — heading from the Earth rate (gyrocompassing), drag-coupled
    biases — show up as σ trajectories with their convergence time
    readable directly.

    Args:
        ekf      — the `EKF` transform (`EKF(world, ...)`).
        horizon  — analysis window (s).
        dt       — filter step (s).
        state    — starting operating point (nested or flat), merged over
                   the world's initial state.
        control  — `{name: value}` or `t -> {name: value}` nominal inputs.
        sensors  — restrict to these outputs (full names / suffixes);
                   `None` ⇒ all registered on the EKF.
        P0       — initial tangent covariance: full matrix, diagonal
                   vector, or scalar·I. Default `0.1·I` (as `nees`). Use a
                   generous prior on the states in question — σ can only
                   show convergence the prior leaves room for.
        Q        — process-noise override (else the model's auto `L Σ Lᵀ`).
        t0       — start time (matters on a time-dependent world, e.g. a
                   rotating planet).
        samples  — how many points along the trajectory F/Q/H/R are
                   re-evaluated at (held constant in between).
        record   — max number of recorded σ samples.

    Returns:
        :class:`SigmaHorizonReport`.
    """
    import casadi as ca

    ir = _resolve_ir(ekf)
    sys = ir.sys
    spec = ir.spec
    n = spec.tangent_dim
    steps = max(1, int(round(horizon / dt)))

    # --- P0: scalar | diag vector | full matrix --------------------------
    if P0 is None:
        P = np.eye(n) * 0.1
    else:
        P0 = np.asarray(P0, dtype=float)
        if P0.ndim == 0:
            P = np.eye(n) * float(P0)
        elif P0.ndim == 1:
            P = np.diag(P0)
        else:
            P = P0.copy()
    if P.shape != (n, n):
        raise ValueError(f"sigma_horizon: P0 must be scalar, ({n},) or "
                         f"({n},{n}); got shape {np.shape(P0)}")

    # --- per-sensor H/R/rate ---------------------------------------------
    x_s, u_s, dt_s, t_s = sys.x_sym, sys.u_sym, sys.dt_sym, sys.t_sym
    zero_dt = ca.MX.zeros(1, 1)
    chosen = []                                  # (full, dim, H_fn, R_fn, period)
    for H_fn, full in _select_sensors(ir, sensors, who="sigma_horizon"):
        s = sys.sensors[full]
        L_h = (ca.substitute(s.L_h_sym, dt_s, zero_dt)
               if s.L_h_sym is not None and sys.Sigma is not None else None)
        R_expr = lin_cov(L_h, ca.DM(sys.Sigma) if L_h is not None else None,
                         s.dim)
        R_fn = ca.Function(f"R_{entry_ident(full)}",
                           [x_s, u_s, t_s], [R_expr])
        rate = sys.sample_rates.get(full)
        period = max(1, int(round(1.0 / (rate * dt)))) if rate else 1
        chosen.append((full, s.dim, H_fn, R_fn, period))
    names = [full for full, *_ in chosen]

    # --- Q: model auto L Σ Lᵀ unless overridden ---------------------------
    Q_fn = None
    if Q is not None:
        Q_const = np.asarray(Q, dtype=float)
    elif sys.L_sym is not None:
        Q_fn = ca.Function("Q_auto", [x_s, u_s, dt_s, t_s],
                           [lin_cov(sys.L_sym, ca.DM(sys.Sigma), n)])
        Q_const = None
    else:
        Q_const = np.zeros((n, n))

    # --- the recursion -----------------------------------------------------
    x = _operating_point(ir, state)
    refresh = max(1, steps // max(1, samples))
    rec_every = max(1, steps // max(1, record))
    slots = [(s.name, s.tangent_offset, s.tangent_offset + s.tangent_dim)
             for s in spec.slots]

    times: list[float] = []
    sigmas: dict[str, list[float]] = {name: [] for name, _, _ in slots}

    def record_point(t: float) -> None:
        times.append(t)
        for name, lo, hi in slots:
            block = P[lo:hi, lo:hi]
            sigmas[name].append(float(np.sqrt(max(
                np.max(np.linalg.eigvalsh(0.5 * (block + block.T))), 0.0))))

    record_point(t0)
    F = Qk = None
    HRs: list = []
    for i in range(steps):
        t = t0 + i * dt
        u_dict = control(t) if callable(control) else (control or None)
        u_vec = ir._build_u(u_dict)
        if i % refresh == 0:                     # re-linearize along the way
            F = np.asarray(sys.F_fn(x, u_vec, dt, t), float).reshape(n, n)
            Qk = (Q_const if Q_fn is None else
                  np.asarray(Q_fn(x, u_vec, dt, t), float).reshape(n, n))
            HRs = []
            for full, dim, H_fn, R_fn, period in chosen:
                H = np.asarray(H_fn(x, u_vec, 0.0, t), float).reshape(dim, n)
                R = np.asarray(R_fn(x, u_vec, t), float).reshape(dim, dim)
                if not np.any(np.abs(R) > 0):
                    raise ValueError(
                        f"sigma_horizon: sensor {full!r} has zero R — the "
                        f"update is singular. Declare a noise σ on it or "
                        f"exclude it via sensors=[...].")
                HRs.append((H, R, period))
        x = np.asarray(sys.predict_fn(x, u_vec, dt, t), float).reshape(-1)
        P = F @ P @ F.T + Qk
        for H, R, period in HRs:
            if i % period:
                continue
            _, P, _, _ = joseph_update_np(P, H, R)   # covariance-only fold
        P = symmetrize(P)
        if (i + 1) % rec_every == 0 or i == steps - 1:
            record_point(t0 + (i + 1) * dt)

    return SigmaHorizonReport(
        horizon=horizon, dt=dt, sensors=names, times=np.asarray(times),
        sigmas={k: np.asarray(v) for k, v in sigmas.items()}, P_final=P)

manta.estimation.observability_trajectory

observability_trajectory(world, *, dt, steps, control=None, sensors=None, samples=30, rtol=1e-06)

Observability accumulated over a trajectory, not at one point.

Local observability() is evaluated at a single operating point, where a state can look unobservable that a maneuver would reveal (absolute heading from GPS+DVL is the classic case: unobservable at rest, observable while turning). This rolls out the deterministic nominal trajectory under control, evaluates the local observability matrix at ~samples points along it, and reports the rank / unobservable slots / observable basis of their union — i.e. a direction counts as observable if it is locally observable at any configuration the trajectory visits. (Union of bounded local matrices, so it stays well conditioned — unlike propagating one matrix through the whole run, where the integrators blow the conditioning up.)

Args mirror nees/observability: control is {name: value} or a t -> {name: value} callable; sensors restricts the suite; samples caps how many trajectory points are linearized.

Source code in manta/estimation/observability.py
def observability_trajectory(world, *, dt: float, steps: int,
                             control: "Callable | dict | None" = None,
                             sensors: list[str] | None = None,
                             samples: int = 30,
                             rtol: float = 1e-6) -> ObservabilityReport:
    """Observability accumulated **over a trajectory**, not at one point.

    Local `observability()` is evaluated at a single operating point, where
    a state can look unobservable that a maneuver would reveal (absolute
    heading from GPS+DVL is the classic case: unobservable at rest,
    observable while turning). This rolls out the *deterministic* nominal
    trajectory under `control`, evaluates the local observability matrix at
    ~`samples` points along it, and reports the rank / unobservable slots /
    observable basis of their **union** — i.e. a direction counts as
    observable if it is locally observable at *any* configuration the
    trajectory visits. (Union of bounded local matrices, so it stays well
    conditioned — unlike propagating one matrix through the whole run,
    where the integrators blow the conditioning up.)

    Args mirror `nees`/`observability`: `control` is `{name: value}` or a
    `t -> {name: value}` callable; `sensors` restricts the suite; `samples`
    caps how many trajectory points are linearized.
    """
    from ..codegen.numpy import TargetNumpy
    from ..sim import Sim
    from .ekf import EKF

    sim_ir, ekf_ir = Sim(world), EKF(world)
    spec = ekf_ir.spec
    n = spec.tangent_dim
    sim = TargetNumpy(sim_ir)

    pairs = _select_sensors(ekf_ir, sensors, who="observability_trajectory")
    names = [full for _, full in pairs]
    if not pairs:
        return ObservabilityReport(n, 0, [], [(s.name, 1.0) for s in spec.slots],
                                   np.zeros(1), np.zeros((n, 0)))

    def truth_vec():
        return spec.pack_any(sim.state)

    every = max(1, steps // max(1, samples))
    blocks = []
    for i in range(steps):
        t = i * dt
        u_dict = control(t) if callable(control) else (control or {})
        if i % every == 0:
            blocks.append(_local_O(ekf_ir, truth_vec(),
                                   ekf_ir._build_u(u_dict or None), dt, t, pairs, n))
        sim.step(dt, u=u_dict)
    return _report_from_O(np.vstack(blocks), spec, names, rtol)

manta.estimation.sigma_horizon

sigma_horizon(ekf, *, horizon, dt=0.02, state=None, control=None, sensors=None, P0=None, Q=None, t0=0.0, samples=60, record=200)

Per-slot σ attainable after horizon seconds — the covariance recursion run open-loop (no data), i.e. the linear-Gaussian CRLB along the nominal trajectory.

Where :func:observability asks the binary "is this direction in the observable subspace?" over an n-step window, this asks the graded question the rank test cannot: how tight does each state get, and how fast? It propagates the nominal state with the filter's own predict, evaluates F, Q, H, R along it (all already baked on the EKF), and runs

P ← F P Fᵀ + Q;   per due sensor: P ← Joseph(P, H, R)

recording each slot's worst-direction σ. Slow channels the rank test misses — heading from the Earth rate (gyrocompassing), drag-coupled biases — show up as σ trajectories with their convergence time readable directly.

Args: ekf — the EKF transform (EKF(world, ...)). horizon — analysis window (s). dt — filter step (s). state — starting operating point (nested or flat), merged over the world's initial state. control — {name: value} or t -> {name: value} nominal inputs. sensors — restrict to these outputs (full names / suffixes); None ⇒ all registered on the EKF. P0 — initial tangent covariance: full matrix, diagonal vector, or scalar·I. Default 0.1·I (as nees). Use a generous prior on the states in question — σ can only show convergence the prior leaves room for. Q — process-noise override (else the model's auto L Σ Lᵀ). t0 — start time (matters on a time-dependent world, e.g. a rotating planet). samples — how many points along the trajectory F/Q/H/R are re-evaluated at (held constant in between). record — max number of recorded σ samples.

Returns: :class:SigmaHorizonReport.

Source code in manta/estimation/observability.py
def sigma_horizon(ekf, *, horizon: float, dt: float = 0.02,
                  state=None, control: "Callable | dict | None" = None,
                  sensors: list[str] | None = None,
                  P0: "np.ndarray | float | None" = None,
                  Q: np.ndarray | None = None,
                  t0: float = 0.0, samples: int = 60,
                  record: int = 200) -> SigmaHorizonReport:
    """Per-slot σ attainable after `horizon` seconds — the covariance
    recursion run open-loop (no data), i.e. the linear-Gaussian CRLB along
    the nominal trajectory.

    Where :func:`observability` asks the binary "is this direction in the
    observable subspace?" over an `n`-step window, this asks the graded
    question the rank test cannot: *how tight does each state get, and how
    fast?* It propagates the nominal state with the filter's own predict,
    evaluates F, Q, H, R along it (all already baked on the EKF), and runs

        P ← F P Fᵀ + Q;   per due sensor: P ← Joseph(P, H, R)

    recording each slot's worst-direction σ. Slow channels the rank test
    misses — heading from the Earth rate (gyrocompassing), drag-coupled
    biases — show up as σ trajectories with their convergence time
    readable directly.

    Args:
        ekf      — the `EKF` transform (`EKF(world, ...)`).
        horizon  — analysis window (s).
        dt       — filter step (s).
        state    — starting operating point (nested or flat), merged over
                   the world's initial state.
        control  — `{name: value}` or `t -> {name: value}` nominal inputs.
        sensors  — restrict to these outputs (full names / suffixes);
                   `None` ⇒ all registered on the EKF.
        P0       — initial tangent covariance: full matrix, diagonal
                   vector, or scalar·I. Default `0.1·I` (as `nees`). Use a
                   generous prior on the states in question — σ can only
                   show convergence the prior leaves room for.
        Q        — process-noise override (else the model's auto `L Σ Lᵀ`).
        t0       — start time (matters on a time-dependent world, e.g. a
                   rotating planet).
        samples  — how many points along the trajectory F/Q/H/R are
                   re-evaluated at (held constant in between).
        record   — max number of recorded σ samples.

    Returns:
        :class:`SigmaHorizonReport`.
    """
    import casadi as ca

    ir = _resolve_ir(ekf)
    sys = ir.sys
    spec = ir.spec
    n = spec.tangent_dim
    steps = max(1, int(round(horizon / dt)))

    # --- P0: scalar | diag vector | full matrix --------------------------
    if P0 is None:
        P = np.eye(n) * 0.1
    else:
        P0 = np.asarray(P0, dtype=float)
        if P0.ndim == 0:
            P = np.eye(n) * float(P0)
        elif P0.ndim == 1:
            P = np.diag(P0)
        else:
            P = P0.copy()
    if P.shape != (n, n):
        raise ValueError(f"sigma_horizon: P0 must be scalar, ({n},) or "
                         f"({n},{n}); got shape {np.shape(P0)}")

    # --- per-sensor H/R/rate ---------------------------------------------
    x_s, u_s, dt_s, t_s = sys.x_sym, sys.u_sym, sys.dt_sym, sys.t_sym
    zero_dt = ca.MX.zeros(1, 1)
    chosen = []                                  # (full, dim, H_fn, R_fn, period)
    for H_fn, full in _select_sensors(ir, sensors, who="sigma_horizon"):
        s = sys.sensors[full]
        L_h = (ca.substitute(s.L_h_sym, dt_s, zero_dt)
               if s.L_h_sym is not None and sys.Sigma is not None else None)
        R_expr = lin_cov(L_h, ca.DM(sys.Sigma) if L_h is not None else None,
                         s.dim)
        R_fn = ca.Function(f"R_{entry_ident(full)}",
                           [x_s, u_s, t_s], [R_expr])
        rate = sys.sample_rates.get(full)
        period = max(1, int(round(1.0 / (rate * dt)))) if rate else 1
        chosen.append((full, s.dim, H_fn, R_fn, period))
    names = [full for full, *_ in chosen]

    # --- Q: model auto L Σ Lᵀ unless overridden ---------------------------
    Q_fn = None
    if Q is not None:
        Q_const = np.asarray(Q, dtype=float)
    elif sys.L_sym is not None:
        Q_fn = ca.Function("Q_auto", [x_s, u_s, dt_s, t_s],
                           [lin_cov(sys.L_sym, ca.DM(sys.Sigma), n)])
        Q_const = None
    else:
        Q_const = np.zeros((n, n))

    # --- the recursion -----------------------------------------------------
    x = _operating_point(ir, state)
    refresh = max(1, steps // max(1, samples))
    rec_every = max(1, steps // max(1, record))
    slots = [(s.name, s.tangent_offset, s.tangent_offset + s.tangent_dim)
             for s in spec.slots]

    times: list[float] = []
    sigmas: dict[str, list[float]] = {name: [] for name, _, _ in slots}

    def record_point(t: float) -> None:
        times.append(t)
        for name, lo, hi in slots:
            block = P[lo:hi, lo:hi]
            sigmas[name].append(float(np.sqrt(max(
                np.max(np.linalg.eigvalsh(0.5 * (block + block.T))), 0.0))))

    record_point(t0)
    F = Qk = None
    HRs: list = []
    for i in range(steps):
        t = t0 + i * dt
        u_dict = control(t) if callable(control) else (control or None)
        u_vec = ir._build_u(u_dict)
        if i % refresh == 0:                     # re-linearize along the way
            F = np.asarray(sys.F_fn(x, u_vec, dt, t), float).reshape(n, n)
            Qk = (Q_const if Q_fn is None else
                  np.asarray(Q_fn(x, u_vec, dt, t), float).reshape(n, n))
            HRs = []
            for full, dim, H_fn, R_fn, period in chosen:
                H = np.asarray(H_fn(x, u_vec, 0.0, t), float).reshape(dim, n)
                R = np.asarray(R_fn(x, u_vec, t), float).reshape(dim, dim)
                if not np.any(np.abs(R) > 0):
                    raise ValueError(
                        f"sigma_horizon: sensor {full!r} has zero R — the "
                        f"update is singular. Declare a noise σ on it or "
                        f"exclude it via sensors=[...].")
                HRs.append((H, R, period))
        x = np.asarray(sys.predict_fn(x, u_vec, dt, t), float).reshape(-1)
        P = F @ P @ F.T + Qk
        for H, R, period in HRs:
            if i % period:
                continue
            _, P, _, _ = joseph_update_np(P, H, R)   # covariance-only fold
        P = symmetrize(P)
        if (i + 1) % rec_every == 0 or i == steps - 1:
            record_point(t0 + (i + 1) * dt)

    return SigmaHorizonReport(
        horizon=horizon, dt=dt, sensors=names, times=np.asarray(times),
        sigmas={k: np.asarray(v) for k, v in sigmas.items()}, P_final=P)

manta.estimation.nees

nees(world, *, dt, steps, control=None, sensors=None, P0=None, Q=None, observable_basis=None, runs=20, seed=0, warmup=None, alpha=0.05)

Monte-Carlo NEES consistency check for EKF(world).

Each run jitters the truth with the model's process noise (a NoiseDriver) and the measurements with their R, draws the initial estimate from P0, runs simekf over steps, and records NEES at each post-warmup step. Returns an :class:NEESReport.

Args: world — the model. dt, steps — filter step and run length. control — per-tick inputs: {name: value} (constant) or a t -> {name: value} callable. Excite the trajectory so the observable states are actually exercised. sensors — restrict to these sensor outputs (full names / suffixes); None ⇒ all registered. They must declare noise (nonzero R), else the update is singular. P0 — initial estimate covariance (tangent). Default 0.1·I. Q — process-noise override for the predict (else the model's auto-assembled Q). Useful to probe consistency vs. an assumed Q, or to validate the check responds to scaling. observable_basis — (n, r) orthonormal basis of the observable subspace (from observability(...).basis or observability_trajectory). When given, NEES is measured only in that subspace (dof = r) — isolating "is my noise modeling right where I can estimate?" from overconfidence on unobservable directions. runs, seed — ensemble size and base RNG seed. warmup — steps to skip before recording (default steps // 5). alpha — significance for the band (default 0.05 ⇒ 95%).

Source code in manta/estimation/consistency.py
def nees(world, *, dt: float, steps: int,
         control: Callable[[float], dict] | dict | None = None,
         sensors: list[str] | None = None,
         P0: np.ndarray | None = None, Q: np.ndarray | None = None,
         observable_basis: np.ndarray | None = None,
         runs: int = 20, seed: int = 0, warmup: int | None = None,
         alpha: float = 0.05) -> NEESReport:
    """Monte-Carlo NEES consistency check for `EKF(world)`.

    Each run jitters the truth with the model's process noise (a
    `NoiseDriver`) and the measurements with their R, draws the initial
    estimate from `P0`, runs `sim`↔`ekf` over `steps`, and records NEES at
    each post-`warmup` step. Returns an :class:`NEESReport`.

    Args:
        world    — the model.
        dt, steps — filter step and run length.
        control  — per-tick inputs: `{name: value}` (constant) or a
                   `t -> {name: value}` callable. Excite the trajectory so
                   the observable states are actually exercised.
        sensors  — restrict to these sensor outputs (full names / suffixes);
                   `None` ⇒ all registered. They must declare noise (nonzero
                   R), else the update is singular.
        P0       — initial estimate covariance (tangent). Default `0.1·I`.
        Q        — process-noise override for the predict (else the model's
                   auto-assembled Q). Useful to probe consistency vs. an
                   assumed Q, or to validate the check responds to scaling.
        observable_basis — `(n, r)` orthonormal basis of the observable
                   subspace (from `observability(...).basis` or
                   `observability_trajectory`). When given, NEES is measured
                   only in that subspace (dof = r) — isolating "is my noise
                   modeling right where I *can* estimate?" from overconfidence
                   on unobservable directions.
        runs, seed — ensemble size and base RNG seed.
        warmup   — steps to skip before recording (default `steps // 5`).
        alpha    — significance for the band (default 0.05 ⇒ 95%).
    """
    import casadi as ca
    from ..codegen.numpy import NoiseDriver, TargetNumpy
    from ..sim import Sim
    from .ekf import EKF
    from .observability import resolve_sensor_set

    sim_ir, ekf_ir = Sim(world), EKF(world)
    spec = ekf_ir.spec
    n = spec.tangent_dim
    if warmup is None:
        warmup = steps // 5
    if P0 is None:
        P0 = np.eye(n) * 0.1
    L0 = np.linalg.cholesky(P0)

    xa, xb = ca.MX.sym("xa", spec.ambient_dim), ca.MX.sym("xb", spec.ambient_dim)
    boxminus = ca.Function("bm", [xa, xb], [spec.boxminus_sym(xa, xb)])

    # Sensor selection resolves like everywhere else — unknown/ambiguous
    # names raise instead of silently dropping a typo.
    names = resolve_sensor_set(ekf_ir, sensors, who="nees")

    def truth_vec(world_rt) -> np.ndarray:
        return spec.pack_any(world_rt.state)

    nees_samples: list[float] = []
    for r in range(runs):
        rng = np.random.default_rng(seed + r)
        sim = TargetNumpy(sim_ir)
        sim.attach_driver(NoiseDriver(seed=seed + 1000 + r))
        ekf = TargetNumpy(ekf_ir)
        # Truth starts at the world's initial state; the estimate is drawn
        # from N(truth, P0) so the initial NEES is itself χ²-distributed.
        x_truth0 = truth_vec(sim)
        x_est0 = spec.boxplus_num(x_truth0, L0 @ rng.standard_normal(n))
        ekf.reset(state=x_est0, P=P0)
        ekf.Q = Q
        gates = {full: sim.rate_gate(full) for full in names}

        for i in range(steps):
            t = i * dt
            u = _controls_at(control, t)
            sim.step(dt, u=u)
            for full in names:
                if gates[full].due(t):
                    ekf.update(full, sim.reading(full), u=u, t=t)
            ekf.predict(dt, u=u, t=t)
            if i >= warmup:
                e = np.asarray(boxminus(truth_vec(sim), ekf.x)).reshape(-1)
                P = ekf.P
                if observable_basis is not None:
                    e = observable_basis.T @ e
                    P = observable_basis.T @ P @ observable_basis
                try:
                    nees_samples.append(float(e @ np.linalg.solve(P, e)))
                except np.linalg.LinAlgError:
                    nees_samples.append(float(e @ np.linalg.pinv(P) @ e))

    dof = n if observable_basis is None else observable_basis.shape[1]
    anees = float(np.mean(nees_samples))
    # Band sized by the number of independent trajectories (runs), which
    # accounts for within-run time correlation: runs·ANEES ~ χ²_{runs·dof}.
    k = runs * dof
    lower = _chi2_quantile(k, alpha / 2) / runs
    upper = _chi2_quantile(k, 1 - alpha / 2) / runs
    return NEESReport(dof=dof, anees=anees, lower=lower, upper=upper,
                      runs=runs, samples=len(nees_samples))