SignalFilters/Code_Python/KalmanFilter.py

68 wiersze
1.2 KiB
Python
Czysty Zwykły widok Historia

2020-06-15 12:08:33 +00:00
"""
- generalize to N and M
2020-06-14 11:24:04 +00:00
2020-06-15 12:08:33 +00:00
M = 1
N = 2
"""
2020-06-14 11:24:04 +00:00
import numpy as np
dt = 1.
2020-06-15 12:08:33 +00:00
measurements = np.array([ 1., 2., 3., 4., 5., 6., 7., 8, 9, 10])
# State vector
# (N, 1)
2020-06-14 11:24:04 +00:00
x = np.array([[ 0. ],
[ 0. ]])
2020-06-15 12:08:33 +00:00
# Prediction uncertainty (covariance matrix of x)
# (N, N)
2020-06-14 11:24:04 +00:00
P = np.array([[ 1000., 0. ],
[ 0., 1000. ]])
2020-06-15 12:08:33 +00:00
2020-06-14 11:24:04 +00:00
# External motion
2020-06-15 12:08:33 +00:00
# (N, 1)
2020-06-14 11:24:04 +00:00
U = np.array([[ 0. ],
[ 0. ]])
2020-06-15 12:08:33 +00:00
# Update matrix (state transition matrix)
# (N, N)
2020-06-14 11:24:04 +00:00
F = np.array([[ 1., dt ],
[ 0., 1. ]])
2020-06-15 12:08:33 +00:00
# Measurement function (extraction matrix)
# (M, N)
2020-06-14 11:24:04 +00:00
H = np.array([[ 1., 0. ]])
2020-06-15 12:08:33 +00:00
# Measurement uncertainty/noise (covariance matrix of z)
# (M, M)
2020-06-14 11:24:04 +00:00
R = np.array([[ 1. ]])
2020-06-15 12:08:33 +00:00
# z = measurament vector
# (M, 1)
2020-06-14 11:24:04 +00:00
def filter(x, P):
2020-06-15 12:08:33 +00:00
step = 0
for z in (measurements):
step += 1
print("step = ", step, " meas. = ", z)
2020-06-14 11:24:04 +00:00
# Measurement
2020-06-15 12:08:33 +00:00
S = H @ P @ H.T + R # (M, M)
K = P @ H.T @ np.linalg.inv(S) # (N, M)
y = z - H @ x
xp = x + K @ y
Pp = P - K @ H @ P
2020-06-14 11:24:04 +00:00
# Prediction
2020-06-15 12:08:33 +00:00
x = F @ xp + U
P = F @ Pp @ F.T
2020-06-14 11:24:04 +00:00
2020-06-15 12:08:33 +00:00
print('x =')
print(x)
print('P =')
print(P)
2020-06-14 11:24:04 +00:00
filter(x, P)