-
Notifications
You must be signed in to change notification settings - Fork 0
/
estimators.py
1774 lines (1500 loc) · 74.7 KB
/
estimators.py
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import numpy.matlib
import numpy as np
from scipy.linalg import block_diag
from scipy.special import comb
from scipy.optimize import least_squares
import itertools
from collections import Iterable
try:
import torch
torch_imported = True
except ImportError:
print("Unable to import pytorch module")
torch_imported = False
def sample_gaussian(mu, Sigma, N=1):
"""
Draw N random row vectors from a Gaussian distribution
Args:
mu (numpy array [n x 1]): expected value vector
Sigma (numpy array [n x n]): covariance matrix
N (int): scalar number of samples
Returns:
M (numpy array [n x N]): samples from Gaussian distribtion
"""
N = int(N)
n = len(mu)
U, s, V = np.linalg.svd(Sigma)
S = np.zeros(Sigma.shape)
for i in range(min(Sigma.shape)):
S[i, i] = math.sqrt(s[i])
M = np.random.normal(size=(n, N))
M = np.dot(np.dot(U, S), M) + mu
return M
def kinematic_state_observer(initial_cond, yaw_rates, inertial_accs, long_vs, T, alpha):
"""
Not working yet!
"""
num_sol = len(T)
states = np.zeros((2, num_sol))
states[:, 0] = np.squeeze(initial_cond[3:5])
# fixed matrices
C = np.array([1, 0])
B = np.identity(2)
A = np.zeros((2, 2))
for i in range(1, num_sol):
# current yaw rate
yaw_rate = yaw_rates[i-1]
# put yaw_rate in A matrix
A[0, 1] = yaw_rate
A[1, 0] = -yaw_rate
# gain matrix based on yaw rate
K = 1.0*np.array([2*alpha*math.fabs(yaw_rate),
(alpha**2 - 1)*yaw_rate])
# state observer equation
states_dot = np.matmul(
(A - np.matmul(K, C)), states[:, i-1]) + np.matmul(B, inertial_accs[:, i-1]) + K*long_vs[i-1]
dt = T[i] - T[i-1]
states[:, i] = states[:, i-1] + dt*states_dot
return states
class PointBasedFilter(object):
"""
Class for performing UKF/CKF prediction or update
Args:
method (str): The method for filtering algorithm, there are two choices: 'UKF' for unscented Filter
and 'CKF' for Cubature Filter
order (int): Order of accuracy for integration rule. Currently, there are two choices: 2 and 4
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False. User has
be careful and make sure that all other inputs are tensors as well
tensor_device (bool): device in which the tensor is located and to be operated (CPU or GPU); defaults
to None which refers to CPU
"""
def __init__(self, method, order, use_torch_tensor=False, tensor_device=None):
methods = ['UKF', 'CKF']
orders = [2, 4]
assert method in methods, "Given method not implemented or doesn't exist. Current methods available are 'UKF' and 'CKF'"
assert order in orders, "Given order not implemented. Current available orders are 2 and 4"
self.method = method
self.order = order
self.use_torch_tensor = use_torch_tensor
# check if torch library was successfully imported
if self.use_torch_tensor:
assert torch_imported, "Pytorch module was not successfully imported which prohibits the use of tensor with this library"
if tensor_device is None:
tensor_device = torch.device("cpu")
assert isinstance(
tensor_device, torch.device), "Supplied tensor_device is a not a torch device object"
self.tensor_device = tensor_device
def predict_and_or_update(self, X, P, f, h, Q, R, u, y, u_next=None, Qu=None, additional_args_pm=[], additional_args_om=[], innovation_bound_func={}, predict_flag=True):
"""
Perform one iteration of prediction and/or update.
algorithm reference: Algorithm 5.1, page 104 of "Compressed Estimation in Coupled High-dimensional Processes"
Args:
X (numpy array [n x 1]): expected value of the states
P (numpy array [n x n]): covariance of the states
f (function): function handle for the process model; expected signature f(state, input, model noise, input noise, ...)
h (function): function handle for the observation model; expected signature h(state, input, noise, ...)
Q (numpy array [nq x nq]): process model noise covariance in the prediction step
R (numpy array [nr x nr]): observation model noise covariance in the update step
u (*): current input required for function f & possibly function h
y (numpy array [nu x 1]): current measurement/output of the system
u_next (*): next input required for function h, defaults to None which will take values of u
Qu (numpy array [nqu x nqu]): input noise covariance in the prediction step
additional_args_pm (list): list of additional arguments to be passed to the process model during the prediction step
additional_args_om (list): list of additional arguments to be passed to the observation model during the update step
innovation_bound_func (dict): dictionary with innovation index as keys and callable function as value to bound
innovation when needed
predict_flag (bool): perform prediction? defaults to true
Returns:
X (numpy array [n x 1]): expected value of the states after prediction and update
P (numpy array [n x n]): covariance of the states after prediction and update
"""
# create augmented system of the states and the noises (step 1 of algorithm 5.1, equation 5.42)
n = len(X)
nq = Q.shape[0]
if Qu is not None:
nqu = Qu.shape[0]
else:
nqu = 0
if self.use_torch_tensor:
Qu = torch.zeros((nqu, nqu), dtype=X.dtype,
device=self.tensor_device)
else:
Qu = np.zeros((nqu, nqu))
nr = R.shape[0]
if self.use_torch_tensor:
X1 = torch.cat(
(X, torch.zeros((nq+nqu+nr, 1), dtype=X.dtype, device=self.tensor_device)), dim=0)
P1 = torch.block_diag(P, Q, Qu, R)
else:
X1 = np.concatenate((X, np.zeros((nq+nqu+nr, 1))), axis=0)
P1 = block_diag(P, Q, Qu, R)
# if next input is not specified, take current one
if u_next is None:
u_next = u
# generate cubature/sigma points and the weights based on the method (steps 2-4 of algorithm 5.1)
if self.method == 'UKF':
if self.order == 2:
x, L, W, WeightMat = self.sigmas2(X1, P1)
elif self.order == 4:
x, L, W, WeightMat = self.sigmas4(X1, P1)
elif self.method == 'CKF':
if self.order == 2:
x, L, W, WeightMat = self.cubature2(X1, P1)
elif self.order == 4:
x, L, W, WeightMat = self.cubature4(X1, P1)
ia = np.arange(n)
if predict_flag:
ib = np.arange(n, n+nq)
ic = np.arange(n+nq, n+nq+nqu)
# prediction step (step 5 of algorithm 5.1) by implementing equations 5.25, 5.34 and 5.35 (pages 105-106)
X2, x2, P2, x2_cent = self.unscented_transformF(
x, W, WeightMat, L, f, u, ia, ib, ic, additional_args_pm)
else:
X2 = X
P2 = P
x2 = x
x2_cent = x[ia, :] - X
# update step (step 6 of algorithm 5.1) by implementing equations 5.36-5.41 (page 106)
if len(y):
# check if innovation keys is valid
for key in innovation_bound_func:
assert key in range(len(
y)), "Key of innovation bound function dictionary should be within the length of the output"
assert callable(
innovation_bound_func[key]), "Innovation bound function is not callable"
ip = np.arange(n+nq+nqu, n+nq+nqu+nr)
Z, _, Pz, z2 = self.unscented_transformH(
x, W, WeightMat, L, h, u_next, ia, ip, len(y), additional_args_om)
if self.use_torch_tensor:
# transformed cross-covariance (equation 5.38)
Pxy = torch.matmul(torch.matmul(x2_cent, WeightMat), z2.T)
# Kalman gain
K = torch.matmul(Pxy, torch.linalg.inv(Pz))
else:
# transformed cross-covariance (equation 5.38)
Pxy = np.matmul(np.matmul(x2_cent, WeightMat), z2.T)
# Kalman gain
K = np.matmul(Pxy, np.linalg.inv(Pz))
# state update (equation 5.40)
innovation = y - Z
for key in innovation_bound_func:
innovation[key, :] = innovation_bound_func[key](
innovation[key, :])
if self.use_torch_tensor:
X3 = X2 + torch.matmul(K, innovation)
# covariance update (equation 5.41)
P3 = P2 - torch.matmul(K, Pxy.T)
else:
X3 = X2 + np.matmul(K, innovation)
# covariance update (equation 5.41)
P3 = P2 - np.matmul(K, Pxy.T)
else:
X3 = X2
P3 = P2
return X3, P3
def unscented_transformH(self, x, W, WeightMat, L, f, u, ia, iq, n, additional_args):
"""
Function to propagate sigma/cubature points through observation function.
Args:
x (numpy array [n_a x L]): sigma/cubature points
W (numpy array [L x 1 or 1 x L]: 1D Weight array
WeightMat (numpy array [L x L]): weight matrix with weights of the points on the diagonal
L (int): number of points
f (function): function handle for the observation model; expected signature f(state, input, noise, ...)
u (?): current input required for function f
ia (numpy array [n_s x 1]): row indices of the states in sima/cubature points
iq (numpy array [n_q x 1]): row indices of the observation noise in sigma/cubature points
n (int): dimensionality of output or return from function f
additional_args (list): list of additional arguments to be passed to the observation model
Returns:
Y (numpy array [n x 1]): Expected value vector of the result from transformation function f
y (numpy array [n x L]): Transformed sigma/cubature points
P (numpy array [n x n]): Covariance matrix of the result from transformation function f
y1 (numpy array [n x L]): zero-mean Transformed sigma/cubature points
"""
if self.use_torch_tensor:
Y = torch.zeros((n, 1), dtype=x.dtype, device=self.tensor_device)
y = torch.zeros((n, L), dtype=x.dtype, device=self.tensor_device)
else:
Y = np.zeros((n, 1))
y = np.zeros((n, L))
# Propagating sigma/cubature points through function (equation 5.36)
for k in range(L):
y[:, k] = f(x[ia, k], u, x[iq, k], *additional_args)
# Calculating mean (equation 5.37)
if self.use_torch_tensor:
Y += W[0, k]*y[:, k:k+1]
else:
Y += W.flat[k]*y[:, k:k+1]
# Calculating covariance (equation 5.39)
y1 = y - Y
if self.use_torch_tensor:
P = torch.matmul(torch.matmul(y1, WeightMat), y1.T)
else:
P = np.matmul(np.matmul(y1, WeightMat), y1.T)
return Y, y, P, y1
def unscented_transformF(self, x, W, WeightMat, L, f, u, ia, iq, iqu, additional_args):
"""
Function to propagate sigma/cubature points through process model function.
Args:
x (numpy array [n_a x L]): sigma/cubature points
W (numpy array [L x 1 or 1 x L]: 1D Weight array of the sigma/cubature points
WeightMat (numpy array [L x L]): weight matrix with weights in W of the points on the diagonal
L (int): number of points
f (function): function handle for the process model; expected signature f(state, input, noise, ...)
u (?): current input required for function f
ia (numpy array [n_s x 1]): row indices of the states in sima/cubature points
iq (numpy array [n_q x 1]): row indices of the process noise in sigma/cubature points
iqu (numpy array [n_qu x 1]): row indices of the input noise in sigma/cubature points
additional_args (list): list of additional arguments to be passed to the process model
Returns:
Y (numpy array [n_s x 1]): Expected value vector of the result from transformation function f
y (numpy array [n_a x L]): Transformed sigma/cubature points
P (numpy array [n_s x n_s]): Covariance matrix of the result from transformation function f
y1 (numpy array [n_s x L]): zero-mean Transformed sigma/cubature points
"""
order = len(ia)
if self.use_torch_tensor:
Y = torch.zeros((order, 1), dtype=x.dtype,
device=self.tensor_device)
else:
Y = np.zeros((order, 1))
y = x
# Propagating sigma/cubature points through function (equation 5.25)
for k in range(L):
if len(iqu):
y[ia, k] = f(x[ia, k], u, x[iq, k],
x[iqu, k], *additional_args)
else:
y[ia, k] = f(x[ia, k], u, x[iq, k], torch.zeros(u.shape, dtype=x.dtype, device=self.tensor_device)
if self.use_torch_tensor else np.zeros(u.shape), *additional_args)
# Calculating mean (equation 5.34)
if self.use_torch_tensor:
Y += W[0, k]*y[np.arange(order), k:k+1]
else:
Y += W.flat[k]*y[np.arange(order), k:k+1]
# Calculating covariance (equation 5.35)
y1 = y[np.arange(order), :] - Y
if self.use_torch_tensor:
P = torch.matmul(torch.matmul(y1, WeightMat), y1.T)
else:
P = np.matmul(np.matmul(y1, WeightMat), y1.T)
return Y, y, P, y1
def sigmas2(self, X, P):
"""
function to generate second order sigma points
reference: Appendix G.1 of "Compressed Estimation in Coupled High-dimensional Processes"
Args:
X (numpy array [n x 1]): mean of Gaussian distribution
P (numpy array [n x n]): covariance matrix of Gaussian distribution
Returns:
x (numpy array [n x L]): second order sigma point
L (int): number of sigma points
W (numpy array [1 x L]): 1D Weight array of sigma points
WeightMat (numpy array [L x L]): weight matrix with weights in W of the points on the diagonal
"""
n = X.shape[0]
# some constants based on augmented dimentionality
Params = [1 - n/3.0, 1.0/6.0, math.sqrt(3.0)]
L = 2*n + 1
W = np.concatenate(
(np.array([[Params[0]]]), np.matlib.repmat(Params[1], 1, 2*n)), axis=1)
WeightMat = np.diag(np.squeeze(W))
if self.use_torch_tensor:
W = torch.from_numpy(W).to(self.tensor_device)
WeightMat = torch.from_numpy(WeightMat).to(self.tensor_device)
# first perform SVD to get the square root matrix (step 3 of algorithm 5.1, equation 5.22)
if self.use_torch_tensor:
U, D, _ = torch.linalg.svd(P)
sqP = torch.matmul(U, torch.diag(D**0.5))
else:
U, D, _ = np.linalg.svd(P)
sqP = np.matmul(U, np.diag(D**0.5))
# create sigma point set (step 2 of algorithm 5.1)
temp = np.zeros((n, L))
loc = np.arange(n)
l_index = loc*L + loc + 1
temp.flat[l_index] = Params[2]
l_index += n
temp.flat[l_index] = -Params[2]
# step 4 of algorithm 5.1 equation 5.24
if self.use_torch_tensor:
temp = torch.from_numpy(temp).to(self.tensor_device)
Y = torch.tile(X, (1, L))
x = Y + torch.matmul(sqP, temp)
else:
Y = np.matlib.repmat(X, 1, L)
x = Y + np.matmul(sqP, temp)
# for debugging
#self.verifySigma(temp, W, 3)
#print(self.verifyTransformedSigma(x, WeightMat, X, P))
return x, L, W, WeightMat
def sigmas4(self, X, P):
"""
function to generate fourth order sigma points
Note: No analytical results exist for generating 4th order sigma points as it requires performing
non-linear least square (see Appendix G.2 of "Compressed Estimation in Coupled High-dimensional Processes".
A separate scheme is used here, see equation 5.20 instead.
Args:
X (numpy array [n x 1]): mean of Gaussian distribution
P (numpy array [n x n]): covariance matrix of Gaussian distribution
Returns:
x (numpy array [n x L]): fourth order sigma point
L (int): number of sigma points
W (numpy array [1 x L]): 1D Weight array of sigma points
WeightMat (numpy array [L x L]): weight matrix with weights in W of the points on the diagonal
"""
n = X.shape[0]
# some constants based on augmented dimensionality
L = 2*n**2 + 1
W = np.concatenate((np.array([[1 + (n**2-7.0*n)/18.0]]), np.matlib.repmat(
(4-n)/18.0, 1, 2*n), np.matlib.repmat(1.0/36.0, 1, 2*n**2-2*n)), axis=1)
WeightMat = np.diag(np.squeeze(W))
if self.use_torch_tensor:
W = torch.from_numpy(W).to(self.tensor_device)
WeightMat = torch.from_numpy(WeightMat).to(self.tensor_device)
# first perform SVD to get the square root matrix (step 3 of algorithm 5.1, equation 5.22)
if self.use_torch_tensor:
U, D, _ = torch.linalg.svd(P)
sqP = torch.matmul(U, torch.diag(D**0.5))
else:
U, D, _ = np.linalg.svd(P)
sqP = np.matmul(U, np.diag(D**0.5))
# create sigma point set (step 2 of algorithm 5.1)
s = math.sqrt(3.0)
temp = np.zeros((n, 2*n+1))
loc = np.arange(n)
l_index = loc*(2*n+1) + loc + 1
temp.flat[l_index] = s
l_index += n
temp.flat[l_index] = -s
# step 4 of algorithm 5.1 equation 5.24
if self.use_torch_tensor:
temp = torch.from_numpy(temp).to(self.tensor_device)
Y = torch.tile(X, (1, 2*n+1))
x = Y + torch.matmul(sqP, temp)
else:
Y = np.matlib.repmat(X, 1, 2*n+1)
x = Y + np.matmul(sqP, temp)
# create second type of sigma point: 2n**2 - 2n points based on (s2,s2) structure (step 2 of algorithm 5.1)
temp1 = np.zeros((n, 2*n**2 - 2*n))
count = comb(n, 2, exact=True)
loc = np.fromiter(itertools.chain.from_iterable(
itertools.combinations(range(n), 2)), int, count=count*2).reshape(-1, 2)
l_index = loc*(2*n**2 - 2*n) + \
np.matlib.repmat(np.arange(count)[:, np.newaxis], 1, 2)
for i in itertools.product([1, 2], repeat=2):
temp1.flat[l_index[:, 0]] = (-1)**i[0]*s
temp1.flat[l_index[:, 1]] = (-1)**i[1]*s
l_index += count
# step 4 of algorithm 5.1 equation 5.24
if self.use_torch_tensor:
temp1 = torch.from_numpy(temp1).to(self.tensor_device)
Y = torch.tile(X, (1, 2*n**2 - 2*n))
x = torch.cat((x, Y + torch.matmul(sqP, temp1)), dim=1)
else:
Y = np.matlib.repmat(X, 1, 2*n**2 - 2*n)
x = np.concatenate((x, Y + np.matmul(sqP, temp1)), axis=1)
# for debugging
"""
if self.use_torch_tensor:
temp2 = torch.cat((temp, temp1), dim=1)
else:
temp2 = np.concatenate((temp, temp1), axis=1)
self.verifySigma(temp2, W, 5)
print(self.verifyTransformedSigma(x, WeightMat, X, P))
"""
return x, L, W, WeightMat
def cubature2(self, X, P):
"""
function to generate second order cubature points
reference: paper "Cubature Kalman Fitlers"
Args:
X (numpy array [n x 1]): mean of Gaussian distribution
P (numpy array [n x n]): covariance matrix of Gaussian distribution
Returns:
x (numpy array [n x L]): second order cubature point
L (int): number of cubature points
W (numpy array [1 x L]): 1D Weight array of cubature points
WeightMat (numpy array [L x L]): weight matrix with weights in W of the points on the diagonal
"""
n = X.shape[0]
# some constants based on augmented dimensionality
L = 2*n
W = np.matlib.repmat(1.0/L, 1, L)
WeightMat = np.diag(np.squeeze(W))
if self.use_torch_tensor:
W = torch.from_numpy(W).to(self.tensor_device)
WeightMat = torch.from_numpy(WeightMat).to(self.tensor_device)
# first perform SVD to get the square root matrix (step 3 of algorithm 5.1, equation 5.22)
if self.use_torch_tensor:
U, D, _ = torch.linalg.svd(P)
sqP = torch.matmul(U, torch.diag(D**0.5))
else:
U, D, _ = np.linalg.svd(P)
sqP = np.matmul(U, np.diag(D**0.5))
# create sigma point set (step 2 of algorithm 5.1)
s = math.sqrt(n)
temp = np.zeros((n, L))
loc = np.arange(n)
l_index = loc*L + loc
temp.flat[l_index] = s
l_index += n
temp.flat[l_index] = -s
# step 4 of algorithm 5.1 equation 5.24
if self.use_torch_tensor:
temp = torch.from_numpy(temp).to(self.tensor_device)
Y = torch.tile(X, (1, L))
x = Y + torch.matmul(sqP, temp)
else:
Y = np.matlib.repmat(X, 1, L)
x = Y + np.matmul(sqP, temp)
# for debugging
#self.verifySigma(temp, W, 2)
#print(self.verifyTransformedSigma(x, WeightMat, X, P))
return x, L, W, WeightMat
def cubature4(self, X, P):
"""
function to generate fourth order cubature points
reference: paper "High-degree cubature kalman filter"
Args:
X (numpy array [n x 1]): mean of Gaussian distribution
P (numpy array [n x n]): covariance matrix of Gaussian distribution
Returns:
x (numpy array [n x L]): fourth order cubature point
L (int): number of cubature points
W (numpy array [1 x L]): 1D Weight array of cubature points
WeightMat (numpy array [L x L]): weight matrix with weights in W of the points on the diagonal
"""
n = X.shape[0]
# some constants based on augmented dimensionality
L = 2*n**2 + 1
W = np.concatenate((np.array([[2.0/(n+2.0)]]), np.matlib.repmat((4-n)/(2.0*(
n+2)**2), 1, 2*n), np.matlib.repmat(1.0/((n+2.0)**2), 1, 2*n**2-2*n)), axis=1)
WeightMat = np.diag(np.squeeze(W))
if self.use_torch_tensor:
W = torch.from_numpy(W).to(self.tensor_device)
WeightMat = torch.from_numpy(WeightMat).to(self.tensor_device)
# first perform SVD to get the square root matrix (step 3 of algorithm 5.1, equation 5.22)
if self.use_torch_tensor:
U, D, _ = torch.linalg.svd(P)
sqP = torch.matmul(U, torch.diag(D**0.5))
else:
U, D, _ = np.linalg.svd(P)
sqP = np.matmul(U, np.diag(D**0.5))
# create sigma point set (step 2 of algorithm 5.1)
s = math.sqrt(n+2.0)
temp = np.zeros((n, 2*n+1))
loc = np.arange(n)
l_index = loc*(2*n+1) + loc + 1
temp.flat[l_index] = s
l_index += n
temp.flat[l_index] = -s
# step 4 of algorithm 5.1 equation 5.24
if self.use_torch_tensor:
temp = torch.from_numpy(temp).to(self.tensor_device)
Y = torch.tile(X, (1, 2*n+1))
x = Y + torch.matmul(sqP, temp)
else:
Y = np.matlib.repmat(X, 1, 2*n+1)
x = Y + np.matmul(sqP, temp)
# create second type of sigma point: 2n**2 - 2n points based on (s2,s2) structure (step 2 of algorithm 5.1)
s = math.sqrt(n+2.0)/math.sqrt(2.0)
temp1 = np.zeros((n, 2*n**2 - 2*n))
count = comb(n, 2, exact=True)
loc = np.fromiter(itertools.chain.from_iterable(
itertools.combinations(range(n), 2)), int, count=count*2).reshape(-1, 2)
l_index = loc*(2*n**2 - 2*n) + \
np.matlib.repmat(np.arange(count)[:, np.newaxis], 1, 2)
for i in itertools.product([1, 2], repeat=2):
temp1.flat[l_index[:, 0]] = (-1)**i[0]*s
temp1.flat[l_index[:, 1]] = (-1)**i[1]*s
l_index += count
# step 4 of algorithm 5.1 equation 5.24
if self.use_torch_tensor:
temp1 = torch.from_numpy(temp1).to(self.tensor_device)
Y = torch.tile(X, (1, 2*n**2 - 2*n))
x = torch.cat((x, Y + torch.matmul(sqP, temp1)), dim=1)
else:
Y = np.matlib.repmat(X, 1, 2*n**2 - 2*n)
x = np.concatenate((x, Y + np.matmul(sqP, temp1)), axis=1)
# for debugging
"""
if self.use_torch_tensor:
temp2 = torch.cat((temp, temp1), dim=1)
else:
temp2 = np.concatenate((temp, temp1), axis=1)
self.verifySigma(temp2, W, 5)
print(self.verifyTransformedSigma(x, WeightMat, X, P))
"""
return x, L, W, WeightMat
def verifyTransformedSigma(self, x, WeightMat, X, P):
"""
Verify if the transformed sigma/cubature point captures the mean and covariance of the
target Gaussian distribution
Args:
x (numpy array [n x L]): sigma/cubature points
WeightMat (numpy array [L x L]): weight matrix with weights of the points on the diagonal
X (numpy array [n x 1]): mean of Gaussian distribution
P (numpy array [n x n]): covariance matrix of Gaussian distribution
Returns:
mean_close (bool): whether mean of the distibution is captured by the sigma/cubature points
cov_close (bool): whether covariance of the distibution is captured by the sigma/cubature points
"""
sigma_mean = np.zeros(X.shape)
if self.use_torch_tensor:
W = np.diag(WeightMat.detach().numpy())
x_copy = x.detach().numpy()
else:
W = np.diag(WeightMat)
x_copy = x
for i in range(x.shape[1]):
sigma_mean += W[i]*x_copy[:, i:i+1]
if self.use_torch_tensor:
sigma_cov = np.matmul(np.matmul(
(x_copy - sigma_mean), WeightMat.detach().numpy()), np.transpose(x_copy - sigma_mean))
mean_close = np.allclose(X.detach().numpy(), sigma_mean)
cov_close = np.allclose(P.detach().numpy(), sigma_cov)
else:
sigma_cov = np.matmul(
np.matmul((x_copy - sigma_mean), WeightMat), np.transpose(x_copy - sigma_mean))
mean_close = np.allclose(X, sigma_mean)
cov_close = np.allclose(P, sigma_cov)
return mean_close, cov_close
def verifySigma(self, x, W, order=2):
"""
Since originally the points of PBGF are generated from standard Gaussian distribution,
check if moments up to specified order are being captured. Raises error when mismatch is found.
Args:
x (numpy array [n x L]): sigma/cubature points
W (numpy array [1 x L or L x 1]): 1D Weight array of sigma/cubature points
order (int): moment order in which the sampled points are generated from
"""
n, L = x.shape
if self.use_torch_tensor:
x_copy = x.detach().numpy()
W_copy = W.detach().numpy()
else:
x_copy = x
W_copy = W
# check moment and cross moment of each order
for i in range(1, order+1):
# find all possible combinations for adding up to order i
arr = [0]*n
outputs = []
findCombinationsUtil(arr, 0, i, i, outputs)
for output in outputs:
theoretical_moment = 1.0
for power in output:
theoretical_moment *= self.stdGaussMoment(power)
if theoretical_moment == 0:
break
elem_combinations = itertools.permutations(
range(n), len(output))
for elem_combination in elem_combinations:
moment = (
W_copy*np.prod(x_copy[elem_combination, :]**np.matlib.repmat(output, L, 1).T, axis=0)).sum()
assert np.isclose(moment, theoretical_moment), "The {}th moment with element {} and power {} yielded value of {} instead of {}".format(
i, elem_combination, output, moment, theoretical_moment)
def stdGaussMoment(self, order):
"""
Calculate order-th moment of univariate standard Gaussian distribution (zero mean, 1 std)
Args:
order (int): scalar moment order
Returns:
prod (int): requested order-th moment of standard Gaussian distribution
"""
if order % 2:
return 0.0
else:
prod = 1.0
for i in range(1, order, 2):
prod *= i
return prod
def findCombinationsUtil(arr, index, num, reducedNum, output):
"""
Find all combinations of < n numbers from 1 to num with repetition that add up to reducedNum
Args:
arr (list size n): current items that add up to <= reducedNum (in the 0th recursion)
index (int): index of the next slot of arr list
num (int): limit of what numbers to be chosen from -> [1, num]
reducedNum (int): remaining number to add up to required sum
output (list): for appending the results to
"""
# Base condition
if reducedNum < 0:
return
# If combination is found, store it
if reducedNum == 0:
output.append(arr[:index])
return
# find pervious number stored
prev = 1 if (index == 0) else arr[index-1]
# start loop from previous number
for k in range(prev, num+1):
# next element of array
arr[index] = k
# recursively try this combination with reduced number
findCombinationsUtil(arr, index+1, num, reducedNum-k, output)
class PointBasedFixedLagSmoother(PointBasedFilter):
"""
Class for performing UKF/CKF fixed-lag smoothing
Args:
method (str): The method for filtering algorithm, there are two choices: 'UKF' for unscented Filter
and 'CKF' for Cubature Filter
order (int): Order of accuracy for integration rule. Currently, there are two choices: 2 and 4
lag_interval (int): lag interval for producing smoothed estimate
"""
def __init__(self, method, order, lag_interval):
super(PointBasedFixedLagSmoother, self).__init__(method, order)
self.lag_interval = lag_interval
# pre-allocate some storage during forward pass (filtering)
self.pred_density = []
self.filter_density = []
self.gain = []
self.init_cond_set = False
self.latest_action = None
self.backward_pass = False
self.prevX = None
self.prevP = None
def set_initial_cond(self, X, P):
"""
Set the initial condition of the smoother, i.e. the distribution at time zero.
Args:
X (numpy array [n x 1]): expected value of the states
P (numpy array [n x n]): covariance of the states
"""
self.init_cond_set = True
self.n = len(X)
self.filter_density.append((X.copy(), P.copy()))
self.latest_action = 'update'
def predict_and_or_update(self, f, h, Q, R, u, y, u_next=None, Qu=None, additional_args_pm=[], additional_args_om=[], innovation_bound_func={}, predict_flag=True):
"""
Perform one iteration of prediction and/or update + backward pass to produce smoothed estimate when applicable.
algorithm reference: Algorithm 10.6, page 162 of "Bayesian Filtering and Smoothing"
Args:
f (function): function handle for the process model; expected signature f(state, input, model noise, input noise, ...)
h (function): function handle for the observation model; expected signature h(state, input, noise, ...)
Q (numpy array [nq x nq]): process model noise covariance in the prediction step
R (numpy array [nr x nr]): observation model noise covariance in the update step
u (*): current input required for function f & possibly function h
y (numpy array [nu x 1]): current measurement/output of the system
u_next (*): next input required for function h, defaults to None which will take values of u
Qu (numpy array [nqu x nqu]): input noise covariance in the prediction step
additional_args_pm (list): list of additional arguments to be passed to the process model during the prediction step
additional_args_om (list): list of additional arguments to be passed to the observation model during the update step
innovation_bound_func (dict): dictionary with innovation index as keys and callable function as value to bound
innovation when needed
predict_flag (bool): perform prediction? defaults to true
Returns:
X_fi (numpy array [n x 1]): fixed-interval list of smoothed expected values of the states with recent prediction & update
P_fi (numpy array [n x n]): fixed-interval list of smoothed covariance of the states with recent prediction & update
smoothed_flag (bool): whether estimate returned is filtered or smoothed estimate; filtered estimate is initially
returned until a lag_length worth of observations have been cumulated.
"""
assert self.init_cond_set, "User must specify the initial condition separately"
# pre-allocate fixed-interval results
X_fi = [[]]*(self.lag_interval+1)
P_fi = [[]]*(self.lag_interval+1)
# create augmented system of the states and the noises (step 1 of algorithm 5.1, equation 5.42)
n = self.n
nq = Q.shape[0]
if Qu is not None:
nqu = Qu.shape[0]
else:
nqu = 0
Qu = np.zeros((nqu, nqu))
nr = R.shape[0]
if self.latest_action == 'update':
X1 = np.concatenate(
(self.filter_density[-1][0], self.filter_density[-1][0], np.zeros((nq+nqu+nr, 1))), axis=0)
P1 = block_diag(
self.filter_density[-1][1], self.filter_density[-1][1], Q, Qu, R)
P1[0:n, n:2*n] = self.filter_density[-1][1]
P1[n:2*n, 0:n] = self.filter_density[-1][1]
else:
X1 = np.concatenate(
(self.prevX, np.zeros((nq+nqu+nr, 1))), axis=0)
P1 = block_diag(self.prevP, Q, Qu, R)
# if next input is not specified, take current one
if u_next is None:
u_next = u
# generate cubature/sigma points and the weights based on the method (steps 2-4 of algorithm 5.1)
if self.method == 'UKF':
if self.order == 2:
x, L, W, WeightMat = self.sigmas2(X1, P1)
elif self.order == 4:
x, L, W, WeightMat = self.sigmas4(X1, P1)
elif self.method == 'CKF':
if self.order == 2:
x, L, W, WeightMat = self.cubature2(X1, P1)
elif self.order == 4:
x, L, W, WeightMat = self.cubature4(X1, P1)
if predict_flag:
# prediction step (step 5 of algorithm 5.1) by implementing equations 5.25, 5.34 and 5.35 (pages 105-106)
ia = np.arange(n)
ib = np.arange(n, 2*n)
iq = np.arange(2*n, 2*n+nq)
iqu = np.arange(2*n+nq, 2*n+nq+nqu)
X, x, P, x1 = self.unscented_transformF(
x, W, WeightMat, L, f, u, ia, ib, iq, iqu, additional_args_pm)
# store augmented belief to be used in the future
self.prevX = X.copy()
self.prevP = P.copy()
# temporary return values
X_fi[self.lag_interval] = X[ib, :]
P_fi[self.lag_interval] = P[n:2*n, n:2*n]
# latest action is predict
self.latest_action = 'predict'
# update step (step 6 of algorithm 5.1) by implementing equations 5.36-5.41 (page 106)
if len(y):
# store predictive density and gain
if self.latest_action == 'predict':
if not self.backward_pass:
self.pred_density.append((
X[ib, :].copy(), P[n:2*n, n:2*n].copy()))
self.gain.append(
np.matmul(P[0:n, n:2*n], np.linalg.inv(P[n:2*n, n:2*n])))
if len(self.gain) >= self.lag_interval:
self.backward_pass = True
else:
self.pred_density[:-1] = self.pred_density[1:]
self.pred_density[-1] = (X[ib, :].copy(),
P[n:2*n, n:2*n].copy())
self.gain[:-1] = self.gain[1:]
self.gain[-1] = np.matmul(P[0:n, n:2*n],
np.linalg.inv(P[n:2*n, n:2*n]))
# check if innovation keys is valid
for key in innovation_bound_func:
assert key in range(len(
y)), "Key of innovation bound function dictionary should be within the length of the output"
assert callable(
innovation_bound_func[key]), "Innovation bound function is not callable"
ip = np.arange(2*n+nq+nqu, 2*n+nq+nqu+nr)
Z, _, Pz, z2 = self.unscented_transformH(
x, W, WeightMat, L, h, u_next, ib, ip, len(y), additional_args_om)
# transformed cross-covariance (equation 5.38)
Pxy = np.matmul(np.matmul(x1, WeightMat), z2.T)
# Kalman gain
K = np.matmul(Pxy, np.linalg.inv(Pz))
# state update (equation 5.40)
innovation = y - Z
for key in innovation_bound_func:
innovation[key, :] = innovation_bound_func[key](
innovation[key, :])
X += np.matmul(K, innovation)
# covariance update (equation 5.41)
P -= np.matmul(K, Pxy.T)
# perform backward pass
X_fi[self.lag_interval] = X[ib, :]
P_fi[self.lag_interval] = P[n:2*n, n:2*n]
if self.backward_pass:
for j in range(self.lag_interval-1, -1, -1):
X_fi[j] = self.filter_density[j][0] + np.matmul(
self.gain[j], X_fi[j+1] - self.pred_density[j][0])
P_fi[j] = self.filter_density[j][1] + np.matmul(
np.matmul(self.gain[j], P_fi[j+1] - self.pred_density[j][1]), self.gain[j].T)
# store the filtered density
if self.latest_action == 'update':
self.filter_density[-1] = (X[ib, :], P[n:2*n, n:2*n])
elif len(self.gain) < self.lag_interval:
self.filter_density.append((X[ib, :], P[n:2*n, n:2*n]))
else:
self.filter_density[:-1] = self.filter_density[1:]
self.filter_density[-1] = (X[ib, :], P[n:2*n, n:2*n])
# update latest action
self.latest_action = 'update'
return X_fi, P_fi, self.backward_pass
def unscented_transformF(self, x, W, WeightMat, L, f, u, ia, ib, iq, iqu, additional_args):
"""
Function to propagate sigma/cubature points through process model function.
Args:
x (numpy array [n_a x L]): sigma/cubature points
W (numpy array [L x 1 or 1 x L]: 1D Weight array of the sigma/cubature points
WeightMat (numpy array [L x L]): weight matrix with weights in W of the points on the diagonal
L (int): number of points
f (function): function handle for the process model; expected signature f(state, input, noise, ...)
u (?): current input required for function f
ia (numpy array [n_s x 1]): row indices of the frozen states in sima/cubature points
ib (numpy array [n_s x 1]): row indices of the dynamic states in sima/cubature points
iq (numpy array [n_q x 1]): row indices of the process noise in sigma/cubature points
iqu (numpy array [n_qu x 1]): row indices of the input noise in sigma/cubature points
additional_args (list): list of additional arguments to be passed to the process model
Returns:
Y (numpy array [n_s x 1]): Expected value vector of the result from transformation function f
y (numpy array [n_a x L]): Transformed sigma/cubature points
P (numpy array [n_s x n_s]): Covariance matrix of the result from transformation function f
y1 (numpy array [n_s x L]): zero-mean Transformed sigma/cubature points
"""
order = len(ia) + len(ib)
Y = np.zeros((order, 1))
y = x
# Propagating sigma/cubature points through function (equation 5.25)
for k in range(L):
if len(iqu):
y[ib, k] = f(x[ib, k], u, x[iq, k],
x[iqu, k], *additional_args)
else:
y[ib, k] = f(x[ib, k], u, x[iq, k],
np.zeros(u.shape), *additional_args)
# Calculating mean (equation 5.34)
Y += W.flat[k]*y[np.arange(order), k:k+1]
# Calculating covariance (equation 5.35)
y1 = y[np.arange(order), :] - Y
P = np.matmul(np.matmul(y1, WeightMat), y1.T)
return Y, y, P, y1
class PointBasedFixedLagSmootherAugmented(PointBasedFilter):
"""
Class for performing UKF/CKF fixed-lag smoothing similar to PointBasedFixedLagSmoother but more computationally intensive