-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1824 lines (1668 loc) · 89.2 KB
/
main.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
'''
This script formulates and solves a trajectory optimization problem such
as to generate a three-dimensional muscle-driven predictive simulation of
human walking.
OpenSim is used for modeling the musculoskeletal model but is not needed
to run this script. In brief, we use a custom version of OpenSim that
supports automatic differentiation. The OpenSim-related part is compiled
in advance as a library, which is then imported as an external function
(details in Falisse et al. 2019b). If you use a different musculoskeletal
model, you will need to use OpenSim's Python API to extract certain model
parameters. See here how to setup your environment to use the Python API:
https://simtk-confluence.stanford.edu/display/OpenSim/Scripting+in+Python.
CasADi is used for automatic differentiation and numerical optimization.
Make sure you install CasADi beforehand: https://web.casadi.org/get/.
Associated publications:
- Falisse et al. (2019a): https://doi.org/10.1098/rsif.2019.0402
- Falisse et al. (2019b): https://doi.org/10.1371/journal.pone.0217730
- Falisse et al. (2022): https://doi.org/10.1371/journal.pone.0256311
Please contact me if you find bugs or have suggestions to improve this
script. There is definitely room for improvement.
Author: Antoine Falisse
Date: 2022/01
'''
import os
import casadi as ca
import numpy as np
import copy
import platform
# High-level settings.
# This script includes both code for solving the problem and for processing the
# results. Yet if you solved the optimal control problem and saved the results,
# you might want to latter only load and process the results without re-solving
# the problem. Playing with the settings below allows you to do exactly that.
solveProblem = True # Set True to solve the optimal control problem.
saveResults = True # Set True to save the results of the optimization.
analyzeResults = True # Set True to analyze the results.
loadResults = True # Set True to load the results of the optimization.
writeMotionFiles = True # Set True to write motion files for use in OpenSim GUI
saveOptimalTrajectories = True # Set True to save optimal trajectories
# Select the case(s) for which you want to solve the associated problem(s) or
# process the results. Specify the settings of the case(s) in the
# 'settings' module.
cases = [str(i) for i in range(42,43)]
# Import settings.
from settings import getSettings
settings = getSettings()
for case in cases:
# %% Settings.
###########################################################################
# Model settings.
model = 'new_model' # default model
if 'model' in settings[case]:
model = settings[case]['model']
knee_axis = '' # default knee flexion axis (FK)
if 'knee_axis' in settings[case]:
knee_axis = '_' + settings[case]['knee_axis']
adjustAchillesTendonStiffness = False # default Achilles tendon stiffness.
if 'adjustAchillesTendonStiffness' in settings[case]:
adjustAchillesTendonStiffness = (
settings[case]['adjustAchillesTendonStiffness'])
withMTP = True # default model includes mtp joints
if 'withMTP' in settings[case]:
withMTP = settings[case]['withMTP']
contactConfiguration = 'generic' # default contact configuration
if 'contactConfiguration' in settings[case]:
contactConfiguration = settings[case]['contactConfiguration']
modelMass = settings[case]['modelMass']
dampingMtp = 0.4
if 'dampingMtp' in settings[case]:
dampingMtp = settings[case]['dampingMtp']
###########################################################################
# Problem formulation settings.
targetSpeed = 1.33 # default target walking.
if 'targetSpeed' in settings[case]:
targetSpeed = settings[case]['targetSpeed']
guessType = 'coldStart' # default initial guess mode.
if 'guessType' in settings[case]:
guessType = settings[case]['guessType']
# Cost term weights.
weights = {'metabolicEnergyRateTerm' : 500, # default.
'activationTerm': 2000,
'jointAccelerationTerm': 50000,
'armExcitationTerm': 1000000,
'passiveTorqueTerm': 1000,
'controls': 0.001}
if 'metabolicEnergyRateTerm' in settings[case]:
weights['metabolicEnergyRateTerm'] = (
settings[case]['metabolicEnergyRateTerm'])
if 'activationTerm' in settings[case]:
weights['activationTerm'] = (
settings[case]['activationTerm'])
if 'jointAccelerationTerm' in settings[case]:
weights['jointAccelerationTerm'] = (
settings[case]['jointAccelerationTerm'])
if 'armExcitationTerm' in settings[case]:
weights['armExcitationTerm'] = (
settings[case]['armExcitationTerm'])
if 'passiveTorqueTerm' in settings[case]:
weights['passiveTorqueTerm'] = (
settings[case]['passiveTorqueTerm'])
if 'controls' in settings[case]:
weights['controls'] = (
settings[case]['controls'])
###########################################################################
# Numerical settings.
tol = 4 # default IPOPT convergence tolerance.
if 'tol' in settings[case]:
tol = settings[case]['tol']
N = 50 # default number of mesh intervals.
if 'N' in settings[case]:
N = settings[case]['N']
d = 3 # default interpolating polynomial order.
if 'd' in settings[case]:
d = settings[case]['d']
nThreads = 10 # default number of threads.
if 'nThreads' in settings[case]:
nThreads = settings[case]['nThreads']
parallelMode = "thread" # only supported mode.
# %% Paths.
pathMain = os.getcwd()
pathOpenSimModel = os.path.join(pathMain, 'OpenSimModel')
pathData = os.path.join(pathOpenSimModel, model)
pathModelFolder = os.path.join(pathData, 'Model')
if withMTP:
modelName = '{}_scaled{}'.format(model, knee_axis)
else:
modelName = '{}_noMTP_scaled{}'.format(model, knee_axis)
pathModel = os.path.join(pathModelFolder, modelName + '.osim')
pathMuscleAnalysis = os.path.join(pathData, 'MA', 'ResultsMA', modelName,
modelName + '_MuscleAnalysis_')
pathExternalFunction = os.path.join(pathModelFolder, 'ExternalFunction')
pathCase = 'Case_' + case
pathTrajectories = os.path.join(pathMain, 'Results')
pathResults = os.path.join(pathTrajectories, pathCase)
os.makedirs(pathResults, exist_ok=True)
# %% Muscles.
# This section is very specific to the OpenSim model being used.
# The list 'muscles' includes all right leg muscles, as well both side
# trunk muscles.
muscles = [
'glut_med1_r', 'glut_med2_r', 'glut_med3_r', 'glut_min1_r',
'glut_min2_r', 'glut_min3_r', 'semimem_r', 'semiten_r', 'bifemlh_r',
'bifemsh_r', 'sar_r', 'add_long_r', 'add_brev_r', 'add_mag1_r',
'add_mag2_r', 'add_mag3_r', 'tfl_r', 'pect_r', 'grac_r',
'glut_max1_r', 'glut_max2_r', 'glut_max3_r', 'iliacus_r', 'psoas_r',
'quad_fem_r', 'gem_r', 'peri_r', 'rect_fem_r', 'vas_med_r',
'vas_int_r', 'vas_lat_r', 'med_gas_r', 'lat_gas_r', 'soleus_r',
'tib_post_r', 'flex_dig_r', 'flex_hal_r', 'tib_ant_r', 'per_brev_r',
'per_long_r', 'per_tert_r', 'ext_dig_r', 'ext_hal_r', 'ercspn_r',
'intobl_r', 'extobl_r', 'ercspn_l', 'intobl_l', 'extobl_l']
rightSideMuscles = muscles[:-3]
leftSideMuscles = [muscle[:-1] + 'l' for muscle in rightSideMuscles]
bothSidesMuscles = leftSideMuscles + rightSideMuscles
nMuscles = len(bothSidesMuscles)
nSideMuscles = len(rightSideMuscles)
# Muscle-tendon parameters.
from muscleData import getMTParameters
# Support loading/saving muscle-tendon parameters such that OpenSim does
# not need to be loaded. In case no muscle-tendon parameters are saved,
# they will be loaded from the model using OpenSim's Python API.
loadMTParameters = False
if os.path.exists(os.path.join(
pathModelFolder, 'mtParameters_{}.npy'.format(modelName))):
loadMTParameters = True
sideMtParameters = getMTParameters(pathModel, rightSideMuscles,
loadMTParameters, modelName,
pathModelFolder)
mtParameters = np.concatenate((sideMtParameters, sideMtParameters), axis=1)
# Tendon stiffness.
from muscleData import tendonStiffness
# Same stiffness for all tendons by default.
sideTendonStiffness = tendonStiffness(nSideMuscles)
# Adjust Achilles tendon stiffness (triceps surae).
if adjustAchillesTendonStiffness:
AchillesTendonStiffness = settings[case]['AchillesTendonStiffness']
musclesAchillesTendon = ['med_gas_r', 'lat_gas_r', 'soleus_r']
idxMusclesAchillesTendon = [
rightSideMuscles.index(muscleAchillesTendon)
for muscleAchillesTendon in musclesAchillesTendon]
sideTendonStiffness[0, idxMusclesAchillesTendon] = (
AchillesTendonStiffness)
tendonStiffness = np.concatenate((sideTendonStiffness,
sideTendonStiffness), axis=1)
# Muscle specific tension.
from muscleData import specificTension
sideSpecificTension = specificTension(rightSideMuscles)
specificTension = np.concatenate((sideSpecificTension,
sideSpecificTension), axis=1)
# Hill-equilibrium. We use as muscle model the DeGrooteFregly2016 model
# introduced in: https://pubmed.ncbi.nlm.nih.gov/27001399/.
# In particular, we use the third formulation introduced in the paper,
# with "normalized tendon force as a state and the scaled time derivative
# of the normalized tendon force as a new control simplifying the
# contraction dynamic equations".
from casadiFunctions import hillEquilibrium
f_hillEquilibrium = hillEquilibrium(mtParameters, tendonStiffness,
specificTension)
# Activation dynamics time constants.
activationTimeConstant = 0.015
deactivationTimeConstant = 0.06
# Indices periodic muscles.
idxPerMuscles = (list(range(nSideMuscles, nMuscles)) +
list(range(0, nSideMuscles)))
# %% Joints.
# This section is very specific to the OpenSim model being used.
# The list 'joints' includes all coordinates of the model.
joints = ['pelvis_tilt', 'pelvis_list', 'pelvis_rotation',
'pelvis_tx', 'pelvis_ty', 'pelvis_tz',
'hip_flexion_l', 'hip_adduction_l', 'hip_rotation_l',
'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r',
'knee_angle_l', 'knee_angle_r',
'ankle_angle_l', 'ankle_angle_r',
'subtalar_angle_l', 'subtalar_angle_r',
'mtp_angle_l', 'mtp_angle_r',
'lumbar_extension', 'lumbar_bending', 'lumbar_rotation',
'arm_flex_l', 'arm_add_l', 'arm_rot_l',
'arm_flex_r', 'arm_add_r', 'arm_rot_r',
'elbow_flex_l', 'elbow_flex_r']
# Mtp joints.
mtpJoints = ['mtp_angle_l', 'mtp_angle_r']
nMtpJoints = len(mtpJoints)
if not withMTP:
for joint in mtpJoints:
joints.remove(joint)
nJoints = len(joints)
# Rotational joints.
rotationalJoints = copy.deepcopy(joints)
rotationalJoints.remove('pelvis_tx')
rotationalJoints.remove('pelvis_ty')
rotationalJoints.remove('pelvis_tz')
from utilities import getJointIndices
idxRotJoints = getJointIndices(joints, rotationalJoints)
# Helper lists for periodic constraints.
# The joint positions in periodicQsJointsA after half a gait cycle should
# match the positions in periodicQsJointsB at the first time instant.
# The order matters, eg 'hip_flexion_l' should match 'hip_flexion_r'.
periodicQsJointsA = [
'pelvis_tilt', 'pelvis_ty',
'hip_flexion_l', 'hip_adduction_l', 'hip_rotation_l',
'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r',
'knee_angle_l', 'knee_angle_r',
'ankle_angle_l', 'ankle_angle_r',
'subtalar_angle_l', 'subtalar_angle_r',
'mtp_angle_l', 'mtp_angle_r',
'lumbar_extension',
'arm_flex_l', 'arm_add_l', 'arm_rot_l',
'arm_flex_r', 'arm_add_r', 'arm_rot_r',
'elbow_flex_l', 'elbow_flex_r']
if not withMTP:
for joint in mtpJoints:
periodicQsJointsA.remove(joint)
idxPerQsJointsA = getJointIndices(joints, periodicQsJointsA)
periodicQsJointsB = [
'pelvis_tilt', 'pelvis_ty',
'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r',
'hip_flexion_l', 'hip_adduction_l', 'hip_rotation_l',
'knee_angle_r', 'knee_angle_l',
'ankle_angle_r', 'ankle_angle_l',
'subtalar_angle_r', 'subtalar_angle_l',
'mtp_angle_r', 'mtp_angle_l',
'lumbar_extension',
'arm_flex_r', 'arm_add_r', 'arm_rot_r',
'arm_flex_l', 'arm_add_l', 'arm_rot_l',
'elbow_flex_r', 'elbow_flex_l']
if not withMTP:
for joint in mtpJoints:
periodicQsJointsB.remove(joint)
idxPerQsJointsB = getJointIndices(joints, periodicQsJointsB)
# The joint velocities in periodicQdsJointsA after half a gait cycle
# should match the velocities in periodicQdsJointsB at the first time
# instant.
# The order matters, eg 'hip_flexion_l' should match 'hip_flexion_r'.
periodicQdsJointsA = [
'pelvis_tilt', 'pelvis_tx', 'pelvis_ty',
'hip_flexion_l', 'hip_adduction_l', 'hip_rotation_l',
'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r',
'knee_angle_l', 'knee_angle_r',
'ankle_angle_l', 'ankle_angle_r',
'subtalar_angle_l', 'subtalar_angle_r',
'mtp_angle_l', 'mtp_angle_r',
'lumbar_extension',
'arm_flex_l', 'arm_add_l', 'arm_rot_l',
'arm_flex_r', 'arm_add_r', 'arm_rot_r',
'elbow_flex_l', 'elbow_flex_r']
if not withMTP:
for joint in mtpJoints:
periodicQdsJointsA.remove(joint)
idxPerQdsJointsA = getJointIndices(joints, periodicQdsJointsA)
periodicQdsJointsB = [
'pelvis_tilt', 'pelvis_tx', 'pelvis_ty',
'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r',
'hip_flexion_l', 'hip_adduction_l', 'hip_rotation_l',
'knee_angle_r', 'knee_angle_l',
'ankle_angle_r', 'ankle_angle_l',
'subtalar_angle_r', 'subtalar_angle_l',
'mtp_angle_r', 'mtp_angle_l',
'lumbar_extension',
'arm_flex_r', 'arm_add_r', 'arm_rot_r',
'arm_flex_l', 'arm_add_l', 'arm_rot_l',
'elbow_flex_r', 'elbow_flex_l']
if not withMTP:
for joint in mtpJoints:
periodicQdsJointsB.remove(joint)
idxPerQdsJointsB = getJointIndices(joints, periodicQdsJointsB)
# The joint positions and velocities in periodicOppositeJoints after half
# a gait cycle should be opposite to those at the first time instant.
periodicOppositeJoints = ['pelvis_list', 'pelvis_rotation', 'pelvis_tz',
'lumbar_bending', 'lumbar_rotation']
idxPerOppJoints = getJointIndices(joints, periodicOppositeJoints)
# Arm joints.
armJoints = ['arm_flex_l', 'arm_add_l', 'arm_rot_l',
'arm_flex_r', 'arm_add_r', 'arm_rot_r',
'elbow_flex_l', 'elbow_flex_r']
nArmJoints = len(armJoints)
idxArmJoints = getJointIndices(joints, armJoints)
# The activations in periodicArmJoints after half a gait cycle should
# match the activation in armJoints at the first time instant.
periodicArmJoints = ['arm_flex_r', 'arm_add_r', 'arm_rot_r',
'arm_flex_l', 'arm_add_l', 'arm_rot_l',
'elbow_flex_r', 'elbow_flex_l']
idxPerArmJoints = getJointIndices(armJoints, periodicArmJoints)
# All but arm joints.
noArmJoints = copy.deepcopy(joints)
for joint in armJoints:
noArmJoints.remove(joint)
nNoArmJoints = len(noArmJoints)
idxNoArmJoints = getJointIndices(joints, noArmJoints)
# Ground pelvis joints.
groundPelvisJoints = ['pelvis_tilt', 'pelvis_list', 'pelvis_rotation',
'pelvis_tx', 'pelvis_ty', 'pelvis_tz']
idxGroundPelvisJoints = getJointIndices(joints, groundPelvisJoints)
# Joints with passive torques.
# We here hard code the list to replicate previous results.
passiveTorqueJoints = [
'hip_flexion_r', 'hip_flexion_l', 'hip_adduction_r',
'hip_adduction_l', 'hip_rotation_r', 'hip_rotation_l',
'knee_angle_r', 'knee_angle_l',
'ankle_angle_r', 'ankle_angle_l',
'subtalar_angle_r', 'subtalar_angle_l',
'lumbar_extension', 'lumbar_bending', 'lumbar_rotation',
'mtp_angle_l', 'mtp_angle_r']
if not withMTP:
for joint in mtpJoints:
passiveTorqueJoints.remove(joint)
nPassiveTorqueJoints = len(passiveTorqueJoints)
# Trunk joints.
trunkJoints = ['lumbar_extension', 'lumbar_bending', 'lumbar_rotation']
# Muscle-driven joints.
# We here hard code the list to replicate previous results. The order of
# the coordinates is slightly different as compared to the list joints,
# which results in different constraints order and different trajectories.
muscleDrivenJoints = [
'hip_flexion_l', 'hip_flexion_r', 'hip_adduction_l',
'hip_adduction_r', 'hip_rotation_l', 'hip_rotation_r',
'knee_angle_l', 'knee_angle_r',
'ankle_angle_l', 'ankle_angle_r',
'subtalar_angle_l', 'subtalar_angle_r',
'lumbar_extension', 'lumbar_bending', 'lumbar_rotation']
# %% Polynomial approximations.
# Muscle-tendon lengths, velocities, and moment arms are estimated based
# on polynomial approximations of joint positions and velocities. The
# polynomial coefficients are fitted based on data from OpenSim and saved
# for the current model. See more info in the instructions about how to
# estimate the polynomial coefficients with a different model.
from casadiFunctions import polynomialApproximation
leftPolynomialJoints = [
'hip_flexion_l', 'hip_adduction_l', 'hip_rotation_l', 'knee_angle_l',
'ankle_angle_l', 'subtalar_angle_l', 'mtp_angle_l',
'lumbar_extension', 'lumbar_bending', 'lumbar_rotation']
rightPolynomialJoints = [
'hip_flexion_r', 'hip_adduction_r', 'hip_rotation_r', 'knee_angle_r',
'ankle_angle_r', 'subtalar_angle_r', 'mtp_angle_r',
'lumbar_extension', 'lumbar_bending', 'lumbar_rotation']
if not withMTP:
leftPolynomialJoints.remove(mtpJoints[0])
rightPolynomialJoints.remove(mtpJoints[1])
nPolynomialJoints = len(leftPolynomialJoints)
from muscleData import getPolynomialData
pathCoordinates = os.path.join(pathOpenSimModel, 'templates', 'MA',
'dummy_motion.mot')
loadPolynomialData = False
# Support loading/saving polynomial data such that they do not needed to
# be recomputed every time.
if os.path.exists(os.path.join(
pathModelFolder, 'polynomialData_{}.npy'.format(modelName))):
loadPolynomialData = True
polynomialData = getPolynomialData(
loadPolynomialData, pathModelFolder, modelName, pathCoordinates,
pathMuscleAnalysis, rightPolynomialJoints, muscles)
if loadPolynomialData:
polynomialData = polynomialData.item()
# The function f_polynomial takes as inputs joint positions and velocities
# from one side (trunk included), and returns muscle-tendon lengths,
# velocities, and moments for the muscle of that side (trunk included).
f_polynomial = polynomialApproximation(muscles, polynomialData,
nPolynomialJoints)
leftPolJointIdx = getJointIndices(joints, leftPolynomialJoints)
rightPolJointIdx = getJointIndices(joints, rightPolynomialJoints)
# The left and right polynomialMuscleIndices below are used to identify
# the left and right muscles in the output of f_polynomial. Since
# f_polynomial return data from side muscles (trunk included), we have the
# side leg muscles + all trunk muscles as output. Here we make sure we
# only include the side trunk muscles when identifying all side muscles.
# This is pretty sketchy I know.
rightPolMuscleIdx = [muscles.index(i) for i in rightSideMuscles]
rightTrunkMuscles = ['ercspn_r', 'intobl_r', 'extobl_r']
leftTrunkMuscles = ['ercspn_l', 'intobl_l', 'extobl_l']
leftPolMuscleIdx = (
[muscles.index(i) for i in rightSideMuscles
if i not in rightTrunkMuscles] +
[muscles.index(i) for i in leftTrunkMuscles])
from utilities import getMomentArmIndices
momentArmIndices = getMomentArmIndices(
rightSideMuscles, leftPolynomialJoints, rightPolynomialJoints,
polynomialData)
trunkMomentArmPolynomialIndices = (
[muscles.index(i) for i in leftTrunkMuscles] +
[muscles.index(i) for i in rightTrunkMuscles])
# Plot polynomial approximations (when possible) for sanity check.
plotPolynomials = False
if plotPolynomials:
from polynomials import testPolynomials
momentArms = testPolynomials(pathCoordinates, pathMuscleAnalysis,
rightPolynomialJoints, muscles,
f_polynomial, polynomialData,
momentArmIndices,
trunkMomentArmPolynomialIndices)
# %% External function.
# The external function is written in C++ and compiled as a library, which
# can then be called with CasADi. In the external function, we build the
# OpenSim model and run inverse dynamics. The function takes as inputs
# joint positions, velocities, and accelerations, which are states and
# controls of the optimal control problem. The external function returns
# joint torques as well as some outputs of interest, eg segment origins,
# that you may want to use as part of the problem formulation.
# We distinguish two external functions: F and F1. F is used during the
# problem formulation but F1 is only used for post-processing - F1 has
# outputs we do not use as part of the problem formulation. Having unused
# outputs might slightly impact the optimal control problem, since the
# external function is used for instance when computing the constraint
# Jacobian; the number of inputs and outputs therefore matters.
if platform.system() == 'Windows':
ext_F = '.dll'
elif platform.system() == 'Darwin':
ext_F = '.dylib'
else:
raise ValueError("Platform not supported.")
suff_F = ''
if contactConfiguration == 'generic_low':
suff_F = '_' + contactConfiguration
F = ca.external('F', os.path.join(
pathExternalFunction, modelName + suff_F + ext_F))
if analyzeResults:
F1 = ca.external('F', os.path.join(
pathExternalFunction, modelName + suff_F + '_pp' + ext_F))
# The external function F outputs joint torques, as well as the 2D
# coordinates of some body origins. The order matters. The joint torques
# are returned in the order of the list joints above. The indices of the
# 2D coordinates of the body origins are then hard-coded as follows.
# Origins calcaneus (2D).
idxCalcOr_r = list(range(nJoints, nJoints+2))
idxCalcOr_l = list(range(idxCalcOr_r[-1]+1, idxCalcOr_r[-1]+3))
# Origins femurs (2D).
idxFemurOr_r = list(range(idxCalcOr_l[-1]+1, idxCalcOr_l[-1]+3))
idxFemurOr_l = list(range(idxFemurOr_r[-1]+1, idxFemurOr_r[-1]+3))
# Origins hands (2D).
idxHandOr_r = list(range(idxFemurOr_l[-1]+1, idxFemurOr_l[-1]+3))
idxHandOr_l = list(range(idxHandOr_r[-1]+1, idxHandOr_r[-1]+3))
# Origins tibias (2D).
idxTibiaOr_r = list(range(idxHandOr_l[-1]+1, idxHandOr_l[-1]+3))
idxTibiaOr_l = list(range(idxTibiaOr_r[-1]+1, idxTibiaOr_r[-1]+3))
# Origins toes (2D).
idxToesOr_r = list(range(idxTibiaOr_l[-1]+1, idxTibiaOr_l[-1]+3))
idxToesOr_l = list(range(idxToesOr_r[-1]+1, idxToesOr_r[-1]+3))
# The external function F1 outputs joint torques, ground reaction forces,
# 3D coordinates of the origin of both calcaneus, and ground reaction
# moments. The order matters. The joint torques are returned in the order
# of the list joints above. The indices of the remaining outputs are then
# hard-coded as follows.
# Ground reaction forces (GRFs).
idxGRF_r = list(range(nJoints, nJoints+3))
idxGRF_l = list(range(idxGRF_r[-1]+1, idxGRF_r[-1]+4))
idxGRF = idxGRF_r + idxGRF_l
NGRF = len(idxGRF)
# Origins calcaneus (3D).
idxCalcOr3D_r = list(range(idxGRF_l[-1]+1, idxGRF_l[-1]+4))
idxCalcOr3D_l = list(range(idxCalcOr3D_r[-1]+1, idxCalcOr3D_r[-1]+4))
idxCalcOr3D = idxCalcOr3D_r + idxCalcOr3D_l
NCalcOr3D = len(idxCalcOr3D)
# Ground reaction moments (GRMs).
idxGRM_r = list(range(idxCalcOr3D_l[-1]+1, idxCalcOr3D_l[-1]+4))
idxGRM_l = list(range(idxGRM_r[-1]+1, idxGRM_r[-1]+4))
idxGRM = idxGRM_r + idxGRM_l
NGRM = len(idxGRM)
# Number of outputs of F1.
NF1_out = idxGRM_l[-1] + 1
# %% Metabolic energy model.
maximalIsometricForce = mtParameters[0, :]
optimalFiberLength = mtParameters[1, :]
muscleVolume = np.multiply(maximalIsometricForce, optimalFiberLength)
muscleMass = np.divide(np.multiply(muscleVolume, 1059.7),
np.multiply(specificTension[0, :].T, 1e6))
from muscleData import slowTwitchRatio
sideSlowTwitchRatio = slowTwitchRatio(rightSideMuscles)
slowTwitchRatio = (np.concatenate((sideSlowTwitchRatio,
sideSlowTwitchRatio), axis=1))[0, :].T
smoothingConstant = 10
from casadiFunctions import metabolicsBhargava
f_metabolicsBhargava = metabolicsBhargava(
slowTwitchRatio, maximalIsometricForce, muscleMass, smoothingConstant)
# %% Arm activation dynamics.
from casadiFunctions import armActivationDynamics
f_armActivationDynamics = armActivationDynamics(nArmJoints)
# %% Passive joint torques.
from casadiFunctions import getLimitTorques
from muscleData import passiveTorqueData
damping = 0.1
f_passiveTorque = {}
for joint in passiveTorqueJoints:
f_passiveTorque[joint] = getLimitTorques(
passiveTorqueData(joint)[0],
passiveTorqueData(joint)[1], damping)
from casadiFunctions import getLinearPassiveTorques
stiffnessArm = 0
dampingArm = 0.1
f_linearPassiveArmTorque = getLinearPassiveTorques(stiffnessArm,
dampingArm)
stiffnessMtp = 25
f_linearPassiveMtpTorque = getLinearPassiveTorques(stiffnessMtp,
dampingMtp)
# %% Other helper CasADi functions.
from casadiFunctions import normSumPow
from casadiFunctions import diffTorques
f_NMusclesSum2 = normSumPow(nMuscles, 2)
f_nArmJointsSum2 = normSumPow(nArmJoints, 2)
f_nNoArmJointsSum2 = normSumPow(nNoArmJoints, 2)
f_nPassiveTorqueJointsSum2 = normSumPow(nPassiveTorqueJoints, 2)
f_diffTorques = diffTorques()
# %% Bounds of the optimal control problem.
# Load average walking motion used for setting up some of the bounds and
# initial guess.
motion_walk = 'walking'
nametrial_walk_id = 'average_' + motion_walk + '_HGC_mtp'
nametrial_walk_IK = 'IK_' + nametrial_walk_id
pathIK_walk = os.path.join(pathOpenSimModel, 'templates', 'IK',
nametrial_walk_IK + '.mot')
from utilities import getIK
Qs_walk_filt = getIK(pathIK_walk, joints)[1]
from bounds import bounds
bounds = bounds(Qs_walk_filt, joints, rightSideMuscles, armJoints,
targetSpeed)
# Static parameters.
ubFinalTime, lbFinalTime = bounds.getBoundsFinalTime()
# States.
ubA, lbA, scalingA = bounds.getBoundsActivation()
ubAk = ca.vec(ubA.to_numpy().T * np.ones((1, N+1))).full()
lbAk = ca.vec(lbA.to_numpy().T * np.ones((1, N+1))).full()
ubAj = ca.vec(ubA.to_numpy().T * np.ones((1, d*N))).full()
lbAj = ca.vec(lbA.to_numpy().T * np.ones((1, d*N))).full()
ubF, lbF, scalingF = bounds.getBoundsForce()
ubFk = ca.vec(ubF.to_numpy().T * np.ones((1, N+1))).full()
lbFk = ca.vec(lbF.to_numpy().T * np.ones((1, N+1))).full()
ubFj = ca.vec(ubF.to_numpy().T * np.ones((1, d*N))).full()
lbFj = ca.vec(lbF.to_numpy().T * np.ones((1, d*N))).full()
ubQs, lbQs, scalingQs, ubQs0, lbQs0 = bounds.getBoundsPosition()
ubQsk = ca.vec(ubQs.to_numpy().T * np.ones((1, N+1))).full()
lbQsk = ca.vec(lbQs.to_numpy().T * np.ones((1, N+1))).full()
ubQsj = ca.vec(ubQs.to_numpy().T * np.ones((1, d*N))).full()
lbQsj = ca.vec(lbQs.to_numpy().T * np.ones((1, d*N))).full()
# We want to further constraint the pelvis_tx position at the first mesh
# point, such that the model starts walking with pelvis_tx=0.
lbQsk[joints.index('pelvis_tx')] = lbQs0['pelvis_tx'].to_numpy()
ubQsk[joints.index('pelvis_tx')] = ubQs0['pelvis_tx'].to_numpy()
ubQds, lbQds, scalingQds = bounds.getBoundsVelocity()
ubQdsk = ca.vec(ubQds.to_numpy().T * np.ones((1, N+1))).full()
lbQdsk = ca.vec(lbQds.to_numpy().T * np.ones((1, N+1))).full()
ubQdsj = ca.vec(ubQds.to_numpy().T * np.ones((1, d*N))).full()
lbQdsj = ca.vec(lbQds.to_numpy().T * np.ones((1, d*N))).full()
ubArmA, lbArmA, scalingArmA = bounds.getBoundsArmActivation()
ubArmAk = ca.vec(ubArmA.to_numpy().T * np.ones((1, N+1))).full()
lbArmAk = ca.vec(lbArmA.to_numpy().T * np.ones((1, N+1))).full()
ubArmAj = ca.vec(ubArmA.to_numpy().T * np.ones((1, d*N))).full()
lbArmAj = ca.vec(lbArmA.to_numpy().T * np.ones((1, d*N))).full()
# Controls.
ubADt, lbADt, scalingADt = bounds.getBoundsActivationDerivative()
ubADtk = ca.vec(ubADt.to_numpy().T * np.ones((1, N))).full()
lbADtk = ca.vec(lbADt.to_numpy().T * np.ones((1, N))).full()
ubArmE, lbArmE, scalingArmE = bounds.getBoundsArmExcitation()
ubArmEk = ca.vec(ubArmE.to_numpy().T * np.ones((1, N))).full()
lbArmEk = ca.vec(lbArmE.to_numpy().T * np.ones((1, N))).full()
# Slack controls.
ubQdds, lbQdds, scalingQdds = bounds.getBoundsAcceleration()
ubQddsj = ca.vec(ubQdds.to_numpy().T * np.ones((1, d*N))).full()
lbQddsj = ca.vec(lbQdds.to_numpy().T * np.ones((1, d*N))).full()
ubFDt, lbFDt, scalingFDt = bounds.getBoundsForceDerivative()
ubFDtj = ca.vec(ubFDt.to_numpy().T * np.ones((1, d*N))).full()
lbFDtj = ca.vec(lbFDt.to_numpy().T * np.ones((1, d*N))).full()
# Other.
_, _, scalingMtpE = bounds.getBoundsMtpExcitation()
# %% Initial guess of the optimal control problem.
if guessType == 'coldStart':
from guesses import coldStart
guess = coldStart(N, d, joints, bothSidesMuscles, targetSpeed)
elif guessType == 'hotStart':
from guesses import hotStart
guess = hotStart(Qs_walk_filt, N, d, joints, bothSidesMuscles,
targetSpeed, periodicQsJointsA,
periodicQdsJointsA, periodicOppositeJoints)
# Static parameters.
gFinalTime = guess.getGuessFinalTime()
# States.
gA = guess.getGuessActivation(scalingA)
gACol = guess.getGuessActivationCol()
gF = guess.getGuessForce(scalingF)
gFCol = guess.getGuessForceCol()
gQs = guess.getGuessPosition(scalingQs)
gQsCol = guess.getGuessPositionCol()
gQds = guess.getGuessVelocity(scalingQds)
gQdsCol = guess.getGuessVelocityCol()
gArmA = guess.getGuessTorqueActuatorActivation(armJoints)
gArmACol = guess.getGuessTorqueActuatorActivationCol(armJoints)
# Controls.
gADt = guess.getGuessActivationDerivative(scalingADt)
gArmE = guess.getGuessTorqueActuatorExcitation(armJoints)
# Slack controls.
gQdds = guess.getGuessAcceleration(scalingQdds)
gQddsCol = guess.getGuessAccelerationCol()
gFDt = guess.getGuessForceDerivative(scalingFDt)
gFDtCol = guess.getGuessForceDerivativeCol()
# %% Optimal control problem.
if solveProblem:
#######################################################################
# Initialize opti instance.
# Opti is a collection of CasADi helper classes:
# https://web.casadi.org/docs/#opti-stack
opti = ca.Opti()
#######################################################################
# Static parameters.
# Final time.
finalTime = opti.variable()
opti.subject_to(opti.bounded(lbFinalTime.iloc[0]['time'],
finalTime,
ubFinalTime.iloc[0]['time']))
opti.set_initial(finalTime, gFinalTime)
assert lbFinalTime.iloc[0]['time'] <= gFinalTime, (
"Error lower bound final time")
assert ubFinalTime.iloc[0]['time'] >= gFinalTime, (
"Error upper bound final time")
#######################################################################
# States.
# Muscle activation at mesh points.
a = opti.variable(nMuscles, N+1)
opti.subject_to(opti.bounded(lbAk, ca.vec(a), ubAk))
opti.set_initial(a, gA.to_numpy().T)
assert np.alltrue(lbAk <= ca.vec(gA.to_numpy().T).full()), (
"Error lower bound muscle activation")
assert np.alltrue(ubAk >= ca.vec(gA.to_numpy().T).full()), (
"Error upper bound muscle activation")
# Muscle activation at collocation points.
a_col = opti.variable(nMuscles, d*N)
opti.subject_to(opti.bounded(lbAj, ca.vec(a_col), ubAj))
opti.set_initial(a_col, gACol.to_numpy().T)
assert np.alltrue(lbAj <= ca.vec(gACol.to_numpy().T).full()), (
"Error lower bound muscle activation collocation points")
assert np.alltrue(ubAj >= ca.vec(gACol.to_numpy().T).full()), (
"Error upper bound muscle activation collocation points")
# Tendon force at mesh points.
normF = opti.variable(nMuscles, N+1)
opti.subject_to(opti.bounded(lbFk, ca.vec(normF), ubFk))
opti.set_initial(normF, gF.to_numpy().T)
assert np.alltrue(lbFk <= ca.vec(gF.to_numpy().T).full()), (
"Error lower bound muscle force")
assert np.alltrue(ubFk >= ca.vec(gF.to_numpy().T).full()), (
"Error upper bound muscle force")
# Tendon force at collocation points.
normF_col = opti.variable(nMuscles, d*N)
opti.subject_to(opti.bounded(lbFj, ca.vec(normF_col), ubFj))
opti.set_initial(normF_col, gFCol.to_numpy().T)
assert np.alltrue(lbFj <= ca.vec(gFCol.to_numpy().T).full()), (
"Error lower bound muscle force collocation points")
assert np.alltrue(ubFj >= ca.vec(gFCol.to_numpy().T).full()), (
"Error upper bound muscle force collocation points")
# Joint position at mesh points.
Qs = opti.variable(nJoints, N+1)
opti.subject_to(opti.bounded(lbQsk, ca.vec(Qs), ubQsk))
opti.set_initial(Qs, gQs.to_numpy().T)
if not guessType == 'coldStart':
assert np.alltrue(lbQsk <= ca.vec(gQs.to_numpy().T).full()), (
"Error lower bound joint position")
assert np.alltrue(ubQsk >= ca.vec(gQs.to_numpy().T).full()), (
"Error upper bound joint position")
# Joint position at collocation points.
Qs_col = opti.variable(nJoints, d*N)
opti.subject_to(opti.bounded(lbQsj, ca.vec(Qs_col), ubQsj))
opti.set_initial(Qs_col, gQsCol.to_numpy().T)
if not guessType == 'coldStart':
assert np.alltrue(lbQsj <= ca.vec(gQsCol.to_numpy().T).full()), (
"Error lower bound joint position collocation points")
assert np.alltrue(ubQsj >= ca.vec(gQsCol.to_numpy().T).full()), (
"Error upper bound joint position collocation points")
# Joint velocity at mesh points.
Qds = opti.variable(nJoints, N+1)
opti.subject_to(opti.bounded(lbQdsk, ca.vec(Qds), ubQdsk))
opti.set_initial(Qds, gQds.to_numpy().T)
assert np.alltrue(lbQdsk <= ca.vec(gQds.to_numpy().T).full()), (
"Error lower bound joint velocity")
assert np.alltrue(ubQdsk >= ca.vec(gQds.to_numpy().T).full()), (
"Error upper bound joint velocity")
# Joint velocity at collocation points.
Qds_col = opti.variable(nJoints, d*N)
opti.subject_to(opti.bounded(lbQdsj, ca.vec(Qds_col), ubQdsj))
opti.set_initial(Qds_col, gQdsCol.to_numpy().T)
assert np.alltrue(lbQdsj <= ca.vec(gQdsCol.to_numpy().T).full()), (
"Error lower bound joint velocity collocation points")
assert np.alltrue(ubQdsj >= ca.vec(gQdsCol.to_numpy().T).full()), (
"Error upper bound joint velocity collocation points")
# Arm activation at mesh points.
aArm = opti.variable(nArmJoints, N+1)
opti.subject_to(opti.bounded(lbArmAk, ca.vec(aArm), ubArmAk))
opti.set_initial(aArm, gArmA.to_numpy().T)
assert np.alltrue(lbArmAk <= ca.vec(gArmA.to_numpy().T).full()), (
"Error lower bound arm activation")
assert np.alltrue(ubArmAk >= ca.vec(gArmA.to_numpy().T).full()), (
"Error upper bound arm activation")
# Arm activation at collocation points.
aArm_col = opti.variable(nArmJoints, d*N)
opti.subject_to(opti.bounded(lbArmAj, ca.vec(aArm_col), ubArmAj))
opti.set_initial(aArm_col, gArmACol.to_numpy().T)
assert np.alltrue(lbArmAj <= ca.vec(gArmACol.to_numpy().T).full()), (
"Error lower bound arm activation collocation points")
assert np.alltrue(ubArmAj >= ca.vec(gArmACol.to_numpy().T).full()), (
"Error upper bound arm activation collocation points")
#######################################################################
# Controls.
# Muscle activation derivative at mesh points.
aDt = opti.variable(nMuscles, N)
opti.subject_to(opti.bounded(lbADtk, ca.vec(aDt), ubADtk))
opti.set_initial(aDt, gADt.to_numpy().T)
assert np.alltrue(lbADtk <= ca.vec(gADt.to_numpy().T).full()), (
"Error lower bound muscle activation derivative")
assert np.alltrue(ubADtk >= ca.vec(gADt.to_numpy().T).full()), (
"Error upper bound muscle activation derivative")
# Arm excitation at mesh points.
eArm = opti.variable(nArmJoints, N)
opti.subject_to(opti.bounded(lbArmEk, ca.vec(eArm), ubArmEk))
opti.set_initial(eArm, gArmE.to_numpy().T)
assert np.alltrue(lbArmEk <= ca.vec(gArmE.to_numpy().T).full()), (
"Error lower bound arm excitation")
assert np.alltrue(ubArmEk >= ca.vec(gArmE.to_numpy().T).full()), (
"Error upper bound arm excitation")
#######################################################################
# Slack controls.
# Tendon force derivative at collocation points.
normFDt_col = opti.variable(nMuscles, d*N)
opti.subject_to(opti.bounded(lbFDtj, ca.vec(normFDt_col), ubFDtj))
opti.set_initial(normFDt_col, gFDtCol.to_numpy().T)
assert np.alltrue(lbFDtj <= ca.vec(gFDtCol.to_numpy().T).full()), (
"Error lower bound muscle force derivative")
assert np.alltrue(ubFDtj >= ca.vec(gFDtCol.to_numpy().T).full()), (
"Error upper bound muscle force derivative")
# Joint velocity derivative (acceleration) at collocation points.
Qdds_col = opti.variable(nJoints, d*N)
opti.subject_to(opti.bounded(lbQddsj, ca.vec(Qdds_col),
ubQddsj))
opti.set_initial(Qdds_col, gQddsCol.to_numpy().T)
assert np.alltrue(lbQddsj <= ca.vec(gQddsCol.to_numpy().T).full()), (
"Error lower bound joint velocity derivative")
assert np.alltrue(ubQddsj >= ca.vec(gQddsCol.to_numpy().T).full()), (
"Error upper bound joint velocity derivative")
#######################################################################
# Parallel formulation - initialize variables.
# Static parameters.
tf = ca.MX.sym('tf')
# States.
ak = ca.MX.sym('ak', nMuscles)
aj = ca.MX.sym('aj', nMuscles, d)
akj = ca.horzcat(ak, aj)
normFk = ca.MX.sym('normFk', nMuscles)
normFj = ca.MX.sym('normFj', nMuscles, d)
normFkj = ca.horzcat(normFk, normFj)
Qsk = ca.MX.sym('Qsk', nJoints)
Qsj = ca.MX.sym('Qsj', nJoints, d)
Qskj = ca.horzcat(Qsk, Qsj)
Qdsk = ca.MX.sym('Qdsk', nJoints)
Qdsj = ca.MX.sym('Qdsj', nJoints, d)
Qdskj = ca.horzcat(Qdsk, Qdsj)
aArmk = ca.MX.sym('aArmk', nArmJoints)
aArmj = ca.MX.sym('aArmj', nArmJoints, d)
aArmkj = ca.horzcat(aArmk, aArmj)
# Controls.
aDtk = ca.MX.sym('aDtk', nMuscles)
eArmk = ca.MX.sym('eArmk', nArmJoints)
# Slack controls.
normFDtj = ca.MX.sym('normFDtj', nMuscles, d);
Qddsj = ca.MX.sym('Qddsj', nJoints, d)
#######################################################################
# Time step.
h = tf / N
#######################################################################
# Collocation matrices.
tau = ca.collocation_points(d,'radau');
[C,D] = ca.collocation_interpolators(tau);
# Missing matrix B, add manually.
B = [-8.88178419700125e-16, 0.376403062700467, 0.512485826188421,
0.111111111111111]
#######################################################################
# Initialize cost function and constraint vectors.
J = 0
eq_constr = []
ineq_constr1 = []
ineq_constr2 = []
ineq_constr3 = []
ineq_constr4 = []
ineq_constr5 = []
ineq_constr6 = []
#######################################################################
# Loop over collocation points.
for j in range(d):
###################################################################
# Unscale variables.
# States.
normFkj_nsc = normFkj * (scalingF.to_numpy().T * np.ones((1, d+1)))
Qskj_nsc = Qskj * (scalingQs.to_numpy().T * np.ones((1, d+1)))
Qdskj_nsc = Qdskj * (scalingQds.to_numpy().T * np.ones((1, d+1)))
# Controls.
aDtk_nsc = aDtk * (scalingADt.to_numpy().T)
# Slack controls.
normFDtj_nsc = normFDtj * (
scalingFDt.to_numpy().T * np.ones((1, d)))
Qddsj_nsc = Qddsj * (scalingQdds.to_numpy().T * np.ones((1, d)))
# Qs and Qds are intertwined in the external function.
QsQdskj_nsc = ca.MX(nJoints*2, d+1)
QsQdskj_nsc[::2, :] = Qskj_nsc
QsQdskj_nsc[1::2, :] = Qdskj_nsc
###################################################################
# Polynomial approximations.
# Left side.
Qsinj_l = Qskj_nsc[leftPolJointIdx, j+1]
Qdsinj_l = Qdskj_nsc[leftPolJointIdx, j+1]
[lMTj_l, vMTj_l, dMj_l] = f_polynomial(Qsinj_l, Qdsinj_l)
# Right side.
Qsinj_r = Qskj_nsc[rightPolJointIdx, j+1]
Qdsinj_r = Qdskj_nsc[rightPolJointIdx, j+1]
[lMTj_r, vMTj_r, dMj_r] = f_polynomial(Qsinj_r, Qdsinj_r)
# Muscle-tendon lengths and velocities.
lMTj_lr = ca.vertcat(lMTj_l[leftPolMuscleIdx],
lMTj_r[rightPolMuscleIdx])
vMTj_lr = ca.vertcat(vMTj_l[leftPolMuscleIdx],
vMTj_r[rightPolMuscleIdx])
# Moment arms.
dMj = {}
# Left side.
for joint in leftPolynomialJoints:
if ((joint != 'mtp_angle_l') and
(joint != 'lumbar_extension') and
(joint != 'lumbar_bending') and
(joint != 'lumbar_rotation')):
dMj[joint] = dMj_l[momentArmIndices[joint],
leftPolynomialJoints.index(joint)]
# Right side.
for joint in rightPolynomialJoints:
if ((joint != 'mtp_angle_r') and
(joint != 'lumbar_extension') and
(joint != 'lumbar_bending') and
(joint != 'lumbar_rotation')):
# We need to adjust momentArmIndices for the right side
# since the polynomial indices are 'one-sided'. We
# subtract by the number of side muscles.
c_ma = [
i - nSideMuscles for i in momentArmIndices[joint]]
dMj[joint] = dMj_r[c_ma,
rightPolynomialJoints.index(joint)]
# Trunk.
for joint in trunkJoints:
dMj[joint] = dMj_l[trunkMomentArmPolynomialIndices,
leftPolynomialJoints.index(joint)]
###################################################################
# Hill-equilibrium.
[hillEquilibriumj, Fj, activeFiberForcej, passiveFiberForcej,
normActiveFiberLengthForcej, normFiberLengthj, fiberVelocityj] = (
f_hillEquilibrium(akj[:, j+1], lMTj_lr, vMTj_lr,
normFkj_nsc[:, j+1], normFDtj_nsc[:, j]))
###################################################################
# Metabolic energy rate.
metabolicEnergyRatej = f_metabolicsBhargava(
akj[:, j+1], akj[:, j+1], normFiberLengthj, fiberVelocityj,
activeFiberForcej, passiveFiberForcej,
normActiveFiberLengthForcej)[5]
###################################################################
# Passive joint torques.
passiveTorque_j = {}
passiveTorquesj = ca.MX(nPassiveTorqueJoints, 1)
for cj, joint in enumerate(passiveTorqueJoints):
passiveTorque_j[joint] = f_passiveTorque[joint](
Qskj_nsc[joints.index(joint), j+1],
Qdskj_nsc[joints.index(joint), j+1])
passiveTorquesj[cj, 0] = passiveTorque_j[joint]
linearPassiveTorqueArms_j = {}
for joint in armJoints:
linearPassiveTorqueArms_j[joint] = f_linearPassiveArmTorque(
Qskj_nsc[joints.index(joint), j+1],
Qdskj_nsc[joints.index(joint), j+1])
if withMTP:
linearPassiveTorqueMtp_j = {}
for joint in mtpJoints:
linearPassiveTorqueMtp_j[joint] = f_linearPassiveMtpTorque(
Qskj_nsc[joints.index(joint), j+1],
Qdskj_nsc[joints.index(joint), j+1])