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 = require_positive(beta, name="Madgwick.beta", allow_zero=True)
    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 = require_positive(kp, name="Mahony.kp", allow_zero=True)
    self.ki = require_positive(ki, name="Mahony.ki", allow_zero=True)
    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)

manta.IMUPreintegrator

IMUPreintegrator(*, accel_noise_density=0.0, gyro_noise_density=0.0, name='imu_preintegrator')

Bases: RecurrenceBlock

Accumulate high-rate IMU samples into an INS prediction packet.

Args: accel_noise_density: accelerometer white-noise density in m/s^2/sqrt(Hz). gyro_noise_density: gyro white-noise density in rad/s/sqrt(Hz). name: codegen basename / default C++ class stem.

accel_bias and gyro_bias are latched from the first sample after reset and become the packet's bias reference. Later values supplied before the next reset are intentionally ignored; one packet must have one linearization point.

Source code in manta/estimation/imu_preintegrator.py
def __init__(self, *, accel_noise_density: float = 0.0,
             gyro_noise_density: float = 0.0,
             name: str = "imu_preintegrator") -> None:
    self.accel_noise_density = _finite_nonnegative(
        accel_noise_density, name="accel_noise_density")
    self.gyro_noise_density = _finite_nonnegative(
        gyro_noise_density, name="gyro_noise_density")
    sigma_a = self.accel_noise_density
    sigma_g = self.gyro_noise_density

    def rec(x, u, dt, t):
        del t
        q = x["delta_orientation"]
        dv = x["delta_velocity"]
        dp = x["delta_position"]
        covariance = ca.reshape(x["covariance"], 9, 9)
        delta_start_cross = ca.reshape(
            x["delta_start_gyro_cross_covariance"], 9, 3)
        bias_jacobian = ca.reshape(x["bias_jacobian"], 9, 6)
        first = x["sample_count"] < 0.5

        gyro_bias_ref = ca.if_else(
            first, u["gyro_bias"], x["gyro_bias_reference"])
        accel_bias_ref = ca.if_else(
            first, u["accel_bias"], x["accel_bias_reference"])
        accel = u["accel"] - accel_bias_ref
        gyro = u["gyro"] - gyro_bias_ref

        def compose(q0, dv0, dp0, a, w):
            # Left-endpoint specific-force integration, matching the raw
            # INS recurrence. Ordered quaternion products preserve coning.
            from ..ir._rotation import quat_to_rotmat
            a0 = quat_to_rotmat(q0) @ a
            return (
                _normalise(quat_mul(q0, so3_exp(w * dt))),
                dv0 + a0 * dt,
                dp0 + dv0 * dt + 0.5 * a0 * dt * dt,
            )

        q_next, dv_next, dp_next = compose(q, dv, dp, accel, gyro)

        # Error transition A over [dtheta, dv, dp], obtained from the
        # recurrence itself rather than maintained as hand-coded algebra.
        error = ca.MX.sym("preint_error", 9, 1)
        q_pert = quat_mul(q, so3_exp(error[0:3]))
        qp, dvp, dpp = compose(
            q_pert, dv + error[3:6], dp + error[6:9], accel, gyro)
        propagated_error = _local_error(
            qp, dvp, dpp, q_next, dv_next, dp_next)
        A = ca.substitute(ca.jacobian(propagated_error, error), error,
                          ca.MX.zeros(9, 1))

        # Bias sensitivities use [gyro bias, accel bias]. A packet can be
        # corrected at the main filter's current bias without replaying
        # the high-rate samples while the first-order approximation holds.
        db = ca.MX.sym("preint_db", 6, 1)
        qb, dvb, dpb = compose(
            q, dv, dp, accel - db[3:6], gyro - db[0:3])
        bias_error = _local_error(
            qb, dvb, dpb, q_next, dv_next, dp_next)
        B = ca.substitute(ca.jacobian(bias_error, db), db,
                          ca.MX.zeros(6, 1))
        J_next = A @ bias_jacobian + B

        # The constructor takes continuous white-noise densities. A held
        # rate sample has sigma_density/sqrt(dt); autodiff maps that sample
        # uncertainty through the same nonlinear composition.
        white = ca.MX.sym("preint_white", 6, 1)
        sqrt_dt = ca.sqrt(dt)
        qn, dvn, dpn = compose(
            q, dv, dp,
            accel + (sigma_a / sqrt_dt) * white[3:6],
            gyro + (sigma_g / sqrt_dt) * white[0:3])
        noise_error = _local_error(
            qn, dvn, dpn, q_next, dv_next, dp_next)
        G = ca.substitute(ca.jacobian(noise_error, white), white,
                          ca.MX.zeros(6, 1))
        C_next = A @ covariance @ A.T + G @ G.T
        C_next = 0.5 * (C_next + C_next.T)

        # Retain the correlations which a lower-rate filter cannot
        # reconstruct from C_next.  The boundary coordinates are unit
        # normal variables; the matching physical rate sigmas travel in
        # the packet.  On the first step the start and recurrence-end
        # gyro are the same sample.  On later steps the recurrence-end
        # is the current, independent sample.
        G_gyro = G[:, 0:3]
        delta_start_cross_next = (
            A @ delta_start_cross
            + ca.if_else(first, G_gyro, ca.MX.zeros(9, 3))
        )
        delta_end_cross_next = G_gyro
        start_end_correlation_next = ca.if_else(
            first, ca.MX.eye(3), ca.MX.zeros(3, 3))
        gyro_sample_sigma = ca.repmat(sigma_g / sqrt_dt, 3, 1)
        start_gyro_sigma_next = ca.if_else(
            first, gyro_sample_sigma, x["start_gyro_noise_sigma"])

        start_gyro = ca.if_else(first, u["gyro"], x["start_gyro"])
        # Deterministic left-hold quadrature, independent of the planet.
        # V[j] = sum h*t_left**j;
        # P[j] = sum h*(T-t_left-h/2)*t_left**j.
        # The companion uses these to rotate inertial force integrals.
        elapsed = x["duration"]
        powers = ca.vertcat(1, elapsed, elapsed**2, elapsed**3)
        velocity_moments = x["velocity_time_moments"] + dt * powers
        position_moments = (x["position_time_moments"]
                            + dt * x["velocity_time_moments"]
                            + 0.5 * dt * dt * powers)
        nxt = {
            "delta_orientation": q_next,
            "delta_velocity": dv_next,
            "delta_position": dp_next,
            "covariance": ca.reshape(C_next, 81, 1),
            "delta_start_gyro_cross_covariance": ca.reshape(
                delta_start_cross_next, 27, 1),
            "delta_end_gyro_cross_covariance": ca.reshape(
                delta_end_cross_next, 27, 1),
            "start_end_gyro_correlation": ca.reshape(
                start_end_correlation_next, 9, 1),
            "start_gyro_noise_sigma": start_gyro_sigma_next,
            "end_gyro_noise_sigma": gyro_sample_sigma,
            "bias_jacobian": ca.reshape(J_next, 54, 1),
            "gyro_bias_reference": gyro_bias_ref,
            "accel_bias_reference": accel_bias_ref,
            "start_gyro": start_gyro,
            "end_accel": u["accel"],
            "end_gyro": u["gyro"],
            "duration": x["duration"] + dt,
            "sample_count": x["sample_count"] + 1.0,
            "velocity_time_moments": velocity_moments,
            "position_time_moments": position_moments,
        }
        return nxt, dict(nxt)

    zero3 = np.zeros(3)
    self._build_recurrence(
        name=name,
        state=[
            ("delta_orientation", SO3Manifold()),
            ("delta_velocity", R3Manifold()),
            ("delta_position", R3Manifold()),
            ("covariance", RnManifold(81)),
            ("delta_start_gyro_cross_covariance", RnManifold(27)),
            ("delta_end_gyro_cross_covariance", RnManifold(27)),
            ("start_end_gyro_correlation", RnManifold(9)),
            ("start_gyro_noise_sigma", R3Manifold()),
            ("end_gyro_noise_sigma", R3Manifold()),
            ("bias_jacobian", RnManifold(54)),
            ("gyro_bias_reference", R3Manifold()),
            ("accel_bias_reference", R3Manifold()),
            ("start_gyro", R3Manifold()),
            ("end_accel", R3Manifold()),
            ("end_gyro", R3Manifold()),
            ("duration", ScalarManifold()),
            ("sample_count", ScalarManifold()),
            ("velocity_time_moments", RnManifold(4)),
            ("position_time_moments", RnManifold(4)),
        ],
        inputs=[("accel", 3), ("gyro", 3),
                ("accel_bias", 3), ("gyro_bias", 3)],
        outputs=[
            ("delta_orientation", 4),
            ("delta_velocity", 3),
            ("delta_position", 3),
            ("covariance", 81),
            ("delta_start_gyro_cross_covariance", 27),
            ("delta_end_gyro_cross_covariance", 27),
            ("start_end_gyro_correlation", 9),
            ("start_gyro_noise_sigma", 3),
            ("end_gyro_noise_sigma", 3),
            ("bias_jacobian", 54),
            ("gyro_bias_reference", 3),
            ("accel_bias_reference", 3),
            ("start_gyro", 3),
            ("end_accel", 3),
            ("end_gyro", 3),
            ("duration", 1),
            ("sample_count", 1),
            ("velocity_time_moments", 4),
            ("position_time_moments", 4),
        ],
        x0={
            "delta_orientation": (1.0, 0.0, 0.0, 0.0),
            "delta_velocity": zero3,
            "delta_position": zero3,
            "covariance": np.zeros(81),
            "delta_start_gyro_cross_covariance": np.zeros(27),
            "delta_end_gyro_cross_covariance": np.zeros(27),
            "start_end_gyro_correlation": np.zeros(9),
            "start_gyro_noise_sigma": zero3,
            "end_gyro_noise_sigma": zero3,
            "bias_jacobian": np.zeros(54),
            "gyro_bias_reference": zero3,
            "accel_bias_reference": zero3,
            "start_gyro": zero3,
            "end_accel": zero3,
            "end_gyro": zero3,
            "duration": 0.0,
            "sample_count": 0.0,
            "velocity_time_moments": np.zeros(4),
            "position_time_moments": np.zeros(4),
        },
        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 each model-derived estimator IR. 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.

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 — an EKF, UKF, or INS transform. 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      — an `EKF`, `UKF`, or `INS` transform.
        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.sys.resolve_u(inputs, who="observability")

    pairs = _select_sensors(ir, sensors, who="observability")
    names = [full for _, full in pairs]
    if not pairs:
        return _empty_report(spec, n)
    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, estimator=None)

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. estimator picks the filter transform carrying the linearized IR — an EKF/UKF/INS instance over this world, or a class/callable applied to it (default EKF); the analysis itself is linearized either way.

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,
                             estimator=None) -> 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. `estimator` picks the
    filter transform carrying the linearized IR — an `EKF`/`UKF`/`INS` instance
    over this world, or a class/callable applied to it (default `EKF`);
    the analysis itself is linearized either way.
    """
    from ..codegen.numpy import TargetNumpy
    from ..sim import Sim

    ekf_ir = _resolve_estimator(world, estimator)
    sim_ir = Sim(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 _empty_report(spec, n)

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

    every = max(1, steps // max(1, samples))
    blocks = []
    metadata = ekf_ir.module().metadata
    packet_map = dict(metadata.get("preintegration_input_map", {}))
    prediction_names = {
        packet_map[name] for name in ("end_accel", "end_gyro")
    } if packet_map else set(metadata.get("prediction_inputs", ()))
    previous_x = None
    previous_control = None
    previous_prediction_readings = None
    previous_measurement_u = None
    for i in range(steps + 1 if packet_map else steps):
        t = i * dt
        u_dict = _controls_at(control, t)
        x_before = truth_vec()
        sim.step(dt, u=u_dict)
        measurement_u = estimator_observation_inputs(
            ekf_ir, u_dict, reading=sim.reading)
        current_prediction_readings = {
            name: np.asarray(sim.reading(name), dtype=float).copy()
            for name in prediction_names
        }
        if packet_map and previous_prediction_readings is not None:
            interval = i - 1
            estimator_u = estimator_interval_inputs(
                ekf_ir,
                previous_control,
                start_reading=previous_prediction_readings,
                end_reading=current_prediction_readings,
                dt=dt,
            )
            if interval % every == 0:
                blocks.append(_local_O(
                    ekf_ir,
                    previous_x,
                    ekf_ir.sys.resolve_u(
                        estimator_u, who="observability_trajectory"
                    ),
                    dt,
                    t - dt,
                    pairs,
                    n,
                    measurement_u=ekf_ir.sys.resolve_u(
                        previous_measurement_u,
                        who="observability_trajectory measurement",
                    ),
                ))
        elif not packet_map and i % every == 0:
            blocks.append(_local_O(
                ekf_ir, x_before,
                ekf_ir.sys.resolve_u(measurement_u,
                                     who="observability_trajectory"),
                dt, t, pairs, n))
        previous_x = x_before
        previous_control = u_dict
        previous_prediction_readings = current_prediction_readings
        previous_measurement_u = measurement_u
    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. Preintegrated INS is explicitly unsupported because a correct recursion also needs nominal packets, packet covariance, and carried boundary cross-covariance; a raw-process-Q approximation would report optimistic sigma.

Args: ekf — an EKF, UKF, or INS transform. For INS, control must also provide its IMU prediction samples because this open-loop covariance analysis has no truth simulator. 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. Preintegrated INS is explicitly unsupported because a
    correct recursion also needs nominal packets, packet covariance, and
    carried boundary cross-covariance; a raw-process-Q approximation would
    report optimistic sigma.

    Args:
        ekf      — an `EKF`, `UKF`, or `INS` transform. For INS, `control`
                   must also provide its IMU prediction samples because this
                   open-loop covariance analysis has no truth simulator.
        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
    if ir.module().metadata.get("propagation") == "preintegrated":
        raise NotImplementedError(
            "sigma_horizon does not support preintegrated INS: its covariance "
            "recursion requires nominal packets, packet covariance, and "
            "carried boundary cross-covariance"
        )
    spec = ir.spec
    n = spec.tangent_dim
    n_consider = consider_dimension(sys)
    P_consider = np.zeros((n, n_consider))
    consider_covariance = np.eye(n_consider)
    steps = max(1, 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
    chosen = []
    for H_fn, full in _select_sensors(ir, sensors, who="sigma_horizon"):
        s = sys.sensors[full]
        R_expr = sensor_R_expr(sys, s)
        R_fn = ca.Function(f"R_{entry_ident(full)}",
                           [x_s, u_s, t_s], [R_expr])
        G_fn = ca.Function(
            f"G_consider_{entry_ident(full)}",
            [x_s, u_s, t_s],
            [sensor_consider_jacobian(sys, s)],
        )
        rate = sys.sample_rates.get(full)
        period = max(1, round(1.0 / (rate * dt))) if rate else 1
        chosen.append((full, s.dim, H_fn, G_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(symmetrize(block))), 0.0))))

    record_point(t0)
    F = Qk = None
    HRs: list = []
    for i in range(steps):
        t = t0 + i * dt
        u_dict = _controls_at(control, t) or None
        u_vec = ir.sys.resolve_u(u_dict, who="sigma_horizon")
        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, G_fn, R_fn, period in chosen:
                H = np.asarray(H_fn(x, u_vec, 0.0, t), float).reshape(dim, n)
                G = np.asarray(G_fn(x, u_vec, t), float).reshape(
                    dim, n_consider
                )
                R = np.asarray(R_fn(x, u_vec, t), float).reshape(dim, dim)
                if not np.any(np.abs(R) > 0):
                    # Same failure `require_active_R` refuses at filter
                    # construction, reached here when a state-dependent R
                    # vanishes mid-recursion — so it says the same thing.
                    raise ValueError(zero_R_message(full, "sigma_horizon"))
                HRs.append((H, G, R, period))
        x = np.asarray(sys.predict_fn(x, u_vec, dt, t), float).reshape(-1)
        P = F @ P @ F.T + Qk
        if n_consider:
            P_consider = F @ P_consider
        for H, G, R, period in HRs:
            if i % period:
                continue
            if n_consider:
                P, P_consider, _ = schmidt_update_np(
                    P, P_consider, consider_covariance, H, G, R
                )
            else:
                _, 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, estimator=None)

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. estimator picks the filter transform carrying the linearized IR — an EKF/UKF/INS instance over this world, or a class/callable applied to it (default EKF); the analysis itself is linearized either way.

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,
                             estimator=None) -> 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. `estimator` picks the
    filter transform carrying the linearized IR — an `EKF`/`UKF`/`INS` instance
    over this world, or a class/callable applied to it (default `EKF`);
    the analysis itself is linearized either way.
    """
    from ..codegen.numpy import TargetNumpy
    from ..sim import Sim

    ekf_ir = _resolve_estimator(world, estimator)
    sim_ir = Sim(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 _empty_report(spec, n)

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

    every = max(1, steps // max(1, samples))
    blocks = []
    metadata = ekf_ir.module().metadata
    packet_map = dict(metadata.get("preintegration_input_map", {}))
    prediction_names = {
        packet_map[name] for name in ("end_accel", "end_gyro")
    } if packet_map else set(metadata.get("prediction_inputs", ()))
    previous_x = None
    previous_control = None
    previous_prediction_readings = None
    previous_measurement_u = None
    for i in range(steps + 1 if packet_map else steps):
        t = i * dt
        u_dict = _controls_at(control, t)
        x_before = truth_vec()
        sim.step(dt, u=u_dict)
        measurement_u = estimator_observation_inputs(
            ekf_ir, u_dict, reading=sim.reading)
        current_prediction_readings = {
            name: np.asarray(sim.reading(name), dtype=float).copy()
            for name in prediction_names
        }
        if packet_map and previous_prediction_readings is not None:
            interval = i - 1
            estimator_u = estimator_interval_inputs(
                ekf_ir,
                previous_control,
                start_reading=previous_prediction_readings,
                end_reading=current_prediction_readings,
                dt=dt,
            )
            if interval % every == 0:
                blocks.append(_local_O(
                    ekf_ir,
                    previous_x,
                    ekf_ir.sys.resolve_u(
                        estimator_u, who="observability_trajectory"
                    ),
                    dt,
                    t - dt,
                    pairs,
                    n,
                    measurement_u=ekf_ir.sys.resolve_u(
                        previous_measurement_u,
                        who="observability_trajectory measurement",
                    ),
                ))
        elif not packet_map and i % every == 0:
            blocks.append(_local_O(
                ekf_ir, x_before,
                ekf_ir.sys.resolve_u(measurement_u,
                                     who="observability_trajectory"),
                dt, t, pairs, n))
        previous_x = x_before
        previous_control = u_dict
        previous_prediction_readings = current_prediction_readings
        previous_measurement_u = measurement_u
    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. Preintegrated INS is explicitly unsupported because a correct recursion also needs nominal packets, packet covariance, and carried boundary cross-covariance; a raw-process-Q approximation would report optimistic sigma.

Args: ekf — an EKF, UKF, or INS transform. For INS, control must also provide its IMU prediction samples because this open-loop covariance analysis has no truth simulator. 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. Preintegrated INS is explicitly unsupported because a
    correct recursion also needs nominal packets, packet covariance, and
    carried boundary cross-covariance; a raw-process-Q approximation would
    report optimistic sigma.

    Args:
        ekf      — an `EKF`, `UKF`, or `INS` transform. For INS, `control`
                   must also provide its IMU prediction samples because this
                   open-loop covariance analysis has no truth simulator.
        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
    if ir.module().metadata.get("propagation") == "preintegrated":
        raise NotImplementedError(
            "sigma_horizon does not support preintegrated INS: its covariance "
            "recursion requires nominal packets, packet covariance, and "
            "carried boundary cross-covariance"
        )
    spec = ir.spec
    n = spec.tangent_dim
    n_consider = consider_dimension(sys)
    P_consider = np.zeros((n, n_consider))
    consider_covariance = np.eye(n_consider)
    steps = max(1, 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
    chosen = []
    for H_fn, full in _select_sensors(ir, sensors, who="sigma_horizon"):
        s = sys.sensors[full]
        R_expr = sensor_R_expr(sys, s)
        R_fn = ca.Function(f"R_{entry_ident(full)}",
                           [x_s, u_s, t_s], [R_expr])
        G_fn = ca.Function(
            f"G_consider_{entry_ident(full)}",
            [x_s, u_s, t_s],
            [sensor_consider_jacobian(sys, s)],
        )
        rate = sys.sample_rates.get(full)
        period = max(1, round(1.0 / (rate * dt))) if rate else 1
        chosen.append((full, s.dim, H_fn, G_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(symmetrize(block))), 0.0))))

    record_point(t0)
    F = Qk = None
    HRs: list = []
    for i in range(steps):
        t = t0 + i * dt
        u_dict = _controls_at(control, t) or None
        u_vec = ir.sys.resolve_u(u_dict, who="sigma_horizon")
        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, G_fn, R_fn, period in chosen:
                H = np.asarray(H_fn(x, u_vec, 0.0, t), float).reshape(dim, n)
                G = np.asarray(G_fn(x, u_vec, t), float).reshape(
                    dim, n_consider
                )
                R = np.asarray(R_fn(x, u_vec, t), float).reshape(dim, dim)
                if not np.any(np.abs(R) > 0):
                    # Same failure `require_active_R` refuses at filter
                    # construction, reached here when a state-dependent R
                    # vanishes mid-recursion — so it says the same thing.
                    raise ValueError(zero_R_message(full, "sigma_horizon"))
                HRs.append((H, G, R, period))
        x = np.asarray(sys.predict_fn(x, u_vec, dt, t), float).reshape(-1)
        P = F @ P @ F.T + Qk
        if n_consider:
            P_consider = F @ P_consider
        for H, G, R, period in HRs:
            if i % period:
                continue
            if n_consider:
                P, P_consider, _ = schmidt_update_np(
                    P, P_consider, consider_covariance, H, G, R
                )
            else:
                _, 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, estimator=None, truth_world_factory=None, progress=None)

