Module contents
Lesson 16 of 33Core 115 min

State estimation and sensor fusion

Apply filtering to robots whose states lie on manifolds and whose sensors have biases, delays, and different rates. Develop motion and observation models, an SO(3) error-state Kalman filter, fusion architectures, timing and consistency checks.

After this lesson you can

  • Write probabilistic motion and observation models for a mobile robot and a biased IMU.
  • Derive and implement an error-state Kalman filter with orientation in SO(3).
  • Fuse IMU, odometry and GNSS at different rates and delays.
  • Validate filter consistency using NEES and NIS and tune noise covariances.
  • Compare loosely and tightly coupled fusion and select according to the sensor.

Before you start

Sensors make different mistakes

An IMU provides acceleration and angular velocity at high frequency, but integrating even a small bias makes the error grow. GNSS provides absolute position less frequently and may arrive late or disappear between buildings. Wheel odometry measures relative displacement and fails if wheels slip. An estimator combines predictions and measurements with their uncertainty and records when each was taken.

Motion and measurements

Motion models describe the distribution of a future state given the current state and control. For a planar robot with speed vv, turn rate ω\omega, and step Δt\Delta t, an approximation is x+=x+vΔtcos⁡θx^+=x+v\Delta t\cos\theta, y+=y+vΔtsin⁡θy^+=y+v\Delta t\sin\theta, and θ+=θ+ωΔt\theta^+=\theta+\omega\Delta t, plus noise. For a finite turn with ω≠0\omega\ne0 the arc can be integrated exactly. Angular uncertainty makes diverging future trajectories form a curved region; a local Gaussian ellipse may describe it poorly over long horizons.

Observation models relate state and measurement, z=h(x)+n\vb{z}=h(\vb{x})+\vb{n}. A known landmark at (mx,my)(m_x,m_y) produces range r=(mx−x)2+(my−y)2r=\sqrt{(m_x-x)^2+(m_y-y)^2} and bearing ϕ=atan2⁡(my−y,mx−x)−θ\phi=\operatorname{atan2}(m_y-y,m_x-x)-\theta. Wrap the angular residual into (−π,π](-\pi,\pi]. GNSS can measure position or satellite pseudoranges; a camera measures pixels through the pinhole model and its extrinsic pose. A LiDAR beam depends on its first intersection with the map, not just an obstacle’s center.

With dx=mx−xd_x=m_x-x, dy=my−yd_y=m_y-y and r>0r>0, the range and bearing Jacobian with respect to (x,y,θ)(x,y,\theta) is

H=[−dx/r−dy/r0dy/r2−dx/r2−1].\mat{H}=\begin{bmatrix}-d_x/r&-d_y/r&0\\d_y/r^2&-d_x/r^2&-1\end{bmatrix}.

It is singular at r=0r=0, where bearing is also undefined. The landmark’s identity must be known to use this equation: a wrong association produces an innovation that does not represent the same object. Rejecting a large innovation can guard against an outlier, but can also reject a correct measurement if the state or its covariance is already wrong.

For a constant turn, the exact planar arc is

x+=x+vω(sin⁡(θ+ωΔt)−sin⁡θ),y+=y+vω(−cos⁡(θ+ωΔt)+cos⁡θ).x^+=x+\frac{v}{\omega}\big(\sin(\theta+\omega\Delta t)-\sin\theta\big),\quad y^+=y+\frac{v}{\omega}\big(-\cos(\theta+\omega\Delta t)+\cos\theta\big).

As ω→0\omega\to0, the limit is straight-line motion; implement that limit to avoid numerically unstable division. If a wheel slips, odometry error is not necessarily independent white noise: it may persist and correlate with the terrain. Similarly, a GNSS receiver’s covariance can change with satellite geometry or multipath. A filter can be mathematically well implemented and still be inconsistent if its model of those errors is wrong.

An IMU and its drift

The IMU model distinguishes measured specific force am=R⊤(aw−g)+ba+na\vb{a}_m=\mat{R}\T(\vb{a}_w-\vb{g})+\vb{b}_a+\vb{n}_a from measured angular velocity ωm=ω+bg+ng\vb{\omega}_m=\vb{\omega}+\vb{b}_g+\vb{n}_g. Here R\mat{R} maps vectors from body to world, g\vb{g} is gravity in the world frame, and biases can be modeled as random walks. If an accelerometer has a constant bias of 0.05 m/s20.05\,\mathrm{m/s^2} and starts with correct velocity, after 10 s the position error in that direction is 12bt2=2.5 m\tfrac12bt^2=2.5\,\mathrm{m}. A gyro bias also tilts estimated gravity, contaminating horizontal acceleration. In general motion, not all drift grows exactly quadratically.

