-
Notifications
You must be signed in to change notification settings - Fork 310
/
Model.cpp
2207 lines (1891 loc) · 78.7 KB
/
Model.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: Model.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): Frank C. Anderson, Peter Loan, Ayman Habib, Ajay Seth, *
* Michael Sherman *
* *
* 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 "Model.h"
#include "Actuator.h"
#include "AnalysisSet.h"
#include "BodySet.h"
#include "ComponentSet.h"
#include "ContactGeometrySet.h"
#include "ControllerSet.h"
#include "CoordinateSet.h"
#include "ForceSet.h"
#include "Ligament.h"
#include "MarkerSet.h"
#include "ProbeSet.h"
#include "SimTKcommon/internal/SystemGuts.h"
#include <iostream>
#include <string>
#include <OpenSim/Common/Constant.h>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/Logger.h>
#include <OpenSim/Common/ScaleSet.h>
#include <OpenSim/Common/Storage.h>
#include <OpenSim/Common/XMLDocument.h>
#include <OpenSim/Simulation/AssemblySolver.h>
#include <OpenSim/Simulation/CoordinateReference.h>
#include <OpenSim/Simulation/SimbodyEngine/FreeJoint.h>
#include <OpenSim/Simulation/SimbodyEngine/PointConstraint.h>
#include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h>
#include <OpenSim/Simulation/SimbodyEngine/WeldConstraint.h>
using namespace std;
using namespace OpenSim;
using namespace SimTK;
//=============================================================================
// STATICS
//=============================================================================
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/*
* Default constructor.
*/
Model::Model() : ModelComponent(),
_fileName("Unassigned"),
_analysisSet(AnalysisSet()),
_coordinateSet(CoordinateSet()),
_workingState(),
_useVisualizer(false),
_allControllersEnabled(true)
{
constructProperties();
setNull();
finalizeFromProperties();
}
//_____________________________________________________________________________
/*
* Constructor from an XML file
*/
Model::Model(const string &aFileName) :
ModelComponent(aFileName, false),
_fileName("Unassigned"),
_analysisSet(AnalysisSet()),
_coordinateSet(CoordinateSet()),
_workingState(),
_useVisualizer(false),
_allControllersEnabled(true)
{
constructProperties();
setNull();
updateFromXMLDocument();
// Check is done below because only Model files have migration issues, version is not available until
// updateFromXMLDocument is called. Fixes core issue #2395
OPENSIM_THROW_IF(getDocument()->getDocumentVersion() < 10901,
Exception,
"Model file " + aFileName + " is using unsupported file format"
". Please open model and save it in OpenSim version 3.3 to upgrade.");
_fileName = aFileName;
log_info("Loaded model {} from file {}", getName(), getInputFileName());
try {
finalizeFromProperties();
}
catch(const InvalidPropertyValue& err) {
log_error("Model was unable to finalizeFromProperties."
"Update the model file and reload OR update the property and "
"call finalizeFromProperties() on the model."
"(details: {}).",
err.what());
}
}
Model* Model::clone() const
{
// Invoke default copy constructor.
Model* clone = new Model(*this);
try {
clone->finalizeFromProperties();
}
catch (const InvalidPropertyValue& err) {
log_error(
"clone() was unable to finalizeFromProperties."
"Update the model and call clone() again OR update the clone's "
" property and call finalizeFromProperties() on it. (details: {}).",
err.what());
}
return clone;
}
//_____________________________________________________________________________
/*
* Override default implementation by object to intercept and fix the XML node
* underneath the model to match current version
*/
/*virtual*/
void Model::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
if (versionNumber < XMLDocument::getLatestVersion()){
log_info("Updating Model file from {} to latest format...",
versionNumber);
// Version has to be 1.6 or later, otherwise assert
if (versionNumber == 10600){
// Get node for DynamicsEngine
SimTK::Xml::element_iterator engIter =
aNode.element_begin("DynamicsEngine");
//Get node for SimbodyEngine
if (engIter != aNode.element_end()){
SimTK::Xml::element_iterator simbodyEngIter =
engIter->element_begin("SimbodyEngine");
// Move all Children of simbodyEngineNode to be children of _node
// we'll keep inserting before enginesNode then remove it;
SimTK::Array_<SimTK::Xml::Element> elts =
simbodyEngIter->getAllElements();
while (elts.size() != 0){
// get first child and move it to Model
aNode.insertNodeAfter(aNode.element_end(),
simbodyEngIter->removeNode(simbodyEngIter->element_begin()));
elts = simbodyEngIter->getAllElements();
}
engIter->eraseNode(simbodyEngIter);
}
// Now handling the rename of ActuatorSet to ForceSet
XMLDocument::renameChildNode(aNode, "ActuatorSet", "ForceSet");
}
if (versionNumber < 30501) {
// Create JointSet node after BodySet under <OpenSimDocument>/<Model>
SimTK::Xml::Element jointSetElement("JointSet");
SimTK::Xml::Element jointObjects("objects");
jointSetElement.insertNodeBefore(jointSetElement.element_begin(), jointObjects);
SimTK::Xml::element_iterator bodySetNode = aNode.element_begin("BodySet");
aNode.insertNodeAfter(bodySetNode, jointSetElement);
// Cycle through Bodies and move their Joint nodes under the Model's JointSet
SimTK::Xml::element_iterator objects_node =
bodySetNode->element_begin("objects");
SimTK::Xml::element_iterator bodyIter =
objects_node->element_begin("Body");
for (; bodyIter != objects_node->element_end(); ++bodyIter) {
std::string body_name = bodyIter->getOptionalAttributeValue("name");
if (body_name == "ground") {
SimTK::Xml::Element newGroundElement("Ground");
newGroundElement.setAttributeValue("name", "ground");
SimTK::Xml::element_iterator geometryIter =
bodyIter->element_begin("geometry");
if (geometryIter != bodyIter->element_end()) {
SimTK::Xml::Element cloneOfGeomety = geometryIter->clone();
newGroundElement.insertNodeAfter(newGroundElement.node_end(),
cloneOfGeomety);
}
SimTK::Xml::element_iterator visObjIter =
bodyIter->element_begin("VisibleObject");
if (visObjIter != bodyIter->element_end()) {
SimTK::Xml::Element cloneOfVisObj = visObjIter->clone();
newGroundElement.insertNodeAfter(newGroundElement.node_end(),
cloneOfVisObj);
}
SimTK::Xml::element_iterator wrapSetIter =
bodyIter->element_begin("WrapObjectSet");
if (wrapSetIter != bodyIter->element_end()) {
SimTK::Xml::Element cloneOfWrapSet = wrapSetIter->clone();
newGroundElement.insertNodeAfter(newGroundElement.node_end(),
cloneOfWrapSet);
}
String test;
newGroundElement.writeToString(test);
objects_node->eraseNode(bodyIter);
aNode.insertNodeBefore(bodySetNode, newGroundElement);
break;
}
}
bodyIter = objects_node->element_begin("Body");
for (; bodyIter != objects_node->element_end(); ++bodyIter) {
std::string body_name = bodyIter->getOptionalAttributeValue("name");
SimTK::Xml::element_iterator joint_node =
bodyIter->element_begin("Joint");
if (joint_node->element_begin() != joint_node->element_end()){
SimTK::Xml::Element detach_joint_node = joint_node->clone();
SimTK::Xml::element_iterator concreteJointNode =
detach_joint_node.element_begin();
detach_joint_node.removeNode(concreteJointNode);
SimTK::Xml::element_iterator parentBodyElement =
concreteJointNode->element_begin("parent_body");
SimTK::String parent_name = "ground";
parentBodyElement->getValueAs<SimTK::String>(parent_name);
// In version 30501, this Joint is 1 level deep (in the
// model's JointSet), and the Bodies are necessarily 1
// level deep (in the model's BodySet). Prepend "../" to
// get the correct relative path.
std::string parent_frame = parent_name;
if (!parent_frame.empty())
parent_frame = "../" + parent_frame;
XMLDocument::addConnector(*concreteJointNode,
"Connector_PhysicalFrame_", "parent_frame",
parent_frame);
std::string child_frame = body_name;
if (!child_frame.empty())
child_frame = "../" + child_frame;
XMLDocument::addConnector(*concreteJointNode,
"Connector_PhysicalFrame_", "child_frame",
child_frame);
concreteJointNode->eraseNode(parentBodyElement);
jointObjects.insertNodeAfter(jointObjects.node_end(),
*concreteJointNode);
detach_joint_node.clearOrphan();
}
bodyIter->eraseNode(joint_node);
}
}
if (versionNumber < 30512) {
// FrameSet was removed from Model as of 30512 and this update
// is responsible for moving the Frames in the FrameSet to
// the Model's list of components.
SimTK::Xml::element_iterator componentsNode =
aNode.element_begin("components");
SimTK::Xml::element_iterator framesNode =
aNode.element_begin("FrameSet");
// If no FrameSet nothing to be done
if (framesNode != aNode.element_end()) {
if (componentsNode == aNode.element_end()) {
// if no 'components' list element, create one and insert it
SimTK::Xml::Element componentsElement("components");
aNode.insertNodeBefore(framesNode, componentsElement);
}
componentsNode = aNode.element_begin("components");
SimTK::Xml::element_iterator objects_node =
framesNode->element_begin("objects");
SimTK::Xml::element_iterator frameIter =
objects_node->element_begin();
for (; frameIter != objects_node->element_end(); ++frameIter) {
SimTK::Xml::Element cloneOfFrame = frameIter->clone();
componentsNode->insertNodeAfter(componentsNode->node_end(),
cloneOfFrame);
}
// now delete the FrameSet
framesNode->getParentElement().eraseNode(framesNode);
}
}
}
// Call base class now assuming _node has been corrected for current version
Super::updateFromXMLNode(aNode, versionNumber);
setDefaultProperties();
}
//=============================================================================
// CONSTRUCTION METHODS
//=============================================================================
//_____________________________________________________________________________
/**
* Set the values of all data members to an appropriate "null" value.
*/
void Model::setNull()
{
_useVisualizer = false;
_allControllersEnabled = true;
_validationLog="";
_analysisSet.setMemoryOwner(false);
}
void Model::constructProperties()
{
constructProperty_assembly_accuracy(1e-9);
constructProperty_ground(Ground());
constructProperty_gravity(SimTK::Vec3(0.0, -9.80665, 0.0));
constructProperty_credits("Frank Anderson, Peter Loan, Ayman Habib, Ajay Seth, Michael Sherman");
constructProperty_publications("List of publications related to model...");
constructProperty_length_units("meters");
_lengthUnits = Units::Meters;
constructProperty_force_units("N");
_forceUnits = Units::Newtons;
BodySet bodies;
bodies.setName(IO::Lowercase(bodies.getConcreteClassName()));
constructProperty_BodySet(bodies);
JointSet joints;
joints.setName(IO::Lowercase(joints.getConcreteClassName()));
constructProperty_JointSet(joints);
ControllerSet controllers;
controllers.setName(IO::Lowercase(controllers.getConcreteClassName()));
constructProperty_ControllerSet(controllers);
ConstraintSet constraints;
constraints.setName(IO::Lowercase(constraints.getConcreteClassName()));
constructProperty_ConstraintSet(constraints);
ForceSet forces;
forces.setName(IO::Lowercase(forces.getConcreteClassName()));
constructProperty_ForceSet(forces);
MarkerSet markers;
markers.setName(IO::Lowercase(markers.getConcreteClassName()));
constructProperty_MarkerSet(markers);
ContactGeometrySet contacts;
contacts.setName(IO::Lowercase(contacts.getConcreteClassName()));
constructProperty_ContactGeometrySet(contacts);
ProbeSet probes;
probes.setName(IO::Lowercase(probes.getConcreteClassName()));
constructProperty_ProbeSet(probes);
ComponentSet miscComponents;
miscComponents.setName(IO::Lowercase(miscComponents.getConcreteClassName()));
constructProperty_ComponentSet(miscComponents);
ModelVisualPreferences mvps;
mvps.setName(IO::Lowercase(mvps.getConcreteClassName()));
constructProperty_ModelVisualPreferences(mvps);
}
// Append to the Model's validation log
void Model::appendToValidationLog(const std::string& note) {
_validationLog.append(note);
}
//------------------------------------------------------------------------------
// BUILD SYSTEM
//------------------------------------------------------------------------------
// Perform some final checks on the Model, wire up all its components, and then
// build a computational System for it.
void Model::buildSystem() {
// Finish connecting up the Model.
setup();
// Create the computational System representing this Model.
createMultibodySystem();
// Create a Visualizer for this Model if one has been requested. This adds
// necessary elements to the System. Doesn't initialize geometry yet.
if (getUseVisualizer())
_modelViz.reset(new ModelVisualizer(*this));
}
//------------------------------------------------------------------------------
// INITIALIZE STATE
//------------------------------------------------------------------------------
// Requires that buildSystem() has already been called.
SimTK::State& Model::initializeState() {
if (!hasSystem())
throw Exception("Model::initializeState(): call buildSystem() first.");
// This tells Simbody to finalize the System.
getMultibodySystem().invalidateSystemTopologyCache();
getMultibodySystem().realizeTopology();
// Set the model's operating state (internal member variable) to the
// default state that is stored inside the System.
_workingState = getMultibodySystem().getDefaultState();
// Set the Simbody modeling option that tells any joints that use
// quaternions to use Euler angles instead.
_matter->setUseEulerAngles(_workingState, true);
// Process the modified modeling option.
getMultibodySystem().realizeModel(_workingState);
// Invoke the ModelComponent interface for initializing the state.
initStateFromProperties(_workingState);
// Realize instance variables that may have been set above. This
// means floating point parameters such as mass properties and
// geometry placements are frozen.
getMultibodySystem().realize(_workingState, Stage::Instance);
// Realize the initial configuration in preparation for assembly. This
// initial configuration does not necessarily satisfy constraints.
getMultibodySystem().realize(_workingState, Stage::Position);
// Reset (initialize) all underlying Probe SimTK::Measures
for (int i=0; i<getProbeSet().getSize(); ++i)
getProbeSet().get(i).reset(_workingState);
// Do the assembly
createAssemblySolver(_workingState);
assemble(_workingState);
// We can now collect up all the fixed geometry, which needs full configuration.
if (getUseVisualizer())
_modelViz->collectFixedGeometry(_workingState);
return _workingState;
}
SimTK::State& Model::updWorkingState()
{
if (!isValidSystem())
throw Exception("Model::updWorkingState(): call initializeState() first.");
return _workingState;
}
const SimTK::State& Model::getWorkingState() const
{
if (!isValidSystem())
throw Exception("Model::getWorkingState(): call initializeState() first.");
return _workingState;
}
void Model::assemble(SimTK::State& s, const Coordinate *coord, double weight)
{
bool constrained = false;
const CoordinateSet &coords = getCoordinateSet();
for(int i=0; i<coords.getSize(); ++i){
constrained = constrained || coords[i].isConstrained(s);
}
// Don't bother assembling if the model has no constraints
if(get_ConstraintSet().getSize()< 1){
// just realize the current state to position
getMultibodySystem().realize(s, Stage::Position);
// if a coordinate is locked or prescribed, then project will suffice
if(constrained){
// correct position constraint violations due to prescribed motion
getMultibodySystem().projectQ(s, 1e-10);
// Have a new working configuration so should realize to velocity
getMultibodySystem().realize(s, Stage::Velocity);
// correct velocity constraint violations due to prescribed motion
getMultibodySystem().projectU(s, 1e-10);
}
return;
}
if (!_assemblySolver){
createAssemblySolver(s);
}
const Array_<CoordinateReference>& coordRefs = _assemblySolver->getCoordinateReferences();
for(unsigned int i=0; i<coordRefs.size(); i++){
const string &coordName = coordRefs[i].getName();
Coordinate& c = _coordinateSet.get(coordName);
_assemblySolver->updateCoordinateReference(coordName, c.getValue(s));
}
if(coord) // use specified weighting for coordinate being set
_assemblySolver->updateCoordinateReference(coord->getName(), coord->getValue(s), weight);
try{
// Try to track first with model satisfying the constraints exactly.
_assemblySolver->track(s);
}
catch (const std::exception&) {
try{
// Otherwise try to do a full-blown assemble
_assemblySolver->assemble(s);
}
catch (const std::exception& ex){
// Constraints are probably infeasible so try again relaxing constraints
log_error("Model unable to assemble: {}."
"Model relaxing constraints and trying again.",
ex.what());
try{
// Try to satisfy with constraints as errors weighted heavily.
_assemblySolver->setConstraintWeight(20.0);
_assemblySolver->assemble(s);
}
catch (const std::exception& ex){
log_error("Model unable to assemble with relaxed constraints: {}",
ex.what());
}
}
}
// Have a new working configuration so should realize to velocity
getMultibodySystem().realize(s, Stage::Velocity);
}
void Model::invalidateSystem()
{
if (_system)
_system->getSystemGuts().invalidateSystemTopologyCache();
}
bool Model::isValidSystem() const
{
if (_system)
return _system->systemTopologyHasBeenRealized();
else
return false;
}
//_____________________________________________________________________________
/**
* Create the multibody system.
*
*/
void Model::createMultibodySystem()
{
// We must reset these unique_ptr's before deleting the System (through
// reset()), since deleting the System puts a null handle pointer inside
// the subsystems (since System deletes the subsystems).
_matter.reset();
_forceSubsystem.reset();
_contactSubsystem.reset();
// create system
_system.reset(new SimTK::MultibodySystem);
_matter.reset(new SimTK::SimbodyMatterSubsystem(*_system));
_forceSubsystem.reset(new SimTK::GeneralForceSubsystem(*_system));
_contactSubsystem.reset(new SimTK::GeneralContactSubsystem(*_system));
// create gravity force, a direction is needed even if magnitude=0 for
// PotentialEnergy purposes.
double magnitude = get_gravity().norm();
SimTK::UnitVec3 direction = magnitude==0 ? SimTK::UnitVec3(0,-1,0) : SimTK::UnitVec3(get_gravity()/magnitude);
_gravityForce.reset(new SimTK::Force::Gravity(*_forceSubsystem, *_matter,
direction, magnitude));
addToSystem(*_system);
}
std::vector<SimTK::ReferencePtr<const Coordinate>>
Model::getCoordinatesInMultibodyTreeOrder() const
{
OPENSIM_THROW_IF_FRMOBJ(!isValidSystem(), Exception,
"Cannot order Coordinates without a valid MultibodySystem.");
int nc = getNumCoordinates();
auto coordinates = getComponentList<Coordinate>();
std::vector<SimTK::ReferencePtr<const Coordinate>>
coordinatesInTreeOrder(nc,
SimTK::ReferencePtr<const Coordinate>(*coordinates.begin()));
// We have a valid MultibodySystem underlying the Coordinates
const SimTK::State& s = getWorkingState();
SimTK_ASSERT_ALWAYS(nc <= s.getNQ(),
"Number of Coordinates exceeds the number of generalized coordinates in "
"the underlying MultibodySystem.");
auto& matter = getSystem().getMatterSubsystem();
int cnt = 0;
for (auto& coord : coordinates) {
auto mbix = coord.getBodyIndex();
auto mqix = coord.getMobilizerQIndex();
int cix = matter.getMobilizedBody(mbix).getFirstUIndex(s) + mqix;
SimTK_ASSERT_ALWAYS(cix < nc, "Index exceeds the number of Coordinates "
"in this Model.");
coordinatesInTreeOrder.at(cix).reset(&coord);
cnt++;
}
SimTK_ASSERT_ALWAYS(cnt == nc,
"The number of ordered Coordinates does not correspond to the number of "
"Coordinates in the Model's CoordinateSet.");
return coordinatesInTreeOrder;
}
std::string Model::getWarningMesssageForMotionTypeInconsistency() const
{
std::string message;
auto enumToString = [](Coordinate::MotionType mt)->std::string {
switch (mt) {
case Coordinate::MotionType::Rotational :
return "Rotational";
case Coordinate::MotionType::Translational :
return "Translational";
case Coordinate::MotionType::Coupled :
return "Coupled";
default:
return "Undefined";
}
};
auto coordinates = getComponentList<Coordinate>();
for (auto& coord : coordinates) {
const Coordinate::MotionType oldMotionType =
coord.getUserSpecifiedMotionTypePriorTo40();
const Coordinate::MotionType motionType = coord.getMotionType();
if( (oldMotionType != Coordinate::MotionType::Undefined ) &&
(oldMotionType != motionType) ){
message += "Coordinate '" + coord.getName() +
"' was labeled as '" + enumToString(oldMotionType) +
"' but was found to be '" + enumToString(motionType) + "' based on the joint definition.\n";
}
}
// We have a reason to provide a warning. Add more details about the model
// and how to resolve future issues.
if (message.size()) {
message = "\nModel '" + getName() + "' has inconsistencies:\n" + message;
message +=
"You must update any motion files you generated in versions prior to 4.0. You can:\n"
" (1) Run the updatePre40KinematicsFilesFor40MotionType() utility (in the scripting shell) OR\n"
" (2) Re-run the Inverse Kinematics Tool with the updated model in 4.0.\n"
"In versions prior to 4.0, we allowed some Coupled coordinates to be incorrectly\n"
"labeled as Rotational. This leads to incorrect motion when playing back a pre-4.0\n"
"motion file (.mot or .sto in degrees) and incorrect inverse dynamics and\n"
"static optimization results.";
}
return message;
}
void Model::extendFinalizeFromProperties()
{
Super::extendFinalizeFromProperties();
// wipe-out the existing System
_matter.reset();
_forceSubsystem.reset();
_contactSubsystem.reset();
_system.reset();
if(getForceSet().getSize()>0)
{
ForceSet &fs = updForceSet();
// Update internal subsets of the ForceSet
fs.updActuators();
fs.updMuscles();
}
std::string warn = getWarningMesssageForMotionTypeInconsistency();
appendToValidationLog(warn);
updCoordinateSet().populate(*this);
}
void Model::createMultibodyTree()
{
// building the system for the first time, need to tell
// multibodyTree builder what joints are available
_multibodyTree.clearGraph();
_multibodyTree.setWeldJointTypeName("WeldJoint");
_multibodyTree.setFreeJointTypeName("FreeJoint");
ArrayPtrs<OpenSim::Joint> availablJointTypes;
Object::getRegisteredObjectsOfGivenType<OpenSim::Joint>(availablJointTypes);
for (int i = 0; i< availablJointTypes.getSize(); i++) {
OpenSim::Joint* jt = availablJointTypes[i];
if ((jt->getConcreteClassName() == "WeldJoint") ||
(jt->getConcreteClassName() == "FreeJoint")) {
continue;
}
else {
_multibodyTree.addJointType(
availablJointTypes[i]->getConcreteClassName(),
availablJointTypes[i]->numCoordinates(), false);
}
}
Ground& ground = updGround();
// assemble a multibody tree according to the PhysicalFrames in the
// OpenSim model, which include Ground and Bodies
_multibodyTree.addBody(ground.getAbsolutePathString(),
0, false, &ground);
auto bodies = getComponentList<Body>();
for (auto& body : bodies) {
_multibodyTree.addBody( body.getAbsolutePathString(),
body.getMass(), false,
const_cast<Body*>(&body) );
}
std::vector<SimTK::ReferencePtr<Joint>> joints;
for (auto& joint : updComponentList<Joint>()) {
joints.push_back(SimTK::ReferencePtr<Joint>(&joint));
}
// Complete multibody tree description by indicating how (mobilized)
// "bodies" are connected by joints.
for (auto& joint : joints) {
std::string name = joint->getAbsolutePathString();
IO::TrimWhitespace(name);
// Currently we need to take a first pass at connecting the joints
// in order to ask the joint for the frames that they attach to and
// to determine their underlying base (physical) frames.
joint->finalizeConnections(*this);
// Verify that the underlying frames are also connected so we can
// traverse to the base frame and get its name. This allows the
// (offset) frames to satisfy the sockets of Joint to be added
// to a Body, for example, and not just joint itself.
const PhysicalFrame& parent = joint->getParentFrame();
const PhysicalFrame& child = joint->getChildFrame();
const_cast<PhysicalFrame&>(parent).finalizeConnections(*this);
const_cast<PhysicalFrame&>(child).finalizeConnections(*this);
OPENSIM_THROW_IF(&parent.findBaseFrame() == &child.findBaseFrame(),
JointFramesHaveSameBaseFrame, getName(),
parent.getName(), child.getName(), child.findBaseFrame().getName());
// Use joints to define the underlying multibody tree
_multibodyTree.addJoint(name,
joint->getConcreteClassName(),
// Multibody tree builder only cares about bodies not intermediate
// frames that joints actually connect to.
parent.findBaseFrame().getAbsolutePathString(),
child.findBaseFrame().getAbsolutePathString(),
false,
joint.get());
}
}
void Model::extendConnectToModel(Model &model)
{
Super::extendConnectToModel(model);
if (&model != this){
log_info("Model:: {} is being connected to model {}.", getName(),
model.getName());
// if part of another Model, that Model is in charge
// of creating a valid Multibody tree that includes
// Components of this Model.
return;
}
// Create the Multibody tree according to the components that
// form this model.
createMultibodyTree();
// generate the graph of the Multibody tree to determine the order in
// which subcomponents will be added to the MultibodySystem (in addToSystem)
_multibodyTree.generateGraph();
//_multibodyTree.dumpGraph(cout);
//cout << endl;
// Ground is the first component of any MultibodySystem
Ground& ground = updGround();
setNextSubcomponentInSystem(ground);
// The JointSet of the Model is only being manipulated for consistency with
// Tool expectations. TODO fix Tools and remove
JointSet& joints = upd_JointSet();
bool isMemoryOwner = joints.getMemoryOwner();
//Temporarily set owner ship to false so we
//can swap to rearrange order of the joints
joints.setMemoryOwner(false);
// Run through all the mobilizers in the multibody tree, adding
// a joint in the correct sequence. Also add massless bodies,
// loop closure constraints, etc... to form the valid tree.
for (int m = 0; m < _multibodyTree.getNumMobilizers(); ++m) {
// Get a mobilizer from the tree, then extract its corresponding
// joint and bodies. Note that these should have equivalents in OpenSim.
const MultibodyGraphMaker::Mobilizer& mob
= _multibodyTree.getMobilizer(m);
if (mob.isSlaveMobilizer()){
// add the slave body and joint
Body* outbMaster = static_cast<Body*>(mob.getOutboardMasterBodyRef());
Joint* useJoint = static_cast<Joint*>(mob.getJointRef());
Body* outb = static_cast<Body*>(mob.getOutboardBodyRef());
// the joint must be added to the system next
setNextSubcomponentInSystem(*useJoint);
if (!outb) {
outb = outbMaster->addSlave();
useJoint->setSlaveBodyForChild(*outb);
SimTK::Transform o(SimTK::Vec3(0));
//Now add the constraints that weld the slave to the master at the
// body origin
std::string pathName = outb->getAbsolutePathString();
WeldConstraint* weld = new WeldConstraint(outb->getName()+"_weld",
*outbMaster, o, *outb, o);
// include within adopted list of owned components
adoptSubcomponent(weld);
setNextSubcomponentInSystem(*weld);
}
}
if (mob.isAddedBaseMobilizer()){
// create and add the base joint to enable these dofs
Body* child = static_cast<Body*>(mob.getOutboardBodyRef());
log_warn("Body '{}' not connected by a Joint."
"A FreeJoint will be added to connect it to ground.",
child->getName());
Ground* ground = static_cast<Ground*>(mob.getInboardBodyRef());
std::string jname = "free_" + child->getName();
SimTK::Vec3 zeroVec(0.0);
Joint* free = new FreeJoint(jname, *ground, *child);
free->isReversed = mob.isReversedFromJoint();
// TODO: Joints are currently required to be in the JointSet
// When the reordering of Joints is eliminated (see following else block)
// this limitation can be removed and the free joint adopted as in
// internal subcomponent (similar to the weld constraint above)
addJoint(free);
setNextSubcomponentInSystem(*free);
}
else{
// Update the directionality of the joint according to tree's
// preferential direction
static_cast<Joint*>(mob.getJointRef())->isReversed =
mob.isReversedFromJoint();
// order the joint components in the order of the multibody tree
Joint* joint = static_cast<Joint*>(mob.getJointRef());
setNextSubcomponentInSystem(*joint);
}
}
joints.setMemoryOwner(isMemoryOwner);
// Add the loop joints if any.
for (int lcx = 0; lcx < _multibodyTree.getNumLoopConstraints(); ++lcx) {
const MultibodyGraphMaker::LoopConstraint& loop =
_multibodyTree.getLoopConstraint(lcx);
Joint& joint = *(Joint*)loop.getJointRef();
Body& parent = *(Body*)loop.getParentBodyRef();
Body& child = *(Body*)loop.getChildBodyRef();
if (joint.getConcreteClassName() == "WeldJoint") {
WeldConstraint* weld = new WeldConstraint( joint.getName()+"_Loop",
parent, joint.getParentFrame().findTransformInBaseFrame(),
child, joint.getChildFrame().findTransformInBaseFrame());
adoptSubcomponent(weld);
setNextSubcomponentInSystem(*weld);
}
else if (joint.getConcreteClassName() == "BallJoint") {
PointConstraint* point = new PointConstraint(
parent, joint.getParentFrame().findTransformInBaseFrame().p(),
child, joint.getChildFrame().findTransformInBaseFrame().p());
point->setName(joint.getName() + "_Loop");
adoptSubcomponent(point);
setNextSubcomponentInSystem(*point);
}
else if (joint.getConcreteClassName() == "FreeJoint") {
// A "free" loop constraint is no constraint at all so we can
// just ignore it. It might be more convenient if there were
// a 0-constraint Constraint::Free, just as there is a 0-mobility
// MobilizedBody::Weld.
}
else
throw std::runtime_error(
"Unrecognized loop constraint type '" + joint.getConcreteClassName() + "'.");
}
// Now include all remaining Components beginning with PhysicalOffsetFrames
// since Constraints, Forces and other components can only be applied to
// PhyicalFrames, which include PhysicalOffsetFrames.
// PhysicalOffsetFrames require that their parent frame (a PhysicalFrame)
// be added to the System first. So for each PhysicalOffsetFrame locate its
// parent and verify its presence in the _orderedList otherwise add it first.
auto poFrames = updComponentList<PhysicalOffsetFrame>();
for (auto& pof : poFrames) {
// Ground and Body type PhysicalFrames are included in the Multibody graph
// PhysicalOffsetFrame can be listed in any order and may be attached
// to any other PhysicalOffsetFrame, so we need to find their parent(s)
// in the tree and add them first.
pof.finalizeConnections(*this);
const PhysicalOffsetFrame* parentPof =
dynamic_cast<const PhysicalOffsetFrame*>(&pof.getParentFrame());
std::vector<const PhysicalOffsetFrame*> parentPofs;
while (parentPof) {
const auto found =
std::find(parentPofs.begin(), parentPofs.end(), parentPof);
OPENSIM_THROW_IF_FRMOBJ(found != parentPofs.end(),
PhysicalOffsetFramesFormLoop, (*found)->getName());
parentPofs.push_back(parentPof);
// Given a chain of offsets, the most proximal must have Ground or
// Body as its parent. When that happens we can stop.
parentPof =
dynamic_cast<const PhysicalOffsetFrame*>(&parentPof->getParentFrame());
}
while (parentPofs.size()) {
setNextSubcomponentInSystem(*parentPofs.back());
parentPofs.pop_back();
}
setNextSubcomponentInSystem(pof);
}
// and everything else including Forces, Controllers, etc...
// belonging to the model
auto components = getImmediateSubcomponents();
for (const auto& comp : components) {
setNextSubcomponentInSystem(comp.getRef());
}
// Populate the model's list of Coordinates as references into
// the individual Joints.
updCoordinateSet().populate(*this);
updForceSet().setupGroups();
updControllerSet().setActuators(updActuators());
// TODO: Get rid of the SimbodyEngine
updSimbodyEngine().connectSimbodyEngineToModel(*this);
// Now that the model is fully connected, cache controllers
// locally to reduce the runtime cost of Model::computeControls()
this->_enabledControllers.clear();
for (const Controller& controller : getComponentList<Controller>()) {
if (controller.isEnabled()) {
this->_enabledControllers.emplace_back(controller);
}
}
}
// ModelComponent interface enables this model to be a subcomponent of another
// model. In that case, it adds itself to the parent model's system.
void Model::extendAddToSystem(SimTK::MultibodySystem& system) const
{
Super::extendAddToSystem(system);
Model *mutableThis = const_cast<Model *>(this);
//Analyses are not Components so add them after legit
//Components have been wired-up correctly.
mutableThis->updAnalysisSet().setModel(*mutableThis);