-
Notifications
You must be signed in to change notification settings - Fork 46
/
dynamics_functions.py
1099 lines (970 loc) · 42.4 KB
/
dynamics_functions.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
from casadi import horzcat, vertcat, MX, SX
from ..misc.enums import RigidBodyDynamics, DefectType
from .fatigue.fatigue_dynamics import FatigueList
from ..optimization.optimization_variable import OptimizationVariable
from ..optimization.non_linear_program import NonLinearProgram
from .dynamics_evaluation import DynamicsEvaluation
from ..interfaces.stochastic_bio_model import StochasticBioModel
class DynamicsFunctions:
"""
Implementation of all the dynamic functions
Methods
-------
custom(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp: NonLinearProgram) -> MX
Interface to custom dynamic function provided by the user
torque_driven(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp, with_contact: bool)
Forward dynamics driven by joint torques, optional external forces can be declared.
torque_activations_driven(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp, with_contact) -> MX:
Forward dynamics driven by joint torques activations.
torque_derivative_driven(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp, with_contact: bool) -> MX:
Forward dynamics driven by joint torques, optional external forces can be declared.
forces_from_torque_driven(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp) -> MX:
Contact forces of a forward dynamics driven by joint torques with contact constraints.
muscles_driven(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp, with_contact: bool) -> MX:
Forward dynamics driven by muscle.
forces_from_muscle_driven(states: MX.sym, controls: MX.sym, parameters: MX.sym, nlp) -> MX:
Contact forces of a forward dynamics driven by muscles activations and joint torques with contact constraints.
get(var: OptimizationVariable, cx: MX | SX):
Main accessor to a variable in states or controls (cx)
apply_parameters(parameters: MX.sym, nlp: NonLinearProgram)
Apply the parameter variables to the model. This should be called before calling the dynamics
reshape_qdot(nlp: NonLinearProgram, q: MX | SX, qdot: MX | SX):
Easy accessor to derivative of q
forward_dynamics(nlp: NonLinearProgram, q: MX | SX, qdot: MX | SX, tau: MX | SX, with_contact: bool):
Easy accessor to derivative of qdot
compute_muscle_dot(nlp: NonLinearProgram, muscle_excitations: MX | SX):
Easy accessor to derivative of muscle activations
compute_tau_from_muscle(nlp: NonLinearProgram, q: MX | SX, qdot: MX | SX, muscle_activations: MX | SX):
Easy accessor to tau computed from muscles
"""
@staticmethod
def custom(
time: MX.sym, states: MX.sym, controls: MX.sym, parameters: MX.sym, stochastic_variables: MX.sym, nlp
) -> DynamicsEvaluation:
"""
Interface to custom dynamic function provided by the user.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
Returns
----------
MX.sym
The derivative of the states
MX.sym
The defects of the implicit dynamics
"""
return nlp.dynamics_type.dynamic_function(time, states, controls, parameters, stochastic_variables, nlp)
@staticmethod
def torque_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_contact: bool,
with_passive_torque: bool,
with_ligament: bool,
with_friction: bool,
rigidbody_dynamics: RigidBodyDynamics,
fatigue: FatigueList,
external_forces: list = None,
) -> DynamicsEvaluation:
"""
Forward dynamics driven by joint torques, optional external forces can be declared.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
with_contact: bool
If the dynamic with contact should be used
with_passive_torque: bool
If the dynamic with passive torque should be used
with_ligament: bool
If the dynamic with ligament should be used
with_friction: bool
If the dynamic with friction should be used
rigidbody_dynamics: RigidBodyDynamics
which rigidbody dynamics should be used
fatigue : FatigueList
A list of fatigue elements
Returns
----------
DynamicsEvaluation
The derivative of the states and the defects of the implicit dynamics
"""
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
dq = DynamicsFunctions.compute_qdot(nlp, q, qdot)
tau = DynamicsFunctions.__get_fatigable_tau(nlp, states, controls, fatigue)
tau = tau + nlp.model.passive_joint_torque(q, qdot) if with_passive_torque else tau
tau = tau + nlp.model.ligament_joint_torque(q, qdot) if with_ligament else tau
tau = tau + nlp.model.friction_coefficients @ qdot if with_friction else tau
if (
rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS
or rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS
):
dxdt = MX(nlp.states.shape, 1)
dxdt[nlp.states["q"].index, :] = dq
dxdt[nlp.states["qdot"].index, :] = DynamicsFunctions.get(nlp.controls["qddot"], controls)
elif (
rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS_JERK
or rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS_JERK
):
dxdt = MX(nlp.states.shape, 1)
dxdt[nlp.states["q"].index, :] = dq
qddot = DynamicsFunctions.get(nlp.states["qddot"], states)
dxdt[nlp.states["qdot"].index, :] = qddot
dxdt[nlp.states["qddot"].index, :] = DynamicsFunctions.get(nlp.controls["qdddot"], controls)
else:
ddq = DynamicsFunctions.forward_dynamics(nlp, q, qdot, tau, with_contact, external_forces)
dxdt = MX(nlp.states.shape, ddq.shape[1])
dxdt[nlp.states["q"].index, :] = horzcat(*[dq for _ in range(ddq.shape[1])])
dxdt[nlp.states["qdot"].index, :] = ddq
if fatigue is not None and "tau" in fatigue:
dxdt = fatigue["tau"].dynamics(dxdt, nlp, states, controls)
defects = None
# TODO: contacts and fatigue to be handled with implicit dynamics
if rigidbody_dynamics is not RigidBodyDynamics.ODE or (
rigidbody_dynamics is RigidBodyDynamics.ODE and nlp.ode_solver.defects_type == DefectType.IMPLICIT
):
if not with_contact and fatigue is None:
qddot = DynamicsFunctions.get(nlp.states_dot["qddot"], nlp.states_dot.scaled.mx_reduced)
tau_id = DynamicsFunctions.inverse_dynamics(nlp, q, qdot, qddot, with_contact)
defects = MX(dq.shape[0] + tau_id.shape[0], tau_id.shape[1])
dq_defects = []
for _ in range(tau_id.shape[1]):
dq_defects.append(
dq
- DynamicsFunctions.compute_qdot(
nlp,
q,
DynamicsFunctions.get(nlp.states_dot.scaled["qdot"], nlp.states_dot.scaled.mx_reduced),
)
)
defects[: dq.shape[0], :] = horzcat(*dq_defects)
# We modified on purpose the size of the tau to keep the zero in the defects in order to respect the dynamics
defects[dq.shape[0] :, :] = tau - tau_id
return DynamicsEvaluation(dxdt, defects)
@staticmethod
def stochastic_torque_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_contact: bool,
with_friction: bool,
) -> DynamicsEvaluation:
"""
Forward dynamics subject to motor and sensory noise driven by joint torques, optional external forces can be declared.
Parameters
----------
time: MX.sym
The time
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic variables of the system
nlp: NonLinearProgram
The definition of the system
with_contact: bool
If the dynamic with contact should be used
with_friction: bool
If the dynamic with friction should be used
Returns
----------
DynamicsEvaluation
The derivative of the states and the defects of the implicit dynamics
"""
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
tau = DynamicsFunctions.get(nlp.controls["tau"], controls)
ref = DynamicsFunctions.get(nlp.stochastic_variables["ref"], stochastic_variables)
k = DynamicsFunctions.get(nlp.stochastic_variables["k"], stochastic_variables)
k_matrix = StochasticBioModel.reshape_to_matrix(k, nlp.model.matrix_shape_k)
sensory_input = nlp.model.sensory_reference(states, controls, parameters, stochastic_variables, nlp)
mapped_motor_noise = nlp.model.motor_noise_sym
mapped_sensory_feedback_torque = k_matrix @ ((sensory_input - ref) + nlp.model.sensory_noise_sym)
if "tau" in nlp.model.motor_noise_mapping.keys():
mapped_motor_noise = nlp.model.motor_noise_mapping["tau"].to_second.map(nlp.model.motor_noise_sym)
mapped_sensory_feedback_torque = nlp.model.motor_noise_mapping["tau"].to_second.map(
mapped_sensory_feedback_torque
)
tau += mapped_motor_noise + mapped_sensory_feedback_torque
tau = tau + nlp.model.friction_coefficients @ qdot if with_friction else tau
# dq = DynamicsFunctions.compute_qdot(nlp, q, qdot)
dq = qdot
ddq = DynamicsFunctions.forward_dynamics(nlp, q, qdot, tau, with_contact)
dxdt = MX(nlp.states.shape, ddq.shape[1])
dxdt[nlp.states["q"].index, :] = horzcat(*[dq for _ in range(ddq.shape[1])])
dxdt[nlp.states["qdot"].index, :] = ddq
return DynamicsEvaluation(dxdt=dxdt, defects=None)
@staticmethod
def __get_fatigable_tau(nlp: NonLinearProgram, states: MX, controls: MX, fatigue: FatigueList) -> MX:
"""
Apply the forward dynamics including (or not) the torque fatigue
Parameters
----------
nlp: NonLinearProgram
The current phase
states: MX
The states variable that may contains the tau and the tau fatigue variables
controls: MX
The controls variable that may contains the tau
fatigue: FatigueList
The dynamics for the torque fatigue
Returns
-------
The generalized accelerations
"""
tau_var, tau_mx = (nlp.controls, controls) if "tau" in nlp.controls else (nlp.states, states)
tau = DynamicsFunctions.get(tau_var["tau"], tau_mx)
if fatigue is not None and "tau" in fatigue:
tau_fatigue = fatigue["tau"]
tau_suffix = fatigue["tau"].suffix
# Only homogeneous state_only is implemented yet
n_state_only = sum([t.models.state_only for t in tau_fatigue])
if 0 < n_state_only < len(fatigue["tau"]):
raise NotImplementedError("fatigue list without homogeneous state_only flag is not supported yet")
apply_to_joint_dynamics = sum([t.models.apply_to_joint_dynamics for t in tau_fatigue])
if 0 < n_state_only < len(fatigue["tau"]):
raise NotImplementedError(
"fatigue list without homogeneous apply_to_joint_dynamics flag is not supported yet"
)
if apply_to_joint_dynamics != 0:
raise NotImplementedError("apply_to_joint_dynamics is not implemented for joint torque")
if not tau_fatigue[0].models.split_controls and "tau" in nlp.controls:
pass
elif tau_fatigue[0].models.state_only:
tau = sum([DynamicsFunctions.get(tau_var[f"tau_{suffix}"], tau_mx) for suffix in tau_suffix])
else:
tau = MX()
for i, t in enumerate(tau_fatigue):
tau_tp = MX(1, 1)
for suffix in tau_suffix:
model = t.models.models[suffix]
tau_tp += (
DynamicsFunctions.get(nlp.states[f"tau_{suffix}_{model.dynamics_suffix()}"], states)[i]
* model.scaling
)
tau = vertcat(tau, tau_tp)
return tau
@staticmethod
def torque_activations_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_contact: bool,
with_passive_torque: bool,
with_residual_torque: bool,
with_ligament: bool,
external_forces: list = None,
):
"""
Forward dynamics driven by joint torques activations.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
with_contact: bool
If the dynamic with contact should be used
with_passive_torque: bool
If the dynamic with passive torque should be used
with_residual_torque: bool
If the dynamic should be added with residual torques
with_ligament: bool
If the dynamic with ligament should be used
external_forces: list[Any]
The external forces
Returns
----------
DynamicsEvaluation
The derivative of the states and the defects of the implicit dynamics
"""
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
tau_activation = DynamicsFunctions.get(nlp.controls["tau"], controls)
tau = nlp.model.torque(tau_activation, q, qdot)
if with_passive_torque:
tau += nlp.model.passive_joint_torque(q, qdot)
if with_residual_torque:
tau += DynamicsFunctions.get(nlp.controls["residual_tau"], controls)
if with_ligament:
tau += nlp.model.ligament_joint_torque(q, qdot)
dq = DynamicsFunctions.compute_qdot(nlp, q, qdot)
ddq = DynamicsFunctions.forward_dynamics(nlp, q, qdot, tau, with_contact, external_forces)
dq = horzcat(*[dq for _ in range(ddq.shape[1])])
return DynamicsEvaluation(dxdt=vertcat(dq, ddq), defects=None)
@staticmethod
def torque_derivative_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
rigidbody_dynamics: RigidBodyDynamics,
with_contact: bool,
with_passive_torque: bool,
with_ligament: bool,
external_forces: list = None,
) -> DynamicsEvaluation:
"""
Forward dynamics driven by joint torques, optional external forces can be declared.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
rigidbody_dynamics: RigidBodyDynamics
which rigidbody dynamics should be used
with_contact: bool
If the dynamic with contact should be used
with_passive_torque: bool
If the dynamic with passive torque should be used
with_ligament: bool
If the dynamic with ligament should be used
external_forces: list[Any]
The external forces
Returns
----------
DynamicsEvaluation
The derivative of the states and the defects of the implicit dynamics
"""
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
tau = DynamicsFunctions.get(nlp.states["tau"], states)
tau = tau + nlp.model.passive_joint_torque(q, qdot) if with_passive_torque else tau
tau = tau + nlp.model.ligament_joint_torque(q, qdot) if with_ligament else tau
dq = DynamicsFunctions.compute_qdot(nlp, q, qdot)
dtau = DynamicsFunctions.get(nlp.controls["taudot"], controls)
if (
rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS
or rigidbody_dynamics == RigidBodyDynamics.DAE_FORWARD_DYNAMICS
):
ddq = DynamicsFunctions.get(nlp.states["qddot"], states)
dddq = DynamicsFunctions.get(nlp.controls["qdddot"], controls)
dxdt = MX(nlp.states.shape, 1)
dxdt[nlp.states["q"].index, :] = dq
dxdt[nlp.states["qdot"].index, :] = ddq
dxdt[nlp.states["qddot"].index, :] = dddq
dxdt[nlp.states["tau"].index, :] = dtau
else:
ddq = DynamicsFunctions.forward_dynamics(nlp, q, qdot, tau, with_contact, external_forces)
dxdt = MX(nlp.states.shape, ddq.shape[1])
dxdt[nlp.states["q"].index, :] = horzcat(*[dq for _ in range(ddq.shape[1])])
dxdt[nlp.states["qdot"].index, :] = ddq
dxdt[nlp.states["tau"].index, :] = horzcat(*[dtau for _ in range(ddq.shape[1])])
return DynamicsEvaluation(dxdt=dxdt, defects=None)
@staticmethod
def forces_from_torque_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_passive_torque: bool = False,
with_ligament: bool = False,
external_forces: list = None,
) -> MX:
"""
Contact forces of a forward dynamics driven by joint torques with contact constraints.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic variables of the system
nlp: NonLinearProgram
The definition of the system
with_passive_torque: bool
If the dynamic with passive torque should be used
with_ligament: bool
If the dynamic with ligament should be used
external_forces: list[Any]
The external forces
Returns
----------
MX.sym
The contact forces that ensure no acceleration at these contact points
"""
q_nlp, q_var = (nlp.states["q"], states) if "q" in nlp.states else (nlp.controls["q"], controls)
qdot_nlp, qdot_var = (nlp.states["qdot"], states) if "qdot" in nlp.states else (nlp.controls["qdot"], controls)
tau_nlp, tau_var = (nlp.states["tau"], states) if "tau" in nlp.states else (nlp.controls["tau"], controls)
q = DynamicsFunctions.get(q_nlp, q_var)
qdot = DynamicsFunctions.get(qdot_nlp, qdot_var)
tau = DynamicsFunctions.get(tau_nlp, tau_var)
tau = tau + nlp.model.passive_joint_torque(q, qdot) if with_passive_torque else tau
tau = tau + nlp.model.ligament_joint_torque(q, qdot) if with_ligament else tau
return nlp.model.contact_forces(q, qdot, tau, external_forces)
@staticmethod
def forces_from_torque_activation_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_passive_torque: bool = False,
with_ligament: bool = False,
external_forces: list = None,
) -> MX:
"""
Contact forces of a forward dynamics driven by joint torques with contact constraints.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
with_passive_torque: bool
If the dynamic with passive torque should be used
with_ligament: bool
If the dynamic with ligament should be used
external_forces: list[Any]
The external forces
Returns
----------
MX.sym
The contact forces that ensure no acceleration at these contact points
"""
q_nlp, q_var = (nlp.states["q"], states) if "q" in nlp.states else (nlp.controls["q"], controls)
qdot_nlp, qdot_var = (nlp.states["qdot"], states) if "qdot" in nlp.states else (nlp.controls["qdot"], controls)
tau_nlp, tau_var = (nlp.states["tau"], states) if "tau" in nlp.states else (nlp.controls["tau"], controls)
q = DynamicsFunctions.get(q_nlp, q_var)
qdot = DynamicsFunctions.get(qdot_nlp, qdot_var)
tau_activations = DynamicsFunctions.get(tau_nlp, tau_var)
tau = nlp.model.torque(tau_activations, q, qdot)
tau = tau + nlp.model.passive_joint_torque(q, qdot) if with_passive_torque else tau
tau = tau + nlp.model.ligament_joint_torque(q, qdot) if with_ligament else tau
return nlp.model.contact_forces(q, qdot, tau, external_forces)
@staticmethod
def muscles_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_contact: bool,
with_passive_torque: bool = False,
with_ligament: bool = False,
rigidbody_dynamics: RigidBodyDynamics = RigidBodyDynamics.ODE,
with_residual_torque: bool = False,
fatigue=None,
external_forces: list = None,
) -> DynamicsEvaluation:
"""
Forward dynamics driven by muscle.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
with_contact: bool
If the dynamic with contact should be used
with_passive_torque: bool
If the dynamic with passive torque should be used
with_ligament: bool
If the dynamic with ligament should be used
rigidbody_dynamics: RigidBodyDynamics
which rigidbody dynamics should be used
fatigue: FatigueDynamicsList
To define fatigue elements
with_residual_torque: bool
If the dynamic should be added with residual torques
external_forces: list[Any]
The external forces
Returns
----------
DynamicsEvaluation
The derivative of the states and the defects of the implicit dynamics
"""
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
residual_tau = (
DynamicsFunctions.__get_fatigable_tau(nlp, states, controls, fatigue) if with_residual_torque else None
)
mus_act_nlp, mus_act = (nlp.states, states) if "muscles" in nlp.states else (nlp.controls, controls)
mus_activations = DynamicsFunctions.get(mus_act_nlp["muscles"], mus_act)
fatigue_states = None
if fatigue is not None and "muscles" in fatigue:
mus_fatigue = fatigue["muscles"]
fatigue_name = mus_fatigue.suffix[0]
# Sanity check
n_state_only = sum([m.models.state_only for m in mus_fatigue])
if 0 < n_state_only < len(fatigue["muscles"]):
raise NotImplementedError(
f"{fatigue_name} list without homogeneous state_only flag is not supported yet"
)
apply_to_joint_dynamics = sum([m.models.apply_to_joint_dynamics for m in mus_fatigue])
if 0 < apply_to_joint_dynamics < len(fatigue["muscles"]):
raise NotImplementedError(
f"{fatigue_name} list without homogeneous apply_to_joint_dynamics flag is not supported yet"
)
dyn_suffix = mus_fatigue[0].models.models[fatigue_name].dynamics_suffix()
fatigue_suffix = mus_fatigue[0].models.models[fatigue_name].fatigue_suffix()
for m in mus_fatigue:
for key in m.models.models:
if (
m.models.models[key].dynamics_suffix() != dyn_suffix
or m.models.models[key].fatigue_suffix() != fatigue_suffix
):
raise ValueError(f"{fatigue_name} must be of all same types")
if n_state_only == 0:
mus_activations = DynamicsFunctions.get(nlp.states[f"muscles_{dyn_suffix}"], states)
if apply_to_joint_dynamics > 0:
fatigue_states = DynamicsFunctions.get(nlp.states[f"muscles_{fatigue_suffix}"], states)
muscles_tau = DynamicsFunctions.compute_tau_from_muscle(nlp, q, qdot, mus_activations, fatigue_states)
tau = muscles_tau + residual_tau if residual_tau is not None else muscles_tau
tau = tau + nlp.model.passive_joint_torque(q, qdot) if with_passive_torque else tau
tau = tau + nlp.model.ligament_joint_torque(q, qdot) if with_ligament else tau
dq = DynamicsFunctions.compute_qdot(nlp, q, qdot)
if rigidbody_dynamics == RigidBodyDynamics.DAE_INVERSE_DYNAMICS:
ddq = DynamicsFunctions.get(nlp.controls["qddot"], controls)
dxdt = MX(nlp.states.shape, 1)
dxdt[nlp.states["q"].index, :] = dq
dxdt[nlp.states["qdot"].index, :] = DynamicsFunctions.get(nlp.controls["qddot"], controls)
else:
ddq = DynamicsFunctions.forward_dynamics(nlp, q, qdot, tau, with_contact, external_forces)
dxdt = MX(nlp.states.shape, ddq.shape[1])
dxdt[nlp.states["q"].index, :] = horzcat(*[dq for _ in range(ddq.shape[1])])
dxdt[nlp.states["qdot"].index, :] = ddq
has_excitation = True if "muscles" in nlp.states else False
if has_excitation:
mus_excitations = DynamicsFunctions.get(nlp.controls["muscles"], controls)
dmus = DynamicsFunctions.compute_muscle_dot(nlp, mus_excitations)
dxdt[nlp.states["muscles"].index, :] = horzcat(*[dmus for _ in range(ddq.shape[1])])
if fatigue is not None and "muscles" in fatigue:
dxdt = fatigue["muscles"].dynamics(dxdt, nlp, states, controls)
defects = None
# TODO: contacts and fatigue to be handled with implicit dynamics
if rigidbody_dynamics is not RigidBodyDynamics.ODE or (
rigidbody_dynamics is RigidBodyDynamics.ODE and nlp.ode_solver.defects_type == DefectType.IMPLICIT
):
if not with_contact and fatigue is None:
qddot = DynamicsFunctions.get(nlp.states_dot["qddot"], nlp.states_dot.mx_reduced)
tau_id = DynamicsFunctions.inverse_dynamics(nlp, q, qdot, qddot, with_contact, external_forces)
defects = MX(dq.shape[0] + tau_id.shape[0], tau_id.shape[1])
dq_defects = []
for _ in range(tau_id.shape[1]):
dq_defects.append(
dq
- DynamicsFunctions.compute_qdot(
nlp,
q,
DynamicsFunctions.get(nlp.states_dot["qdot"], nlp.states_dot.mx_reduced),
)
)
defects[: dq.shape[0], :] = horzcat(*dq_defects)
defects[dq.shape[0] :, :] = tau - tau_id
return DynamicsEvaluation(dxdt=dxdt, defects=defects)
@staticmethod
def forces_from_muscle_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
with_passive_torque: bool = False,
with_ligament: bool = False,
external_forces: list = None,
) -> MX:
"""
Contact forces of a forward dynamics driven by muscles activations and joint torques with contact constraints.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
with_passive_torque: bool
If the dynamic with passive torque should be used
with_ligament: bool
If the dynamic with ligament should be used
external_forces: list[Any]
The external forces
Returns
----------
MX.sym
The contact forces that ensure no acceleration at these contact points
"""
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
residual_tau = DynamicsFunctions.get(nlp.controls["tau"], controls) if "tau" in nlp.controls else None
mus_act_nlp, mus_act = (nlp.states, states) if "muscles" in nlp.states else (nlp.controls, controls)
mus_activations = DynamicsFunctions.get(mus_act_nlp["muscles"], mus_act)
muscles_tau = DynamicsFunctions.compute_tau_from_muscle(nlp, q, qdot, mus_activations)
tau = muscles_tau + residual_tau if residual_tau is not None else muscles_tau
tau = tau + nlp.model.passive_joint_torque(q, qdot) if with_passive_torque else tau
tau = tau + nlp.model.ligament_joint_torque(q, qdot) if with_ligament else tau
return nlp.model.contact_forces(q, qdot, tau, external_forces)
@staticmethod
def joints_acceleration_driven(
time: MX.sym,
states: MX.sym,
controls: MX.sym,
parameters: MX.sym,
stochastic_variables: MX.sym,
nlp,
rigidbody_dynamics: RigidBodyDynamics = RigidBodyDynamics.ODE,
) -> DynamicsEvaluation:
"""
Forward dynamics driven by joints accelerations of a free floating body.
Parameters
----------
time: MX.sym
The time of the system
states: MX.sym
The state of the system
controls: MX.sym
The controls of the system
parameters: MX.sym
The parameters of the system
stochastic_variables: MX.sym
The stochastic_variables of the system
nlp: NonLinearProgram
The definition of the system
rigidbody_dynamics: RigidBodyDynamics
which rigid body dynamics to use
Returns
----------
MX.sym
The derivative of states
"""
if rigidbody_dynamics != RigidBodyDynamics.ODE:
raise NotImplementedError("Implicit dynamics not implemented yet.")
q = DynamicsFunctions.get(nlp.states["q"], states)
qdot = DynamicsFunctions.get(nlp.states["qdot"], states)
qddot_joints = DynamicsFunctions.get(nlp.controls["qddot_joints"], controls)
qddot_root = nlp.model.forward_dynamics_free_floating_base(q, qdot, qddot_joints)
qddot_reordered = nlp.model.reorder_qddot_root_joints(qddot_root, qddot_joints)
qdot_mapped = nlp.variable_mappings["qdot"].to_first.map(qdot)
qddot_mapped = nlp.variable_mappings["qdot"].to_first.map(qddot_reordered)
qddot_root_mapped = nlp.variable_mappings["qddot_roots"].to_first.map(qddot_root)
qddot_joints_mapped = nlp.variable_mappings["qddot_joints"].to_first.map(qddot_joints)
# defects
defects = None
if rigidbody_dynamics is not RigidBodyDynamics.ODE or (
rigidbody_dynamics is RigidBodyDynamics.ODE and nlp.ode_solver.defects_type == DefectType.IMPLICIT
):
qddot_root_defects = DynamicsFunctions.get(nlp.states_dot["qddot_roots"], nlp.states_dot.mx_reduced)
qddot_defects_reordered = nlp.model.reorder_qddot_root_joints(qddot_root_defects, qddot_joints)
floating_base_constraint = nlp.model.inverse_dynamics(q, qdot, qddot_defects_reordered)[: nlp.model.nb_root]
defects = MX(qdot_mapped.shape[0] + qddot_root_mapped.shape[0] + qddot_joints_mapped.shape[0], 1)
defects[: qdot_mapped.shape[0], :] = qdot_mapped - nlp.variable_mappings["qdot"].to_first.map(
DynamicsFunctions.compute_qdot(
nlp, q, DynamicsFunctions.get((nlp.states_dot["qdot"]), nlp.states_dot.mx_reduced)
)
)
defects[
qdot_mapped.shape[0] : (qdot_mapped.shape[0] + qddot_root_mapped.shape[0]), :
] = floating_base_constraint
defects[
(qdot_mapped.shape[0] + qddot_root_mapped.shape[0]) :, :
] = qddot_joints_mapped - nlp.variable_mappings["qddot_joints"].to_first.map(
DynamicsFunctions.get(nlp.states_dot["qddot_joints"], nlp.states_dot.mx_reduced)
)
return DynamicsEvaluation(dxdt=vertcat(qdot_mapped, qddot_mapped), defects=defects)
@staticmethod
def get(var: OptimizationVariable, cx: MX | SX):
"""
Main accessor to a variable in states or controls (cx)
Parameters
----------
var: OptimizationVariable
The variable from nlp.states["name"] or nlp.controls["name"]
cx: MX | SX
The actual SX or MX variables
Returns
-------
The sliced values
"""
return var.mapping.to_second.map(cx[var.index, :])
@staticmethod
def apply_parameters(parameters: MX.sym, nlp):
"""
Apply the parameter variables to the model. This should be called before calling the dynamics
Parameters
----------
parameters: MX.sym
The state of the system
nlp: NonLinearProgram
The definition of the system
"""
for param in nlp.parameters:
# Call the pre dynamics function
if param.function[0]:
param.function[0](nlp.model, parameters[param.index], **param.params)
@staticmethod
def compute_qdot(nlp: NonLinearProgram, q: MX | SX, qdot: MX | SX):
"""
Easy accessor to derivative of q
Parameters
----------
nlp: NonLinearProgram
The phase of the program
q: MX | SX
The value of q from "get"
qdot: MX | SX
The value of qdot from "get"
Returns
-------
The derivative of q
"""
q_nlp = nlp.states["q"] if "q" in nlp.states else nlp.controls["q"]
return q_nlp.mapping.to_first.map(nlp.model.reshape_qdot(q, qdot))
@staticmethod
def forward_dynamics(
nlp: NonLinearProgram,
q: MX | SX,
qdot: MX | SX,
tau: MX | SX,
with_contact: bool,
external_forces: list = None,
):
"""
Easy accessor to derivative of qdot
Parameters
----------
nlp: NonLinearProgram
The phase of the program
q: MX | SX
The value of q from "get"
qdot: MX | SX
The value of qdot from "get"
tau: MX | SX
The value of tau from "get"
with_contact: bool
If the dynamics with contact should be used
external_forces: list[]
The external forces
Returns
-------
The derivative of qdot
"""
qdot_var = nlp.states["qdot"] if "qdot" in nlp.states else nlp.controls["qdot"]
if external_forces is None:
if with_contact:
qddot = nlp.model.constrained_forward_dynamics(q, qdot, tau)
else:
qddot = nlp.model.forward_dynamics(q, qdot, tau)
return qdot_var.mapping.to_first.map(qddot)
else:
dxdt = MX(len(qdot_var.mapping.to_first), nlp.ns)
for i, f_ext in enumerate(external_forces):
if with_contact:
qddot = nlp.model.constrained_forward_dynamics(q, qdot, tau, f_ext)
else:
qddot = nlp.model.forward_dynamics(q, qdot, tau, f_ext)
dxdt[:, i] = qdot_var.mapping.to_first.map(qddot)
return dxdt
@staticmethod
def inverse_dynamics(
nlp: NonLinearProgram,
q: MX | SX,
qdot: MX | SX,
qddot: MX | SX,
with_contact: bool,
external_forces: list = None,
):
"""
Easy accessor to torques from inverse dynamics
Parameters
----------
nlp: NonLinearProgram
The phase of the program
q: MX | SX
The value of q from "get"
qdot: MX | SX
The value of qdot from "get"
qddot: MX | SX
The value of qddot from "get"
with_contact: bool
If the dynamics with contact should be used
external_forces: list[]
The external forces
Returns
-------
Torques in tau
"""
if nlp.external_forces is None:
tau = nlp.model.inverse_dynamics(q, qdot, qddot)
else:
if "tau" in nlp.states:
tau_shape = nlp.states["tau"].mx.shape[0]
elif "tau" in nlp.controls:
tau_shape = nlp.controls["tau"].mx.shape[0]
else:
tau_shape = nlp.model.nb_tau
tau = MX(tau_shape, nlp.ns)
for i, f_ext in enumerate(nlp.external_forces):
tau[:, i] = nlp.model.inverse_dynamics(q, qdot, qddot, f_ext)