InteractiveIntegrate and correct
  • True trajectory
  • Estimate
  • Simplified 2σ radius
0.05
0.010
0.03
0.002
20.0
Position error (m)0.44
Declared deviation (m)0.14
The vehicle follows a planar circle at constant speed. The simulation integrates acceleration and rotation with biases and reproducible noise and optionally applies GNSS at 1 Hz. The dashed circle represents two standard deviations of a simplified covariance that ignores biases and angular error: compare it with actual error, and do not treat it as a guarantee.

Error state in SO(3)

The error-state Kalman filter (ESKF) maintains a nominal state (p^,v^,R^,b^g,b^a)(\hat{\vb{p}},\hat{\vb{v}},\hat{\mat{R}},\hat{\vb{b}}_g,\hat{\vb{b}}_a) and a covariance for a 15-dimensional error vector. We adopt a right perturbation: Rreal=R^exp⁡([δθ]×)\mat{R}_{\mathrm{real}}=\hat{\mat{R}}\exp([\delta\vb{\theta}]_\times). Other errors are additive, actual minus nominal. This convention fixes the sign of the equations and reset; a left perturbation uses different Jacobians. See Solà and the SO(3) exponential map.

With f^=am−b^a\hat{\vb{f}}=\vb{a}_m-\hat{\vb{b}}_a and ω^=ωm−b^g\hat{\vb{\omega}}=\vb{\omega}_m-\hat{\vb{b}}_g, continuous nominal propagation is p^˙=v^\dot{\hat{\vb{p}}}=\hat{\vb{v}}, v^˙=R^f^+g\dot{\hat{\vb{v}}}=\hat{\mat{R}}\hat{\vb{f}}+\vb{g} and R^˙=R^[ω^]×\dot{\hat{\mat{R}}}=\hat{\mat{R}}[\hat{\vb{\omega}}]_\times. To first order, ignoring products of errors,

δp˙=δv,δv˙=−R^[f^]×δθ−R^δba−R^na,δθ˙=−[ω^]×δθ−δbg−ng.\begin{aligned} \delta\dot{\vb{p}}&=\delta\vb{v},\\ \delta\dot{\vb{v}}&=-\hat{\mat{R}}[\hat{\vb{f}}]_\times\delta\vb{\theta}-\hat{\mat{R}}\delta\vb{b}_a-\hat{\mat{R}}\vb{n}_a,\\ \delta\dot{\vb{\theta}}&=-[\hat{\vb{\omega}}]_\times\delta\vb{\theta}-\delta\vb{b}_g-\vb{n}_g. \end{aligned}

Both biases evolve with their random-walk noise. To derive the angular equation, compare R˙real=Rreal[ωm−bg,real−ng]×\dot{\mat{R}}_{\rm real}=\mat{R}_{\rm real}[\vb{\omega}_m-\vb{b}_{g,\rm real}-\vb{n}_g]_\times with the derivative of nominal times error and retain linear terms. Rotation of the error by nominal motion produces the term −[ω^]×δθ-[\hat{\vb{\omega}}]_\times\delta\vb{\theta}.

More explicitly, let E=R^⊤Rreal\mat{E}=\hat{\mat{R}}\T\mat{R}_{\rm real}. Then E˙=−[ω^]×E+E[ω^−δbg−ng]×\dot{\mat{E}}=-[\hat\omega]_\times\mat{E}+\mat{E}[\hat\omega-\delta b_g-n_g]_\times. Substitute E≈I+[δθ]×\mat{E}\approx\mat{I}+[\delta\theta]_\times and eliminate products of errors. The commutator [δθ]×[ω^]×−[ω^]×[δθ]×[\delta\theta]_\times[\hat\omega]_\times-[\hat\omega]_\times[\delta\theta]_\times equals [−ω^×δθ]×[-\hat\omega\times\delta\theta]_\times, yielding the angular equation. This derivation fixes exactly what the transport term’s sign means.

The error order is (δp,δv,δθ,δbg,δba)(\delta\vb{p},\delta\vb{v},\delta\vb{\theta},\delta\vb{b}_g,\delta\vb{b}_a). In that order, the nonzero blocks of F\mat{F} are Fp,v=IF_{p,v}=I, Fv,θ=−R^[f^]×F_{v,\theta}=-\hat R[\hat f]_\times, Fv,ba=−R^F_{v,b_a}=-\hat R, Fθ,θ=−[ω^]×F_{\theta,\theta}=-[\hat\omega]_\times and Fθ,bg=−IF_{\theta,b_g}=-I. Accelerometer and gyroscope noise enter velocity and orientation; random-walk noise enters the respective biases. Each block is 3×33\times3. This bookkeeping avoids a common error: noise expressed in body axes must be rotated before applying it to world-frame velocity error.

Spectral density and a sample’s standard deviation are not interchangeable. If continuous white noise of density qq is averaged over Δt\Delta t, the averaged sample variance scales as q/Δtq/\Delta t; the integrated increment has variance proportional to qΔtq\Delta t. In the lab, noise contains density standard deviations, so the simulated sample divides by Δt\sqrt{\Delta t} while the bias walk multiplies by Δt\sqrt{\Delta t}. That convention must match the units in the IMU datasheet.

A first-order discretization uses Φ≈I+FΔt\mat{\Phi}\approx\mat{I}+\mat{F}\Delta t and P−≈ΦPΦ⊤+GQcG⊤Δt\mat{P}^-\approx\mat{\Phi}\mat{P}\mat{\Phi}\T+\mat{G}\mat{Q}_c\mat{G}\T\Delta t, with continuous spectral densities in Qc\mat{Q}_c. Larger steps require a more accurate discretization. When a measurement arrives, form the innovation and Kalman gain. Then inject the additive increments and R^←R^exp⁡([δθ^]×)\hat{\mat{R}}\leftarrow\hat{\mat{R}}\exp([\delta\hat{\vb{\theta}}]_\times); reset the error mean to zero and transform covariance with the reset Jacobian. Under this convention, the angular block is the right Jacobian Jr(δθ^)≈I−12[δθ^]×\mat{J}_r(\delta\hat{\vb{\theta}})\approx\mat{I}-\tfrac12[\delta\hat{\vb{\theta}}]_\times.

For direct GNSS position, H=[I  0  0  0  0]\mat{H}=[\mat{I}\;\mat{0}\;\mat{0}\;\mat{0}\;\mat{0}] and ν=z−p^\vb{\nu}=\vb{z}-\hat{\vb{p}}. Although H\mat{H} observes position alone, correlations in P\mat{P} allow correction of velocity, orientation, and biases. That does not mean they are instantaneously observable: motion and measurement history must contain enough information. The Joseph form, P+=(I−KH)P−(I−KH)⊤+KVK⊤\mat{P}^+=(\mat{I}-\mat{K}\mat{H})\mat{P}^-(\mat{I}-\mat{K}\mat{H})\T+\mat{K}\mat{V}\mat{K}\T, helps preserve symmetry and positive semidefiniteness numerically. After changing the error origin, apply P←JP+J⊤\mat{P}\leftarrow\mat{J}\mat{P}^+\mat{J}\T.

Why is that final step needed? Before injection, the actual orientation is R^exp⁡([δθ]×)\hat R\exp([\delta\theta]_{\times}); afterward it is R^exp⁡([δθ^]×)exp⁡([δθnuevo]×)\hat R\exp([\delta\hat\theta]_{\times})\exp([\delta\theta_{nuevo}]_{\times}). Equating these expressions changes the random error’s coordinates. Setting its mean to zero does not by itself change the basis in which its covariance is expressed. For a small correction the difference is first order in the increment; mixing right and left conventions changes that term’s sign.

InteractiveAn error-state cycle
  • Reference frame
  • Nominal axis
  • Angular measurement

Start with a nominal state and covariance.

step 1 of 6
Nominal orientation (rad)0.150
Tangent correction (rad)0
Angular variance0.090
A single-axis reduction uses nominal 0.15 rad, measurement 0.30 rad, prior variance 0.09 and measurement variance 0.04. Step through: the scalar gain calculates the tangent correction before injection and reset. Rotations commute on a fixed axis and the scalar angular reset has Jacobian one; the full filter below handles three axes.

