-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcar_dynamics.py
1887 lines (1584 loc) · 74.9 KB
/
car_dynamics.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 as np
import abc
from collections import Iterable
from estimators import sample_nlds
try:
import torch
torch_imported = True
except ImportError:
print("Unable to import pytorch module")
torch_imported = False
def cal_vxvy_from_coord(state, state_prev, dt, x_ind=0, y_ind=1, theta_ind=2):
"""
Calculate longitudinal and lateral velocity by rotating current position into the frame of previous position.
Args:
state (numpy array [4 x nt]): state of the system at different time instances
state_prev (numpy array [4 x nt]): corresponding previous states of state
dt (numpy array [nt] or float): time step/difference between state and state_prev
x_ind (int): row index for x coordinate of state and state_prev; defaults to 0
y_ind (int): row index for y coordinate of state and state_prev; defaults to 1
theta_ind (int): row index for theta coordinate of state and state_prev; defaults to 2
Returns:
vxy (numpy array [2 x nt]): linear and lateral velocities at different time instances
"""
if len(state.shape) == 1:
state = state[:, np.newaxis]
if len(state_prev.shape) == 1:
state_prev = state_prev[:, np.newaxis]
prev_ang = state_prev[theta_ind, :]
R = np.array([[np.cos(prev_ang), np.sin(prev_ang)],
[-np.sin(prev_ang), np.cos(prev_ang)]])
xy_dot = (state[[x_ind, y_ind], :] - state_prev[[x_ind, y_ind], :]) / dt
vxy = np.zeros(xy_dot.shape)
for i in range(xy_dot.shape[1]):
vxy[:, i:i + 1] = np.matmul(R[:, :, i], xy_dot[:, i:i + 1])
return vxy
class AbstractDyn(object):
"""
Abstract dynamics class with useful base functions for derived classes
Args:
param_dict (dict): dictionary of parameters needed for defining the dynamics
state_keys (list): list of states string that are observed by sensor; defaults to empty
state_dot_keys (list): list of derivative of states string that are observed by sensor; defaults to empty
additional_output_keys (list): list of additional things that are observed by sensors; defaults to empty
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False
"""
__metaclass__ = abc.ABCMeta
def __init__(self,
param_dict,
state_keys=[],
state_dot_keys=[],
additional_output_keys=[],
use_torch_tensor=False):
# store the parameter dictionary for the vehicle dynamics
self.param_dict = param_dict.copy()
# store expected keys of param dictionary
self.expected_keys = self.global_expected_keys.copy()
# copy state dict from global
self.state_dict = self.global_state_dict.copy()
# store whether user will be using torch tensor or not
self.use_torch_tensor = use_torch_tensor
self.use_pre_alloc_tensors = False
# default value of tensor complaince of dynamic object to False
if 'tensor_compliance' not in self.__dir__():
self.tensor_compliance = False
# assert if dynamic class is not tensor compliant
self.assert_tensor_compliance()
# check if param dictionary is valid
assert self.check_param_dict(
), "Parameter dictionary does not contain all requried keys"
# store state its derivative indices for generating output
self.state_indices = []
self.state_dot_indices = []
for key in state_keys:
if key in self.state_dict:
self.state_indices.append(self.state_dict[key])
for key_dot in state_dot_keys:
if key_dot in self.state_dict:
self.state_dot_indices.append(self.state_dict[key_dot])
# store the additional output keys
self.additional_output_keys = additional_output_keys
# dimensionality of states, inputs and outputs
self.num_states = len(self.state_dict.keys())
self.num_out = len(self.state_indices) + \
len(self.state_dot_indices) + len(self.additional_output_keys)
self.num_in = 0
def check_param_dict(self):
"""
Basic checking of parameter dictionary. Returns false if any expected keys is not present in param_dict.
Returns:
(bool): True if all expected keys are present in param_dict and False otherwise
"""
for key in self.expected_keys:
if key not in self.param_dict.keys():
return False
return True
def assert_tensor_compliance(self):
"""
Check if torch library was successfully imported or if the dynamic library is torch compliant
"""
if self.use_torch_tensor:
assert torch_imported, "Pytorch module was not successfully imported which prohibits the use of tensor with this library"
assert self.tensor_compliance, "Dynamic class is not yet tensor compliant"
def pre_alloc_tensors(self, num_params, tensor_device, dtype):
"""
Pre-allocate some tensors instead of creating them on the fly
Args:
num_params (int): dimensionality of parameters to be estimated
tensor_device : device in which pre-allocated tensor is to be stored
dtype (type): type for tensor
"""
if self.use_torch_tensor:
# turn on the flag
self.use_pre_alloc_tensors = True
# default empty tensor
self.tensor_empty = torch.empty(0,
device=tensor_device,
dtype=dtype)
# zero tensor to be augmented when performing partial dxdt
self.tensor_params_dxdt = torch.zeros((1, num_params),
device=tensor_device,
dtype=dtype)
def sample_nlds(self,
z0,
U,
T,
Q=None,
P0=None,
R=None,
Qu=None,
store_variables=True,
overwrite_keys=[],
overwrite_vals=[]):
"""
Retrieve ground truth, initial and output data (SNLDS: Stochastic non-linear dynamic system)
Args:
z0 (numpy array [n x 1]): initial ground truth condition
U (numpy array [nu x nt]): inputs for the process and observation model
T (numpy array [nt x 1 or 1 x nt]): time instances for retrieving ground truth and output data
Q (numpy array [nq x nq]): noise covariance matrix involved in the stochastic dynamic model
P0 (numpy array [n x n]): initial covariance for the initial estimate around the ground truth
R (numpy array [nr x nr]): covariance matrix of the noise involved in observed sensor data
Qu (numpy array [nqu x nqu]): noise covariance matrix involved in the input
store_variables (bool): whether to store ground truth, initial and output arrays within the class
overwrite_keys (list): list of state keys to be overwritten
overwrite_vals (list): list of ground truth values to overwrite state propagation
"""
# check sizes of received matrices
num_sol = len(T)
assert len(
z0
) == self.num_states, "True initial condition is of incorrect size"
assert U.shape == (self.num_in,
num_sol), "Incorrect size of input matrix"
def process_model(x, u, noise, input_noise, dt, param_dict):
return self.forward_prop(
x, self.dxdt(x, u + input_noise, param_dict), dt) + noise
def observation_model(x, u, noise, param_dict):
return self.output_model(x, u, param_dict) + noise
# check size of array of parameter dictionary
for key in self.param_dict:
if not isinstance(self.param_dict[key], Iterable):
self.param_dict[key] = [self.param_dict[key]] * num_sol
else:
assert len(
self.param_dict[key]
) == num_sol, "Parameter {} should have the length of nt".format(
key)
# convert param dictionary to additional input for process model
self.param_list = []
for i in range(num_sol):
param_dict = dict()
for key in self.param_dict:
param_dict[key] = self.param_dict[key][i]
self.param_list.append(param_dict)
# obtain indices of ground truth states to be overwritten
overwrite_inds = []
for key in overwrite_keys:
assert key in self.state_dict.keys(
), "State key {} to be overwritten doesn't exist".format(key)
overwrite_inds.append(self.state_dict[key])
# get ground truth data, initial and output data
dts = np.diff(T)
dts = np.append(dts, dts[-1])
gt_states, initial_cond, outputs, additional_args_pm_list, additional_args_om_list = sample_nlds(
z0,
U,
num_sol,
process_model,
observation_model,
self.num_out,
Q=Q,
P0=P0,
R=R,
Qu=Qu,
additional_args_pm=[dts, self.param_list],
additional_args_om=[self.param_list],
overwrite_inds=overwrite_inds,
overwrite_vals=overwrite_vals)
# separately, get the derivative of ground truth
gt_states_dot = np.zeros(gt_states.shape)
for i in range(1, num_sol):
gt_states_dot[:, i - 1] = self.dxdt(gt_states[:, i - 1], U[:,
i - 1],
self.param_list[i - 1])
gt_states_dot[:, num_sol - 1] = self.dxdt(gt_states[:, num_sol - 1],
U[:, num_sol - 1],
self.param_list[num_sol - 1])
# store varibles to avoid parsing things around?
if store_variables:
self.Q = Q
self.Qu = Qu
self.R = R
self.P0 = P0
self.U = U
self.T = T
self.gt_states = gt_states
self.gt_states_dot = gt_states_dot
self.initial_cond = initial_cond
self.outputs = outputs
self.process_model = process_model
self.observation_model = observation_model
self.additional_args_pm_list = additional_args_pm_list
self.additional_args_om_list = additional_args_om_list
return gt_states, gt_states_dot, initial_cond, outputs
@abc.abstractmethod
def dxdt(self, state, u, param_dict):
"""
Abstract Differential model for the dynamic model. Must be overwritten in derived classes.
Args:
state (numpy array [n x 1 or 1 x n]): current state vector
u (*): current input
param_dict (dict): dictionary of current parameters needed for defining the dynamics
Returns:
state_dot (numpy array [n x 1 or 1 x n]): current derivative of the state
"""
return
def forward_prop(self, state, state_dot, dt):
"""
Forward propagation of model via first order Euler approximation, i.e. X[k+1] = X[k] + dt*X'[k], where X' is the derivative.
Args:
state (numpy array [n x 1 or 1 x n]): current state vector
state_dot (numpy array [n x 1 or 1 x n]): current derivative of the state
dt (float): time step/difference between discrete step k and step k+1
Returns:
state (numpy array [n x 1 or 1 x n]): next time-step state vector
"""
return state + dt * state_dot
def additional_output_model(self, state, u, param_dict):
"""
Additional output model for the system that does not simply involve the bare states or their derivatives.
Must be overwritten in derived classes if expected additional outputs.
Args:
state (numpy array [n x 1 or 1 x n]): current state vector
u (*): current input
param_dict (dict): dictionary of current parameters needed for defining the dynamics
Returns:
output (numpy array [len(self.additional_output_keys) x 1): observed additional output
"""
if self.use_torch_tensor:
if self.use_pre_alloc_tensors:
return self.tensor_empty
else:
return torch.empty(0, device=state.device)
else:
return np.array([])
def output_model(self, state, u, param_dict):
"""
Simulate the output of the system.
Args:
state (numpy array [n x 1]): current state vector
u (*): current input
param_dict (dict): dictionary of current parameters needed for defining the dynamics
Returns:
output (numpy array [len(self.state_indices) + len(self.state_dot_indices) + len(self.additional_output_keys) x 1]):
observed state and state derivatives of the system
"""
if self.use_torch_tensor:
if len(self.state_dot_indices):
dxdt = self.dxdt(state, u, param_dict)
state_dot_out = dxdt[0, self.state_dot_indices]
else:
if self.use_pre_alloc_tensors:
state_dot_out = self.tensor_empty
else:
state_dot_out = torch.empty(0).to(state.device)
return torch.cat(
(state[self.state_indices], state_dot_out,
self.additional_output_model(state, u, param_dict)))
else:
return np.concatenate(
(state[self.state_indices],
self.dxdt(state, u, param_dict)[0, self.state_dot_indices],
self.additional_output_model(state, u, param_dict)))
def cal_vxvy_from_coord(self, output=True):
"""
Calculate longitudinal and lateral velocity by rotating current position into the frame of previous position
using the available function on encapsulated data.
Args:
output (bool): whether to use ground truth or output data
Returns:
vxy (numpy array [2 x nt]): linear and lateral velocities at different time instances
"""
# error checking
assert 'x' in self.state_dict, "Function requires dynamic class to contain x coordinate state"
assert 'y' in self.state_dict, "Function requires dynamic class to contain y coordinate state"
assert 'theta' in self.state_dict, "Function requires dynamic class to contain theta coordinate state"
if output:
# check if x,y and theta are part of the output
assert self.state_dict[
'x'] in self.state_indices, "No output for state x available"
assert self.state_dict[
'y'] in self.state_indices, "No output for state y available"
assert self.state_dict[
'theta'] in self.state_indices, "No output for state theta available"
state = self.outputs[:, 1:]
state_prev = self.outputs[:, :-1]
else:
state = self.gt_states[:, 1:]
state_prev = self.gt_states[:, :-1]
return cal_vxvy_from_coord(state,
state_prev,
np.diff(self.T),
x_ind=self.state_dict['x'],
y_ind=self.state_dict['y'],
theta_ind=self.state_dict['theta'])
class FrontSteered(AbstractDyn):
"""
Front Steered model derived from AbstractDyn class. The assumptions of the this model are:
(i) steering angles of the front left and right wheels are the same. front steered only.
(ii) steering command is small enough such that sin(steering) = steering
(iii) vehicle operates in the linear region of the tire-force curve with negligible inclination and bang angles
(iv) left and right wheels on each axle have the same stiffness
(v) dominant forces are the tire-road contact forces. influences due to wind and air resistance are ignored.
model from: "Tire-Stiffness and Vehicle-State Estimation Based on Noise-Adaptive Particle Filtering"
inputs = [steering_angle, wf, wr]; wf -> front wheel rotation rate, wr -> rear wheel rotation rate
states = [x, y, theta, vx, vy, omega]
Args:
param_dict (dict): dictionary of parameters needed for defining the dynamics
state_keys (list): list of states string that are observed by sensor
state_dot_keys (list): list of derivative of states string that are observed by sensor; defaults to empty
additional_output_keys (list): list of additional things that are observed by sensors; defaults to empty
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False
"""
# state dictionary for this model
global_state_dict = {
'x': 0,
'y': 1,
'theta': 2,
'vx': 3,
'vy': 4,
'omega': 5
}
# expected keys/parameters of this model
global_expected_keys = [
"mass", "lr", "lf", "e_wr", "cxf", "cxr", "cyf", "cyr", "iz"
]
def __init__(self,
param_dict,
state_keys,
state_dot_keys=[],
additional_output_keys=[],
use_torch_tensor=False):
super(FrontSteered,
self).__init__(param_dict,
state_keys=state_keys,
state_dot_keys=state_dot_keys,
additional_output_keys=additional_output_keys,
use_torch_tensor=use_torch_tensor)
# dimensionality of input
self.num_in = 3
def dxdt(self, state, u, param_dict):
"""
Obtain derivative of the state based on current state and input
Args:
state (numpy array [6 x 1]): current state of the system consisting of x, y, theta, vx, vy and omega
u (numpy array [3 x 1]): current input consisting of steering_angle, wf and wr
param_dict (dict): dictionary of current parameters needed for defining the dynamics
Returns:
state_dot (numpy array [6 x 1]): derivative of the states
"""
# get the inputs
steering_angle = u[0]
wf = u[1]
wr = u[2]
# get the states
heading = state[self.state_dict['theta']]
vx = state[self.state_dict['vx']]
vy = state[self.state_dict['vy']]
omega = state[self.state_dict['omega']]
# calculate lateral tire forces
if vx != 0.0:
slip_ang_f = steering_angle - (vy + param_dict['lf'] * omega) / vx
slip_ang_r = (param_dict['lr'] * omega - vy) / vx
else:
slip_ang_f = 0.0
slip_ang_r = 0.0
fy_f = param_dict['cyf'] * slip_ang_f
fy_r = param_dict['cyr'] * slip_ang_r
# calculate longitudinal force
wheel_slip_f = (vx - param_dict['e_wr']*wf) / \
max(vx, param_dict['e_wr']*wf)
wheel_slip_r = (vx - param_dict['e_wr']*wr) / \
max(vx, param_dict['e_wr']*wr)
fx_f = param_dict['cxf'] * wheel_slip_f
fx_r = param_dict['cxr'] * wheel_slip_r
# calculate lateral and longitudinal acceleration
vx_dot = (fx_f * math.cos(steering_angle) + fx_r +
fy_f * math.sin(steering_angle) +
param_dict['mass'] * vy * omega) / param_dict['mass']
ax_inertial = vx_dot - vy * omega
vy_dot = (fy_f * math.cos(steering_angle) + fy_r +
fx_f * math.sin(steering_angle) -
param_dict['mass'] * vx * omega) / param_dict['mass']
ay_inertial = vy_dot + vx * omega
# calculate angular acceleration
omega_dot = (
param_dict['lf'] *
(fy_f * math.cos(steering_angle) + fx_f * math.sin(steering_angle))
- param_dict['lr'] * fy_r) / param_dict['iz']
# kinematic model based on derived dynamic quantities
x_dot = vx * math.cos(heading) - vy * math.sin(heading)
y_dot = vx * math.sin(heading) + vy * math.cos(heading)
heading_dot = omega
return np.array(
[[x_dot, y_dot, heading_dot, vx_dot, vy_dot, omega_dot]])
def additional_output_model(self, state, u, param_dict):
"""
Specialisation of inherited method to provide inertial accelerations.
Args:
state (numpy array [6 x 1]): current state of the system consisting of x, y, theta, vx, vy and omega
u (numpy array [3 x 1]): current input consisting of steering_angle, wf and wr
Returns:
output (numpy array [len(self.additional_output_keys) x 1): observed additional output
"""
# get the inputs
steering_angle = u[0]
wf = u[1]
wr = u[2]
# get the states
heading = state[2]
vx = state[3]
vy = state[4]
omega = state[5]
# calculate lateral tire forces
if vx != 0.0:
slip_ang_f = steering_angle - (vy + param_dict['lf'] * omega) / vx
slip_ang_r = (param_dict['lr'] * omega - vy) / vx
else:
slip_ang_f = 0.0
slip_ang_r = 0.0
fy_f = param_dict['cyf'] * slip_ang_f
fy_r = param_dict['cyr'] * slip_ang_r
# calculate longitudinal force
wheel_slip_f = (vx - param_dict['e_wr']*wf) / \
max(vx, param_dict['e_wr']*wf)
wheel_slip_r = (vx - param_dict['e_wr']*wr) / \
max(vx, param_dict['e_wr']*wr)
fx_f = param_dict['cxf'] * wheel_slip_f
fx_r = param_dict['cxr'] * wheel_slip_r
ax_inertial = (fx_f * math.cos(steering_angle) + fx_r +
fy_f * math.sin(steering_angle)) / param_dict['mass']
ay_inertial = (fy_f * math.cos(steering_angle) + fy_r +
fx_f * math.sin(steering_angle)) / param_dict['mass']
# create output array to return
output = np.array([])
if 'ax' in self.additional_output_keys:
output = np.append(output, ax_inertial)
if 'ay' in self.additional_output_keys:
output = np.append(output, ay_inertial)
return output
class RoverDyn(AbstractDyn):
"""
Class derived from AbstractDyn class
model from: Michigan guys' RTD python repo
inputs = [steering_angle, commanded velocity]
states = [x, y, theta, vx]
Args:
param_dict (dict): dictionary of parameters needed for defining the dynamics
state_keys (list): list of states string that are observed by sensor
state_dot_keys (list): list of derivative of states string that are observed by sensor; defaults to empty
additional_output_keys (list): list of additional things that are observed by sensors; defaults to empty
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False
"""
# state dictionary for this model
global_state_dict = {'x': 0, 'y': 1, 'theta': 2, 'vx': 3}
# expected keys/parameters of this model
global_expected_keys = [
"c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9"
]
def __init__(self,
param_dict,
state_keys,
state_dot_keys=[],
additional_output_keys=[],
use_torch_tensor=False):
super(RoverDyn,
self).__init__(param_dict,
state_keys=state_keys,
state_dot_keys=state_dot_keys,
additional_output_keys=additional_output_keys,
use_torch_tensor=use_torch_tensor)
# specify expected dimensionality of input
self.num_in = 2
def dxdt(self, state, u, param_dict):
"""
Obtain derivative of the state based on current state and input
Args:
state (numpy array [4 x 1]): current state of the system consisting of x, y, theta and vx
u (numpy array [2 x 1]): current input consisting of steering angle and commanded velocity
param_dict (dict): dictionary of current parameters needed for defining the dynamics
Returns:
state_dot (numpy array [4 x 1]): derivative of the states
"""
# get the inputs
steering_angle = u[0]
vx_cmd = u[1]
# get the states
theta = state[self.state_dict['theta']]
vx = state[self.state_dict['vx']]
ang_rate = math.tan(param_dict['c1'] * steering_angle +
param_dict['c2']) * vx / (param_dict['c3'] +
param_dict['c4'] * vx**2)
vy = ang_rate * (param_dict['c8'] + param_dict['c9'] * vx**2)
# calculate the derivatives
x_dot = vx * math.cos(theta) - vy * math.sin(theta)
y_dot = vx * math.sin(theta) + vy * math.cos(theta)
heading_dot = ang_rate
vx_dot = param_dict['c5'] + param_dict['c6'] * \
(vx - vx_cmd) + param_dict['c7']*(vx - vx_cmd)**2
return np.array([[x_dot, y_dot, heading_dot, vx_dot]])
def additional_output_model(self, state, u, param_dict):
"""
Specialisation of inherited method to provide lateral velocity.
Args:
state (numpy array [4 x 1]): current state of the system consisting of x, y, theta and vx
u (numpy array [2 x 1]): current input consisting of steering angle and commanded velocity
param_dict (dict): dictionary of current parameters needed for defining the dynamics
Returns:
output (numpy array [len(self.additional_output_keys) x 1): observed additional output
"""
# get the inputs
steering_angle = u[0]
# get the states
vx = state[self.state_dict['vx']]
ang_rate = math.tan(param_dict['c1'] * steering_angle +
param_dict['c2']) * vx / (param_dict['c3'] +
param_dict['c4'] * vx**2)
vy = ang_rate * (param_dict['c8'] + param_dict['c9'] * vx**2)
# create output array
output = np.array([])
if 'vy' in self.additional_output_keys:
output = np.append(output, vy)
return output
def partial_init(obj,
class_type,
est_params,
param_dict,
state_keys,
simulate_gt,
state_dot_keys=[],
additional_output_keys=[],
use_torch_tensor=False):
"""
Function to help initialise an Estimate class deriving from the dynamic class.
Args:
obj (Est obj): object in which the initialisation is being performed (self)
class_type (obj type): pass in the class of the object to be used when invoking super
est_params (list): list of parameter strings to be estimated with the states
param_dict (dict): dictionary of parameters needed for defining the dynamics
state_keys (list): list of states string that are observed by sensor
simulate_gt (bool): specify whether model is during the stage of simulating ground truth
state_dot_keys (list): list of derivative of states string that are observed by sensor; defaults to empty
additional_output_keys (list): list of additional things that are observed by sensors; defaults to empty
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False
"""
# store if we are simulating ground truth or not
obj.simulate_gt = simulate_gt
if obj.simulate_gt:
super(class_type,
obj).__init__(param_dict,
state_keys,
state_dot_keys=state_dot_keys,
additional_output_keys=additional_output_keys,
use_torch_tensor=False)
obj.later_use_torch_tensor = use_torch_tensor
else:
# remove parameters to be estimated from dictionary
pruned_param_dict = param_dict.copy()
for est_param in est_params:
if est_param in pruned_param_dict:
del pruned_param_dict[est_param]
super(class_type,
obj).__init__(pruned_param_dict,
state_keys,
state_dot_keys=state_dot_keys,
additional_output_keys=additional_output_keys,
use_torch_tensor=use_torch_tensor)
# check if est_params are in expected keys
for est_param in est_params:
assert est_param in obj.global_expected_keys, "Parameter {} to be estimated is not in expected keys".format(
est_param)
obj.expected_keys.remove(est_param)
# append state dictionary
for i, est_param in enumerate(est_params):
obj.state_dict[est_param] = obj.num_states + i
# dimensionalities of different things
obj.est_params = list(est_params)
obj.num_dyn_states = obj.num_states
obj.num_states += len(obj.est_params)
def re_initialise(obj):
"""
Function to help re-initialise an Estimate class deriving from the dynamic class after simulation of ground truth data is completed.
Args:
obj (Est obj): object in which the re-initialisation is being performed (self)
"""
if obj.simulate_gt:
# turn off simulation mode
obj.simulate_gt = False
# check if est_params are in expected keys
for est_param in obj.est_params:
assert est_param in obj.global_expected_keys, "Parameter {} to be estimated is not in expected keys".format(
est_param)
obj.expected_keys.remove(est_param)
# remove parameters to be estimated from dictionary
for est_param in obj.est_params:
if est_param in obj.param_dict:
del obj.param_dict[est_param]
# check if param dictionary is valid
assert obj.check_param_dict(
), "Parameter dictionary does not contain all requried keys"
# retrieve initially proved direction on usage of torch tensor
obj.use_torch_tensor = obj.later_use_torch_tensor
del obj.later_use_torch_tensor
# assert if dynamic class is not tensor compliant
obj.assert_tensor_compliance()
def partial_dxdt(obj, class_type, state, u, param_dict):
"""
Function to help calculate derivative of an Estimate class deriving from dynamic class. It does the calculation by the getting
the states' derivatives from its parent's class and assuming that the estimated parameters are stationary (not drifting over time).
Args:
obj (Est obj): object in which the initialisation is being performed (self)
class_type (obj type): pass in the class of the object to be used when invoking super
state (numpy array [num_states x 1]): current state of the system
u (numpy array [num_in x 1]): current input
param_dict (dict): dictionary of current non-estimated parameters needed for defining the dynamics
"""
# put the parameters into the dictionary
if not obj.simulate_gt:
for i, est_param in enumerate(obj.est_params):
param_dict[est_param] = state[obj.num_dyn_states + i]
state_dot = super(class_type, obj).dxdt(state, u, param_dict)
if obj.use_torch_tensor:
for i, est_param in enumerate(obj.est_params):
param_dict[est_param] = param_dict[est_param].cpu().item()
if obj.use_pre_alloc_tensors:
params_dxdt = obj.tensor_params_dxdt
else:
params_dxdt = torch.zeros((1, len(obj.est_params)),
device=state_dot.device,
dtype=state_dot.dtype)
return torch.cat((state_dot, params_dxdt), dim=1)
else:
return np.concatenate((state_dot, np.zeros((1, len(obj.est_params)))),
axis=1)
class RoverPartialDynEst(RoverDyn):
"""
Class derived from RoverDyn class
model from: same as RoverDyn but some parameters are the states themselves to be estimated online
inputs = [steering_angle, commanded velocity]
states = [x, y, theta, vx, ...]
Args:
param_dict (dict): dictionary of parameters needed for defining the dynamics
est_params (list): list of parameter strings to be estimated with the states
state_keys (list): list of states string that are observed by sensor
state_dot_keys (list): list of derivative of states string that are observed by sensor; defaults to empty
simulate_gt (bool): specify whether model is during the stage of simulating ground truth
additional_output_keys (list): list of additional things that are observed by sensors; defaults to empty
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False
"""
def __init__(self,
param_dict,
est_params,
state_keys,
state_dot_keys=[],
simulate_gt=False,
additional_output_keys=[],
use_torch_tensor=False):
partial_init(self,
RoverPartialDynEst,
est_params,
param_dict,
state_keys,
simulate_gt,
state_dot_keys,
additional_output_keys,
use_torch_tensor=use_torch_tensor)
def re_initialise(self):
"""
re-initialise after ground truth data has been generated using its parent's derivative and raw possibly time-varying parameters
"""
re_initialise(self)
def dxdt(self, state, u, param_dict):
"""
Obtain derivative of the state based on current state and input similar to RoverDyn. Derivatives of
estimated parameters are zero, i.e. assuming they are constant and not drifting over time.
Args:
state (numpy array [4+len(self.est_params) x 1]): current state of the system consisting of x, y, theta, vx
and estimated parameters
u (numpy array [2 x 1]): current input consisting of steering angle and commanded velocity
param_dict (dict): dictionary of current non-estimated parameters needed for defining the dynamics
Returns:
state_dot (numpy array [4+len(self.est_params) x 1]): derivative of the states
"""
return partial_dxdt(self, RoverPartialDynEst, state, u, param_dict)
class OneWheelFriction(AbstractDyn):
"""
Class derived from AbstractDyn class
model from: "Application of Extended Kalman Filter for Road Condition Estimation" paper
inputs = [wheel torque]
states = [v, w, z]
The assumptions of this model are:
(i) velocity is longitudinal only, i.e. no lateral component
(ii) Tire model taken LuGre dynamic model with steady-state error compensation
The model parameters are:
sigma_0: rubber longitudinal lumped stiffness (1/m)
sigma_1: rubber longitudinal lumped damping (s/m)
sigma_2: viscous relative damping (Ns/m)
sigma_w: coefficient of viscous friction (Nm/s)
L: contact patch length (m)
mu_c: normalised Coulomb friction
mu_s: normalised static friction
vs: Stribeck relative velocity (m/s)
theta: road condition coefficient
r: wheel radius
m: wheel mass (kg)
J: moment of inertia of the wheel (kgm^2)
k: lumped model constant (usually between 1.2 and 1.4)
Fn: normal force
Args:
param_dict (dict): dictionary of parameters needed for defining the dynamics
state_keys (list): list of states string that are observed by sensor
state_dot_keys (list): list of derivative of states string that are observed by sensor; defaults to empty
additional_output_keys (list): list of additional things that are observed by sensors; defaults to empty
use_torch_tensor (bool): whether to use tensor instead of numpy arrays; defaults to False
"""
# state dictionary for this model
global_state_dict = {'v': 0, 'w': 1, 'z': 2}
# expected keys/parameters of this model
global_expected_keys = [
"sigma_0", "sigma_1", "sigma_2", "sigma_w", "L", "mu_c", "mu_s", "vs",
"theta", "r", "m", "J", "k", "Fn"
]
tensor_compliance = True
def __init__(self,
param_dict,
state_keys,
state_dot_keys=[],
additional_output_keys=[],
use_torch_tensor=False):
super(OneWheelFriction,
self).__init__(param_dict,
state_keys=state_keys,
state_dot_keys=state_dot_keys,
additional_output_keys=additional_output_keys,
use_torch_tensor=use_torch_tensor)
# specify expected dimensionality of input
self.num_in = 1
def dxdt(self, state, u, param_dict):
"""
Obtain derivative of the state based on current state and input
Args:
state(numpy array[3 x 1]): current state of the system consisting of v, w and z
u(numpy array[1 x 1]): current input consisting of torque acting on wheel axis
param_dict(dict): dictionary of current parameters needed for defining the dynamics
Returns:
state_dot(numpy array[3 x 1]): derivative of the states
"""
# get the parameters
mu_c = param_dict['mu_c']
mu_s = param_dict['mu_s']
vs = param_dict['vs']
Fn = param_dict['Fn']
m = param_dict['m']
sigma_0 = param_dict['sigma_0']
sigma_1 = param_dict['sigma_1']
sigma_2 = param_dict['sigma_2']
sigma_w = param_dict['sigma_w']
r = param_dict['r']
theta = param_dict['theta']
k = param_dict['k']
L = param_dict['L']
J = param_dict['J']
# get the inputs
if isinstance(u, Iterable):
ur = u[0]
else:
ur = u
# get the states
v = state[self.state_dict['v']]
z = state[self.state_dict['z']]
w = state[self.state_dict['w']]
# define function
def gvr(vr):
if self.use_torch_tensor:
return mu_c + (
mu_s - mu_c) * torch.exp(-torch.sqrt(torch.abs(vr / vs)))
else:
return mu_c + (mu_s -
mu_c) * math.exp(-math.sqrt(math.fabs(vr / vs)))
# calculate the state derivatives
vr = r * w - v
if self.use_torch_tensor:
zdot = vr - z * (theta * sigma_0 * torch.abs(vr) / gvr(vr) +
k * r * torch.abs(w) / L)
else:
zdot = vr - z * (theta * sigma_0 * math.fabs(vr) / gvr(vr) +
k * r * math.fabs(w) / L)
vdot = Fn / m * (sigma_0 * z + sigma_1 * zdot + sigma_2 * vr)
wdot = (-r * Fn *
(sigma_0 * z + sigma_1 * zdot) - sigma_w * w + ur) / J
if self.use_torch_tensor:
return torch.stack([vdot, wdot, zdot]).unsqueeze(0)
else:
return np.array([[vdot, wdot, zdot]])
class OneWheelFrictionEst(OneWheelFriction):
"""
Class derived from OneWheelFriction class
model from: same as OneWheelFriction but some parameters are the states themselves to be estimated online
inputs = [wheel torque]