Skip to content

Commit a27080e

Browse files
committed
reduce allocation all Kalman Filters
1 parent e97e607 commit a27080e

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

src/estimator/kalman.jl

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,10 @@ The [`SteadyKalmanFilter`](@ref) updates it with the precomputed Kalman gain ``\
182182
function update_estimate!(estim::SteadyKalmanFilter, u, ym, d=empty(estim.x̂))
183183
Â, B̂u, B̂d, Ĉm, D̂dm = estim.Â, estim.B̂u, estim.B̂d, estim.Ĉm, estim.D̂dm
184184
x̂, K̂ = estim.x̂, estim.
185-
x̂[:] =*+ B̂u*u + B̂d*d +*(ym - Ĉm*- D̂dm*d)
185+
v̂, x̂LHS = similar(ym), similar(x̂)
186+
# in-place operations to recuce allocations:
187+
v̂ .= ym .- Ĉm*.- D̂dm*d
188+
x̂ .= mul!(x̂LHS, Â, x̂) .+ mul!(x̂LHS, B̂u, u) .+ mul!(x̂LHS, B̂d, d) .+ mul!(x̂LHS, K̂, v̂)
186189
return nothing
187190
end
188191

@@ -579,9 +582,9 @@ function update_estimate!(estim::UnscentedKalmanFilter{NT}, u, ym, d) where NT<:
579582
= Hermitian(Ȳm ** Ȳm' + R̂, :L)
580583
mul!(K̂, X̄, lmul!(Ŝ, Ȳm'))
581584
rdiv!(K̂, cholesky(M̂))
582-
v̂m = ŷm
583-
v̂m .= ym .- ŷm
584-
x̂_cor =+* v̂m
585+
= ŷm
586+
.= ym .- ŷm
587+
x̂_cor =+*
585588
P̂_cor =- Hermitian(K̂ **', :L)
586589
# --- prediction step ---
587590
X̂_cor, sqrt_P̂_cor = X̂, sqrt_P̂
@@ -594,9 +597,9 @@ function update_estimate!(estim::UnscentedKalmanFilter{NT}, u, ym, d) where NT<:
594597
for j in axes(X̂_next, 2)
595598
X̂_next[:, j] = @views (estim, estim.model, X̂_cor[:, j], u, d)
596599
end
597-
mul!(x̂, X̂_next, m̂)
600+
x̂_next = mul!(x̂, X̂_next, m̂)
598601
X̄_next = X̂_next
599-
X̄_next .= X̂_next .-
602+
X̄_next .= X̂_next .- x̂_next
600603
.data .= X̄_next ** X̄_next' .+# .data is necessary for Hermitians
601604
return nothing
602605
end
@@ -796,12 +799,14 @@ only the covariance `P̂` is updated.
796799
function update_estimate_kf!(estim, u, ym, d, Â, Ĉm, P̂, x̂=nothing)
797800
Q̂, R̂, M̂ = estim.Q̂, estim.R̂, estim.
798801
mul!(M̂, P̂, Ĉm')
799-
rdiv!(M̂, cholesky!(Hermitian(Ĉm ** Ĉm' + R̂)))
802+
rdiv!(M̂, cholesky!(Hermitian(Ĉm ** Ĉm' .+ R̂)))
800803
if !isnothing(x̂)
801804
mul!(estim.K̂, Â, M̂)
802805
ŷm = @views (estim, estim.model, x̂, d)[estim.i_ym]
803-
x̂ .= (estim, estim.model, x̂, u, d) .+ estim.* (ym - ŷm)
806+
= ŷm
807+
v̂ .= ym .- ŷm
808+
x̂ .= (estim, estim.model, x̂, u, d) .+ mul!(x̂, estim.K̂, v̂)
804809
end
805-
.data .=* (P̂ -* Ĉm * P̂) *' +# .data is necessary for Hermitians
810+
.data .=* (P̂ .-* Ĉm * P̂) *' .+# .data is necessary for Hermitians
806811
return nothing
807812
end

0 commit comments

Comments
 (0)