| 1 |
#!/usr/bin/env python3 |
| 2 |
"""Integration tests for python3-filterpy. |
| 3 |
|
| 4 |
Each test simulates a realistic filtering scenario and asserts that the |
| 5 |
filter converges to the true value within a numerical tolerance. |
| 6 |
""" |
| 7 |
|
| 8 |
import sys |
| 9 |
import numpy as np |
| 10 |
|
| 11 |
np.random.seed(42) |
| 12 |
|
| 13 |
PASS = 0 |
| 14 |
FAIL = 0 |
| 15 |
|
| 16 |
|
| 17 |
def check(name, condition, detail=''): |
| 18 |
global PASS, FAIL |
| 19 |
if condition: |
| 20 |
print(f'PASS {name}') |
| 21 |
PASS += 1 |
| 22 |
else: |
| 23 |
print(f'FAIL {name}' + (f': {detail}' if detail else '')) |
| 24 |
FAIL += 1 |
| 25 |
|
| 26 |
|
| 27 |
# --------------------------------------------------------------------------- |
| 28 |
# 1. KalmanFilter — constant-velocity 1-D tracking |
| 29 |
# --------------------------------------------------------------------------- |
| 30 |
def test_kalman_filter(): |
| 31 |
from filterpy.kalman import KalmanFilter |
| 32 |
|
| 33 |
dt = 1.0 |
| 34 |
kf = KalmanFilter(dim_x=2, dim_z=1) |
| 35 |
kf.F = np.array([[1., dt], [0., 1.]]) |
| 36 |
kf.H = np.array([[1., 0.]]) |
| 37 |
kf.R = np.array([[5.]]) |
| 38 |
kf.Q = np.array([[0.1, 0.1], [0.1, 0.1]]) |
| 39 |
kf.x = np.array([[0.], [1.]]) |
| 40 |
kf.P = np.eye(2) * 500. |
| 41 |
|
| 42 |
true_pos = 0. |
| 43 |
errors_early, errors_late = [], [] |
| 44 |
for i in range(60): |
| 45 |
true_pos += 1.0 |
| 46 |
z = true_pos + np.random.randn() * np.sqrt(5.) |
| 47 |
kf.predict() |
| 48 |
kf.update(np.array([[z]])) |
| 49 |
err = abs(kf.x[0, 0] - true_pos) |
| 50 |
if i < 10: |
| 51 |
errors_early.append(err) |
| 52 |
if i >= 50: |
| 53 |
errors_late.append(err) |
| 54 |
|
| 55 |
check('KalmanFilter: converges (late error < early error)', |
| 56 |
np.mean(errors_late) < np.mean(errors_early)) |
| 57 |
check('KalmanFilter: late position error < 2.0', |
| 58 |
np.mean(errors_late) < 2.0, |
| 59 |
f'mean late error={np.mean(errors_late):.3f}') |
| 60 |
check('KalmanFilter: covariance is positive definite', |
| 61 |
np.all(np.linalg.eigvals(kf.P) > 0)) |
| 62 |
|
| 63 |
|
| 64 |
# --------------------------------------------------------------------------- |
| 65 |
# 2. UnscentedKalmanFilter — nonlinear radar (range/bearing) tracking |
| 66 |
# --------------------------------------------------------------------------- |
| 67 |
def test_ukf(): |
| 68 |
from filterpy.kalman import UnscentedKalmanFilter, MerweScaledSigmaPoints |
| 69 |
|
| 70 |
def fx(x, dt): |
| 71 |
return np.array([x[0] + x[1]*dt, x[1], x[2] + x[3]*dt, x[3]]) |
| 72 |
|
| 73 |
def hx(x): |
| 74 |
r = np.sqrt(x[0]**2 + x[2]**2) |
| 75 |
b = np.arctan2(x[2], x[0]) |
| 76 |
return np.array([r, b]) |
| 77 |
|
| 78 |
dt = 0.1 |
| 79 |
points = MerweScaledSigmaPoints(4, alpha=0.1, beta=2., kappa=-1.) |
| 80 |
ukf = UnscentedKalmanFilter(dim_x=4, dim_z=2, dt=dt, fx=fx, hx=hx, |
| 81 |
points=points) |
| 82 |
ukf.x = np.array([100., 0., 100., -1.]) |
| 83 |
ukf.P = np.diag([1., 0.1, 1., 0.1]) |
| 84 |
ukf.R = np.diag([0.5, 0.01]) |
| 85 |
ukf.Q = np.diag([0.01, 0.001, 0.01, 0.001]) |
| 86 |
|
| 87 |
true_x = np.array([100., 0., 100., -1.]) |
| 88 |
errors_late = [] |
| 89 |
for i in range(80): |
| 90 |
true_x = fx(true_x, dt) |
| 91 |
z = hx(true_x) + np.random.randn(2) * np.sqrt([0.5, 0.01]) |
| 92 |
ukf.predict() |
| 93 |
ukf.update(z) |
| 94 |
if i >= 60: |
| 95 |
errors_late.append(np.linalg.norm(ukf.x[[0, 2]] - true_x[[0, 2]])) |
| 96 |
|
| 97 |
check('UKF: late position error < 3.0', |
| 98 |
np.mean(errors_late) < 3.0, |
| 99 |
f'mean={np.mean(errors_late):.3f}') |
| 100 |
check('UKF: covariance is symmetric', |
| 101 |
np.allclose(ukf.P, ukf.P.T, atol=1e-10)) |
| 102 |
|
| 103 |
|
| 104 |
# --------------------------------------------------------------------------- |
| 105 |
# 3. GHFilter — constant-velocity g-h filter |
| 106 |
# --------------------------------------------------------------------------- |
| 107 |
def test_gh_filter(): |
| 108 |
from filterpy.gh import GHFilter |
| 109 |
|
| 110 |
f = GHFilter(x=0., dx=1., dt=1., g=0.6, h=0.02) |
| 111 |
true_pos = 0. |
| 112 |
errors_late = [] |
| 113 |
for i in range(50): |
| 114 |
true_pos += 1.0 |
| 115 |
z = true_pos + np.random.randn() * 1.5 |
| 116 |
f.update(z) |
| 117 |
if i >= 40: |
| 118 |
errors_late.append(abs(f.x - true_pos)) |
| 119 |
|
| 120 |
check('GHFilter: late position error < 3.0', |
| 121 |
np.mean(errors_late) < 3.0, |
| 122 |
f'mean={np.mean(errors_late):.3f}') |
| 123 |
check('GHFilter: velocity estimate positive', |
| 124 |
f.dx > 0) |
| 125 |
|
| 126 |
|
| 127 |
# --------------------------------------------------------------------------- |
| 128 |
# 4. discrete_bayes — 1-D hallway localisation |
| 129 |
# --------------------------------------------------------------------------- |
| 130 |
def test_discrete_bayes(): |
| 131 |
from filterpy.discrete_bayes import update, predict |
| 132 |
|
| 133 |
# hallway: 1=door, 0=wall; dog starts at position 3 |
| 134 |
hallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0]) |
| 135 |
prior = np.ones(10) / 10. |
| 136 |
|
| 137 |
# sense door at position 3 (hallway[3]=0), actually a miss — use a door pos |
| 138 |
# Robot at pos 2 (hallway[2]=0), senses correctly |
| 139 |
# Just verify the math: posterior concentrates on door positions |
| 140 |
likelihood = np.array([0.75 if h == 1 else 0.1 for h in hallway]) |
| 141 |
posterior = update(likelihood, prior) |
| 142 |
|
| 143 |
check('discrete_bayes: posterior sums to 1', |
| 144 |
abs(posterior.sum() - 1.0) < 1e-10, |
| 145 |
f'sum={posterior.sum()}') |
| 146 |
check('discrete_bayes: posterior concentrates on doors', |
| 147 |
posterior[0] > posterior[4], |
| 148 |
f'door={posterior[0]:.3f} wall={posterior[4]:.3f}') |
| 149 |
|
| 150 |
# predict: move one step right with some uncertainty |
| 151 |
kernel = np.array([0.1, 0.8, 0.1]) |
| 152 |
moved = predict(posterior, 1, kernel) |
| 153 |
check('discrete_bayes: predict output sums to 1', |
| 154 |
abs(moved.sum() - 1.0) < 1e-10, |
| 155 |
f'sum={moved.sum()}') |
| 156 |
|
| 157 |
|
| 158 |
# --------------------------------------------------------------------------- |
| 159 |
# 5. Monte Carlo resampling — weights concentrate after resampling |
| 160 |
# --------------------------------------------------------------------------- |
| 161 |
def test_monte_carlo(): |
| 162 |
from filterpy.monte_carlo import (systematic_resample, residual_resample, |
| 163 |
stratified_resample, multinomial_resample) |
| 164 |
|
| 165 |
N = 200 |
| 166 |
# give all weight to first 10 particles |
| 167 |
weights = np.zeros(N) |
| 168 |
weights[:10] = 1.0 / 10. |
| 169 |
|
| 170 |
for name, fn in [('systematic', systematic_resample), |
| 171 |
('residual', residual_resample), |
| 172 |
('stratified', stratified_resample), |
| 173 |
('multinomial', multinomial_resample)]: |
| 174 |
indices = fn(weights) |
| 175 |
check(f'MC resample {name}: returns N indices', |
| 176 |
len(indices) == N) |
| 177 |
check(f'MC resample {name}: indices in range', |
| 178 |
indices.max() < N and indices.min() >= 0) |
| 179 |
# most indices should be from the high-weight region (0-9) |
| 180 |
frac_high = np.mean(indices < 10) |
| 181 |
check(f'MC resample {name}: high-weight particles dominate', |
| 182 |
frac_high > 0.8, |
| 183 |
f'fraction from high-weight region={frac_high:.2f}') |
| 184 |
|
| 185 |
|
| 186 |
# --------------------------------------------------------------------------- |
| 187 |
# 6. EnsembleKalmanFilter — constant signal tracking |
| 188 |
# --------------------------------------------------------------------------- |
| 189 |
def test_ensemble_kalman(): |
| 190 |
from filterpy.kalman import EnsembleKalmanFilter |
| 191 |
|
| 192 |
def hx(x): |
| 193 |
return np.array([x[0]]) |
| 194 |
|
| 195 |
def fx(x, dt): |
| 196 |
return x |
| 197 |
|
| 198 |
N = 50 |
| 199 |
enkf = EnsembleKalmanFilter(x=np.array([0.]), P=np.array([[2.]]), dim_z=1, |
| 200 |
dt=1., N=N, hx=hx, fx=fx) |
| 201 |
enkf.R = np.array([[1.]]) |
| 202 |
|
| 203 |
true_val = 5.0 |
| 204 |
errors_late = [] |
| 205 |
for i in range(40): |
| 206 |
z = np.array([true_val + np.random.randn()]) |
| 207 |
enkf.predict() |
| 208 |
enkf.update(z) |
| 209 |
if i >= 30: |
| 210 |
errors_late.append(abs(enkf.x[0] - true_val)) |
| 211 |
|
| 212 |
check('EnKF: late error < 1.0', |
| 213 |
np.mean(errors_late) < 1.0, |
| 214 |
f'mean={np.mean(errors_late):.3f}') |
| 215 |
|
| 216 |
|
| 217 |
# --------------------------------------------------------------------------- |
| 218 |
# 7. FixedLagSmoother — smoother improves on filter |
| 219 |
# --------------------------------------------------------------------------- |
| 220 |
def test_fixed_lag_smoother(): |
| 221 |
from filterpy.kalman import FixedLagSmoother |
| 222 |
|
| 223 |
dt = 1. |
| 224 |
fls = FixedLagSmoother(dim_x=2, dim_z=1, N=4) |
| 225 |
fls.F = np.array([[1., dt], [0., 1.]]) |
| 226 |
fls.H = np.array([[1., 0.]]) |
| 227 |
fls.R = np.array([[10.]]) |
| 228 |
fls.Q = np.array([[0.01, 0.], [0., 0.01]]) |
| 229 |
fls.x = np.array([[0.], [1.]]) |
| 230 |
fls.P = np.eye(2) * 100. |
| 231 |
|
| 232 |
true_pos = 0. |
| 233 |
for i in range(50): |
| 234 |
true_pos += 1.0 |
| 235 |
z = true_pos + np.random.randn() * np.sqrt(10.) |
| 236 |
fls.smooth(z) |
| 237 |
|
| 238 |
check('FixedLagSmoother: produces smoothed estimates', |
| 239 |
len(fls.xSmooth) > 0) |
| 240 |
check('FixedLagSmoother: smoothed values are finite', |
| 241 |
all(np.isfinite(fls.xSmooth[-1].flatten()))) |
| 242 |
|
| 243 |
|
| 244 |
# --------------------------------------------------------------------------- |
| 245 |
# Run all tests |
| 246 |
# --------------------------------------------------------------------------- |
| 247 |
test_kalman_filter() |
| 248 |
test_ukf() |
| 249 |
test_gh_filter() |
| 250 |
test_discrete_bayes() |
| 251 |
test_monte_carlo() |
| 252 |
test_ensemble_kalman() |
| 253 |
test_fixed_lag_smoother() |
| 254 |
|
| 255 |
print(f'\n{PASS} passed, {FAIL} failed') |
| 256 |
sys.exit(0 if FAIL == 0 else 1) |