This repository has been archived by the owner on Aug 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
srif.go
340 lines (304 loc) · 10.3 KB
/
srif.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package gokalman
import (
"errors"
"fmt"
"math"
"github.com/gonum/matrix/mat64"
)
// NewSRIF returns a new Square Root Information Filter.
// It uses the algorithms from "Statistical Orbit determination" by Tapley, Schutz & Born.
// Set nonTriR to `true` to NOT use the Householder transformation on \bar{R_k}.
func NewSRIF(x0 *mat64.Vector, P0 mat64.Symmetric, measSize int, nonTriR bool, n Noise) (*SRIF, *SRIFEstimate, error) {
// Check the dimensions of each matrix to avoid errors.
if err := checkMatDims(x0, P0, "x0", "P0", rows2cols); err != nil {
return nil, nil, err
}
// Get the initial information matrix, I0.
// NOTE: P0 is always diagonal, so we can just invert each component.
r, _ := P0.Dims()
I0 := mat64.NewSymDense(r, nil)
for i := 0; i < r; i++ {
I0.SetSym(i, i, 1/P0.At(i, i))
}
// Compute the cholesky factorization of the information matrix.
var R0chol mat64.Cholesky
R0chol.Factorize(I0)
var R0tri mat64.TriDense
R0tri.LFromCholesky(&R0chol)
var R0 mat64.Dense
R0.Clone(&R0tri)
b0 := mat64.NewVector(r, nil)
b0.MulVec(&R0, x0)
// Compute the square root of the measurement noise.
var sqrtRchol mat64.Cholesky
sqrtRchol.Factorize(n.MeasurementMatrix())
var sqrtMeasNoise mat64.TriDense
sqrtMeasNoise.LFromCholesky(&sqrtRchol)
var sqrtInvNoise mat64.Dense
if err := sqrtInvNoise.Inverse(&sqrtMeasNoise); err != nil {
return nil, nil, err
}
// Populate with the initial values.
est0 := NewSRIFEstimate(nil, b0, nil, nil, &R0, &R0)
return &SRIF{nil, nil, &sqrtMeasNoise, &est0, nonTriR, true, measSize, 0}, &est0, nil
}
// SRIF defines a square root information filter for non-linear dynamical systems. Use NewSquareRootInformation to initialize.
type SRIF struct {
Φ, Htilde *mat64.Dense
sqrtInvNoise mat64.Matrix
prevEst *SRIFEstimate
nonTriR bool // Do not a triangular R
locked bool // Locks the KF to ensure Prepare is called.
measSize int // Stores the measurement vector size, needed only for Predict()
step int
}
// EKFEnabled always returns false.
func (kf *SRIF) EKFEnabled() bool {
return false
}
// DisableEKF does nothing.
func (kf *SRIF) DisableEKF() {}
// EnableEKF does nothing.
func (kf *SRIF) EnableEKF() {}
// PreparePNT does nothing.
func (kf *SRIF) PreparePNT(Γ *mat64.Dense) {}
// SetNoise updates the Noise.
func (kf *SRIF) SetNoise(n Noise) {
panic("noise not yet supported for SRIF")
}
// Prepare unlocks the KF ready for the next Update call.
func (kf *SRIF) Prepare(Φ, Htilde *mat64.Dense) {
kf.Φ = Φ
kf.Htilde = Htilde
kf.locked = false
}
// Update computes a full time and measurement update.
// Will return an error if the KF is locked (call Prepare to unlock).
func (kf *SRIF) Update(realObservation, computedObservation *mat64.Vector) (est Estimate, err error) {
return kf.fullUpdate(false, realObservation, computedObservation)
}
// Predict computes only the time update (or prediction).
// Will return an error if the KF is locked (call Prepare to unlock).
func (kf *SRIF) Predict() (est Estimate, err error) {
return kf.fullUpdate(true, nil, nil)
}
// fullUpdate performs all the steps of an update and allows to stop right after the pure prediction (or time update) step.
func (kf *SRIF) fullUpdate(purePrediction bool, realObservation, computedObservation *mat64.Vector) (est Estimate, err error) {
if kf.locked {
return nil, errors.New("kf is locked (call Prepare() first)")
}
if !purePrediction {
if err = checkMatDims(realObservation, computedObservation, "real observation", "computed observation", rowsAndcols); err != nil {
return nil, err
}
}
// RBar
var RBar, invΦ mat64.Dense
if ierr := invΦ.Inverse(kf.Φ); ierr != nil {
return nil, fmt.Errorf("could not invert `Φ` at k=%d: %s", kf.step, ierr)
}
RBar.Mul(kf.prevEst.R, &invΦ)
var xBar, bBar mat64.Vector
xBar.MulVec(kf.Φ, kf.prevEst.State())
bBar.MulVec(&RBar, &xBar)
if !kf.nonTriR {
// Make Rbar triangular.
rR, _ := RBar.Dims()
A := mat64.NewDense(rR, rR+1, nil)
A.Augment(&RBar, &bBar)
// Extract the new RBar and bBar
RBar = *(A.Slice(0, rR, 0, rR).(*mat64.Dense))
bBarMat := A.Slice(0, rR, rR, rR+1)
for i := 0; i < rR; i++ {
bBar.SetVec(i, bBarMat.At(i, 0))
}
}
if purePrediction {
tmpEst := NewSRIFEstimate(kf.Φ, &bBar, mat64.NewVector(kf.measSize, nil), mat64.NewVector(kf.measSize, nil), &RBar, &RBar)
est = &tmpEst
kf.prevEst = est.(*SRIFEstimate)
kf.step++
kf.locked = true
return
}
// Compute observation deviation y
var y mat64.Vector
y.SubVec(realObservation, computedObservation)
// Whiten the H and y
var Htilde mat64.Dense
Htilde.Mul(kf.sqrtInvNoise, kf.Htilde)
y.MulVec(kf.sqrtInvNoise, &y)
Rk, bk, _, err := measurementSRIFUpdate(&RBar, &Htilde, &bBar, &y)
if err != nil {
return nil, err
}
tmpEst := NewSRIFEstimate(kf.Φ, bk, realObservation, &y, Rk, &RBar)
est = &tmpEst
kf.prevEst = est.(*SRIFEstimate)
kf.step++
kf.locked = true
return
}
// SmoothAll will smooth all the previous estimates using the provided data. Returns the smoothed estimates.
// Will return an error if there are more estimates than there should be.
// WARNING: overwrites the provided array of estimates.
func (kf *SRIF) SmoothAll(estimates []*SRIFEstimate) (err error) {
if len(estimates) != kf.step {
return fmt.Errorf("incorrect number of estimates provided: %d instead of expected %d\n", len(estimates), kf.step)
}
l := len(estimates) - 1
for k := l - 1; k >= 0; k-- {
estimateKp1 := estimates[k+1]
// SNC was not enabled for this estimate.
var S, SP, SPSt mat64.Dense
if ierr := S.Inverse(estimateKp1.Φ); ierr != nil {
return errors.New("provided STM Φ is not invertible")
}
SP.Mul(&S, estimateKp1.Covariance())
SPSt.Mul(&SP, S.T())
var xHat mat64.Vector
xHat.MulVec(&S, estimateKp1.State())
Pkl, serr := AsSymDense(&SPSt)
if serr != nil {
err = serr
return
}
// WARNING: We do not update the actual values to compute the state and covariance, only the cached values.
estimates[k].cachedState = &xHat
estimates[k].cCovar = Pkl
}
return
}
// SRIFEstimate is the output of each update state of the Vanilla KF.
// It implements the Estimate interface.
type SRIFEstimate struct {
Φ *mat64.Dense // Used for smoothing
sqinfoState, meas *mat64.Vector
Δobs, cachedState *mat64.Vector
R, predR *mat64.Dense
cCovar, cPredCovar mat64.Symmetric
}
// IsWithinNσ returns whether the estimation is within the 2σ bounds.
func (e SRIFEstimate) IsWithinNσ(N float64) bool {
state := e.State()
covar := e.Covariance()
for i := 0; i < state.Len(); i++ {
nσ := N * math.Sqrt(covar.At(i, i))
if state.At(i, 0) > nσ || state.At(i, 0) < -nσ {
return false
}
}
return true
}
// IsWithin2σ returns whether the estimation is within the 2σ bounds.
func (e SRIFEstimate) IsWithin2σ() bool {
return e.IsWithinNσ(2)
}
// State implements the Estimate interface.
func (e SRIFEstimate) State() *mat64.Vector {
if e.cachedState == nil {
rState, _ := e.sqinfoState.Dims()
e.cachedState = mat64.NewVector(rState, nil)
var rInv mat64.Dense
if err := rInv.Inverse(e.R); err != nil {
panic(fmt.Errorf("cannot invert R: %s", err))
}
e.cachedState.MulVec(&rInv, e.sqinfoState)
}
return e.cachedState
}
// Innovation implements the Estimate interface.
func (e SRIFEstimate) Innovation() *mat64.Vector {
return e.sqinfoState
}
// Measurement implements the Estimate interface.
func (e SRIFEstimate) Measurement() *mat64.Vector {
return e.meas
}
// ObservationDev returns the observation deviation.
func (e SRIFEstimate) ObservationDev() *mat64.Vector {
return e.Δobs
}
// Covariance implements the Estimate interface.
func (e SRIFEstimate) Covariance() mat64.Symmetric {
if e.cCovar == nil {
var invR mat64.Dense
if err := invR.Inverse(e.R); err != nil {
fmt.Printf("gokalman: SRIF: R is not (yet) invertible: %s\n%+v\n", err, mat64.Formatted(e.R))
return e.cCovar
}
var tmpCovar mat64.Dense
tmpCovar.Mul(&invR, invR.T())
cCovar, _ := AsSymDense(&tmpCovar)
e.cCovar = cCovar
}
return e.cCovar
}
// PredCovariance implements the Estimate interface.
func (e SRIFEstimate) PredCovariance() mat64.Symmetric {
if e.cPredCovar == nil {
var invPredR mat64.Dense
if err := invPredR.Inverse(e.predR); err != nil {
fmt.Printf("gokalman: SRIF: R is not (yet) invertible: %s\n%+v\n", err, mat64.Formatted(e.R))
return e.cCovar
}
var tmpPredCovar mat64.Dense
tmpPredCovar.Mul(&invPredR, invPredR.T())
preccCovar, _ := AsSymDense(&tmpPredCovar)
e.cPredCovar = preccCovar
}
return e.cPredCovar
}
func (e SRIFEstimate) String() string {
state := mat64.Formatted(e.State(), mat64.Prefix(" "))
meas := mat64.Formatted(e.Measurement(), mat64.Prefix(" "))
covar := mat64.Formatted(e.Covariance(), mat64.Prefix(" "))
predp := mat64.Formatted(e.PredCovariance(), mat64.Prefix(" "))
return fmt.Sprintf("{\ns=%v\ny=%v\nP=%v\nP-=%v\n}", state, meas, covar, predp)
}
// NewSRIFEstimate initializes a new SRIFEstimate.
// NOTE: R0 and predR0 are mat64.Dense for simplicity of implementation, but they should be symmetric.
func NewSRIFEstimate(Φ *mat64.Dense, sqinfoState, meas, Δobs *mat64.Vector, R0, predR0 *mat64.Dense) SRIFEstimate {
return SRIFEstimate{Φ, sqinfoState, meas, Δobs, nil, R0, predR0, nil, nil}
}
// measurementSRIFUpdate prepare the matrix and performs the Householder transformation.
func measurementSRIFUpdate(R, H *mat64.Dense, b, y *mat64.Vector) (*mat64.Dense, *mat64.Vector, *mat64.Vector, error) {
if err := checkMatDims(R, H, "R", "H", cols2cols); err != nil {
return nil, nil, nil, err
}
if err := checkMatDims(R, b, "R", "b", rows2rows); err != nil {
return nil, nil, nil, err
}
if err := checkMatDims(H, y, "H", "y", rows2rows); err != nil {
return nil, nil, nil, err
}
n, _ := b.Dims()
m, _ := y.Dims()
A0 := mat64.NewDense(m+n, n, nil)
A0.Stack(R, H)
col := mat64.NewVector(m+n, nil)
for i := 0; i < m+n; i++ {
if i < n {
col.SetVec(i, b.At(i, 0))
} else {
col.SetVec(i, y.At(i-n, 0))
}
}
A := mat64.NewDense(m+n, n+1, nil)
A.Augment(A0, col)
HouseholderTransf(A, n, m)
// Extract the data.
Rk := A.Slice(0, n, 0, n).(*mat64.Dense)
bkMat := A.Slice(0, n, n, n+1)
bk := mat64.NewVector(n, nil)
for i := 0; i < n; i++ {
bk.SetVec(i, bkMat.At(i, 0))
}
ekMat := A.Slice(n, n+m, n, n+1)
er, _ := ekMat.Dims()
ek := mat64.NewVector(er, nil)
for i := 0; i < er; i++ {
ek.SetVec(i, ekMat.At(i, 0))
}
return Rk, bk, ek, nil
}