/
main.go
137 lines (106 loc) · 2.14 KB
/
main.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
package kalman
import (
"errors"
"github.com/gonum/matrix/mat64"
)
// Config represents config for filter
type Config struct {
// x = F@x + G@v, v ~ N(O,Q)
F *mat64.Dense
G *mat64.Dense
Q *mat64.Dense
// y = H@x + w, w ~ N(O,R)
H *mat64.Dense
R *mat64.Dense
}
// Filter represents kalman filter
type Filter struct {
Config
// Identical Matrix
I *mat64.Dense
// Internal States
X *mat64.Vector
V *mat64.Dense
}
// New creates a new kalman filter instance
func New(c *Config) (*Filter, error) {
//
// dimensions
//
rF, cF := c.F.Dims()
rG, cG := c.G.Dims()
rQ, cQ := c.Q.Dims()
rH, cH := c.H.Dims()
rR, cR := c.R.Dims()
//
// validate
//
if rF != cF {
return nil, errors.New("F must be square matrix")
}
if rQ != cQ {
return nil, errors.New("Q must be square matrix")
}
if rR != cR {
return nil, errors.New("R must be square matrix")
}
if rF != rG {
return nil, errors.New("row dim of F must be matched to row dim of G")
}
if cG != rQ {
return nil, errors.New("column dim of G must be matched to row dim of Q")
}
if cH != cF {
return nil, errors.New("column dim of H must be matched to column dim of F")
}
if rH != rR {
return nil, errors.New("row dim of H must be matched to row dim of R")
}
// init internal states
x := mat64.NewVector(cF, nil)
v := mat64.NewDense(rF, cF, nil)
ident := mat64.NewDense(rF, cF, nil)
for i := 0; i < rF; i++ {
ident.Set(i, i, 1.0)
}
return &Filter{
Config: *c,
I: ident,
X: x,
V: v,
}, nil
}
// Init initializes internal filter states
func (f *Filter) Init(x *mat64.Vector, v mat64.Matrix) error {
rF, cF := f.F.Dims()
//
// X
//
if x == nil {
f.X = mat64.NewVector(cF, nil)
} else {
rX, _ := x.Dims()
if rX != cF {
return errors.New("row dim of x must be matched to column dim of F")
}
f.X = x
}
//
// V
//
if v == nil {
var m *mat64.Dense
m.Mul(f.G, f.Q)
f.V.Mul(m, f.G.T())
} else {
rV, cV := v.Dims()
if rV != cV {
return errors.New("V must be square matrix")
}
if rV != rF {
return errors.New("row dim of V must be matched to row dim of F")
}
f.V = mat64.DenseCopyOf(v)
}
return nil
}