-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy patheskf.py
More file actions
750 lines (600 loc) · 28.3 KB
/
eskf.py
File metadata and controls
750 lines (600 loc) · 28.3 KB
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
# %% imports
from typing import Tuple, Sequence, Any
from dataclasses import dataclass, field
from cat_slice import CatSlice
import numpy as np
import scipy.linalg as la
import math
from quaternion import (
euler_to_quaternion,
quaternion_product,
quaternion_to_euler,
quaternion_to_rotation_matrix,
)
# from state import NominalIndex, ErrorIndex
from utils import cross_product_matrix
# %% indices
POS_IDX = CatSlice(start=0, stop=3)
VEL_IDX = CatSlice(start=3, stop=6)
ATT_IDX = CatSlice(start=6, stop=10)
ACC_BIAS_IDX = CatSlice(start=10, stop=13)
GYRO_BIAS_IDX = CatSlice(start=13, stop=16)
ERR_ATT_IDX = CatSlice(start=6, stop=9)
ERR_ACC_BIAS_IDX = CatSlice(start=9, stop=12)
ERR_GYRO_BIAS_IDX = CatSlice(start=12, stop=15)
# %% The class
@dataclass
class ESKF:
sigma_acc: float
sigma_gyro: float
sigma_acc_bias: float
sigma_gyro_bias: float
p_acc: float = 0
p_gyro: float = 0
S_a: np.ndarray = np.eye(3)
S_g: np.ndarray = np.eye(3)
debug: bool = True
g: np.ndarray = np.array([0, 0, 9.82]) # Ja, i NED-land, der kan alt gå an
Q_err: np.array = field(init=False, repr=False)
def __post_init__(self):
if self.debug:
print(
"ESKF in debug mode, some numeric properties are checked at the expense of calculation speed"
)
self.Q_err = (
la.block_diag(
self.sigma_acc * np.eye(3),
self.sigma_gyro * np.eye(3),
self.sigma_acc_bias * np.eye(3),
self.sigma_gyro_bias * np.eye(3),
)
** 2
)
def predict_nominal(
self,
x_nominal: np.ndarray,
acceleration: np.ndarray,
omega: np.ndarray,
Ts: float,
) -> np.ndarray:
"""
Discrete time prediction, equation (10.58)
Args:
x_nominal (np.ndarray): The nominal state to predict, shape (16,)
acceleration (np.ndarray): The estimated acceleration in body for the predicted interval, shape (3,)
omega (np.ndarray): The estimated rotation rate in body for the prediction interval, shape (3,)
Ts (float): The sampling time
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
np.ndarray: The predicted nominal state, shape (16,)
"""
assert x_nominal.shape == (
16,
), f"ESKF.predict_nominal: x_nominal incorrect shape {x_nominal.shape}"
assert acceleration.shape == (
3,
), f"ESKF.predict_nominal: acceleration incorrect shape {acceleration.shape}"
assert omega.shape == (
3,
), f"ESKF.predict_nominal: omega incorrect shape {omega.shape}"
# Extract states
position = x_nominal[POS_IDX]
velocity = x_nominal[VEL_IDX]
quaternion = x_nominal[ATT_IDX]
acceleration_bias = x_nominal[ACC_BIAS_IDX]
gyroscope_bias = x_nominal[GYRO_BIAS_IDX]
if self.debug:
assert np.allclose(
np.linalg.norm(quaternion), 1, rtol=0, atol=1e-15
), "ESKF.predict_nominal: Quaternion not normalized."
assert np.allclose(
np.sum(quaternion ** 2), 1, rtol=0, atol=1e-15
), "ESKF.predict_nominal: Quaternion not normalized and norm failed to catch it."
#Predict position and velocity
R = quaternion_to_rotation_matrix(quaternion, debug=self.debug)
acceleration=R@acceleration+self.g
position_prediction=position+Ts*velocity+Ts**2/2*acceleration#acceleration maybe wrong
velocity_prediction = velocity+Ts*acceleration #same maybe wrong
k=Ts*omega #local rotation vector increment in body frame
absk=la.norm(k) #ensure pos
#quat_pred = q(k) x e^(k/2)
exp_kdiv2 = np.array(np.array([np.cos(absk/2),*(np.sin(absk/2)*k.T/absk)])) # TODO: Calculate predicted quaternion
quaternion_prediction = quaternion_product(quaternion, exp_kdiv2)
# Normalize quaternion
quaternion_prediction/=la.norm(quaternion_prediction) # TODO: Normalize
acceleration_bias_prediction=(1 - Ts * self.p_acc) * acceleration_bias
gyroscope_bias_prediction=(1 - Ts * self.p_gyro) * gyroscope_bias
x_nominal_predicted = np.concatenate(
(
position_prediction,
velocity_prediction,
quaternion_prediction,
acceleration_bias_prediction,
gyroscope_bias_prediction,
)
)
assert x_nominal_predicted.shape == (
16,
), f"ESKF.predict_nominal: x_nominal_predicted shape incorrect {x_nominal_predicted.shape}"
return x_nominal_predicted
def Aerr(
self, x_nominal: np.ndarray, acceleration: np.ndarray, omega: np.ndarray,
) -> np.ndarray:
"""Calculate the continuous time error state dynamics Jacobian.
Args:
x_nominal (np.ndarray): The nominal state, shape (16,)
acceleration (np.ndarray): The estimated acceleration for the prediction interval, shape (3,)
omega (np.ndarray): The estimated rotation rate for the prediction interval, shape (3,)
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
np.ndarray: Continuous time error state dynamics Jacobian, shape (15, 15)
"""
assert x_nominal.shape == (
16,
), f"ESKF.Aerr: x_nominal shape incorrect {x_nominal.shape}"
assert acceleration.shape == (
3,
), f"ESKF.Aerr: acceleration shape incorrect {acceleration.shape}"
assert omega.shape == (3,), f"ESKF.Aerr: omega shape incorrect {omega.shape}"
# Rotation matrix
R = quaternion_to_rotation_matrix(x_nominal[ATT_IDX], debug=self.debug)
# Allocate the matrix
A = np.zeros((15, 15))
# Set submatrices
A[POS_IDX * VEL_IDX] = np.eye(3) #done
A[VEL_IDX * ERR_ATT_IDX] = -R@cross_product_matrix(acceleration)
A[VEL_IDX * ERR_ACC_BIAS_IDX] = -R
A[ERR_ATT_IDX * ERR_ATT_IDX] = -cross_product_matrix(omega)
A[ERR_ATT_IDX * ERR_GYRO_BIAS_IDX] = -np.eye(3)
A[ERR_ACC_BIAS_IDX * ERR_ACC_BIAS_IDX] = -self.p_acc*np.eye(3)
A[ERR_GYRO_BIAS_IDX * ERR_GYRO_BIAS_IDX] = -self.p_gyro*np.eye(3)
# Bias correction
A[VEL_IDX * ERR_ACC_BIAS_IDX] = A[VEL_IDX * ERR_ACC_BIAS_IDX] @ self.S_a
A[ERR_ATT_IDX * ERR_GYRO_BIAS_IDX] = (
A[ERR_ATT_IDX * ERR_GYRO_BIAS_IDX] @ self.S_g
)
assert A.shape == (
15,
15,
), f"ESKF.Aerr: A-error matrix shape incorrect {A.shape}"
return A
def Gerr(self, x_nominal: np.ndarray,) -> np.ndarray:
"""Calculate the continuous time error state noise input matrix
Args:
x_nominal (np.ndarray): The nominal state, shape (16,)
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
np.ndarray: The continuous time error state noise input matrix, shape (15, 12)
"""
assert x_nominal.shape == (
16,
), f"ESKF.Gerr: x_nominal shape incorrect {x_nominal.shape}"
R = quaternion_to_rotation_matrix(x_nominal[ATT_IDX], debug=self.debug)
G = np.zeros((15, 12))
diagonal=la.block_diag(-R,-np.eye(3),np.eye(3),np.eye(3))
G=np.vstack([np.zeros((3,12)),diagonal])
assert G.shape == (15, 12), f"ESKF.Gerr: G-matrix shape incorrect {G.shape}"
return G
def discrete_error_matrices(
self,
x_nominal: np.ndarray,
acceleration: np.ndarray,
omega: np.ndarray,
Ts: float,
) -> Tuple[np.ndarray, np.ndarray]:
"""Calculate the discrete time linearized error state transition and covariance matrix.
Args:
x_nominal (np.ndarray): The nominal state, shape (16,)
acceleration (np.ndarray): The estimated acceleration in body for the prediction interval, shape (3,)
omega (np.ndarray): The estimated rotation rate in body for the prediction interval, shape (3,)
Ts (float): The sampling time
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
Tuple[np.ndarray, np.ndarray]: Discrete error matrices Tuple(Ad, GQGd)
Ad: The discrete time error state system matrix, shape (15, 15)
GQGd: The discrete time noise covariance matrix, shape (15, 15)
"""
assert x_nominal.shape == (
16,
), f"ESKF.discrete_error_matrices: x_nominal shape incorrect {x_nominal.shape}"
assert acceleration.shape == (
3,
), f"ESKF.discrete_error_matrices: acceleration shape incorrect {acceleration.shape}"
assert omega.shape == (
3,
), f"ESKF.discrete_error_matrices: omega shape incorrect {omega.shape}"
A = self.Aerr(x_nominal, acceleration, omega)
G = self.Gerr(x_nominal)
V = np.zeros((30, 30)) #use this!
V[CatSlice(0,15)*CatSlice(0,15)]=-A*Ts
V[CatSlice(0,15)*CatSlice(15,30)]=G@self.Q_err@G.T*Ts
V[CatSlice(15,30)*CatSlice(15,30)]=A.T*Ts
assert V.shape == (
30,
30,
), f"ESKF.discrete_error_matrices: Van Loan matrix shape incorrect {omega.shape}"
#VanLoanMatrix = la.expm(V) # This can be slow...
VanLoanMatrix=np.eye(30)+V+1/2.0*V@V
V1_T = VanLoanMatrix[CatSlice(15,30)**2].T # = Ad = exp(A' * deltaT)
V2 = VanLoanMatrix[CatSlice(0,15)*CatSlice(15,30)]
#This is the discrete version of Q, given by van loans
Ad = V1_T
GQGd = V1_T@V2 # Qd = V1' * V2 (Therom 4.5.2)
assert Ad.shape == (
15,
15,
), f"ESKF.discrete_error_matrices: Ad-matrix shape incorrect {Ad.shape}"
assert GQGd.shape == (
15,
15,
), f"ESKF.discrete_error_matrices: GQGd-matrix shape incorrect {GQGd.shape}"
return Ad, GQGd
def predict_covariance(
self,
x_nominal: np.ndarray,
P: np.ndarray,
acceleration: np.ndarray,
omega: np.ndarray,
Ts: float,
) -> np.ndarray:
"""Predict the error state covariance Ts time units ahead using linearized continuous time dynamics.
Args:
x_nominal (np.ndarray): The nominal state, shape (16,)
P (np.ndarray): The error state covariance, shape (15, 15)
acceleration (np.ndarray): The estimated acceleration for the prediction interval, shape (3,)
omega (np.ndarray): The estimated rotation rate for the prediction interval, shape (3,)
Ts (float): The sampling time
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
np.ndarray: The predicted error state covariance matrix, shape (15, 15)
"""
assert x_nominal.shape == (
16,
), f"ESKF.predict_covariance: x_nominal shape incorrect {x_nominal.shape}"
assert P.shape == (
15,
15,
), f"ESKF.predict_covariance: P shape incorrect {P.shape}"
assert acceleration.shape == (
3,
), f"ESKF.predict_covariance: acceleration shape incorrect {acceleration.shape}"
assert omega.shape == (
3,
), f"ESKF.predict_covariance: omega shape incorrect {omega.shape}"
Ad, GQGd = self.discrete_error_matrices(x_nominal, acceleration, omega, Ts)
P_predicted=Ad@P@Ad.T+GQGd
assert P_predicted.shape == (
15,
15,
), f"ESKF.predict_covariance: P_predicted shape incorrect {P_predicted.shape}"
return P_predicted
def predict(
self,
x_nominal: np.ndarray,
P: np.ndarray,
z_acc: np.ndarray,
z_gyro: np.ndarray,
Ts: float,
) -> Tuple[np.array, np.array]:
"""Predict the nominal estimate and error state covariance Ts time units using IMU measurements z_*.
Args:
x_nominal (np.ndarray): The nominal state to predict, shape (16,)
P (np.ndarray): The error state covariance to predict, shape (15, 15)
z_acc (np.ndarray): The measured acceleration for the prediction interval, shape (3,)
z_gyro (np.ndarray): The measured rotation rate for the prediction interval, shape (3,)
Ts (float): The sampling time
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
Tuple[ np.array, np.array ]: Prediction Tuple(x_nominal_predicted, P_predicted)
x_nominal_predicted: The predicted nominal state, shape (16,)
P_predicted: The predicted error state covariance, shape (15, 15)
"""
assert x_nominal.shape == (
16,
), f"ESKF.predict: x_nominal shape incorrect {x_nominal.shape}"
assert P.shape == (15, 15), f"ESKF.predict: P shape incorrect {P.shape}"
assert z_acc.shape == (3,), f"ESKF.predict: zAcc shape incorrect {z_acc.shape}"
assert z_gyro.shape == (
3,
), f"ESKF.predict: zGyro shape incorrect {z_gyro.shape}"
# correct measurements
r_z_acc = self.S_a @ z_acc
r_z_gyro = self.S_g @ z_gyro
# correct biases
acc_bias = self.S_a @ x_nominal[ACC_BIAS_IDX]
gyro_bias = self.S_g @ x_nominal[GYRO_BIAS_IDX]
# debias IMU measurements
acceleration = r_z_acc-acc_bias
omega =r_z_gyro-gyro_bias
# perform prediction
x_nominal_predicted = self.predict_nominal(x_nominal,acceleration,omega,Ts)
P_predicted = self.predict_covariance(x_nominal,P,acceleration,omega,Ts) #should it be x_nominal instead??
assert x_nominal_predicted.shape == (
16,
), f"ESKF.predict: x_nominal_predicted shape incorrect {x_nominal_predicted.shape}"
assert P_predicted.shape == (
15,
15,
), f"ESKF.predict: P_predicted shape incorrect {P_predicted.shape}"
return x_nominal_predicted, P_predicted
def inject(
self, x_nominal: np.ndarray, delta_x: np.ndarray, P: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray]:
"""Inject a calculated error state into the nominal state and compensate in the covariance.
Args:
x_nominal (np.ndarray): The nominal state to inject the error state deviation into, shape (16,)
delta_x (np.ndarray): The error state deviation, shape (15,)
P (np.ndarray): The error state covariance matrix
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
Tuple[ np.ndarray, np.ndarray ]: Injected Tuple(x_injected, P_injected):
x_injected: The injected nominal state, shape (16,)
P_injected: The injected error state covariance matrix, shape (15, 15)
"""
assert x_nominal.shape == (
16,
), f"ESKF.inject: x_nominal shape incorrect {x_nominal.shape}"
assert delta_x.shape == (
15,
), f"ESKF.inject: delta_x shape incorrect {delta_x.shape}"
assert P.shape == (15, 15), f"ESKF.inject: P shape incorrect {P.shape}"
### Useful concatenation of indices
# All injection indices, minus the attitude
INJ_IDX = POS_IDX + VEL_IDX + ACC_BIAS_IDX + GYRO_BIAS_IDX
# All error indices, minus the attitude
DTX_IDX = POS_IDX + VEL_IDX + ERR_ACC_BIAS_IDX + ERR_GYRO_BIAS_IDX
x_injected = x_nominal.copy()
x_injected[INJ_IDX]=x_injected[INJ_IDX]+delta_x[DTX_IDX]
x_injected[ATT_IDX] = quaternion_product(x_nominal[ATT_IDX],np.array([1, *delta_x[ERR_ATT_IDX]/2]))
# TODO: Inject error state into nominal state (except attitude / quaternion)
# TODO: Inject attitude
# TODO: Normalize quaternion
x_injected[ATT_IDX] = x_injected[ATT_IDX]/la.norm(x_injected[ATT_IDX])
# Covariance
G = la.block_diag(np.eye(6),np.eye(3)-cross_product_matrix(delta_x[ERR_ATT_IDX]/2),np.eye(6)) # TODO: Compensate for injection in the covariances
P_injected =G@P@G.T
assert x_injected.shape == (
16,
), f"ESKF.inject: x_injected shape incorrect {x_injected.shape}"
assert P_injected.shape == (
15,
15,
), f"ESKF.inject: P_injected shape incorrect {P_injected.shape}"
return x_injected, P_injected
def innovation_GNSS_position(
self,
x_nominal: np.ndarray,
P: np.ndarray,
z_GNSS_position: np.ndarray,
R_GNSS: np.ndarray,
lever_arm: np.ndarray = np.zeros(3),
) -> Tuple[np.ndarray, np.ndarray]:
"""Calculates the innovation and its covariance for a GNSS position measurement
Args:
x_nominal (np.ndarray): The nominal state to calculate the innovation from, shape (16,)
P (np.ndarray): The error state covariance to calculate the innovation covariance from, shape (15, 15)
z_GNSS_position (np.ndarray): The measured 3D position, shape (3,)
R_GNSS (np.ndarray): The estimated covariance matrix of the measurement, shape (3, 3)
lever_arm (np.ndarray, optional): The position of the GNSS receiver from the IMU reference. Defaults to np.zeros(3).
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
Tuple[ np.ndarray, np.ndarray ]: Innovation Tuple(v, S):
v: innovation, shape (3,)
S: innovation covariance, shape (3, 3)
"""
assert x_nominal.shape == (
16,
), f"ESKF.innovation_GNSS: x_nominal shape incorrect {x_nominal.shape}"
assert P.shape == (15, 15), f"ESKF.innovation_GNSS: P shape incorrect {P.shape}"
assert z_GNSS_position.shape == (
3,
), f"ESKF.innovation_GNSS: z_GNSS_position shape incorrect {z_GNSS_position.shape}"
assert R_GNSS.shape == (
3,
3,
), f"ESKF.innovation_GNSS: R_GNSS shape incorrect {R_GNSS.shape}"
assert lever_arm.shape == (
3,
), f"ESKF.innovation_GNSS: lever_arm shape incorrect {lever_arm.shape}"
#H = np.zeros((1,)) # TODO: measurement matrix
H = np.block([np.eye(3), np.zeros((3,12))])
v = z_GNSS_position-x_nominal[POS_IDX]
#TODO: innovation
# leverarm compensation
if not np.allclose(lever_arm, 0):
R = quaternion_to_rotation_matrix(x_nominal[ATT_IDX], debug=self.debug)
H[:, ERR_ATT_IDX] = -R @ cross_product_matrix(lever_arm, debug=self.debug)
v -= R @ lever_arm
S = H@P@H.T+R_GNSS # TODO: innovation covariance
assert v.shape == (3,), f"ESKF.innovation_GNSS: v shape incorrect {v.shape}"
assert S.shape == (3, 3), f"ESKF.innovation_GNSS: S shape incorrect {S.shape}"
return v, S
def update_GNSS_position(
self,
x_nominal: np.ndarray,
P: np.ndarray,
z_GNSS_position: np.ndarray,
R_GNSS: np.ndarray,
lever_arm: np.ndarray = np.zeros(3),
) -> Tuple[np.ndarray, np.ndarray]:
"""Updates the state and covariance from a GNSS position measurement
Args:
x_nominal (np.ndarray): The nominal state to update, shape (16,)
P (np.ndarray): The error state covariance to update, shape (15, 15)
z_GNSS_position (np.ndarray): The measured 3D position, shape (3,)
R_GNSS (np.ndarray): The estimated covariance matrix of the measurement, shape (3, 3)
lever_arm (np.ndarray, optional): The position of the GNSS receiver from the IMU reference, shape (3,). Defaults to np.zeros(3), shape (3,).
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
Tuple[np.ndarray, np.ndarray]: Updated Tuple(x_injected, P_injected):
x_injected: The nominal state after injection of updated error state, shape (16,)
P_injected: The error state covariance after error state update and injection, shape (15, 15)
"""
assert x_nominal.shape == (
16,
), f"ESKF.update_GNSS: x_nominal shape incorrect {x_nominal.shape}"
assert P.shape == (15, 15), f"ESKF.update_GNSS: P shape incorrect {P.shape}"
assert z_GNSS_position.shape == (
3,
), f"ESKF.update_GNSS: z_GNSS_position shape incorrect {z_GNSS_position.shape}"
assert R_GNSS.shape == (
3,
3,
), f"ESKF.update_GNSS: R_GNSS shape incorrect {R_GNSS.shape}"
assert lever_arm.shape == (
3,
), f"ESKF.update_GNSS: lever_arm shape incorrect {lever_arm.shape}"
I = np.eye(*P.shape)
innovation, S = self.innovation_GNSS_position(
x_nominal, P, z_GNSS_position, R_GNSS, lever_arm
)
H = np.block([np.eye(3), np.zeros((3,12))])
# in case of a specified lever arm
if not np.allclose(lever_arm, 0):
R = quaternion_to_rotation_matrix(x_nominal[ATT_IDX], debug=self.debug)
H[:, ERR_ATT_IDX] = -R @ cross_product_matrix(lever_arm, debug=self.debug)
# KF error state update
W = P@H.T@np.linalg.inv(S) # TODO: Kalman gain
delta_x = W@innovation # TODO: delta x
Jo = I - W @ H # for Joseph form
P_update = Jo@P@Jo.T+W@R_GNSS@W.T # TODO: P update
# error state injection
x_injected, P_injected = self.inject(x_nominal, delta_x, P_update)
assert x_injected.shape == (
16,
), f"ESKF.update_GNSS: x_injected shape incorrect {x_injected.shape}"
assert P_injected.shape == (
15,
15,
), f"ESKF.update_GNSS: P_injected shape incorrect {P_injected.shape}"
return x_injected, P_injected
def NIS_GNSS_position(
self,
x_nominal: np.ndarray,
P: np.ndarray,
z_GNSS_position: np.ndarray,
R_GNSS: np.ndarray,
lever_arm: np.ndarray = np.zeros(3),
) -> float:
"""Calculates the NIS for a GNSS position measurement
Args:
x_nominal (np.ndarray): The nominal state to calculate the innovation from, shape (16,)
P (np.ndarray): The error state covariance to calculate the innovation covariance from, shape (15, 15)
z_GNSS_position (np.ndarray): The measured 3D position, shape (3,)
R_GNSS (np.ndarray): The estimated covariance matrix of the measurement, shape (3,)
lever_arm (np.ndarray, optional): The position of the GNSS receiver from the IMU reference, shape (3,). Defaults to np.zeros(3).
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
float: The normalized innovations squared (NIS)
"""
assert x_nominal.shape == (
16,
), "ESKF.NIS_GNSS: x_nominal shape incorrect " + str(x_nominal.shape)
assert P.shape == (15, 15), "ESKF.NIS_GNSS: P shape incorrect " + str(P.shape)
assert z_GNSS_position.shape == (
3,
), "ESKF.NIS_GNSS: z_GNSS_position shape incorrect " + str(
z_GNSS_position.shape
)
assert R_GNSS.shape == (3, 3), "ESKF.NIS_GNSS: R_GNSS shape incorrect " + str(
R_GNSS.shape
)
assert lever_arm.shape == (
3,
), "ESKF.NIS_GNSS: lever_arm shape incorrect " + str(lever_arm.shape)
v, S = self.innovation_GNSS_position(
x_nominal, P, z_GNSS_position, R_GNSS, lever_arm
)
NIS = v.T@np.linalg.inv(S)@v # TODO: Calculate NIS # maybe S not invertable
assert NIS >= 0, "EKSF.NIS_GNSS_positionNIS: NIS not positive"
return NIS
@classmethod
def delta_x(cls, x_nominal: np.ndarray, x_true: np.ndarray,) -> np.ndarray:
"""Calculates the error state between x_nominal and x_true
Args:
x_nominal (np.ndarray): The nominal estimated state, shape (16,)
x_true (np.ndarray): The true state, shape (16,)
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
np.ndarray: The state difference in error state, shape (15,)
"""
assert x_nominal.shape == (
16,
), f"ESKF.delta_x: x_nominal shape incorrect {x_nominal.shape}"
assert x_true.shape == (
16,
), f"ESKF.delta_x: x_true shape incorrect {x_true.shape}"
delta_position = x_true[POS_IDX]-x_nominal[POS_IDX] # TODO: Delta position
delta_velocity = x_true[VEL_IDX]-x_nominal[VEL_IDX] # TODO: Delta velocity
quaternion_conj = np.diag([1,-1,-1,-1])@x_nominal[ATT_IDX] # TODO: Conjugate of quaternion
delta_quaternion = quaternion_product(quaternion_conj,x_true[ATT_IDX]) # TODO: Error quaternion
#can do this cause of general formulation of error
delta_theta = 2*delta_quaternion[1:]
# Concatenation of bias indices
BIAS_IDX = ACC_BIAS_IDX + GYRO_BIAS_IDX
delta_bias = x_true[BIAS_IDX]-x_nominal[BIAS_IDX] # TODO: Error biases
d_x = np.concatenate((delta_position, delta_velocity, delta_theta, delta_bias))
assert d_x.shape == (15,), f"ESKF.delta_x: d_x shape incorrect {d_x.shape}"
return d_x
@classmethod
def NEESes(
cls, x_nominal: np.ndarray, P: np.ndarray, x_true: np.ndarray,
) -> np.ndarray:
"""Calculates the total NEES and the NEES for the substates
Args:
x_nominal (np.ndarray): The nominal estimate
P (np.ndarray): The error state covariance
x_true (np.ndarray): The true state
Raises:
AssertionError: If any input is of the wrong shape, and if debug mode is on, certain numeric properties
Returns:
np.ndarray: NEES for [all, position, velocity, attitude, acceleration_bias, gyroscope_bias], shape (6,)
"""
assert x_nominal.shape == (
16,
), f"ESKF.NEES: x_nominal shape incorrect {x_nominal.shape}"
assert P.shape == (15, 15), f"ESKF.NEES: P shape incorrect {P.shape}"
assert x_true.shape == (
16,
), f"ESKF.NEES: x_true shape incorrect {x_true.shape}"
d_x = cls.delta_x(x_nominal, x_true)
"""
NEES_all = d_x.T@np.linalg.inv(P)@d_x # TODO: NEES all
NEES_pos = d_x[POS_IDX].T@np.linalg.inv(P[POS_IDX**2])@d_x[POS_IDX] # TODO: NEES position
NEES_vel = d_x[VEL_IDX].T@np.linalg.inv(P[VEL_IDX**2])@d_x[VEL_IDX] # TODO: NEES velocity
NEES_att = d_x[ATT_IDX].T@np.linalg.inv(P[ATT_IDX**2])@d_x[ATT_IDX] # TODO: NEES attitude
NEES_accbias = d_x[ACC_BIAS_IDX].T@np.linalg.inv(P[ACC_BIAS_IDX**2])@d_x[ACC_BIAS_IDX] # TODO: NEES accelerometer bias
NEES_gyrobias = d_x[GYRO_BIAS_IDX].T@(P[GYRO_BIAS_IDX**2])@d_x[GYRO_BIAS_IDX] # TODO: NEES gyroscope bias
NEES_gyrobias=cls._NEES(P[ERR_GYRO_BIAS_IDX**2], d_x[ERR_GYRO_BIAS_IDX])
"""
NEES_all = cls._NEES(d_x,P)
NEES_pos = cls._NEES(d_x[POS_IDX],P[POS_IDX**2])
NEES_vel = cls._NEES(d_x[VEL_IDX],P[VEL_IDX**2])
NEES_att = cls._NEES(d_x[ERR_ATT_IDX],P[ERR_ATT_IDX**2])
NEES_accbias = cls._NEES(d_x[ERR_ACC_BIAS_IDX],P[ERR_ACC_BIAS_IDX**2])
NEES_gyrobias = cls._NEES(d_x[ERR_GYRO_BIAS_IDX],P[ERR_GYRO_BIAS_IDX**2])
NEESes = np.array(
[NEES_all, NEES_pos, NEES_vel, NEES_att, NEES_accbias, NEES_gyrobias]
)
assert np.all(NEESes >= 0), "ESKF.NEES: one or more negative NEESes"
#print(NEESes)
#print(type(NEESes))
return NEESes
@classmethod
def _NEES(cls, diff, P):
#print(P)
NEES = diff@la.solve(P,diff)
assert NEES >= 0, "ESKF._NEES: negative NEES"
return NEES
# %%