Monte-Carlo NEES consistency check for a filter over 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%). estimator — the filter under test: an EKF/UKF/INS instance over this world, or a class/callable applied to it (default EKF). Consistency of a UKF's covariance is exactly the case worth auditing — its sigma-point moments are not the EKF's Jacobian push. truth_world_factory — optional run_index -> World factory for an outer ensemble of static model realizations. The returned world supplies simulation truth only; world still defines the default estimator unless estimator is supplied. This is the appropriate boundary for calibration or manufacturing uncertainty that stays correlated for an entire run, rather than white measurement noise. progress — optional callback invoked after each independent run as progress(completed, runs).

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, estimator=None,
         truth_world_factory: Callable[[int], object] | None = None,
         progress: Callable[[int, int], None] | None = None) -> NEESReport:
    """Monte-Carlo NEES consistency check for a filter over `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%).
        estimator — the filter under test: an `EKF`/`UKF`/`INS` instance over
                   this world, or a class/callable applied to it (default
                   `EKF`). Consistency of a UKF's covariance is exactly
                   the case worth auditing — its sigma-point moments are
                   not the EKF's Jacobian push.
        truth_world_factory — optional ``run_index -> World`` factory for an
                   outer ensemble of static model realizations. The returned
                   world supplies simulation truth only; ``world`` still
                   defines the default estimator unless ``estimator`` is
                   supplied. This is the appropriate boundary for calibration
                   or manufacturing uncertainty that stays correlated for an
                   entire run, rather than white measurement noise.
        progress — optional callback invoked after each independent run as
                   ``progress(completed, runs)``.
    """
    import casadi as ca

    from ..codegen.numpy import NoiseDriver, TargetNumpy
    from ..sim import Sim

    ekf_ir = _resolve_estimator(world, estimator)
    sim_ir = None if truth_world_factory is not None else Sim(world)
    spec = ekf_ir.spec
    n = spec.tangent_dim
    tangent_labels = [""] * n
    for slot in spec.slots:
        for index in range(
            slot.tangent_offset, slot.tangent_offset + slot.tangent_dim
        ):
            tangent_labels[index] = slot.name
    if warmup is None:
        warmup = steps // 5
    if P0 is None:
        P0 = np.eye(n) * 0.1
    try:
        L0 = np.linalg.cholesky(P0)
    except np.linalg.LinAlgError as exc:
        raise ValueError(
            f"nees: P0 must be symmetric positive-definite (the initial "
            f"estimate is drawn from N(truth, P0)); "
            f"np.linalg.cholesky failed: {exc}") from exc

    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_projected(world_rt.state)

    nees_samples: list[float] = []
    squared_error_samples: list[np.ndarray] = []
    full_squared_error_samples: list[np.ndarray] = []
    full_marginal_nes_samples: list[np.ndarray] = []
    sensor_updates = {full: 0 for full in names}
    sensor_rejections = {full: 0 for full in names}
    sensor_nis: dict[str, list[float]] = {full: [] for full in names}
    for r in range(runs):
        rng = np.random.default_rng(seed + r)
        run_sim_ir = (
            Sim(truth_world_factory(r))
            if truth_world_factory is not None
            else sim_ir
        )
        sim = TargetNumpy(run_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
        rates = {full: sim.module.port(full).rate for full in names}
        last_fold = {full: None for full in names}

        preintegrated = bool(
            ekf_ir.module().metadata.get("preintegration_input_map")
        )
        prediction_names = tuple(
            ekf_ir.module().metadata.get("prediction_inputs", ())
        )
        sources = ekf_ir.module().metadata.get("measurement_sources", {})
        previous_prediction_readings = None
        previous_control = None

        # Preintegration needs two timestamped IMU boundaries for each
        # interval.  The simulation oracle emits interval-start readings, so
        # one look-ahead plant tick supplies the right endpoint without
        # relabeling the left sample as ``end_gyro``.  Raw/EKF paths retain
        # their ordinary one-tick update-then-predict loop.
        loop_steps = steps + 1 if preintegrated else steps
        for i in range(loop_steps):
            t = i * dt
            u = _controls_at(control, t)
            truth_at_epoch = truth_vec(sim)
            sim.step(dt, u=u)
            current_prediction_readings = {
                name: np.asarray(sim.reading(name), dtype=float).copy()
                for name in prediction_names
                if name in {getattr(ekf_ir.sys, "accel_input", None),
                            getattr(ekf_ir.sys, "gyro_input", None)}
            }
            update_u = estimator_observation_inputs(
                ekf_ir, u, reading=sim.reading
            )

            if preintegrated and previous_prediction_readings is not None:
                estimator_u = estimator_interval_inputs(
                    ekf_ir,
                    previous_control,
                    start_reading=previous_prediction_readings,
                    end_reading=current_prediction_readings,
                    dt=dt,
                )
                interval = i - 1
                ekf.predict(dt, u=estimator_u, t=interval * dt)
                if interval >= warmup:
                    e = np.asarray(
                        boxminus(truth_at_epoch, ekf.x)
                    ).reshape(-1)
                    P = ekf.P
                    full_squared_error_samples.append(np.square(e))
                    full_nees = _strict_nees_sample(
                        e, P, run=r, step=interval, labels=tangent_labels
                    )
                    full_marginal_nes_samples.append(
                        np.square(e) / np.diag(P)
                    )
                    if observable_basis is None:
                        sample_nees = full_nees
                    else:
                        e = observable_basis.T @ e
                        P = observable_basis.T @ P @ observable_basis
                        sample_nees = _strict_nees_sample(
                            e, P, run=r, step=interval, labels=None,
                        )
                    squared_error_samples.append(np.square(e))
                    nees_samples.append(sample_nees)

            # The final look-ahead sample closes the last interval but does
            # not begin another requested interval, so it is not an extra
            # ordinary measurement fold.
            if not preintegrated or i < steps:
                for full in names:
                    rate = rates[full]
                    previous = last_fold[full]
                    if (rate is None or previous is None
                            or t - previous >= 1.0 / rate - 1e-9):
                        source = sources.get(full, full)
                        update = ekf.update(
                            full, sim.reading(source), u=update_u, t=t
                        )
                        sensor_updates[full] += 1
                        sensor_rejections[full] += int(not update.accepted)
                        sensor_nis[full].append(float(update.nis))
                        last_fold[full] = t

            if preintegrated:
                previous_prediction_readings = current_prediction_readings
                previous_control = u
                continue

            ekf.predict(dt, u=update_u, t=t)
            if i >= warmup:
                e = np.asarray(boxminus(truth_vec(sim), ekf.x)).reshape(-1)
                P = ekf.P
                full_squared_error_samples.append(np.square(e))
                full_nees = _strict_nees_sample(
                    e, P, run=r, step=i, labels=tangent_labels
                )
                full_marginal_nes_samples.append(
                    np.square(e) / np.diag(P)
                )
                if observable_basis is None:
                    sample_nees = full_nees
                else:
                    e = observable_basis.T @ e
                    P = observable_basis.T @ P @ observable_basis
                    sample_nees = _strict_nees_sample(
                        e, P, run=r, step=i, labels=None,
                    )
                squared_error_samples.append(np.square(e))
                nees_samples.append(sample_nees)

        if progress is not None:
            progress(r + 1, runs)

    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
    tangent_rmse = tuple(float(value) for value in np.sqrt(
        np.mean(np.asarray(squared_error_samples), axis=0)
    ))
    full_tangent_rmse = tuple(float(value) for value in np.sqrt(
        np.mean(np.asarray(full_squared_error_samples), axis=0)
    ))
    full_marginal_nes = tuple(float(value) for value in np.mean(
        np.asarray(full_marginal_nes_samples), axis=0
    ))
    return NEESReport(
        dof=dof, anees=anees, lower=lower, upper=upper,
        runs=runs, samples=len(nees_samples), tangent_rmse=tangent_rmse,
        full_tangent_rmse=full_tangent_rmse,
        full_marginal_nes=full_marginal_nes,
        sensor_updates=sensor_updates,
        sensor_rejections=sensor_rejections,
        sensor_mean_nis={
            full: float(np.mean(values))
            for full, values in sensor_nis.items()
        },
    )

manta.estimation.chi2_gate

chi2_gate(dof, confidence)

The NIS gate that accepts a fraction confidence of consistent innovations for a dof-dimensional sensor.

The normalized innovation squared of a consistent filter is χ²-distributed with the measurement dimension as its degrees of freedom; gates={"gps.position": chi2_gate(3, 0.99)} therefore rejects a correct 3-vector fix one time in a hundred. Pure numpy-free Python — no scipy dependency — so the same number reaches generated code.

Source code in manta/estimation/consistency.py
def chi2_gate(dof: int, confidence: float) -> float:
    """The NIS gate that accepts a fraction `confidence` of consistent
    innovations for a `dof`-dimensional sensor.

    The normalized innovation squared of a consistent filter is
    χ²-distributed with the measurement dimension as its degrees of
    freedom; `gates={"gps.position": chi2_gate(3, 0.99)}` therefore rejects
    a correct 3-vector fix one time in a hundred. Pure numpy-free Python —
    no scipy dependency — so the same number reaches generated code.
    """
    if isinstance(dof, bool) or not isinstance(dof, int) or dof < 1:
        raise ValueError(
            f"chi2_gate: dof must be a positive int (the measurement "
            f"dimension), got {dof!r}")
    if not isinstance(confidence, (int, float)) or not (
            0.0 < float(confidence) < 1.0):
        raise ValueError(
            f"chi2_gate: confidence must lie in (0, 1), got {confidence!r}")
    return chi2_quantile(dof, float(confidence))

manta.estimation.chi2_quantile

chi2_quantile(dof, p)

The χ² quantile x with P(χ²_dof <= x) = p, to ~1e-12.

Safeguarded Newton on the regularized incomplete gamma CDF, seeded by the Wilson–Hilferty approximation and bracketed by bisection so it converges for every dof >= 1 and 0 < p < 1.

Source code in manta/estimation/consistency.py
def chi2_quantile(dof: float, p: float) -> float:
    """The χ² quantile `x` with `P(χ²_dof <= x) = p`, to ~1e-12.

    Safeguarded Newton on the regularized incomplete gamma CDF, seeded by
    the Wilson–Hilferty approximation and bracketed by bisection so it
    converges for every dof >= 1 and 0 < p < 1.
    """
    dof = float(dof)
    if not math.isfinite(dof) or dof <= 0.0:
        raise ValueError(f"chi2_quantile: dof must be > 0, got {dof!r}")
    if not (0.0 < p < 1.0):
        raise ValueError(f"chi2_quantile: p must lie in (0, 1), got {p!r}")
    z = _norm_ppf(p)
    x = max(1e-12, dof * (1 - 2 / (9 * dof) + z * sqrt(2 / (9 * dof))) ** 3)
    lo, hi = 0.0, max(2.0 * x, dof + 40.0 * sqrt(dof) + 100.0)
    while chi2_cdf(hi, dof) < p:
        hi *= 2.0
    half = 0.5 * dof
    log_norm = -math.lgamma(half) - half * math.log(2.0)
    for _ in range(200):
        f = chi2_cdf(x, dof) - p
        if f > 0.0:
            hi = x
        else:
            lo = x
        if abs(f) < 1e-14:
            break
        density = math.exp(log_norm + (half - 1.0) * math.log(x) - 0.5 * x) \
            if x > 0.0 else 0.0
        step = x - f / density if density > 0.0 else 0.5 * (lo + hi)
        x = step if lo < step < hi else 0.5 * (lo + hi)
        if hi - lo < 1e-15 * max(1.0, hi):
            break
    return x