Fusion and timing

Loosely coupled fusion architectures use a position or velocity solution from the GNSS receiver; tightly coupled ones incorporate per-satellite pseudoranges or velocities into the filter together with their states and clocks. Two satellites do not determine a conventional independent 3D GNSS solution, but two observations can partially constrain the inertial state. They do not by themselves guarantee observability or accuracy: geometry, clock, biases, and additional sensors matter.

Time synchronization distinguishes capture time from arrival time. If a measurement arrives late, updating the current state as though it were simultaneous induces a motion residual. One solution is to return to the state saved at the capture timestamp, apply the measurement there, and propagate again with subsequent inputs, including other measurements already processed. If timestamps belong to different clocks, estimate their offset and possible drift; transport delay is not the same as clock difference.

A smoothing-window alternative retains past states and constraints between them, allowing a delayed observation to be inserted without reducing it to a current-state correction. If the timestamp is outside the available history, discard the measurement or use an explicit approximation. Interpolation also requires care: interpolating positions may be reasonable over a short interval, but orientation should be interpolated on SO(3)SO(3), not by adding quaternion components as if they were Euclidean coordinates.

Consistency, not just a pretty trajectory

Consistency using NEES and NIS compares errors or innovations with predicted uncertainty. For error e\vb{e} and covariance P\mat{P}, NEES=e⊤P−1e\mathrm{NEES}=\vb{e}\T\mat{P}\inv\vb{e}. For innovation ν\vb{\nu} and covariance S\mat{S}, NIS=ν⊤S−1ν\mathrm{NIS}=\vb{\nu}\T\mat{S}\inv\vb{\nu}. Under a correct linear Gaussian model and nonsingular covariance, they follow chi-square distributions with degrees of freedom equal to the corresponding dimension. NEES requires ground truth; NIS can be calculated without it. For nonlinear filters they are approximate diagnostics.

For MM independent simulations at one instant, the sum of NEES for state dimension dd follows χMd2\chi^2_{Md} under those assumptions; divide its quantiles by MM for the mean NEES interval. Do not treat successive samples from one trajectory as independent: they share state and errors. An out-of-band test does not by itself identify which covariance is wrong; also inspect biases, temporal correlation, linearization, and the measurement model.

InteractiveDeclared covariance versus error
  • NEES
  • NIS
  • 95% lower limit
  • 95% upper limit
1.0
1.0
Final mean NEES0.74
Final mean NIS1.00
Each curve averages 30 independent scalar random-walk filters, with actual variances Q = 0.05 and R = 0.5. Change the assumed factors: both statistics are compared with χ² quantiles for 30 degrees of freedom divided by 30. The band is pointwise and corresponds to the correct model; occasional crossings are expected.

Lab: inertial fusion with GNSS

The simulation generates three-dimensional motion with rotation, specific force, random-walk biases, IMU at 200 Hz and GNSS position at 5 Hz with a 0.1 s delay. Correction rewinds to the capture instant and propagates again; with this fixed delay shorter than the measurement interval there are no subsequent updates to replay. A general system must also retain and replay those updates. The initial state is sampled from the filter’s initial covariance. Discretization is first order and the test is small: its bands are an approximate reference, not a consistency certification.

[ ]ESKF, simulation and rewindBrowser
import numpy as np
from scipy.spatial.transform import Rotation
from scipy.stats import chi2

def skew(w):
    x,y,z=w
    return np.array([[0.,-z,y],[z,0.,-x],[-y,x,0.]])

def exp3(w):
    a=np.linalg.norm(w); W=skew(w)
    if a<1e-10: return np.eye(3)+W+0.5*W@W
    return np.eye(3)+np.sin(a)/a*W+(1-np.cos(a))/(a*a)*W@W

def jr(w):
    a=np.linalg.norm(w); W=skew(w)
    if a<1e-8: return np.eye(3)-0.5*W+W@W/6
    return np.eye(3)-(1-np.cos(a))/(a*a)*W+(a-np.sin(a))/(a*a*a)*W@W

