forked from opensim-org/opensim-core
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathThelen2003Muscle.cpp
More file actions
1695 lines (1389 loc) · 61.4 KB
/
Copy pathThelen2003Muscle.cpp
File metadata and controls
1695 lines (1389 loc) · 61.4 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: Thelen2003Muscle.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 *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include <fstream>
#include <OpenSim/Simulation/Model/Model.h>
#include "Thelen2003Muscle.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using namespace SimTK;
//=============================================================================
// CONSTRUCTORS
//=============================================================================
// Uses default (compiler-generated) destructor, copy constructor, copy
// assignment operator.
//_____________________________________________________________________________
/**
* Default constructor.
*/
Thelen2003Muscle::Thelen2003Muscle()
{
setNull();
constructProperties();
}
//_____________________________________________________________________________
/**
* Constructor.
*/
Thelen2003Muscle::
Thelen2003Muscle(const std::string& aName, double aMaxIsometricForce,
double aOptimalFiberLength,double aTendonSlackLength,
double aPennationAngle)
{
setNull();
constructProperties();
setName(aName);
setMaxIsometricForce(aMaxIsometricForce);
setOptimalFiberLength(aOptimalFiberLength);
setTendonSlackLength(aTendonSlackLength);
setPennationAngleAtOptimalFiberLength(aPennationAngle);
}
//==============================================================================
// Component Interface
//==============================================================================
void Thelen2003Muscle::extendFinalizeFromProperties()
{
Super::extendFinalizeFromProperties();
SimTK_ERRCHK1_ALWAYS(get_FmaxTendonStrain() > 0,
"Thelen2003Muscle::extendFinalizeFromProperties",
"%s: FmaxTendonStrain must be greater than zero", getName().c_str());
SimTK_ERRCHK1_ALWAYS(get_FmaxMuscleStrain() > 0,
"Thelen2003Muscle::extendFinalizeFromProperties",
"%s: FmaxMuscleStrain must be greater than zero", getName().c_str());
SimTK_ERRCHK1_ALWAYS(get_KshapeActive() > 0,
"Thelen2003Muscle::extendFinalizeFromProperties",
"%s: KshapeActive must be greater than zero", getName().c_str());
SimTK_ERRCHK1_ALWAYS(get_KshapePassive() > 0,
"Thelen2003Muscle::extendFinalizeFromProperties",
"%s: KshapePassive must be greater than zero", getName().c_str());
SimTK_ERRCHK1_ALWAYS(get_Af() > 0,
"Thelen2003Muscle::extendFinalizeFromProperties",
"%s: Af must be greater than zero", getName().c_str());
SimTK_ERRCHK1_ALWAYS(get_Flen() > 1.0,
"Thelen2003Muscle::extendFinalizeFromProperties",
"%s: Flen must be greater than 1.0", getName().c_str());
SimTK_ERRCHK1_ALWAYS(get_fv_linear_extrap_threshold() > 1.0/get_Flen(),
"Thelen2003::extendFinalizeFromProperties",
"%s: F-v extrapolation threshold must be greater than 1.0/Flen",
getName().c_str());
OPENSIM_THROW_IF_FRMOBJ(get_minimum_activation() < 0.01,
InvalidPropertyValue, getProperty_minimum_activation().getName(),
"Minimum activation cannot be less than 0.01");
OPENSIM_THROW_IF_FRMOBJ(getMinControl() < get_minimum_activation(),
InvalidPropertyValue, getProperty_min_control().getName(),
"Minimum control cannot be less than minimum activation");
// 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& pennMdl =
updMemberSubcomponent<MuscleFixedWidthPennationModel>(pennMdlIdx);
MuscleFixedWidthPennationModel pennMdlCopy(pennMdl);
pennMdl.set_optimal_fiber_length(getOptimalFiberLength());
pennMdl.set_pennation_angle_at_optimal(
getPennationAngleAtOptimalFiberLength());
pennMdl.set_maximum_pennation_angle(get_maximum_pennation_angle());
try {
pennMdl.finalizeFromProperties();
} catch (const InvalidPropertyValue&) {
pennMdl = pennMdlCopy;
throw;
}
// Propagate properties down to activation dynamics model subcomponent.
// Handle invalid properties as above for pennation model.
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;
}
}
//====================================================================
// Model Component Interface
//====================================================================
void Thelen2003Muscle::extendConnectToModel(Model& aModel)
{
Super::extendConnectToModel(aModel);
}
void Thelen2003Muscle::extendInitStateFromProperties(SimTK::State& s) const
{
Super::extendInitStateFromProperties(s);
}
void Thelen2003Muscle::
extendSetPropertiesFromState(const SimTK::State& s)
{
Super::extendSetPropertiesFromState(s);
}
//_____________________________________________________________________________
// Set the data members of this muscle to their null values.
void Thelen2003Muscle::setNull()
{
// no data members
setAuthors("Matthew Millard");
}
//_____________________________________________________________________________
/**
* Populate this object's properties
*/
void Thelen2003Muscle::constructProperties()
{
constructProperty_FmaxTendonStrain(0.04); // was 0.033
constructProperty_FmaxMuscleStrain(0.6);
constructProperty_KshapeActive(0.45);
constructProperty_KshapePassive(5.0);
constructProperty_Af(0.25);
constructProperty_Flen(1.4); //was 1.8,
constructProperty_fv_linear_extrap_threshold(0.95);
//acos(0.1) = 84.26 degrees
constructProperty_maximum_pennation_angle(acos(0.1));
constructProperty_activation_time_constant(0.015);
constructProperty_deactivation_time_constant(0.050);
constructProperty_minimum_activation(0.01);
setMinControl(get_minimum_activation());
}
//=============================================================================
// GET
//=============================================================================
double Thelen2003Muscle::getActivationTimeConstant() const
{ return get_activation_time_constant(); }
double Thelen2003Muscle::getDeactivationTimeConstant() const
{ return get_deactivation_time_constant(); }
double Thelen2003Muscle::getMinimumActivation() const
{ return get_minimum_activation(); }
const MuscleFirstOrderActivationDynamicModel& Thelen2003Muscle::
getActivationModel() const
{
return getMemberSubcomponent<MuscleFirstOrderActivationDynamicModel>(
actMdlIdx);
}
const MuscleFixedWidthPennationModel& Thelen2003Muscle::
getPennationModel() const
{ return getMemberSubcomponent<MuscleFixedWidthPennationModel>(pennMdlIdx); }
double Thelen2003Muscle::getMaximumPennationAngle() const
{ return get_maximum_pennation_angle(); }
//=============================================================================
// SET
//=============================================================================
void Thelen2003Muscle::setActivationTimeConstant(double actTimeConstant)
{ set_activation_time_constant(actTimeConstant); }
void Thelen2003Muscle::setDeactivationTimeConstant(double deactTimeConstant)
{ set_deactivation_time_constant(deactTimeConstant); }
void Thelen2003Muscle::setMinimumActivation(double minimumActivation)
{ set_minimum_activation(minimumActivation); }
void Thelen2003Muscle::setMaximumPennationAngle(double maximumPennationAngle)
{ set_maximum_pennation_angle(maximumPennationAngle); }
//==============================================================================
// START OF DEPRECATED
//==============================================================================
double Thelen2003Muscle::
calcInextensibleTendonActiveFiberForce(SimTK::State& s,
double aActivation) const
{
double inextensibleTendonActiveFiberForce = 0;
double muscleLength = getLength(s);
double muscleVelocity = getLengtheningSpeed(s);
double tendonSlackLength = getTendonSlackLength();
double tendonVelocity = 0.0; //Inextensible tendon;
double fiberLength = getPennationModel().calcFiberLength(muscleLength,
tendonSlackLength);
if(fiberLength > getPennationModel().getMinimumFiberLength()) {
double phi = getPennationModel().calcPennationAngle(fiberLength);
double fiberVelocity = getPennationModel().calcFiberVelocity(
cos(phi),muscleVelocity,tendonVelocity);
inextensibleTendonActiveFiberForce =
calcActiveFiberForceAlongTendon( aActivation,
fiberLength,
fiberVelocity);
}
return inextensibleTendonActiveFiberForce;
}
double Thelen2003Muscle::
calcActiveFiberForceAlongTendon(double activation,
double fiberLength,
double fiberVelocity) const
{
double activeFiberForce = 0;
double clampedFiberLength = getPennationModel()
.clampFiberLength(fiberLength);
//If the fiber is in a legal range, compute the force its generating
if(fiberLength > getPennationModel().getMinimumFiberLength())
{
//Clamp activation to a legal range
double clampedActivation = getActivationModel()
.clampActivation(activation);
//Normalize fiber length and velocity
double normFiberLength = clampedFiberLength/getOptimalFiberLength();
double normFiberVelocity = fiberVelocity /
(getOptimalFiberLength() * getMaxContractionVelocity());
//Evaluate the force active length and force velocity multipliers
double fal = calcfal(normFiberLength);
double fv = SimTK::NaN;
double fvTol = 1e-6;
int fvMaxIter= 100;
fv = calcfvInv( clampedActivation,
fal,
normFiberVelocity,
fvTol,
fvMaxIter);
double fiso = getMaxIsometricForce();
//Evaluate the pennation angle
double phi = getPennationModel().calcPennationAngle(fiberLength);
//Compute the active fiber force
activeFiberForce = fiso * clampedActivation * fal * fv * cos(phi);
}
//Compute the active fiber force
return activeFiberForce;
}
//==============================================================================
// END OF DEPRECATED
//==============================================================================
//==============================================================================
// Muscle.h Interface
//==============================================================================
double Thelen2003Muscle::computeActuation(const SimTK::State& s) const
{
const MuscleDynamicsInfo& mdi = getMuscleDynamicsInfo(s);
setActuation(s, mdi.tendonForce);
return( mdi.tendonForce );
}
void Thelen2003Muscle::computeInitialFiberEquilibrium(SimTK::State& s) const
{
//Initial activation and fiber length from input State, s.
_model->getMultibodySystem().realize(s, SimTK::Stage::Velocity);
double activation = getActivation(s);
//Tolerance, in Newtons, of the desired equilibrium
const double tol = max( 1e-8*getMaxIsometricForce(),
SimTK::SignificantReal * 10 );
int maxIter = 20; //Should this be user settable?
std::pair<StatusFromInitMuscleState, ValuesFromInitMuscleState> result;
try {
result = initMuscleState(s, activation, tol, maxIter);
}
catch (const std::exception& x) {
OPENSIM_THROW_FRMOBJ(MuscleCannotEquilibrate, x.what());
}
switch(result.first) {
case StatusFromInitMuscleState::Success_Converged:
setActuation(s, result.second["tendon_force"]);
setFiberLength(s, result.second["fiber_length"]);
break;
case StatusFromInitMuscleState::Warning_FiberAtLowerBound:
log_warn("Thelen2003Muscle initialization: '{}' is at its minimum "
"fiber length of {}.", getName(),
result.second["fiber_length"]);
setActuation(s, result.second["tendon_force"]);
setFiberLength(s, result.second["fiber_length"]);
break;
case StatusFromInitMuscleState::Failure_MaxIterationsReached:
// Report internal variables and throw exception.
std::ostringstream ss;
ss << "\n Solution error " << abs(result.second["solution_error"])
<< " exceeds tolerance of " << tol << "\n"
<< " Newton iterations reached limit of " << maxIter << "\n"
<< " Activation is " << activation << "\n"
<< " Fiber length is " << result.second["fiber_length"] << "\n";
OPENSIM_THROW_FRMOBJ(MuscleCannotEquilibrate, ss.str());
break;
}
}
void Thelen2003Muscle::calcMuscleLengthInfo(const SimTK::State& s,
MuscleLengthInfo& mli) const
{
try{
double optFiberLength = getOptimalFiberLength();
double mclLength = getLength(s);
double tendonSlackLen = getTendonSlackLength();
//Clamp the minimum fiber length to its minimum physical value.
mli.fiberLength = getPennationModel().clampFiberLength(
getStateVariableValue(s, STATE_FIBER_LENGTH_PATH));
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;
mli.tendonLength = getPennationModel().calcTendonLength(
mli.cosPennationAngle,
mli.fiberLength,mclLength );
mli.normTendonLength = mli.tendonLength / tendonSlackLen;
mli.tendonStrain = mli.normTendonLength - 1.0;
mli.fiberPassiveForceLengthMultiplier= calcfpe(mli.normFiberLength);
mli.fiberActiveForceLengthMultiplier = calcfal(mli.normFiberLength);
}catch(const std::exception &x){
std::string msg = "Exception caught in Thelen2003Muscle::"
"calcMuscleLengthInfo\n"
"of " + getName() + "\n"
+ x.what();
throw OpenSim::Exception(msg);
}
}
void Thelen2003Muscle::calcMusclePotentialEnergyInfo(const SimTK::State& s,
MusclePotentialEnergyInfo& mpei) const
{
try {
// Get the quantities that we've already computed.
const MuscleLengthInfo &mli = getMuscleLengthInfo(s);
mpei.fiberPotentialEnergy = calcfpefisoPE(mli.fiberLength);
mpei.tendonPotentialEnergy= calcfsefisoPE(mli.tendonStrain);
mpei.musclePotentialEnergy= mpei.fiberPotentialEnergy
+ mpei.tendonPotentialEnergy;
}
catch(const std::exception &x){
std::string msg = "Exception caught in Thelen2003Muscle::"
"calcMusclePotentialEnergyInfo\n"
"of " + getName() + "\n"
+ x.what();
throw OpenSim::Exception(msg);
}
}
void Thelen2003Muscle::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 mclLength = getLength(s);
double tendonSlackLen = getTendonSlackLength();
double optFiberLen = getOptimalFiberLength();
//=========================================================================
// Compute fv by inverting the force-velocity relationship in the
// equilibrium equations
//=========================================================================
//1. Get fiber/tendon kinematic information
//clamp activation to a legal range
double a = getActivationModel().clampActivation(getStateVariableValue(s,
STATE_ACTIVATION_PATH));
double lce = mli.fiberLength;
double phi = mli.pennationAngle;
double cosphi=mli.cosPennationAngle;
double sinphi = mli.sinPennationAngle;
//2. compute the tendon length ... because we can with this kind of model
double tl = mli.tendonLength;
//3. Compute force multipliers and the fiber velocity
//This exception was causing headaches, so we're handling the special
//case of a fiber that is at its minimum length instead
//SimTK_ERRCHK1_ALWAYS(cosphi > SimTK::Eps, fcnName.c_str(),
// "%s: Pennation angle is 90 degrees, and is causing a singularity",
// muscleName.c_str());
//6. Invert the force velocity curve to get dlce. Check for singularities
// first
//These exceptions were causing headaches, so we're handling the special
//case of a fiber that is at its minimum length instead
//SimTK_ERRCHK1_ALWAYS(a > SimTK::Eps, fcnName.c_str(),
// "%s: Activation is 0, and is causing a singularity",
// muscleName.c_str());
//SimTK_ERRCHK1_ALWAYS(fal > SimTK::Eps, fcnName.c_str(),
// "%s: The active force length curve value is 0,"
// " and is causing a singularity",
// muscleName.c_str());
//Check for singularity conditions, and clamp output appropriately
//default values that are appropriate when fiber length has been clamped
//to its minimum allowable value.
double fse = calcfse(tl/tendonSlackLen);
double fal = mli.fiberActiveForceLengthMultiplier;
double fpe = mli.fiberPassiveForceLengthMultiplier;
double afalfv = ((fse/cosphi)-fpe); //we can do this without fear of
//a singularity because fiber length
//is clamped
double fv = afalfv/(a*fal);
double dlceN = calcdlceN(a,fal,afalfv);
double dlce = dlceN*getMaxContractionVelocity()*optFiberLen;
double tanPhi = tan(phi);
double dphidt = getPennationModel().calcPennationAngularVelocity(
tanPhi,lce,dlce);
double dlceAT = getPennationModel().calcFiberVelocityAlongTendon(
lce, dlce, sinphi, cosphi, dphidt);
//Switching condition: if the fiber is clamped and the tendon and the
// : fiber are out of equilibrium
double fiberStateClamped = 0.0;
if(isFiberStateClamped(s,dlceN)){
dlce = 0;
dlceAT = 0;
dlceN = 0;
dphidt = 0;
fv = 1.0;
fiberStateClamped = 1.0;
}
//Populate the struct;
fvi.fiberVelocity = dlce;
fvi.fiberVelocityAlongTendon = dlceAT;
fvi.normFiberVelocity = dlceN;
fvi.pennationAngularVelocity = dphidt;
fvi.fiberForceVelocityMultiplier = fv;
fvi.userDefinedVelocityExtras.resize(2);
fvi.userDefinedVelocityExtras[0]=fse;
fvi.userDefinedVelocityExtras[1]=fiberStateClamped;
}
catch(const std::exception &x){
std::string msg = "Exception caught in Thelen2003Muscle::"
"calcFiberVelocityInfo\n"
"of " + getName() + "\n"
+ x.what();
throw OpenSim::Exception(msg);
}
}
//=======================================
// computeFiberVelocityInfo helper functions
//=======================================
void Thelen2003Muscle::calcMuscleDynamicsInfo(const SimTK::State& s,
MuscleDynamicsInfo& mdi) const
{
try {
//Get the quantities that we've already computed
const MuscleLengthInfo &mli = getMuscleLengthInfo(s);
const FiberVelocityInfo &mvi = getFiberVelocityInfo(s);
//Get the static properties of this muscle
// double mclLength = getLength(s);
double tendonSlackLen = getTendonSlackLength();
double optFiberLen = getOptimalFiberLength();
double fiso = getMaxIsometricForce();
double penHeight = getPennationModel().getParallelogramHeight();
//=========================================================================
// Compute required quantities
//=========================================================================
//1. Get fiber/tendon kinematic information
double a = getActivationModel().clampActivation(
getStateVariableValue(s, STATE_ACTIVATION_PATH) );
double lce = mli.fiberLength;
double fiberStateClamped = mvi.userDefinedVelocityExtras[1];
double dlce = mvi.fiberVelocity;
double phi = mli.pennationAngle;
double cosphi = mli.cosPennationAngle;
// double sinphi = mli.sinPennationAngle;
double tl = mli.tendonLength;
double dtl = getTendonVelocity(s);
// double tlN = mli.normTendonLength;
//Default values appropriate when the fiber is clamped to its minimum length
//and is generating no force
//These quantities should already be set to legal values from
//calcFiberVelocityInfo
double fal = mli.fiberActiveForceLengthMultiplier;
double fpe = mli.fiberPassiveForceLengthMultiplier;
double fv = mvi.fiberForceVelocityMultiplier;
double fse = mvi.userDefinedVelocityExtras[0];
double aFm = 0; //active fiber force
double Fm = 0;
double dFm_dlce = 0;
double dFmAT_dlce = 0;
double dFmAT_dlceAT = 0;
double dFt_dtl = 0;
double Ke = 0;
if(fiberStateClamped < 0.5){
aFm = calcActiveFm(a,fal,fv,fiso);
Fm = calcFm(a,fal,fv,fpe,fiso);
dFm_dlce = calcDFmDlce(lce,a,fv,fiso,optFiberLen);
dFmAT_dlce = calcDFmATDlce(lce,phi,cosphi,Fm,dFm_dlce,penHeight);
//The expression below is correct only because we are using a pennation
//model that has a parallelogram of constant height.
dFmAT_dlceAT= dFmAT_dlce*cosphi;
dFt_dtl = calcDFseDtl(tl, fiso, tendonSlackLen);
//Compute the stiffness of the whole muscle/tendon complex
Ke = (dFmAT_dlceAT*dFt_dtl)/(dFmAT_dlceAT+dFt_dtl);
}
mdi.activation = a;
mdi.fiberForce = Fm;
mdi.fiberForceAlongTendon = Fm*cosphi;
mdi.normFiberForce = Fm/fiso;
mdi.activeFiberForce = aFm;
mdi.passiveFiberForce = fpe*fiso;
mdi.tendonForce = fse*fiso;
mdi.normTendonForce = fse;
mdi.fiberStiffness = dFm_dlce;
mdi.fiberStiffnessAlongTendon = dFmAT_dlceAT;
mdi.tendonStiffness = dFt_dtl;
mdi.muscleStiffness = Ke;
//Check that the derivative of system energy less work is zero within
//a reasonable numerical tolerance. Throw an exception if this is not true
double dFibPEdt = fpe*fiso*dlce;
double dTdnPEdt = fse*fiso*dtl;
double dFibWdt = -mdi.activeFiberForce*mvi.fiberVelocity;
double dmcldt = getLengtheningSpeed(s);
double dBoundaryWdt = mdi.tendonForce * dmcldt;
double ddt_KEPEmW = dFibPEdt+dTdnPEdt-dFibWdt-dBoundaryWdt;
SimTK::Vector userVec(1);
userVec(0) = ddt_KEPEmW;
mdi.userDefinedDynamicsExtras = userVec;
/////////////////////////////
//Populate the power entries
/////////////////////////////
mdi.fiberActivePower = dFibWdt;
mdi.fiberPassivePower = -dFibPEdt;
}
catch(const std::exception &x) {
std::string msg = "Exception caught in Thelen2003Muscle::"
"calcMuscleDynamicsInfo\n"
"of " + getName() + "\n"
+ x.what();
throw OpenSim::Exception(msg);
}
}
double Thelen2003Muscle::getMinimumFiberLength() const
{
return getPennationModel().getMinimumFiberLength();
}
bool Thelen2003Muscle::
isFiberStateClamped(const SimTK::State& s, double dlceN) const
{
bool clamped = false;
//Is the fiber length clamped and it is shortening, then the fiber length
//not valid
if( (getStateVariableValue(s, STATE_FIBER_LENGTH_PATH)
<= getMinimumFiberLength())
&& dlceN <= 0){
clamped = true;
}
return clamped;
}
//==============================================================================
// ActivationFiberLength.h Interface
//==============================================================================
/** Get the rate change of activation */
double Thelen2003Muscle::calcActivationRate(const SimTK::State& s) const
{
double excitation = getExcitation(s);
double activation = getActivation(s);
double dadt = getActivationModel().calcDerivative(activation,excitation);
return dadt;
}
//==============================================================================
// Numerical Guts: Initialization
//==============================================================================
std::pair<Thelen2003Muscle::StatusFromInitMuscleState,
Thelen2003Muscle::ValuesFromInitMuscleState>
Thelen2003Muscle::initMuscleState(const SimTK::State& s,
const double aActivation,
const double aSolTolerance,
const int aMaxIterations) const
{
// Using short variable names to facilitate writing out long equations
const double ma = aActivation;
const double ml = getLength(s);
const double dml= getLengtheningSpeed(s);
//Shorter version of the constants
const double tsl = getTendonSlackLength();
const double ofl = getOptimalFiberLength();
const double ophi= getPennationAngleAtOptimalFiberLength();
const double vol = ofl * sin(ophi);
const double fiso= getMaxIsometricForce();
const double vmax = getMaxContractionVelocity();
//Shorter version of normalized muscle multipliers
double fse = 0; //Normalized tendon (series element) force
double fal = 0; //Normalized active force length multiplier
double fpe = 0; //Normalized parallel element force
double fv = 0; //Normalized force-velocity multiplier
//*******************************
//Position level
double tl = getTendonSlackLength()*1.01;
double lce = getPennationModel().calcFiberLength(ml, tl);
double phi = 0.0;
double cosphi = 1.0;
//Normalized quantities
double tlN = tl/tsl;
double lceN = lce/ofl;
//Velocity level
double dtl = 0;
double dlce = 0; // (dml - dtl) * cos(phi);
double dlceN = 0; // dlce / (vmax*ofl);
double dphi = 0; // -(dlce / lce)*tan(phi);
// double dlceAT = dlce*cosphi -vol*dphi;
//*******************************
//Internal variables for the loop
double Fm = 0; // Muscle force
double FmAT=0; // Muscle force along tendon
double Ft = 0; // Tendon force
double ferr = SimTK::MostPositiveReal; // Solution error
double dFm_dlce = 0; // Partial derivative of muscle force w.r.t. lce
double dFmAT_dlce = 0; // Partial derivative of muscle force along
// tendon w.r.t. lce
double dFmAT_dlceAT = 0; // Partial derivative of muscle force along
// tendon w.r.t. lce along the tendon.
double dFt_d_lce = 0; // Partial derivative of tendon force w.r.t. lce
double dFt_d_tl = 0; // Partial derivative of tendon force w.r.t. tl
double dferr_d_lce = 0; // Partial derivative of the solution error w.r.t
// lce
double delta_lce = 0; // Chance in lce
double Ke = 0; // Linearized local stiffness of the muscle
//*******************************
// Helper functions
//Update position level quantities, only if they won't go singular
auto positionFunc = [&] {
phi = getPennationModel().calcPennationAngle(lce);
cosphi = cos(phi);
tl = ml - lce*cosphi;
lceN = lce / ofl;
tlN = tl / tsl;
};
// Functional to update the force multipliers
auto multipliersFunc = [&] {
fse = calcfse(tlN);
fal = calcfal(lceN);
fpe = calcfpe(lceN);
};
// Functional to compute the equilibrium force error
auto ferrFunc = [&] {
Fm = (ma*fal*fv + fpe)*fiso;
FmAT = Fm*cosphi;
Ft = fse*fiso;
ferr = FmAT - Ft;
};
// Functional to compute the partial derivative of muscle force w.r.t. lce
auto partialsFunc = [&] {
dFm_dlce = calcDFmDlce(lce, ma, fv, fiso, ofl);
dFmAT_dlce = calcDFmATDlce(lce, phi, cosphi, Fm, dFm_dlce, vol);
dFmAT_dlceAT = dFmAT_dlce*cosphi;
dFt_d_tl = calcDFseDtl(tl, fiso, tsl);
dFt_d_lce = calcDFseDlce(tl, lce, phi, cosphi, fiso, tsl, vol);
};
// Functional to estimate fiber velocity and force-velocity multiplier
// from the relative fiber and tendon stiffnesses from above partials
auto velocityFunc = [&] {
//Update velocity level quantities: share the muscle velocity
//between the tendon and the fiber according to their relative
//stiffness:
//
//Fm = Ft at equilibrium
//Fm = Km*lceAT
//Ft = Kt*xt
//dFm_d_xm = Km*dlceAT + dKm_d_t*lceAT (assume dKm_d_t = 0)
//dFt_d_xt = Kt*dtl + dKt_d_t*dtl (assume dKt_d_t = 0)
//
//This is a heuristic. The above assumptions are necessary as
//computing the partial derivatives of Km or Kt w.r.t. requires
//acceleration level knowledge, which is not available in
//general.
//Stiffness of the muscle is the stiffness of the tendon and the
//fiber (along the tendon) in series
//the if statement here is to handle the special case when the
//negative stiffness of the fiber (which could happen in this
// model) is equal to the positive stiffness of the tendon.
if (abs(dFmAT_dlceAT + dFt_d_tl) > SimTK::SignificantReal
&& tl > getTendonSlackLength()) {
//Ke = (dFmAT_dlceAT*dFt_d_tl) / (dFmAT_dlceAT + dFt_d_tl);
// resultant stiffness = k1/(k1+k2)
dtl = (dFmAT_dlceAT / (dFmAT_dlceAT + dFt_d_tl)) * dml;
}
else {
dtl = dml;
}
// Update fiber velocity
dlce = getPennationModel().calcFiberVelocity(cosphi, dml, dtl);
dlceN = dlce / (vmax*ofl);
// Update the force-velocity multiplier
fv = calcfvInv(ma, fal, dlceN, aSolTolerance, 100);
};
//*******************************
//Initialize the loop
int iter = 0;
// Estimate the position level quantities (lengths, angles) of the muscle
positionFunc();
// Multipliers based on initial fiber-length estimate
multipliersFunc();
// Starting guess at the force-velocity multiplier
fv = 1.0;
// Estimate partial derivatives of muscle forces
partialsFunc();
// Update the velocity (and multiplier) estimate from partials
velocityFunc();
// Compute the equilibrium error with velocity estimate
ferrFunc();
// Update the partial derivatives of the force error w.r.t. lce with
// newly estimated fv
partialsFunc();
double ferrPrev = ferr;
double lcePrev = lce;
double h = 1.0;
while( (abs(ferr) > aSolTolerance) && (iter < aMaxIterations)) {
// Compute the search direction
dferr_d_lce = dFmAT_dlce - dFt_d_lce;
h = 1.0;
while (abs(ferr) >= abs(ferrPrev)) {
// Compute the Newton step
delta_lce = -h*ferrPrev / dferr_d_lce;
// Take a Newton Step if the step is nonzero
if (abs(delta_lce) > SimTK::SignificantReal)
lce = lcePrev + delta_lce;
else {
// We've stagnated or hit a limit; assume we are hitting local
// minimum and attempt to approach from the other direction.
lce = lcePrev - sign(delta_lce)*SimTK::SqrtEps;
// Force a break, which will update the derivatives of
// the muscle force and estimate of the fiber-velocity
h = 0;
}
if (lce < getMinimumFiberLength()) {
lce = getMinimumFiberLength();
}
// Update the muscles's position level quantities (lengths, angles)
positionFunc();
// Update the muscle force multipliers
multipliersFunc();
// Compute the force error assuming fiber-velocity is unchanged
ferrFunc();
if (h <= SimTK::SqrtEps ) {
break;
}
else
h = 0.5*h;
}
ferrPrev = ferr;
lcePrev = lce;
// Update the partial derivative of the force error w.r.t. lce
partialsFunc();
// Update velocity estimate and velocity multiplier
velocityFunc();
iter++;
}
// Populate the result map.
ValuesFromInitMuscleState resultValues;
if (abs(ferr) < aSolTolerance) { // The solution converged.
resultValues["solution_error"] = ferr;
resultValues["iterations"] = (double)iter;
resultValues["fiber_length"] = lce;
resultValues["passive_force"] = fpe*fiso;
resultValues["tendon_force"] = fse*fiso;
return std::pair<StatusFromInitMuscleState, ValuesFromInitMuscleState>
(StatusFromInitMuscleState::Success_Converged, resultValues);
}
// Fiber length is at or exceeds its lower bound.
if (lce <= getMinimumFiberLength()) {
lce = getMinimumFiberLength();
phi = getPennationModel().calcPennationAngle(lce);
cosphi = cos(phi);
tl = getPennationModel().calcTendonLength(cosphi,lce,ml);
lceN = lce/ofl;
tlN = tl/tsl;
fse = calcfse(tlN);
fpe = calcfpe(lceN);
resultValues["solution_error"] = ferr;
resultValues["iterations"] = (double)iter;
resultValues["fiber_length"] = lce;
resultValues["passive_force"] = fpe*fiso;
resultValues["tendon_force"] = fse*fiso;
return std::pair<StatusFromInitMuscleState, ValuesFromInitMuscleState>
(StatusFromInitMuscleState::Warning_FiberAtLowerBound, resultValues);
}
resultValues["solution_error"] = ferr;
resultValues["iterations"] = (double)iter;
resultValues["fiber_length"] = SimTK::NaN;
resultValues["passive_force"] = SimTK::NaN;
resultValues["tendon_force"] = SimTK::NaN;
return std::pair<StatusFromInitMuscleState, ValuesFromInitMuscleState>
(StatusFromInitMuscleState::Failure_MaxIterationsReached, resultValues);
}
//==============================================================================
//
// STIFFNESS RELATED FUNCTIONS
//
//==============================================================================
double Thelen2003Muscle::calcFm(double ma, double fal, double fv, double fpe,
double fiso) const
{
double Fm = (ma*fal*fv + fpe)*fiso;
return Fm;
}
double Thelen2003Muscle::calcActiveFm(double ma, double fal, double fv,
double fiso) const
{
double aFm = (ma*fal*fv)*fiso;
return aFm;
}
double Thelen2003Muscle::calcDFmDlce(double lce, double ma, double fv,