forked from opensim-org/opensim-core
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMillard2012EquilibriumMuscle.cpp
More file actions
1897 lines (1614 loc) · 74.6 KB
/
Copy pathMillard2012EquilibriumMuscle.cpp
File metadata and controls
1897 lines (1614 loc) · 74.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
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
/* -------------------------------------------------------------------------- *
* OpenSim: Millard2012EquilibriumMuscle.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Matthew Millard, Tom Uchida, Ajay Seth *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may *
* not use this file except in compliance with the License. You may obtain a *
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* -------------------------------------------------------------------------- */
#include "Millard2012EquilibriumMuscle.h"
#include <OpenSim/Simulation/Model/Model.h>
using namespace std;
using namespace OpenSim;
using namespace SimTK;
const string Millard2012EquilibriumMuscle::
STATE_ACTIVATION_NAME = "activation";
const string Millard2012EquilibriumMuscle::
STATE_FIBER_LENGTH_NAME = "fiber_length";
const double MIN_NONZERO_DAMPING_COEFFICIENT = 0.001;
//==============================================================================
// HELPER FUNCTIONS
//==============================================================================
namespace
{
// Calculates the active fiber force.
// @param fiso maximum isometric force
// @param a activation
// @param fal active-force-length multiplier
// @param fv fiber-force-velocity multiplier
double calcFiberForceActive(double fiso, double a, double fal, double fv)
{
return fiso * (a * fal * fv);
}
// Calculates the passive elastic fiber force.
// @param fiso maximum isometric force
// @param fpe passive-force-length multiplier
double calcFiberForcePassiveElastic(double fiso, double fpe)
{
return fiso * fpe;
}
// Calculates the passive damped fiber force.
// @param fiso maximum isometric force
// @param dlceN normalized fiber velocity
// @param beta damping coefficient
double calcFiberForcePassiveDamping(
double fiso,
double dlceN,
double beta)
{
return fiso * beta * dlceN;
}
// Calculates the total, active and passive, fiber force.
// @param fiso maximum isometric force
// @param a activation
// @param fal active-force-length multiplier
// @param fv fiber-force-velocity multiplier
// @param fpe passive-force-length multiplier
// @param dlceN normalized fiber velocity
// @param beta damping coefficient
double calcFiberForce(
double fiso,
double a,
double fal,
double fv,
double fpe,
double dlceN,
double beta)
{
return calcFiberForceActive(fiso, a, fal, fv) +
(calcFiberForcePassiveElastic(fiso, fpe) +
calcFiberForcePassiveDamping(fiso, dlceN, beta));
}
// Calculates the fiber-force-velocity curve value from the force equilibrium,
// assuming zero fiber damping.
// @param a activation
// @param fal active-force-length multiplier
// @param fp passive-force-length multiplier
// @param fse tendon-force-length multiplier
// @param cosPhi cosine of pennation angle
double calcUndampedFiberForceVelocityMultiplier(
double a,
double fal,
double fp,
double fse,
double cosphi)
{
return (fse / cosphi - fp) / (a * fal);
}
// Helper struct containing the result (and byproducts) of solving the
// damped equilibrium force equation for fiber-velocity.
struct DampedFiberVelocityCalculationResult final
{
double normFiberVelocity;
double convergenceError;
bool converged;
};
/* Calculates the fiber velocity that satisfies the damped equilibrium equation
given a fixed fiber length.
@param fiso maximum isometric force
@param a activation
@param fal active-force-length multiplier
@param fpe passive-force-length multiplier
@param fse tendon-force-length multiplier
@param beta damping coefficient
@param cosPhi cosine of pennation angle
@param fvCurve fiber force velocity curve
@param fvInvCurve inverse fiber force velocity curve */
DampedFiberVelocityCalculationResult calcDampedNormFiberVelocity(
double fiso,
double a,
double fal,
double fpe,
double fse,
double beta,
double cosPhi,
const ForceVelocityCurve& fvCurve,
const ForceVelocityInverseCurve& fvInvCurve)
{
int maxIter = 20; // this routine converges quickly; 20 is quite generous
double tol = 1.0e-10 * fiso;
if (tol < SimTK::SignificantReal * 100) {
tol = SimTK::SignificantReal * 100;
}
double perturbation = 0.0;
double fiberForce = 0.0;
double err = 1.0e10;
double derr_d_dlceNdt = 0.0;
double delta = 0.0;
double iter = 0.0;
// Get a really excellent starting position to reduce the number of
// iterations. This reduces the simulation time by about 1%.
double fv = calcUndampedFiberForceVelocityMultiplier(
max(a, 0.01),
max(fal, 0.01),
fpe,
fse,
max(cosPhi, 0.01));
double dlceN_dt = fvInvCurve.calcValue(fv);
// The approximation is poor beyond the maximum velocities.
if (dlceN_dt > 1.0) {
dlceN_dt = 1.0;
}
if (dlceN_dt < -1.0) {
dlceN_dt = -1.0;
}
double df_d_dlceNdt = 0.0;
while (abs(err) > tol && iter < maxIter) {
fv = fvCurve.calcValue(dlceN_dt);
fiberForce = calcFiberForce(fiso, a, fal, fv, fpe, dlceN_dt, beta);
err = fiberForce * cosPhi - fse * fiso;
df_d_dlceNdt =
fiso * (a * fal * fvCurve.calcDerivative(dlceN_dt, 1) + beta);
derr_d_dlceNdt = df_d_dlceNdt * cosPhi;
if (abs(err) > tol && abs(derr_d_dlceNdt) > SimTK::SignificantReal) {
delta = -err / derr_d_dlceNdt;
dlceN_dt = dlceN_dt + delta;
} else if (abs(derr_d_dlceNdt) < SimTK::SignificantReal) {
// Perturb the solution if we've lost rank. This should never happen
// for this problem since dfv_d_dlceNdt > 0 and b > 0 (and so
// derr_d_dlceNdt > 0).
perturbation = 2.0 * ((double)rand()) / ((double)RAND_MAX) - 1.0;
dlceN_dt = dlceN_dt + perturbation * 0.05;
}
iter++;
}
bool converged = abs(err) <= tol;
// If we failed to converge, it's probably because the fiber is at its lower
// bound. That decision is made further down the line, so if convergence
// didn't happen, let the user know and return a NaN.
if (!converged) {
dlceN_dt = -1.;
}
return {
dlceN_dt,
err,
converged,
};
}
} // namespace
//==============================================================================
// PROPERTIES
//==============================================================================
void Millard2012EquilibriumMuscle::setNull()
{ setAuthors("Matthew Millard, Tom Uchida, Ajay Seth"); }
void Millard2012EquilibriumMuscle::constructProperties()
{
constructProperty_fiber_damping(0.1); //damped model used by default
constructProperty_default_activation(0.05);
constructProperty_default_fiber_length(getOptimalFiberLength());
constructProperty_activation_time_constant(0.010);
constructProperty_deactivation_time_constant(0.040);
constructProperty_minimum_activation(0.01);
constructProperty_maximum_pennation_angle(acos(0.1));
constructProperty_ActiveForceLengthCurve(ActiveForceLengthCurve());
constructProperty_ForceVelocityCurve(ForceVelocityCurve());
constructProperty_FiberForceLengthCurve(FiberForceLengthCurve());
constructProperty_TendonForceLengthCurve(TendonForceLengthCurve());
setMinControl(get_minimum_activation());
}
void Millard2012EquilibriumMuscle::extendFinalizeFromProperties()
{
Super::extendFinalizeFromProperties();
// Switch to undamped model if damping coefficient is small.
if (get_fiber_damping() < MIN_NONZERO_DAMPING_COEFFICIENT) {
set_fiber_damping(0.0);
use_fiber_damping = false;
} else {
use_fiber_damping = true;
}
// Set the names of the muscle curves.
const std::string& namePrefix = getName();
ActiveForceLengthCurve& falCurve = upd_ActiveForceLengthCurve();
falCurve.setName(namePrefix + "_ActiveForceLengthCurve");
ForceVelocityCurve& fvCurve = upd_ForceVelocityCurve();
fvCurve.setName(namePrefix + "_ForceVelocityCurve");
FiberForceLengthCurve& fpeCurve = upd_FiberForceLengthCurve();
fpeCurve.setName(namePrefix + "_FiberForceLengthCurve");
TendonForceLengthCurve& fseCurve = upd_TendonForceLengthCurve();
fseCurve.setName(namePrefix + "_TendonForceLengthCurve");
// Include fiber damping in the model only if the damping coefficient is
// larger than MIN_NONZERO_DAMPING_COEFFICIENT. This is done to ensure
// we remain sufficiently far from the numerical singularity at beta=0.
use_fiber_damping = (getFiberDamping() >= MIN_NONZERO_DAMPING_COEFFICIENT);
// To initialize, we need to construct an *inverse* force-velocity curve
// from the parameters of the force-velocity curve.
double conSlopeAtVmax = fvCurve.getConcentricSlopeAtVmax();
double conSlopeNearVmax = fvCurve.getConcentricSlopeNearVmax();
double isometricSlope = fvCurve.getIsometricSlope();
double eccSlopeAtVmax = fvCurve.getEccentricSlopeAtVmax();
double eccSlopeNearVmax = fvCurve.getEccentricSlopeNearVmax();
double conCurviness = fvCurve.getConcentricCurviness();
double eccCurviness = fvCurve.getEccentricCurviness();
double eccForceMax = fvCurve.getMaxEccentricVelocityForceMultiplier();
//Ensure that the slopes near vmax are postive, finite, and above zero
OPENSIM_THROW_IF_FRMOBJ(conSlopeNearVmax < SimTK::SqrtEps,
InvalidPropertyValue,
"ForceVelocityCurve:concentric_slope_near_vmax",
"Slope near concentric vmax cannot be less than SimTK::SqrtEps"
"(1.49e-8)");
OPENSIM_THROW_IF_FRMOBJ(eccSlopeNearVmax < SimTK::SqrtEps,
InvalidPropertyValue,
"ForceVelocityCurve:eccentric_slope_near_vmax",
"Slope near eccentric vmax cannot be less than SimTK::SqrtEps"
"(1.49e-8)");
// A few parameters may need to be adjusted to avoid singularities
// if the classic Hill formulation is being used with an elastic tendon
if(!get_ignore_tendon_compliance() && !use_fiber_damping) {
// Compliant tendon with no damping.
OPENSIM_THROW_IF_FRMOBJ(get_minimum_activation() < 0.01,
InvalidPropertyValue, getProperty_minimum_activation().getName(),
"Minimum activation cannot be less than 0.01 when using"
"the classic Hill model with an elastic tendon due to a"
"singularity in the state derivative for an activation of 0.");
OPENSIM_THROW_IF_FRMOBJ(getMinControl() < get_minimum_activation(),
InvalidPropertyValue, getProperty_min_control().getName(),
"Minimum control cannot be less than minimum activation");
if (falCurve.getMinValue() < 0.1){
log_info("'{}' Parameter update for classic Hill model: "
"ActiveForceLengthCurve parameter '{}' was {} but is now {}.",
getName(),"minimum_value", falCurve.getMinValue(), 0.1);
falCurve.setMinValue(0.1);
}
if (conSlopeAtVmax < conSlopeNearVmax*0.5){
log_info("'{}' Parameter update for classic Hill model: "
"ForceVelocityCurve parameter '{}' was {} but is now {}.",
getName(),"eccentric_slope_near_vmax", conSlopeAtVmax,
conSlopeNearVmax*0.5);
conSlopeAtVmax = conSlopeNearVmax*0.5;
}
if(conSlopeNearVmax < 0.05){
log_info("'{}': Warning slow simulation: classic Hill model"
"is being used with a '{}' of {}. Use the damped model, or "
"increase to {} for faster simulations.", getName(),
"concentric_slope_near_vmax",conSlopeNearVmax, 0.05);
}
if (eccSlopeAtVmax < eccSlopeNearVmax*0.5){
log_info("'{}' Parameter update for classic Hill model: "
"ForceVelocityCurve parameter '{}' was {} but is now {}.",
getName(),"eccentric_slope_near_vmax", eccSlopeAtVmax,
eccSlopeNearVmax*0.5);
eccSlopeAtVmax = eccSlopeNearVmax*0.5;
}
if(eccSlopeNearVmax < 0.05){
log_info("'{}': Warning slow simulation: classic Hill model"
"is being used with a '{}' of {}. Use the damped model, or "
"increase to {} for faster simulations.", getName(),
"eccentric_slope_near_vmax",eccSlopeNearVmax, 0.05);
}
fvCurve.setCurveShape(
conSlopeAtVmax, conSlopeNearVmax, isometricSlope,
eccSlopeAtVmax, eccSlopeNearVmax, eccForceMax);
} else {
const double min_activation = get_minimum_activation();
const double min_activation_clamped = clamp(0, min_activation, 1);
if (min_activation > 0. &&
std::abs(min_activation_clamped -min_activation) > SimTK::Eps) {
log_info("'{}': Parameter update for the damped-model: "
"minimum_activation was {} but is now {}",
getName(), min_activation,
min_activation_clamped);
set_minimum_activation(min_activation_clamped);
}
if(falCurve.getMinValue() > 0.0){
log_info("'{}' Parameter update for the damped-model: "
"ActiveForceLengthCurve minimum value was {} but is now {}.",
getName(), falCurve.getMinValue(), 0.);
falCurve.setMinValue(0.0);
}
if(conSlopeAtVmax > 0.){
log_info("'{}' Parameter update for the damped-model:"
" ForceVelocityCurve '{}' was {} but is now {}.",
getName(),"concentric_slope_at_vmax", conSlopeAtVmax, 0.);
conSlopeAtVmax = 0.;
}
if(eccSlopeAtVmax > 0.){
log_info("'{}' Parameter update for the damped-model: "
"ForceVelocityCurve '{}' was {} but is now {}.",
getName(),"eccentric_slope_at_vmax", eccSlopeAtVmax, 0.);
eccSlopeAtVmax = 0.;
}
fvCurve.setCurveShape(
conSlopeAtVmax, conSlopeNearVmax, isometricSlope,
eccSlopeAtVmax, eccSlopeNearVmax, eccForceMax);
OPENSIM_THROW_IF_FRMOBJ(get_minimum_activation() < 0.0,
InvalidPropertyValue, getProperty_minimum_activation().getName(),
"Minimum activation cannot be less than zero");
//singularity-free model still cannot have excitations below 0
OPENSIM_THROW_IF_FRMOBJ(getMinControl() < get_minimum_activation(),
InvalidPropertyValue, getProperty_min_control().getName(),
"Minimum control cannot be less than minimum activation");
}
//The ForceVelocityInverseCurve is used with both the damped and the
// classic Hill model but in different ways:
//
// The damped model uses the fvInvCurve to provide an initial fiber
// velocity prior to numerically solving the root using Eqn. 8 from
// Millard et al.
//
// The classic Hill formulation uses the fvInvCurve to directly solve for
// fiber velocity using Eqn. 6 from Millard et al.
//
//While the fvCurve and fvInvCurve are inverses of each other between
//concentric-velocity-near-vmax to eccentric-velocity-near-vmax these
//curves differ outside of this region. Why? When an elastic-tendon model
//is used with the classic Hill formulation Eqn. 6 of Millard et al. is
//used to evaluate the state derivative of fiber length. As noted in the
//paper Eqn. 6 has several singularites one of which is related to the
//force-velocity-inverse curve: simply, the force-velocity-inverse curve
//must be invertible.
//
//In this case this is equivalent to saying that the force-velocity-inverse
//curve must have finite endslopes. To avoid this singularity we set the
//end slopes of the force-velocity-inverse curve to be a fraction of the
//`near' slopes used by the force-velocity curve: this value is guaranteed
//to be finite, and is also guaranteed not to break the monotonicity of the
//curve. Also don't forget: the ForceVelocityInverseCurve constructor takes
//in the parameters of the force-velocity-curve that it inverts. So if you
//pass in an endslope of 0 the inverse curve will have an endslope of
//1/0 = infinity! Instead we make sure that we pass in a finite value for
//the end slopes so that the inverse curve has finite endslopes.
//
//The fvCurve is used exclusively by the damped model. As such the fvCurve
//does not need to be invertible since the damped model's state derivative
//(Eqn. 8 of Millard et al.) has no singularities. This means that the user
//can set the endslopes to zero which is particularly useful if simulations
//of very rapid contractions are being performed. This also means that the
//fvInvCurve is not the inverse of fvCurve for concentric velocities faster
//than concentric-velocity-near-vmax and eccentric velocities faster than
//eccentric-velocity-near-vmax: the end slopes differ.
//
//Millard M, Uchida T, Seth A, Delp SL. Flexing computational muscle:
//modeling and simulation of musculotendon dynamics. Journal of
//biomechanical engineering. 2013 Feb 1;135(2).
double eccSlopeAtVmaxFvInv = eccSlopeNearVmax*0.5;
double conSlopeAtVmaxFvInv = conSlopeNearVmax*0.5;
fvInvCurve = ForceVelocityInverseCurve(conSlopeAtVmaxFvInv, conSlopeNearVmax,
isometricSlope, eccSlopeAtVmaxFvInv,
eccSlopeNearVmax, eccForceMax,
conCurviness, eccCurviness);
// Ensure all muscle curves are up-to-date.
falCurve.ensureCurveUpToDate();
fvCurve.ensureCurveUpToDate();
fvInvCurve.ensureCurveUpToDate();
fpeCurve.ensureCurveUpToDate();
fseCurve.ensureCurveUpToDate();
// Propagate properties down to pennation model subcomponent. If any of the
// new property values are invalid, restore the subcomponent's current
// property values (to avoid throwing again when the subcomponent's
// extendFinalizeFromProperties() method is called directly) and then
// re-throw the exception thrown by the subcomponent.
auto& penMdl =
updMemberSubcomponent<MuscleFixedWidthPennationModel>(penMdlIdx);
MuscleFixedWidthPennationModel penMdlCopy(penMdl);
penMdl.set_optimal_fiber_length(getOptimalFiberLength());
penMdl.set_pennation_angle_at_optimal(getPennationAngleAtOptimalFiberLength());
penMdl.set_maximum_pennation_angle(get_maximum_pennation_angle());
try {
penMdl.finalizeFromProperties();
} catch (const InvalidPropertyValue&) {
penMdl = penMdlCopy;
throw;
}
// Propagate properties down to activation dynamics model subcomponent.
// Handle invalid properties as above for pennation model.
if (!get_ignore_activation_dynamics()) {
auto& actMdl =
updMemberSubcomponent<MuscleFirstOrderActivationDynamicModel>(actMdlIdx);
MuscleFirstOrderActivationDynamicModel actMdlCopy(actMdl);
actMdl.set_activation_time_constant(get_activation_time_constant());
actMdl.set_deactivation_time_constant(get_deactivation_time_constant());
actMdl.set_minimum_activation(get_minimum_activation());
try {
actMdl.finalizeFromProperties();
} catch (const InvalidPropertyValue&) {
actMdl = actMdlCopy;
throw;
}
}
// Compute and store values that are used for clamping the fiber length.
const double minActiveFiberLength = falCurve.getMinActiveFiberLength()
* getOptimalFiberLength();
const double minPennatedFiberLength = penMdl.getMinimumFiberLength();
m_minimumFiberLength = max(SimTK::SignificantReal,
max(minActiveFiberLength, minPennatedFiberLength));
const double phi = penMdl.calcPennationAngle(m_minimumFiberLength);
m_minimumFiberLengthAlongTendon =
penMdl.calcFiberLengthAlongTendon(m_minimumFiberLength, cos(phi));
}
//==============================================================================
// CONSTRUCTORS
//==============================================================================
Millard2012EquilibriumMuscle::Millard2012EquilibriumMuscle()
{
setNull();
constructProperties();
}
Millard2012EquilibriumMuscle::Millard2012EquilibriumMuscle(
const std::string &aName, double aMaxIsometricForce, double aOptimalFiberLength,
double aTendonSlackLength, double aPennationAngle)
{
setNull();
constructProperties();
setName(aName);
setMaxIsometricForce(aMaxIsometricForce);
setOptimalFiberLength(aOptimalFiberLength);
setTendonSlackLength(aTendonSlackLength);
setPennationAngleAtOptimalFiberLength(aPennationAngle);
}
//==============================================================================
// GET METHODS
//==============================================================================
bool Millard2012EquilibriumMuscle::getUseFiberDamping() const
{ return use_fiber_damping; }
double Millard2012EquilibriumMuscle::getFiberDamping() const
{ return get_fiber_damping(); }
double Millard2012EquilibriumMuscle::getDefaultActivation() const
{ return get_default_activation(); }
double Millard2012EquilibriumMuscle::getDefaultFiberLength() const
{ return get_default_fiber_length(); }
double Millard2012EquilibriumMuscle::getActivationTimeConstant() const
{ return get_activation_time_constant(); }
double Millard2012EquilibriumMuscle::getDeactivationTimeConstant() const
{ return get_deactivation_time_constant(); }
double Millard2012EquilibriumMuscle::getMinimumActivation() const
{ return get_minimum_activation(); }
const ActiveForceLengthCurve& Millard2012EquilibriumMuscle::
getActiveForceLengthCurve() const
{ return get_ActiveForceLengthCurve(); }
const ForceVelocityCurve& Millard2012EquilibriumMuscle::
getForceVelocityCurve() const
{ return get_ForceVelocityCurve(); }
const FiberForceLengthCurve& Millard2012EquilibriumMuscle::
getFiberForceLengthCurve() const
{ return get_FiberForceLengthCurve(); }
const TendonForceLengthCurve& Millard2012EquilibriumMuscle::
getTendonForceLengthCurve() const
{ return get_TendonForceLengthCurve(); }
const MuscleFixedWidthPennationModel& Millard2012EquilibriumMuscle::
getPennationModel() const
{ return getMemberSubcomponent<MuscleFixedWidthPennationModel>(penMdlIdx); }
const MuscleFirstOrderActivationDynamicModel& Millard2012EquilibriumMuscle::
getActivationModel() const
{ return getMemberSubcomponent<MuscleFirstOrderActivationDynamicModel>(actMdlIdx); }
double Millard2012EquilibriumMuscle::getMinimumFiberLength() const
{ return m_minimumFiberLength; }
double Millard2012EquilibriumMuscle::getMinimumFiberLengthAlongTendon() const
{ return m_minimumFiberLengthAlongTendon; }
double Millard2012EquilibriumMuscle::
getTendonForceMultiplier(SimTK::State& s) const
{ return getMuscleDynamicsInfo(s).normTendonForce; }
double Millard2012EquilibriumMuscle::
getFiberStiffnessAlongTendon(const SimTK::State& s) const
{ return getMuscleDynamicsInfo(s).fiberStiffnessAlongTendon; }
double Millard2012EquilibriumMuscle::
getFiberVelocity(const SimTK::State& s) const
{ return getFiberVelocityInfo(s).fiberVelocity; }
double Millard2012EquilibriumMuscle::
getActivationDerivative(const SimTK::State& s) const
{
if (get_ignore_activation_dynamics())
return 0.0;
return getActivationModel().calcDerivative(getActivation(s),
getExcitation(s));
}
double Millard2012EquilibriumMuscle::
getPassiveFiberElasticForce(const SimTK::State& s) const
{
return getMuscleDynamicsInfo(s).userDefinedDynamicsExtras[0];
}
double Millard2012EquilibriumMuscle::
getPassiveFiberElasticForceAlongTendon(const SimTK::State& s) const
{
return getMuscleDynamicsInfo(s).userDefinedDynamicsExtras[0] *
getMuscleLengthInfo(s).cosPennationAngle;
}
double Millard2012EquilibriumMuscle::
getPassiveFiberDampingForce(const SimTK::State& s) const
{
return getMuscleDynamicsInfo(s).userDefinedDynamicsExtras[1];
}
double Millard2012EquilibriumMuscle::
getPassiveFiberDampingForceAlongTendon(const SimTK::State& s) const
{
return getMuscleDynamicsInfo(s).userDefinedDynamicsExtras[1] *
getMuscleLengthInfo(s).cosPennationAngle;
}
//==============================================================================
// SET METHODS
//==============================================================================
void Millard2012EquilibriumMuscle::
setMuscleConfiguration(bool ignoreTendonCompliance,
bool ignoreActivationDynamics,
double dampingCoefficient)
{
set_ignore_tendon_compliance(ignoreTendonCompliance);
set_ignore_activation_dynamics(ignoreActivationDynamics);
setFiberDamping(dampingCoefficient);
finalizeFromProperties();
}
void Millard2012EquilibriumMuscle::setFiberDamping(double dampingCoefficient)
{ set_fiber_damping(dampingCoefficient); }
void Millard2012EquilibriumMuscle::setDefaultActivation(double activation)
{ set_default_activation(activation); }
void Millard2012EquilibriumMuscle::
setActivation(SimTK::State& s, double activation) const
{
if (get_ignore_activation_dynamics()) {
SimTK::Vector& controls(_model->updControls(s));
setControls(SimTK::Vector(1, activation), controls);
_model->setControls(s, controls);
} else {
setStateVariableValue(s, STATE_ACTIVATION_NAME,
getActivationModel().clampActivation(activation));
}
markCacheVariableInvalid(s, _velInfoCV);
markCacheVariableInvalid(s, _dynamicsInfoCV);
}
void Millard2012EquilibriumMuscle::setDefaultFiberLength(double fiberLength)
{ set_default_fiber_length(fiberLength); }
void Millard2012EquilibriumMuscle::
setActivationTimeConstant(double activationTimeConstant)
{ set_activation_time_constant(activationTimeConstant); }
void Millard2012EquilibriumMuscle::
setDeactivationTimeConstant(double deactivationTimeConstant)
{ set_deactivation_time_constant(deactivationTimeConstant); }
void Millard2012EquilibriumMuscle::
setMinimumActivation(double minimumActivation)
{ set_minimum_activation(minimumActivation); }
void Millard2012EquilibriumMuscle::setActiveForceLengthCurve(
ActiveForceLengthCurve& aActiveForceLengthCurve)
{ set_ActiveForceLengthCurve(aActiveForceLengthCurve); }
void Millard2012EquilibriumMuscle::setForceVelocityCurve(
ForceVelocityCurve& aForceVelocityCurve)
{ set_ForceVelocityCurve(aForceVelocityCurve); }
void Millard2012EquilibriumMuscle::setFiberForceLengthCurve(
FiberForceLengthCurve& aFiberForceLengthCurve)
{ set_FiberForceLengthCurve(aFiberForceLengthCurve); }
void Millard2012EquilibriumMuscle::setTendonForceLengthCurve(
TendonForceLengthCurve& aTendonForceLengthCurve)
{ set_TendonForceLengthCurve(aTendonForceLengthCurve); }
void Millard2012EquilibriumMuscle::
setFiberLength(SimTK::State& s, double fiberLength) const
{
if (!get_ignore_tendon_compliance()) {
setStateVariableValue(s, STATE_FIBER_LENGTH_NAME,
clampFiberLength(fiberLength));
markCacheVariableInvalid(s, _lengthInfoCV);
markCacheVariableInvalid(s, _velInfoCV);
markCacheVariableInvalid(s, _dynamicsInfoCV);
}
}
//==============================================================================
// MUSCLE.H INTERFACE
//==============================================================================
double Millard2012EquilibriumMuscle::
computeActuation(const SimTK::State& s) const
{
const MuscleDynamicsInfo& mdi = getMuscleDynamicsInfo(s);
setActuation(s, mdi.tendonForce);
return mdi.tendonForce;
}
void Millard2012EquilibriumMuscle::
computeFiberEquilibrium(SimTK::State& s, bool solveForVelocity) const
{
if(get_ignore_tendon_compliance()) { // rigid tendon
return;
}
// Elastic tendon initialization routine.
// Initialize activation and fiber length provided by the State s
_model->getMultibodySystem().realize(s, SimTK::Stage::Velocity);
// Compute the fiber length where the fiber and tendon are in static
// equilibrium. Fiber and tendon velocity are set to zero.
// tol is the desired tolerance in Newtons.
const double tol = max(1e-8*getMaxIsometricForce(), SimTK::SignificantReal*10);
int maxIter = 200;
double pathLength = getLength(s);
double pathSpeed = solveForVelocity ? getLengtheningSpeed(s) : 0;
double activation = getActivation(s);
const MuscleStateEstimate result =
estimateMuscleFiberState(
activation,
pathLength,
pathSpeed,
tol,
maxIter,
solveForVelocity);
if (result.status ==
MuscleStateEstimate::Status::Failure_MaxIterationsReached) {
std::ostringstream oss;
oss << "Failed to compute muscle equilibrium state:\n"
<< " Solution error " << std::abs(result.solutionError)
<< " exceeds tolerance of " << tol << "\n"
<< " Newton iterations reached limit of " << maxIter << "\n"
<< " Activation is " << activation << "\n"
<< " Fiber length is " << result.fiberLength << "\n";
OPENSIM_THROW_FRMOBJ(MuscleCannotEquilibrate, oss.str());
}
if (result.status ==
MuscleStateEstimate::Status::Warning_FiberAtLowerBound) {
log_warn(
"Millard2012EquilibriumMuscle static solution: '{}' is at its"
"minimum fiber length of {}.",
getName(),
result.fiberLength);
}
setActuation(s, result.tendonForce);
setFiberLength(s, result.fiberLength);
}
//==============================================================================
// SCALING
//==============================================================================
void Millard2012EquilibriumMuscle::
extendPostScale(const SimTK::State& s, const ScaleSet& scaleSet)
{
Super::extendPostScale(s, scaleSet);
AbstractGeometryPath& path = updPath();
if (path.getPreScaleLength(s) > 0.0)
{
double scaleFactor = path.getLength(s) / path.getPreScaleLength(s);
upd_optimal_fiber_length() *= scaleFactor;
upd_tendon_slack_length() *= scaleFactor;
// Clear the pre-scale length that was stored in the path.
path.setPreScaleLength(s, 0.0);
}
}
//==============================================================================
// MUSCLE INTERFACE REQUIREMENTS -- MUSCLE LENGTH INFO
//==============================================================================
void Millard2012EquilibriumMuscle::calcMuscleLengthInfo(const SimTK::State& s,
MuscleLengthInfo& mli) const
{
// Get musculotendon actuator properties.
//double maxIsoForce = getMaxIsometricForce();
double optFiberLength = getOptimalFiberLength();
double tendonSlackLen = getTendonSlackLength();
try {
// Get muscle-specific properties.
const ActiveForceLengthCurve& falCurve = get_ActiveForceLengthCurve();
const FiberForceLengthCurve& fpeCurve = get_FiberForceLengthCurve();
//const TendonForceLengthCurve& fseCurve = get_TendonForceLengthCurve();
if(get_ignore_tendon_compliance()) { //rigid tendon
mli.fiberLength = clampFiberLength(
getPennationModel().calcFiberLength(getLength(s),
tendonSlackLen));
} else { // elastic tendon
mli.fiberLength = clampFiberLength(
getStateVariableValue(s, STATE_FIBER_LENGTH_NAME));
}
mli.normFiberLength = mli.fiberLength / optFiberLength;
mli.pennationAngle = getPennationModel().
calcPennationAngle(mli.fiberLength);
mli.cosPennationAngle = cos(mli.pennationAngle);
mli.sinPennationAngle = sin(mli.pennationAngle);
mli.fiberLengthAlongTendon = mli.fiberLength * mli.cosPennationAngle;
// Necessary even for the rigid tendon, as it might have gone slack.
mli.tendonLength = getPennationModel().
calcTendonLength(mli.cosPennationAngle,
mli.fiberLength,
getLength(s));
mli.normTendonLength = mli.tendonLength / tendonSlackLen;
mli.tendonStrain = mli.normTendonLength - 1.0;
mli.fiberPassiveForceLengthMultiplier =
fpeCurve.calcValue(mli.normFiberLength);
mli.fiberActiveForceLengthMultiplier =
falCurve.calcValue(mli.normFiberLength);
} catch(const std::exception &x) {
std::string msg = "Exception caught in Millard2012EquilibriumMuscle::"
"calcMuscleLengthInfo from " + getName() + "\n"
+ x.what();
throw OpenSim::Exception(msg);
}
}
//==============================================================================
// MUSCLE INTERFACE REQUIREMENTS -- MUSCLE POTENTIAL ENERGY INFO
//==============================================================================
void Millard2012EquilibriumMuscle::
calcMusclePotentialEnergyInfo(const SimTK::State& s,
MusclePotentialEnergyInfo& mpei) const
{
// Get musculotendon actuator properties.
double maxIsoForce = getMaxIsometricForce();
double optFiberLength = getOptimalFiberLength();
double tendonSlackLen = getTendonSlackLength();
try {
// Get the quantities that we've already computed.
const MuscleLengthInfo &mli = getMuscleLengthInfo(s);
// Get muscle-specific properties.
//const ActiveForceLengthCurve& falCurve = get_ActiveForceLengthCurve();
const FiberForceLengthCurve& fpeCurve = get_FiberForceLengthCurve();
const TendonForceLengthCurve& fseCurve = get_TendonForceLengthCurve();
// Note that the curves return normalized area.
double fiberStrainAtFiso = fpeCurve.getStrainAtOneNormForce()
- fpeCurve.getStrainAtZeroForce();
double fiberStretchAtFiso = fiberStrainAtFiso * optFiberLength;
double fiberPotentialScaling = (fiberStretchAtFiso*maxIsoForce)
/ fiberStrainAtFiso;
mpei.fiberPotentialEnergy = fpeCurve.calcIntegral(mli.normFiberLength)
* fiberPotentialScaling;
mpei.tendonPotentialEnergy = 0;
if(!get_ignore_tendon_compliance()) { // elastic tendon
double tendonStrainAtFiso = fseCurve.getStrainAtOneNormForce();
double tendonStretchAtFiso = tendonStrainAtFiso*tendonSlackLen;
double tendonPotentialScaling = (tendonStretchAtFiso*maxIsoForce)
/ tendonStrainAtFiso;
mpei.tendonPotentialEnergy =
fseCurve.calcIntegral(mli.normTendonLength)
* tendonPotentialScaling;
}
mpei.musclePotentialEnergy = mpei.fiberPotentialEnergy +
mpei.tendonPotentialEnergy;
} catch(const std::exception &x) {
std::string msg = "Exception caught in Millard2012EquilibriumMuscle::"
"calcMusclePotentialEnergyInfo from " + getName() + "\n"
+ x.what();
throw OpenSim::Exception(msg);
}
}
//==============================================================================
// MUSCLE INTERFACE REQUIREMENTS -- FIBER VELOCITY INFO
//==============================================================================
void Millard2012EquilibriumMuscle::
calcFiberVelocityInfo(const SimTK::State& s, FiberVelocityInfo& fvi) const
{
try {
// Get the quantities that we've already computed.
const MuscleLengthInfo &mli = getMuscleLengthInfo(s);
// Get the static properties of this muscle.
double optFibLen = getOptimalFiberLength();
//======================================================================
// Compute fv by inverting the force-velocity relationship in the
// equilibrium equations.
//======================================================================
double dlce = SimTK::NaN;
double dlceN = SimTK::NaN;
double fv = SimTK::NaN;
// Calculate fiber velocity.
if(get_ignore_tendon_compliance()) {
// Rigid tendon.
if(mli.tendonLength < getTendonSlackLength()
- SimTK::SignificantReal) {
// The tendon is buckling, so fiber velocity is zero.
dlce = 0.0;
dlceN = 0.0;
fv = 1.0;
} else {
double dlenMcl = getLengtheningSpeed(s);
dlce = getPennationModel().
calcFiberVelocity(mli.cosPennationAngle, dlenMcl, 0.0);
dlceN = dlce/(optFibLen*getMaxContractionVelocity());
fv = get_ForceVelocityCurve().calcValue(dlceN);
}
} else if(!get_ignore_tendon_compliance() && !use_fiber_damping) {
// Elastic tendon, no damping.
double a = get_ignore_activation_dynamics() ?
getControl(s) :
getStateVariableValue(s, STATE_ACTIVATION_NAME);
a = getActivationModel().clampActivation(a);
const TendonForceLengthCurve& fseCurve =
get_TendonForceLengthCurve();
double fse = fseCurve.calcValue(mli.normTendonLength);
SimTK_ERRCHK_ALWAYS(mli.cosPennationAngle > SimTK::SignificantReal,
"calcFiberVelocityInfo",
"%s: Pennation angle is 90 degrees, causing a singularity");
SimTK_ERRCHK_ALWAYS(a > SimTK::SignificantReal,
"calcFiberVelocityInfo",
"%s: Activation is 0, causing a singularity");
SimTK_ERRCHK_ALWAYS(mli.fiberActiveForceLengthMultiplier >
SimTK::SignificantReal,
"calcFiberVelocityInfo",
"%s: Active-force-length factor is 0, causing a singularity");
fv = calcUndampedFiberForceVelocityMultiplier(
a,
mli.fiberActiveForceLengthMultiplier,
mli.fiberPassiveForceLengthMultiplier,
fse,
mli.cosPennationAngle);
// Evaluate the inverse force-velocity curve.
dlceN = fvInvCurve.calcValue(fv);
dlce = dlceN*getMaxContractionVelocity()*optFibLen;
} else {
// Elastic tendon, with damping.
double a = get_ignore_activation_dynamics() ?
getControl(s) :
getStateVariableValue(s, STATE_ACTIVATION_NAME);
a = getActivationModel().clampActivation(a);
const TendonForceLengthCurve& fseCurve =
get_TendonForceLengthCurve();
double fse = fseCurve.calcValue(mli.normTendonLength);
double beta = get_fiber_damping();
SimTK_ERRCHK_ALWAYS(
beta > SimTK::SignificantReal,
"calcFiberVelocityInfo",
"Fiber damping coefficient must be greater than 0.");
// Newton solve for fiber velocity.
DampedFiberVelocityCalculationResult result =
calcDampedNormFiberVelocity(
getMaxIsometricForce(),