def predict(s,gyro,acc,dt,noise):
    p,v,R,bg,ba,P=s
    w=gyro-bg; f=acc-ba; gravity=np.array([0.,0.,-9.81])
    aw=R@f+gravity
    pn=p+v*dt+0.5*aw*dt*dt; vn=v+aw*dt; Rn=R@exp3(w*dt)
    F=np.zeros((15,15)); F[:3,3:6]=np.eye(3); F[3:6,6:9]=-R@skew(f); F[3:6,12:15]=-R
    F[6:9,6:9]=-skew(w); F[6:9,9:12]=-np.eye(3)
    G=np.zeros((15,12)); G[3:6,:3]=-R; G[6:9,3:6]=-np.eye(3)
    G[9:12,6:9]=np.eye(3); G[12:15,9:12]=np.eye(3)
    Q=np.diag(np.repeat(np.asarray(noise)**2,3))
    Phi=np.eye(15)+F*dt
    Pn=Phi@[email protected]+G@[email protected]*dt
    return pn,vn,Rn,bg,ba,(Pn+Pn.T)/2

def update(s,z,sigma):
    p,v,R,bg,ba,P=s; H=np.zeros((3,15)); H[:,:3]=np.eye(3)
    V=np.eye(3)*sigma**2; y=z-p; S=H@[email protected]+V
    K=np.linalg.solve(S,H@P).T; dx=K@y
    A=np.eye(15)-K@H; Pn=A@[email protected]+K@[email protected]
    J=np.eye(15);J[6:9,6:9]=jr(dx[6:9]);Pn=J@[email protected]
    state=(p+dx[:3],v+dx[3:6],R@exp3(dx[6:9]),bg+dx[9:12],ba+dx[12:15],(Pn+Pn.T)/2)
    return state,float([email protected](S,y))

def simulate(seed, delay_steps=20, corrected=True, steps=800):
    rng=np.random.default_rng(seed); dt=0.005
    noise=(0.03,0.003,0.0002,0.001)
    std0=np.repeat([0.2,0.1,0.03,0.005,0.02],3); P=np.diag(std0**2)
    error=rng.normal(size=15)*std0
    p=np.zeros(3); v=np.zeros(3); R=np.eye(3)
    bg=error[9:12].copy();ba=error[12:15].copy()
    state=(-error[:3],-error[3:6],R@exp3(-error[6:9]),np.zeros(3),np.zeros(3),P)
    history=[state]; measurements=[]; imus=[]; nis=[]
    for k in range(1,steps+1):
        gyro=np.array([0.05,0.04,0.2]);acc=np.array([0.3,0.1,9.81])
        gm=gyro+bg+rng.normal(0,noise[1]/np.sqrt(dt),3)
        am=acc+ba+rng.normal(0,noise[0]/np.sqrt(dt),3)
        bg+=rng.normal(0,noise[2]*np.sqrt(dt),3);ba+=rng.normal(0,noise[3]*np.sqrt(dt),3)
        aw=R@acc+np.array([0.,0.,-9.81]);p=p+v*dt+0.5*aw*dt**2;v=v+aw*dt;R=R@exp3(gyro*dt)
        imus.append((gm,am));state=predict(state,gm,am,dt,noise);history.append(state)
        if k%40==0: measurements.append((k,p+rng.normal(0,0.3,3)))
        for j,z in measurements:
            if j+delay_steps==k:
                if corrected:
                    state, val=update(history[j],z,0.3);history[j]=state
                    for t in range(j,k):
                        state=predict(state,*imus[t],dt,noise);history[t+1]=state
                else:
                    state,val=update(state,z,0.3);history[k]=state
                nis.append(val)
    err=np.concatenate((p-state[0],v-state[1],Rotation.from_matrix(state[2].T@R).as_rotvec(),bg-state[3],ba-state[4]))
    return float([email protected](state[-1],err)),float(np.mean(nis)),float(np.linalg.norm(p-state[0]))
[ ]Diagnostics across simulationsBrowser
samples=[simulate(i) for i in range(8)]
print('promedios NEES, NIS, error final:',np.mean(samples,axis=0))
print('banda NEES medio:',chi2.ppf([.025,.975],8*15)/8)
print('banda ejercicio d=6, M=50:',chi2.ppf([.025,.975],300)/50)
print('error con sesgo 0.05 durante 10 s:',0.5*0.05*10**2)

The band corresponds to the sum of eight 15-dimensional NEES values at the final instant, with independent simulations. The printed NIS is an average over updates and trajectories; updates from the same trajectory are not independent. Use that average as a diagnostic, not as a chi-square test with all instants concatenated.

