Created
October 21, 2020 14:21
-
-
Save slothochdonut/fc238e45772eb05cbee342d22443be6a to your computer and use it in GitHub Desktop.
kalmna filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Distributions, Statistics, LinearAlgebra | |
## simulate sample trajectory | |
μ = [1.0, 0.0] | |
Σ = [0.5 0.0 | |
0.0 0.5] | |
x0 = rand(MultivariateNormal(μ, Σ)) #start point | |
β = [0.0, 0.0] | |
Q = [0.1 0.0 | |
0.0 0.1] | |
T = 1:10 | |
# bulid trajectory | |
function sample_trajectory(x, T, β, Q) | |
s = [x] | |
for t in T | |
x = x + rand(MultivariateNormal(β, Q)) | |
push!(s, x) | |
end | |
return s | |
end | |
s = sample_trajectory(x0, T, β, Q) | |
using Makie | |
lines(first.(s), last.(s)) #real trajectory | |
# add some noise | |
function noise(s, β, Q) | |
s0 = [copy(m) for m in s] | |
for t in 1:11 | |
s0[t] = s0[t] + rand(MultivariateNormal(β, Q)) | |
end | |
return(s0) | |
end | |
noised_s = noise(s, β, Q) | |
scatter!(first.(noised_s), last.(noised_s)) #observed trajectory | |
F = Matrix{Float64}(I, 2, 2) | |
P = I | |
function predict(x, F, P, Q) | |
x = F*x | |
P = F*P*F' + Q | |
x, P | |
end | |
# H: observation matrix | |
# F: state-trasition | |
# Q: the covariance of the process noise | |
# R: the covariance of the observation noise | |
H = Matrix{Float64}(I, 2, 2) | |
R = Q | |
function correct(x, y, Ppred, R, H) | |
yres = y - H*x # innovation residual | |
S = (H*Ppred*H' + R) # innovation covariance | |
K = Ppred*H'/S # Kalman gain | |
x = x + K*yres | |
P = (I - K*H)*Ppred*(I - K*H)' + K*R*K' # Joseph form | |
x, P, yres, S | |
end | |
path = [x0] | |
x = predict(noised_s[1], F, P, Q)[1] | |
for i in 1:11 | |
pre = predict(x, F, P, Q) | |
x = pre[1] | |
P = pre[2] | |
filter_s = correct(x, noised_s[i], P, R, H) | |
x = filter_s[1] | |
P = filter_s[2] | |
push!(path, x) | |
end | |
lines!(first.(path), last.(path), linestyle = :dash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working: