-
Notifications
You must be signed in to change notification settings - Fork 310
/
testForces.cpp
2384 lines (1860 loc) · 84.1 KB
/
testForces.cpp
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: testForces.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): 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. *
* -------------------------------------------------------------------------- */
//==============================================================================
//
// Tests Include:
// 1. PointToPointSpring
// 2. BushingForce
// 3. ElasticFoundationForce
// 4. HuntCrossleyForce
// 5. SmoothSphereHalfSpaceForce
// 6. CoordinateLimitForce
// 7. RotationalCoordinateLimitForce
// 8. ExternalForce
// 9. PathSpring
// 10. ExpressionBasedPointToPointForce
// 11. Blankevoort1991Ligament
//
// Add tests here as Forces are added to OpenSim
//
//==============================================================================
#include "SimTKcommon/internal/Xml.h"
#include <ctime> // clock(), clock_t, CLOCKS_PER_SEC
#include <OpenSim/Analyses/osimAnalyses.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
#include <OpenSim/Simulation/osimSimulation.h>
using namespace OpenSim;
using namespace std;
//==============================================================================
// Common Parameters for the simulations are just global.
const static double integ_accuracy = 1.0e-4;
const static SimTK::Vec3 gravity_vec = SimTK::Vec3(0, -9.8065, 0);
//==============================================================================
void testPathSpring();
void testExternalForce();
void testSpringMass();
void testBushingForce();
void testTwoFrameLinkerUpdateFromXMLNode();
void testFunctionBasedBushingForce();
void testExpressionBasedBushingForceTranslational();
void testExpressionBasedBushingForceRotational();
void testElasticFoundation();
void testHuntCrossleyForce();
void testSmoothSphereHalfSpaceForce();
void testCoordinateLimitForce();
void testCoordinateLimitForceRotational();
void testExpressionBasedPointToPointForce();
void testExpressionBasedCoordinateForce();
void testSerializeDeserialize();
void testTranslationalDampingEffect(Model& osimModel, Coordinate& sliderCoord,
double start_h, Component& componentWithDamping);
void testBlankevoort1991Ligament();
int main() {
SimTK::Array_<std::string> failures;
try { testPathSpring(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testPathSpring");
}
try { testExternalForce(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testExternalForce");
}
try { testSpringMass(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testP2PSpringMass");
}
try { testBushingForce(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testBushingForce");
}
try { testTwoFrameLinkerUpdateFromXMLNode(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testTwoFrameLinkerUpdateFromXMLNode");
}
try { testFunctionBasedBushingForce(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testFunctionBasedBushingForce");
}
try { testExpressionBasedBushingForceTranslational(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testExpressionBasedBushingForceTranslational");
}
try { testExpressionBasedBushingForceRotational(); }
catch (const std::exception& e) {
cout << e.what() << endl;
failures.push_back("testExpressionBasedBushingForceRotational");
}
try { testElasticFoundation(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testElasticFoundation");
}
try { testHuntCrossleyForce(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testHuntCrossleyForce");
}
try { testSmoothSphereHalfSpaceForce(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testSmoothSphereHalfSpaceForce");
}
try { testCoordinateLimitForce(); }
catch (const std::exception& e){
cout << e.what() <<endl; failures.push_back("testCoordinateLimitForce");
}
try { testCoordinateLimitForceRotational(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testCoordinateLimitForceRotational");
}
try { testExpressionBasedPointToPointForce(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testExpressionBasedPointToPointForce");
}
try { testExpressionBasedCoordinateForce(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testExpressionBasedCoordinateForce");
}
try { testSerializeDeserialize(); }
catch (const std::exception& e){
cout << e.what() <<endl;
failures.push_back("testSerializeDeserialize");
}
try {
testBlankevoort1991Ligament();
} catch (const std::exception& e) {
cout << e.what() << endl;
failures.push_back("testBlankevoort1991Ligament");
}
if (!failures.empty()) {
cout << "Done, with failure(s): " << failures << endl;
return 1;
}
cout << "Done. All cases passed." << endl;
return 0;
}
//==============================================================================
// Test Cases
//==============================================================================
void testExpressionBasedCoordinateForce() {
using namespace SimTK;
double mass = 1;
double stiffness = 10;
double damp_coeff = 5;
double start_h = 0.5;
double start_v = 0;
double ball_radius = 0.25;
double omega = sqrt(stiffness / mass);
// note: test case designed for 0 <= zeta < 1 (under damped system)
double zeta = damp_coeff / (2 * sqrt(mass * stiffness));
double damp_freq = omega * sqrt(1 - pow(zeta, 2));
double dh = mass * gravity_vec(1) / stiffness;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("SpringMass");
// OpenSim bodies
const Ground& ground = osimModel.getGround();
;
OpenSim::Body ball(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
ball.attachGeometry(new Sphere(0.1));
ball.scale(Vec3(ball_radius), false);
// Add joints
SliderJoint slider("slider", ground, Vec3(0), Vec3(0, 0, Pi / 2), ball,
Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = slider.updCoordinate();
sliderCoord.setName("ball_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(&ball);
osimModel.addJoint(&slider);
osimModel.setGravity(gravity_vec);
// ode for basic mass-spring-dampener system
ExpressionBasedCoordinateForce spring("ball_h", "-10*q-5*qdot");
osimModel.addForce(&spring);
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
SimTK::State& osim_state = osimModel.initSystem();
// move ball to initial conditions
sliderCoord.setValue(osim_state, start_h);
osimModel.getMultibodySystem().realize(osim_state, Stage::Position);
//==========================================================================
// Compute the force at the specified times.
double final_t = 2.0;
double nsteps = 10;
double dt = final_t / nsteps;
Manager manager(osimModel);
manager.setIntegratorAccuracy(1e-7);
osim_state.setTime(0.0);
manager.initialize(osim_state);
for (int i = 1; i <= nsteps; i++) {
osim_state = manager.integrate(dt * i);
osimModel.getMultibodySystem().realize(osim_state, Stage::Acceleration);
Vec3 pos = ball.findStationLocationInGround(osim_state, Vec3(0));
double height =
exp(-1 * zeta * omega * osim_state.getTime()) *
((start_h - dh) *
cos(damp_freq * osim_state.getTime()) +
((1 / damp_freq) *
(zeta * omega * (start_h - dh) +
start_v) *
sin(damp_freq *
osim_state.getTime()))) +
dh;
ASSERT_EQUAL(height, pos(1), 1e-6);
}
// Test copying
ExpressionBasedCoordinateForce* copyOfSpring = spring.clone();
ASSERT(*copyOfSpring == spring);
osimModel.print("ExpressionBasedCoordinateForceModel.osim");
osimModel.disownAllComponents();
}
void testExpressionBasedPointToPointForce() {
using namespace SimTK;
double mass = 100;
double ball_radius = 0.25;
Random::Uniform rand;
Vec3 p1(rand.getValue(), rand.getValue(), rand.getValue());
Vec3 p2(rand.getValue(), rand.getValue(), rand.getValue());
// Setup OpenSim model
Model model{};
model.setName("ExpressionBasedPointToPointForce");
// OpenSim bodies
const Ground& ground = model.getGround();
OpenSim::Body ball(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(ball_radius));
ball.attachGeometry(new Sphere(ball_radius));
ball.scale(Vec3(ball_radius), false);
// define body's joint
FreeJoint free("free", ground, Vec3(0), Vec3(0, 0, Pi / 2), ball, Vec3(0),
Vec3(0, 0, Pi / 2));
model.addBody(&ball);
model.addJoint(&free);
string expression("2/(d^2)-3.0*(d-0.2)*(1+0.0123456789*ddot)");
ExpressionBasedPointToPointForce* p2pForce =
new ExpressionBasedPointToPointForce(
"ground", p1, "ball", p2, expression);
p2pForce->setName("P2PTestForce");
model.addForce(p2pForce);
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&model);
model.addAnalysis(reporter);
// model.setUseVisualizer(true);
SimTK::State& state = model.initSystem();
model.print("ExpressionBasedPointToPointForceModel.osim");
Vector& q = state.updQ();
Vector& u = state.updU();
for (int i = 0; i < state.getNU(); ++i) {
q[i] = rand.getValue();
u[i] = rand.getValue();
}
//==========================================================================
// Compute the force and torque at the specified times.
Manager manager(model);
manager.setIntegratorAccuracy(1e-6);
state.setTime(0.0);
manager.initialize(state);
double final_t = 1.0;
state = manager.integrate(final_t);
// manager.getStateStorage().print("testExpressionBasedPointToPointForce.sto");
// force is only velocity dependent but is only compute in Dynamics
model.getMultibodySystem().realize(state, Stage::Dynamics);
// Now check that the force reported by spring
double model_force = p2pForce->getForceMagnitude(state);
// Save the forces
// reporter->getForceStorage().print("path_spring_forces.mot");
double d = (p1 - ball.findStationLocationInGround(state, p2)).norm();
const MobilizedBody& b1 = ground.getMobilizedBody();
const MobilizedBody& b2 = ball.getMobilizedBody();
double ddot =
b1.calcStationToStationDistanceTimeDerivative(state, p1, b2, p2);
// string expression("2/(d^2)-3.0*(d-0.2)*(1+0.0123456789*ddot)");
double analytical_force =
2 / (d * d) - 3.0 * (d - 0.2) * (1 + 0.0123456789 * ddot);
// something is wrong if the block does not reach equilibrium
ASSERT_EQUAL(analytical_force, model_force, 1e-5);
// Before exiting lets see if copying the P2P force works
ExpressionBasedPointToPointForce* copyOfP2pForce = p2pForce->clone();
ASSERT(*copyOfP2pForce == *p2pForce);
model.disownAllComponents();
}
void testPathSpring() {
using namespace SimTK;
double mass = 1;
double stiffness = 10;
double restlength = 0.5;
double dissipation = 0.1;
double start_h = 0.5;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("PathSpring");
// OpenSim bodies
const Ground& ground = osimModel.getGround();
;
OpenSim::Body pulleyBody("PulleyBody", mass, Vec3(0),
mass * SimTK::Inertia::brick(0.1, 0.1, 0.1));
OpenSim::Body block("block", mass, Vec3(0),
mass * SimTK::Inertia::brick(0.2, 0.1, 0.1));
block.attachGeometry(new Brick(Vec3(0.2, 0.1, 0.1)));
block.scale(Vec3(0.2, 0.1, 0.1), false);
WrapCylinder* pulley = new WrapCylinder();
pulley->set_radius(0.1);
pulley->set_length(0.05);
// Add the wrap object to the body, which takes ownership of it
pulleyBody.addWrapObject(pulley);
// Add joints
WeldJoint weld("pulley", ground, Vec3(0, 1.0, 0), Vec3(0), pulleyBody,
Vec3(0), Vec3(0));
SliderJoint slider("slider", ground, Vec3(0), Vec3(0, 0, Pi / 2), block,
Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = slider.updCoordinate();
sliderCoord.setName("block_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(&block);
osimModel.addJoint(&weld);
osimModel.addBody(&pulleyBody);
osimModel.addJoint(&slider);
osimModel.setGravity(gravity_vec);
PathSpring spring("spring", restlength, stiffness, dissipation);
spring.updGeometryPath().appendNewPathPoint(
"origin", block, Vec3(-0.1, 0.0, 0.0));
int N = 10;
for (int i = 1; i < N; ++i) {
double angle = i * Pi / N;
double x = 0.1 * cos(angle);
double y = 0.1 * sin(angle);
spring.updGeometryPath().appendNewPathPoint(
"", pulleyBody, Vec3(-x, y, 0.0));
}
spring.updGeometryPath().appendNewPathPoint(
"insertion", block, Vec3(0.1, 0.0, 0.0));
// BUG in defining wrapping API requires that the Force containing the
// GeometryPath be connected to the model before the wrap can be added
osimModel.addForce(&spring);
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
// osimModel.setUseVisualizer(true);
SimTK::State& osim_state = osimModel.initSystem();
sliderCoord.setValue(osim_state, start_h);
osimModel.getMultibodySystem().realize(osim_state, Stage::Position);
//==========================================================================
// Compute the force and torque at the specified times.
Manager manager(osimModel);
manager.setIntegratorAccuracy(1e-6);
osim_state.setTime(0.0);
manager.initialize(osim_state);
double final_t = 10.0;
osim_state = manager.integrate(final_t);
// tension should only be velocity dependent
osimModel.getMultibodySystem().realize(osim_state, Stage::Velocity);
// Now check that the force reported by spring
double model_force = spring.getTension(osim_state);
// get acceleration of the block
osimModel.getMultibodySystem().realize(osim_state, Stage::Acceleration);
double hddot =
osimModel.getCoordinateSet().get("block_h").getAccelerationValue(
osim_state);
// the tension should be half the weight of the block
double analytical_force = -0.5 * (gravity_vec(1) - hddot) * mass;
// Save the forces
reporter->getForceStorage().print("path_spring_forces.mot");
// something is wrong if the block does not reach equilibrium
ASSERT_EQUAL(analytical_force, model_force, 1e-3);
// Before exiting lets see if copying the spring works
PathSpring* copyOfSpring = spring.clone();
ASSERT(*copyOfSpring == spring);
osimModel.disownAllComponents();
}
void testSpringMass() {
using namespace SimTK;
double mass = 1;
double stiffness = 10;
double restlength = 1.0;
double start_h = 0.5;
double ball_radius = 0.25;
double omega = sqrt(stiffness / mass);
double dh = mass * gravity_vec(1) / stiffness;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("SpringMass");
// OpenSim bodies
const Ground& ground = osimModel.getGround();
;
OpenSim::Body ball(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
ball.attachGeometry(new Sphere(0.1));
ball.scale(Vec3(ball_radius), false);
// Add joints
SliderJoint slider("slider", ground, Vec3(0), Vec3(0, 0, Pi / 2), ball,
Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = slider.updCoordinate();
sliderCoord.setName("ball_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(&ball);
osimModel.addJoint(&slider);
osimModel.setGravity(gravity_vec);
PointToPointSpring spring(osimModel.updGround(), Vec3(0., restlength, 0.),
ball, Vec3(0.), stiffness, restlength);
osimModel.addForce(&spring);
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
SimTK::State& osim_state = osimModel.initSystem();
sliderCoord.setValue(osim_state, start_h);
osimModel.getMultibodySystem().realize(osim_state, Stage::Position);
//==========================================================================
// Compute the force and torque at the specified times.
Manager manager(osimModel);
manager.setIntegratorAccuracy(1e-7);
osim_state.setTime(0.0);
manager.initialize(osim_state);
double final_t = 2.0;
double nsteps = 10;
double dt = final_t / nsteps;
for (int i = 1; i <= nsteps; i++) {
osim_state = manager.integrate(dt * i);
osimModel.getMultibodySystem().realize(osim_state, Stage::Acceleration);
Vec3 pos = ball.findStationLocationInGround(osim_state, Vec3(0));
double height = (start_h - dh) * cos(omega * osim_state.getTime()) + dh;
ASSERT_EQUAL(height, pos(1), 1e-5);
// Now check that the force reported by spring
Array<double> model_force = spring.getRecordValues(osim_state);
// get the forces applied to the ground and ball
double analytical_force = -stiffness * height;
// analytical force corresponds in direction to the force on the ball Y
// index = 7
ASSERT_EQUAL(analytical_force, model_force[7], 1e-4);
}
// Save the forces
osimModel.disownAllComponents();
// Before exiting lets see if copying the spring works
PointToPointSpring* copyOfSpring = spring.clone();
ASSERT(*copyOfSpring == spring);
// Verify that the PointToPointSpring is correctly deserialized from
// previous major version of OpenSim.
Model bouncer("bouncing_block_30000.osim");
SimTK::State& s = bouncer.initSystem();
bouncer.realizeAcceleration(s);
/*Vec3 comA =*/bouncer.calcMassCenterAcceleration(s);
}
void testBushingForce() {
using namespace SimTK;
double mass = 1;
double stiffness = 10;
double start_h = 0.5;
double ball_radius = 0.25;
double omega = sqrt(stiffness / mass);
double dh = mass * gravity_vec(1) / stiffness;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("BushingTest");
// OpenSim bodies
const Ground& ground = osimModel.getGround();
;
auto* ball = new OpenSim::Body(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
ball->attachGeometry(new Sphere{0.1});
ball->scale(Vec3(ball_radius), false);
// Add joints
auto* slider = new SliderJoint("slider", ground, Vec3(0),
Vec3(0, 0, Pi / 2), *ball, Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = slider->updCoordinate();
sliderCoord.setName("ball_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(ball);
osimModel.addJoint(slider);
Vec3 rotStiffness(0);
Vec3 transStiffness(stiffness);
Vec3 rotDamping(0);
Vec3 transDamping(0);
osimModel.setGravity(gravity_vec);
auto* spring = new BushingForce("bushing", ground, *ball);
spring->set_translational_stiffness(transStiffness);
spring->set_rotational_stiffness(rotStiffness);
spring->set_translational_damping(transDamping);
spring->set_rotational_damping(rotDamping);
osimModel.addForce(spring);
const BushingForce& bushingForce =
osimModel.getComponent<BushingForce>("forceset/bushing");
// To print (serialize) the latest connections of the model, it is
// necessary to finalizeConnections() first.
osimModel.finalizeConnections();
osimModel.print("BushingForceModel.osim");
Model previousVersionModel("BushingForceModel_30000.osim");
previousVersionModel.print("BushingForceModel_30000_in_Latest.osim");
const BushingForce& bushingForceFromPrevious =
previousVersionModel.getComponent<BushingForce>("forceset/bushing");
ASSERT(bushingForce == bushingForceFromPrevious, __FILE__, __LINE__,
"current bushing force FAILED to match bushing force from previous "
"model.");
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
SimTK::State& osim_state = osimModel.initSystem();
sliderCoord.setValue(osim_state, start_h);
osimModel.getMultibodySystem().realize(osim_state, Stage::Position);
//==========================================================================
// Compute the force and torque at the specified times.
Manager manager(osimModel);
manager.setIntegratorAccuracy(1e-6);
osim_state.setTime(0.0);
manager.initialize(osim_state);
double final_t = 2.0;
double nsteps = 10;
double dt = final_t / nsteps;
for (int i = 1; i <= nsteps; i++) {
osim_state = manager.integrate(dt * i);
osimModel.getMultibodySystem().realize(osim_state, Stage::Acceleration);
Vec3 pos = ball->findStationLocationInGround(osim_state, Vec3(0));
double height = (start_h - dh) * cos(omega * osim_state.getTime()) + dh;
ASSERT_EQUAL(height, pos(1), 1e-4);
// Now check that the force reported by spring
Array<double> model_force = spring->getRecordValues(osim_state);
// get the forces applied to the ground and ball
double analytical_force = -stiffness * height;
// analytical force corresponds in direction to the force on the ball Y
// index = 7
ASSERT_EQUAL(analytical_force, model_force[7], 2e-4);
}
manager.getStateStorage().print("bushing_model_states.sto");
// Save the forces
reporter->getForceStorage().print("bushing_forces.mot");
// Before exiting lets see if copying the spring works
BushingForce* copyOfSpring = spring->clone();
ASSERT(*copyOfSpring == *spring);
}
// testBushingForce() performs similar checks as does this test, but this test
// ensures intermediate offset frames are created correctly. This test still
// uses BushingForce to test the TwoFrameLinker.
void testTwoFrameLinkerUpdateFromXMLNode() {
using namespace SimTK;
double mass = 1;
double start_h = 0.5;
double ball_radius = 0.25;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("TwoFrameLinkerUpdateFromXMLNodeTest");
// OpenSim bodies
const Ground& ground = osimModel.getGround();
;
auto* ball = new OpenSim::Body(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
ball->attachGeometry(new Sphere{0.1});
ball->scale(Vec3(ball_radius), false);
// Add joints
auto* slider = new SliderJoint("slider", ground, Vec3(0),
Vec3(0, 0, Pi / 2), *ball, Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = slider->updCoordinate();
sliderCoord.setName("ball_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(ball);
osimModel.addJoint(slider);
Vec3 rotStiffness(15, 21, 30);
Vec3 transStiffness(10, 10, 10);
Vec3 rotDamping(0.4, 0.5, 0.6);
Vec3 transDamping(0.2, 0.3, 0.4);
osimModel.setGravity(gravity_vec);
auto* spring = new BushingForce("bushing", ground,
Transform(Rotation(BodyRotationSequence, -0.5, XAxis, 0, YAxis, 0.5,
ZAxis),
Vec3(1, 2, 3)),
*ball,
Transform(Rotation(BodyRotationSequence, 0.1, XAxis, 0.2, YAxis,
0.3, ZAxis),
Vec3(4, 5, 6)),
transStiffness, rotStiffness, transDamping, rotDamping);
spring->print("bushingForceAPICreated.xml");
osimModel.addForce(spring);
const BushingForce& bushingForce =
osimModel.getComponent<BushingForce>("./forceset/bushing");
// It's necessary to correct the connectee paths in the BushingForce, which
// we can do with finalizeConnections() (they are incorrect otherwise
// because `spring` is initially orphaned).
osimModel.finalizeConnections();
osimModel.print("BushingForceOffsetModel.osim");
Model previousVersionModel("BushingForceOffsetModel_30000.osim");
previousVersionModel.finalizeConnections();
previousVersionModel.print("BushingForceOffsetModel_30000_in_Latest.osim");
const BushingForce& bushingForceFromPrevious =
previousVersionModel.getComponent<BushingForce>(
"./forceset/bushing");
ASSERT(bushingForce == bushingForceFromPrevious, __FILE__, __LINE__,
"current bushing force FAILED to match bushing force from previous "
"model.");
}
void testFunctionBasedBushingForce() {
using namespace SimTK;
double mass = 1;
double stiffness = 10;
double start_h = 0.5;
double ball_radius = 0.25;
double omega = sqrt(stiffness / mass);
double dh = mass * gravity_vec(1) / stiffness;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("FunctionBasedBushingTest");
// OpenSim bodies
const Ground& ground = osimModel.getGround();
;
OpenSim::Body ball(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
ball.attachGeometry(new Sphere(0.1));
ball.scale(Vec3(ball_radius), false);
// Add joints
SliderJoint slider("slider", ground, Vec3(0), Vec3(0, 0, Pi / 2), ball,
Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = slider.updCoordinate();
sliderCoord.setName("ball_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(&ball);
osimModel.addJoint(&slider);
Vec3 rotStiffness(0);
Vec3 transStiffness(stiffness);
Vec3 rotDamping(0);
Vec3 transDamping(0);
osimModel.setGravity(gravity_vec);
FunctionBasedBushingForce spring("linear_bushing", ground, Vec3(0), Vec3(0),
ball, Vec3(0), Vec3(0), transStiffness, rotStiffness, transDamping,
rotDamping);
osimModel.addForce(&spring);
osimModel.finalizeConnections(); // fix warning on write that results in
// invalid model file
osimModel.print("FunctionBasedBushingForceModel.osim");
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
SimTK::State& osim_state = osimModel.initSystem();
sliderCoord.setValue(osim_state, start_h);
osimModel.getMultibodySystem().realize(osim_state, Stage::Position);
//==========================================================================
// Compute the force and torque at the specified times.
Manager manager(osimModel);
manager.setIntegratorAccuracy(1e-6);
osim_state.setTime(0.0);
manager.initialize(osim_state);
double final_t = 2.0;
double nsteps = 10;
double dt = final_t / nsteps;
for (int i = 1; i <= nsteps; i++) {
osim_state = manager.integrate(dt * i);
osimModel.getMultibodySystem().realize(osim_state, Stage::Acceleration);
Vec3 pos = ball.findStationLocationInGround(osim_state, Vec3(0));
double height = (start_h - dh) * cos(omega * osim_state.getTime()) + dh;
ASSERT_EQUAL(height, pos(1), 1e-4);
// Now check that the force reported by spring
Array<double> model_force = spring.getRecordValues(osim_state);
// get the forces applied to the ground and ball
double analytical_force = -stiffness * height;
// analytical force corresponds in direction to the force on the ball Y
// index = 7
ASSERT_EQUAL(analytical_force, model_force[7], 2e-4);
}
manager.getStateStorage().print("function_based_bushing_model_states.sto");
// Save the forces
reporter->getForceStorage().print("function_based_bushing_forces.mot");
// Now add damping to the bushing force and make sure energy is
// monotonically decreasing
testTranslationalDampingEffect(osimModel, sliderCoord, start_h, spring);
// The following line is BAD but necessary due to mixing stack and heap
// allocation
osimModel.disownAllComponents();
// Before exiting lets see if copying the spring works
FunctionBasedBushingForce* copyOfSpring = spring.clone();
ASSERT(*copyOfSpring == spring);
}
void testExpressionBasedBushingForceTranslational() {
using namespace SimTK;
double mass = 1;
double stiffness = 10;
double start_h = 0.5;
double ball_radius = 0.25;
double omega = sqrt(stiffness / mass);
double dh = mass * gravity_vec(1) / stiffness;
// Setup OpenSim model
Model osimModel{};
osimModel.setName("ExpressionBasedBushingTranslationTest");
osimModel.setGravity(gravity_vec);
// Create ball body and attach it to ground
// with a vertical slider
const Ground& ground = osimModel.getGround();
OpenSim::Body ball(
"ball", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
ball.attachGeometry(new Sphere(0.1));
ball.scale(Vec3(ball_radius), false);
SliderJoint sliderY("slider", ground, Vec3(0), Vec3(0, 0, Pi / 2), ball,
Vec3(0), Vec3(0, 0, Pi / 2));
double positionRange[2] = {-10, 10};
// Rename coordinate for the slider joint
auto& sliderCoord = sliderY.updCoordinate();
sliderCoord.setName("ball_h");
sliderCoord.setRange(positionRange);
osimModel.addBody(&ball);
osimModel.addJoint(&sliderY);
// Create base body and attach it to ground with a weld
OpenSim::Body base(
"base_body", mass, Vec3(0), mass * SimTK::Inertia::sphere(0.1));
base.attachGeometry(new Sphere(0.1));
base.scale(Vec3(ball_radius), false);
WeldJoint weld("weld", ground, Vec3(0), Vec3(0), base, Vec3(0), Vec3(0));
osimModel.addBody(&base);
osimModel.addJoint(&weld);
// create an ExpressionBasedBushingForce that represents an
// uncoupled, linear bushing between the ball body and welded base body
Vec3 rotStiffness(0);
Vec3 transStiffness(stiffness);
Vec3 rotDamping(0);
Vec3 transDamping(0);
ExpressionBasedBushingForce spring("linear_bushing", base, Vec3(0), Vec3(0),
ball, Vec3(0), Vec3(0), transStiffness, rotStiffness, transDamping,
rotDamping);
spring.setName("translational_linear_bushing");
osimModel.addForce(&spring);
osimModel.finalizeConnections();
osimModel.print("ExpressionBasedBushingForceTranslationalModel.osim");
// Create the force reporter
ForceReporter* reporter = new ForceReporter(&osimModel);
osimModel.addAnalysis(reporter);
SimTK::State& osim_state = osimModel.initSystem();
// set the initial height of the ball on slider
sliderCoord.setValue(osim_state, start_h);
osimModel.getMultibodySystem().realize(osim_state, Stage::Position);
//==========================================================================
// Compute the force and torque at the specified times.
Manager manager(osimModel);
manager.setIntegratorAccuracy(1e-6);
osim_state.setTime(0.0);
manager.initialize(osim_state);
double final_t = 2.0;
double nsteps = 10;
double dt = final_t / nsteps;
for (int i = 1; i <= nsteps; ++i) {
osim_state = manager.integrate(dt * i);
osimModel.getMultibodySystem().realize(osim_state, Stage::Acceleration);
Vec3 pos = ball.findStationLocationInGround(osim_state, Vec3(0));
// compute the height based on the analytic solution for 1-D spring-mass
// system with zero-velocity at initial offset.
double height = (start_h - dh) * cos(omega * osim_state.getTime()) + dh;
// check that the simulated solution is equivalent to the analytic
// solution
ASSERT_EQUAL(height, pos(1), 1e-4);