[ ]Treating a delayed measurement as currentBrowser
naive=[simulate(i, corrected=False) for i in range(8)]
print('error final medio, rebobinado:',np.mean(samples,axis=0)[2])
print('error final medio, sin rebobinar:',np.mean(naive,axis=0)[2])

This comparison uses the same seed and measurements for each pair. Rewinding does not correct unknown clock bias or fix model errors; it only applies each measurement at its simulated time. For a different delay or motion, measure again: the effect is not a universal constant.

Local lab: wheels, IMU, and pseudo-GNSS

The MuJoCo differential-drive robot has two encoders and an IMU. Two planar six-state filters estimate position, orientation, speed, turn rate, and gyro bias. The loosely coupled filter converts both encoder readings to linear and angular velocity before updating; the tightly coupled filter incorporates each wheel’s speed separately. The left encoder is missing for one second: the loose filter drops the pair and the tight filter retains the right reading. Outside the dropout, the linear transformation of observations and covariances preserves the same information. Pseudo-GNSS arrives with a 0.1 s delay and is inserted at its capture time, after which later wheel and IMU observations are replayed. It is simulator ground-truth position with noise, not a satellite signal.

The IMU measures acceleration and rotation; this planar filter uses only vertical rotation, so it neither compensates tilt nor models slip. The lab compares these two odometry interfaces, not a complete tightly coupled GNSS implementation. With the indicated seed, the local run produced position RMSE of 0.0291 m and 0.0282 m; these are results for this world and trajectory, not a general conclusion of superiority.

[ ]Differential-drive robot and asynchronous fusionLocal GPU
import numpy as np
import mujoco

xml='''<mujoco model="differential"><option timestep="0.01" gravity="0 0 -9.81" integrator="implicitfast"/>
<worldbody><geom type="plane" size="5 5 .1" friction="1 0.01 0.001"/>
<body name="base" pos="0 0 0.17"><freejoint/>
<geom type="box" size="0.18 0.16 0.04" mass="2"/>
<site name="imu" pos="0 0 0" size="0.01"/>
<geom type="sphere" pos="-0.14 0 -0.07" size="0.035" mass="0.05" friction="0.02 0.001 0.0001"/>
<body name="left" pos="0 0.21 -0.06"><joint name="jl" type="hinge" axis="0 1 0"/>
<geom type="cylinder" quat="0.70710678 0.70710678 0 0" size="0.1 0.035" mass="0.25" friction="1 0.01 0.001"/></body>
<body name="right" pos="0 -0.21 -0.06"><joint name="jr" type="hinge" axis="0 1 0"/>
<geom type="cylinder" quat="0.70710678 0.70710678 0 0" size="0.1 0.035" mass="0.25" friction="1 0.01 0.001"/></body>
</body></worldbody><actuator><velocity joint="jl" kv="0.5"/><velocity joint="jr" kv="0.5"/></actuator>
<sensor><gyro name="gyro" site="imu"/><accelerometer name="acc" site="imu"/>
<jointpos name="enc_l" joint="jl"/><jointpos name="enc_r" joint="jr"/></sensor></mujoco>'''
model=mujoco.MjModel.from_xml_string(xml); d=mujoco.MjData(model)
g=np.random.default_rng(11); dt=model.opt.timestep; width=0.42; radius=0.1

def predict(x,P):
    px,py,theta,v,w,b=x
    xn=x.copy();xn[0]+=v*np.cos(theta)*dt;xn[1]+=v*np.sin(theta)*dt;xn[2]+=w*dt
    F=np.eye(6);F[0,2]=-v*np.sin(theta)*dt;F[1,2]=v*np.cos(theta)*dt
    F[0,3]=np.cos(theta)*dt;F[1,3]=np.sin(theta)*dt;F[2,4]=dt
    Q=np.diag([1e-6,1e-6,1e-6,5e-4,5e-4,1e-7])*dt
    return xn,F@[email protected]+Q

def correct(x,P,z,H,V):
    S=H@[email protected]+V;K=np.linalg.solve(S,H@P).T
    x=x+K@(z-H@x);A=np.eye(6)-K@H
    return x,A@[email protected]+K@[email protected]

est=[(np.zeros(6),np.eye(6)*0.1) for _ in range(2)]
history=[[est[i]] for i in range(2)]; events=[]; gps_queue={}
previous=np.zeros(2); errors=[[],[]]; times=[]
Hgyro=np.zeros((1,6));Hgyro[0,4]=Hgyro[0,5]=1
Hgps=np.zeros((2,6));Hgps[0,0]=Hgps[1,1]=1
Hwheel=np.zeros((2,6));Hwheel[:,3]=1;Hwheel[0,4]=width/2;Hwheel[1,4]=-width/2
A=np.array([[.5,.5],[1/width,-1/width]])
def sensor_step(state, event, mode):
    gyro,speeds,dropout=event
    x,P=predict(*state); x,P=correct(x,P,np.array([gyro]),Hgyro,np.array([[0.003**2]]))
    if mode==0 and not dropout:
        x,P=correct(x,P,A@speeds,A@Hwheel,A@(np.eye(2)*0.005**2)@A.T)
    elif mode==1:
        Hw=Hwheel[:1] if dropout else Hwheel; z=speeds[:1] if dropout else speeds
        x,P=correct(x,P,z,Hw,np.eye(len(z))*0.005**2)
    return x,P

for k in range(600):
    d.ctrl[:]=[4.,6.];mujoco.mj_step(model,d)
    gyro=float(d.sensor('gyro').data[2])+0.01+g.normal(0,0.003)
    angles=np.array([d.sensor('enc_r').data[0],d.sensor('enc_l').data[0]])
    speeds=radius*(angles-previous)/dt;previous=angles
    speeds+=g.normal(0,0.005,2)
    truth=d.body('base').xpos[:2].copy()
    dropout=3 <= d.time < 4
    events.append((gyro,speeds.copy(),dropout))
    if (k+1)%20==0: gps_queue[k+1+10]=(k+1,truth+g.normal(0,0.05,2))
    for mode in range(2):
        state=sensor_step(est[mode],events[-1],mode);history[mode].append(state)
        if k+1 in gps_queue:
            j,z=gps_queue[k+1]
            state=correct(*history[mode][j],z,Hgps,np.eye(2)*0.05**2);history[mode][j]=state
            for t in range(j,k+1):
                state=sensor_step(state,events[t],mode);history[mode][t+1]=state
        est[mode]=state;errors[mode].append(float(np.linalg.norm(state[0][:2]-truth)))
    times.append(d.time)
print('pasos',len(times),'tiempo final',times[-1])
print('posición verdadera final:',d.body('base').xpos[:2].copy())
print('RMSE posición débil/fuerte:',[float(np.sqrt(np.mean(np.array(e)**2))) for e in errors])
print('lecturas finales gyro y acelerómetro:',d.sensor('gyro').data.copy(),d.sensor('acc').data.copy())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofPropagating a right angular error
Prove: Derive the linear angular error equation for a right perturbation.
0
Use Rreal=R^exp⁡([δθ]×)\mat{R}_{real}=\hat{\mat{R}}\exp([\delta\vb{\theta}]_\times) and bias errors defined as actual minus nominal.

Step 1 of 3. What angular velocity does the actual orientation use?

Numeric
With a state of dimension 6 and 50 independent simulations, what is the upper endpoint of the central 95% interval for mean NEES? Give three decimal places.
CodePrediction and position measurement
Implement eskf_predict(s, gyro, acc, dt, noise) and eskf_update(s, z, sigma). The state is (p,v,R,bg,ba,P) and the error order is position, velocity, right rotation, gyro bias, and acceleration bias. noise contains continuous densities for accelerometer, gyroscope, gyro walk, and acceleration walk. Return the new state; the update returns (estado, NIS). You may use the skew, exp3, and jr functions provided by the tests.
import numpy as np
def eskf_predict(s, gyro, acc, dt, noise):
  pass
def eskf_update(s, z, sigma):
  pass
Shift+Enter to run
Numeric
A constant accelerometer bias of 0.05 m/s² is integrated for 10 s from a correct initial velocity. What is the position error in meters?
Quiz
Only two satellites are observed. Which architecture can use their observations together with inertial prediction?
Key idea
A useful estimate preserves coordinate conventions, uncertainty, and time: fusing incompatible data in any of those dimensions produces an apparently precise but misleading trajectory.