-
Notifications
You must be signed in to change notification settings - Fork 468
/
SimbodyTreeState.h
1737 lines (1468 loc) · 70.8 KB
/
SimbodyTreeState.h
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
#ifndef SimTK_SIMBODY_TREE_STATE_H_
#define SimTK_SIMBODY_TREE_STATE_H_
/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2005-12 Stanford University and the Authors. *
* Authors: Michael Sherman *
* Contributors: *
* *
* 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. *
* -------------------------------------------------------------------------- */
/* This file contains the classes which define the SimbodyMatterSubsystem State,
that is, everything that can be changed in a SimbodyMatterSubsystem after
construction.
State variables and computation results are organized into stages:
Stage::Empty virginal state just allocated
Stage::Topology Stored in SimbodyMatterSubsystem object (construction)
---------------------------------------------------------
Stage::Model Stored in the State object
Stage::Instance
Stage::Time
Stage::Position
Stage::Velocity
Stage::Dynamics calculate forces
Stage::Acceleration response to forces in the state
---------------------------------------------------------
Stage::Report only used when outputting something
Construction proceeds until all the bodies and constraints have been specified.
After that, realizeTopology() is called. Construction-related calculations are
performed leading to values which are stored in the SimbodyMatterSubsystem
object, NOT in the State (e.g., total number of bodies). At the same time, an
initial state is built, with space allocated for the state variables that will
be needed by the next stage (Stage::Model),and these are assigned default
values. Then the stage in the SimbodyMatterSubsystem and in the initial state
is set to "Topology".
After that, values for Model stage variables can be set in the State.
When that's done we call realizeModel(), which evaluates the Model states
putting the values into state cache entries allocated for the purpose. Then
all remaining state variables are allocated, and set to their default values.
All defaults must be computable knowing only the Model stage values.
Then the stage is advanced to Stage::Model.
This continues through all the stages, with realizeWhatever() expecting to
receive a state evaluated to stage Whatever-1 equipped with values for stage
Whatever so that it can calculate results and put them in the cache (which is
allocated if necessary), and then advance to stage Whatever. */
#include "simbody/internal/common.h"
#include "simbody/internal/Motion.h"
#include <cassert>
#include <iostream>
using std::cout; using std::endl;
using namespace SimTK;
class SimbodyMatterSubsystemRep;
class RigidBodyNode;
template <int dof, bool noR_FM, bool noX_MB, bool noR_PF>
class RigidBodyNodeSpec;
// defined below
class SBTopologyCache;
class SBModelCache;
class SBInstanceCache;
class SBTimeCache;
class SBTreePositionCache;
class SBConstrainedPositionCache;
class SBCompositeBodyInertiaCache;
class SBArticulatedBodyInertiaCache;
class SBTreeVelocityCache;
class SBConstrainedVelocityCache;
class SBDynamicsCache;
class SBTreeAccelerationCache;
class SBConstrainedAccelerationCache;
class SBModelVars;
class SBInstanceVars;
class SBTimeVars;
class SBPositionVars;
class SBVelocityVars;
class SBDynamicsVars;
class SBAccelerationVars;
// =============================================================================
// TOPOLOGY CACHE
// =============================================================================
// An object of this type is stored in the SimbodyMatterSubsystem after extended
// construction is complete, then copied into a slot in the State upon
// realizeTopology(). It should contain enough information to size the Model
// stage, and State resource index numbers for the Model-stage state variables
// and Model-stage cache entry. This topology cache entry can also contain
// whatever arbitrary data you would like to have in a State to verify that it
// is a match for the SimbodyMatterSubsystem.
//
// Note that this does not include all possible topological information in
// a SimbodyMatterSubsystem -- any subobjects are free to hold their own
// as long as they don't change it after realizeTopology().
class SBTopologyCache {
public:
SBTopologyCache() {clear();}
void clear() {
nBodies = nParticles = nConstraints = nAncestorConstrainedBodies =
nDOFs = maxNQs = sumSqDOFs = -1;
modelingVarsIndex.invalidate();
modelingCacheIndex.invalidate();
topoInstanceVarsIndex.invalidate();
valid = false;
}
// These are topological objects.
int nBodies;
int nParticles;
int nConstraints;
// This is the total number of Constrained Bodies appearing in all
// Constraints where the Ancestor body is not Ground, excluding the
// Ancestor bodies themselves even if they are also Constrained Bodies
// (which is common). This is used for sizing pool entries in various
// caches to hold precalculated Ancestor-frame data about these bodies.
int nAncestorConstrainedBodies;
// TODO: these should be moved to Model stage.
int nDOFs;
int maxNQs;
int sumSqDOFs;
DiscreteVariableIndex modelingVarsIndex;
CacheEntryIndex modelingCacheIndex,instanceCacheIndex, timeCacheIndex,
treePositionCacheIndex, constrainedPositionCacheIndex,
compositeBodyInertiaCacheIndex,
articulatedBodyInertiaCacheIndex,
treeVelocityCacheIndex, constrainedVelocityCacheIndex,
articulatedBodyVelocityCacheIndex,
dynamicsCacheIndex,
treeAccelerationCacheIndex,
constrainedAccelerationCacheIndex;
// These are instance variables that exist regardless of modeling
// settings; they are instance variables corresponding to topological
// elements of the matter subsystem (e.g. mobilized bodies and constraints).
DiscreteVariableIndex topoInstanceVarsIndex;
bool valid;
};
//.............................. TOPOLOGY CACHE ................................
// =============================================================================
// MODEL CACHE
// =============================================================================
// This cache entry contains counts of various things resulting from the
// settings of Model-stage state variables. It also contains the resource index
// numbers for all state variable and state cache resources allocated during
// realizeModel().
//
// Model stage is when the mobilizers settle on the meaning of the q's and u's
// they will employ, so here is where we count up the total number of q's and
// u's and assign particular slots in those arrays to each mobilizer. We also
// determine the sizes of related "pools", including the number of q's which
// are angles (for sincos calculations), and the number of quaternions in use
// (for normalization calculations), and partition the entries in those
// pools among the mobilizers.
//
// Important things we still don't know at this stage:
// - what constraints are enabled
// - how motion will be driven for each coordinate
// -----------------------------------------------------------------------------
// PER MOBILIZED BODY MODEL INFO
class SBModelPerMobodInfo {
public:
SBModelPerMobodInfo()
: nQInUse(-1), nUInUse(-1), hasQuaternionInUse(false),
nQPoolInUse(-1) {}
int nQInUse, nUInUse;
QIndex firstQIndex; // Count from 0 for this SimbodyMatterSubsystem
UIndex firstUIndex;
// In case there is a quaternion in use by this Mobilizer: The index
// here can be used to find precalculated data associated with this
// quaternion, such as its current length.
bool hasQuaternionInUse;
// 0..nQInUse-1: which local coordinate starts the quaternion if any?
MobilizerQIndex startOfQuaternion;
// assigned slot # for this MB's quat, -1 if none
QuaternionPoolIndex quaternionPoolIndex;
// Each mobilizer can request some position-cache storage space for
// precalculations involving its generalized coordinates q.
// Here we keep track of our chunk.
int nQPoolInUse; // reserved space in sizeof(Real) units
MobodQPoolIndex startInQPool; // offset into pool
};
// -----------------------------------------------------------------------------
// MODEL CACHE
class SBModelCache {
public:
SBModelCache() {clear();}
// Restore this cache entry to its just-constructed condition.
void clear() {
totalNQInUse=totalNUInUse=totalNQuaternionsInUse= -1;
totalNQPoolInUse= -1;
mobodModelInfo.clear();
}
// Allocate the entries in this ModelCache based on information provided in
// the TopologyCache.
void allocate(const SBTopologyCache& tc) {
mobodModelInfo.resize(tc.nBodies);
}
// Use these accessors so that you get type checking on the index types.
int getNumMobilizedBodies() const {return (int)mobodModelInfo.size();}
SBModelPerMobodInfo& updMobodModelInfo(MobilizedBodyIndex mbx)
{ return mobodModelInfo[mbx]; }
const SBModelPerMobodInfo& getMobodModelInfo(MobilizedBodyIndex mbx) const
{ return mobodModelInfo[mbx]; }
// These are sums over the per-MobilizedBody counts above.
int totalNQInUse, totalNUInUse, totalNQuaternionsInUse;
int totalNQPoolInUse;
// STATE ALLOCATION FOR THIS SUBSYSTEM
// Note that a MatterSubsystem is only one of potentially many users of a
// System's State, so only a subset of State variables and State Cache
// entries belong to it. Here we record the indices we were given when
// we asked the State for some resources. All indices are private to this
// Subsystem -- they'll start from zero regardless of whether there are
// other State resource consumers.
QIndex qIndex; // NOTE: local, currently always zero
UIndex uIndex;
DiscreteVariableIndex timeVarsIndex, qVarsIndex, uVarsIndex,
dynamicsVarsIndex, accelerationVarsIndex;
private:
// MobilizedBody 0 is Ground.
Array_<SBModelPerMobodInfo,MobilizedBodyIndex> mobodModelInfo;
};
inline std::ostream& operator<<(std::ostream& o, const SBModelCache& c) {
o << "SBModelCache:\n";
o << " " << c.getNumMobilizedBodies() << " Mobilized Bodies:\n";
for (MobilizedBodyIndex mbx(0); mbx < c.getNumMobilizedBodies(); ++mbx) {
const SBModelPerMobodInfo& mInfo = c.getMobodModelInfo(mbx);
o << " " << mbx << ": nq,nu=" << mInfo.nQInUse << "," << mInfo.nUInUse
<< " qix,uix=" << mInfo.firstQIndex << "," << mInfo.firstUIndex << endl;
if (mInfo.hasQuaternionInUse)
o << " firstQuat,quatPoolIx=" << mInfo.startOfQuaternion << "," << mInfo.quaternionPoolIndex << endl;
else o << " no quaternion in use\n";
if (mInfo.nQPoolInUse)
o << " nQPool,qPoolIx=" << mInfo.nQPoolInUse << "," << mInfo.startInQPool << endl;
else o << " no angles in use\n";
}
return o;
}
//............................... MODEL CACHE ..................................
// =============================================================================
// INSTANCE CACHE
// =============================================================================
// This is SimbodyMatterSubsystem information calculated during
// realizeInstance(), possibly based on the settings of Instance-stage state
// variables. At this point we will have determined the following information:
// - final mass properties for all bodies (can calculate total mass)
// - final locations for all mobilizer frames
// - which Constraints are enabled
// - how many and what types of constraint equations are to be included
// - how motion is to be calculated for each mobilizer
//
// We allocate entries in the constraint error and multiplier pools among the
// Constraints, and allocate entries in the prescribed motion and prescribed
// force pools among mobilizers whose motion is prescribed.
//
// At this point we can classify all the mobilizers based on the kind of Motion
// they will undergo. We determine the scope of every Constraint, and classify
// them based on the kinds of mobilizers they affect.
// -----------------------------------------------------------------------------
// PER MOBILIZED BODY INSTANCE INFO
// This is information calculated once we have seen all the Instance-stage
// State variable values that can affect bodies, mobilizers, and motions.
// Notes:
// - all mobilities of a mobilizer must be treated identically
// - if any motion level is fast, then the whole mobilizer is fast
// - if a mobilizer is fast, so are all its outboard mobilizers
class SBInstancePerMobodInfo {
public:
SBInstancePerMobodInfo() {clear();}
void clear() {
qMethod=uMethod=udotMethod=Motion::Free;
firstPresQ.invalidate(); firstPresU.invalidate();
firstPresUDot.invalidate(); firstPresForce.invalidate();
}
Motion::Method qMethod; // how are positions calculated?
Motion::Method uMethod; // how are velocities calculated?
Motion::Method udotMethod; // how are accelerations calculated?
PresQPoolIndex firstPresQ; // if qMethod==Prescribed
PresUPoolIndex firstPresU; // if uMethod==Prescribed
PresUDotPoolIndex firstPresUDot; // if udotMethod==Prescribed
PresForcePoolIndex firstPresForce; // if udotMethod!=Free
};
// -----------------------------------------------------------------------------
// PER CONSTRAINT INSTANCE INFO
// Store some Instance-stage information about each Constraint. Most
// important, we don't know how many constraint equations (if any) the
// Constraint will generate until Instance stage. In particular, a disabled
// Constraint won't generate any equations (it will have an Info entry
// here, however). Also, although we know the Constrained Mobilizers at
// Topology stage, we don't know the specific number or types of internal
// coordinates involved until Instance stage.
// Helper class for per-constrained mobilizer information.
class SBInstancePerConstrainedMobilizerInfo {
public:
SBInstancePerConstrainedMobilizerInfo()
: nQInUse(0), nUInUse(0) { } // assume disabled
// The correspondence between Constrained Mobilizers and Mobilized
// Bodies is Topological information you can pull from the
// TopologyCache. See the MobilizedBody for counts of its q's and u's,
// which define the allocated number of slots for the
// ConstrainedMobilizer as well.
int nQInUse, nUInUse; // same as corr. MobilizedBody unless disabled
ConstrainedQIndex firstConstrainedQIndex; // these count from 0 for
ConstrainedUIndex firstConstrainedUIndex; // each Constraint
};
class SBInstancePerConstraintInfo {
public:
SBInstancePerConstraintInfo() { }
void clear() {
constrainedMobilizerInstanceInfo.clear();
constrainedQ.clear(); constrainedU.clear();
participatingQ.clear(); participatingU.clear();
}
void allocateConstrainedMobilizerInstanceInfo(int nConstrainedMobilizers) {
assert(nConstrainedMobilizers >= 0);
constrainedMobilizerInstanceInfo.resize(nConstrainedMobilizers);
constrainedQ.clear(); // build by appending
constrainedU.clear();
}
int getNumConstrainedMobilizers() const
{ return (int)constrainedMobilizerInstanceInfo.size(); }
const SBInstancePerConstrainedMobilizerInfo&
getConstrainedMobilizerInstanceInfo(ConstrainedMobilizerIndex M) const
{ return constrainedMobilizerInstanceInfo[M]; }
SBInstancePerConstrainedMobilizerInfo&
updConstrainedMobilizerInstanceInfo(ConstrainedMobilizerIndex M)
{ return constrainedMobilizerInstanceInfo[M]; }
int getNumConstrainedQ() const {return (int)constrainedQ.size();}
int getNumConstrainedU() const {return (int)constrainedU.size();}
ConstrainedQIndex addConstrainedQ(QIndex qx) {
constrainedQ.push_back(qx);
return ConstrainedQIndex(constrainedQ.size()-1);
}
ConstrainedUIndex addConstrainedU(UIndex ux) {
constrainedU.push_back(ux);
return ConstrainedUIndex(constrainedU.size()-1);
}
QIndex getQIndexFromConstrainedQ(ConstrainedQIndex i) const
{ return constrainedQ[i]; }
UIndex getUIndexFromConstrainedU(ConstrainedUIndex i) const
{ return constrainedU[i]; }
int getNumParticipatingQ() const {return (int)participatingQ.size();}
int getNumParticipatingU() const {return (int)participatingU.size();}
ParticipatingQIndex addParticipatingQ(QIndex qx) {
participatingQ.push_back(qx);
return ParticipatingQIndex(participatingQ.size()-1);
}
ParticipatingUIndex addParticipatingU(UIndex ux) {
participatingU.push_back(ux);
return ParticipatingUIndex(participatingU.size()-1);
}
QIndex getQIndexFromParticipatingQ(ParticipatingQIndex i) const
{ return participatingQ[i]; }
UIndex getUIndexFromParticipatingU(ParticipatingUIndex i) const
{ return participatingU[i]; }
Segment holoErrSegment; // (offset,mHolo) for each Constraint, within subsystem qErr
Segment nonholoErrSegment; // (offset,mNonholo) same, but for uErr slots (after holo derivs)
Segment accOnlyErrSegment; // (offset,mAccOnly) same, but for udotErr slots (after holo/nonholo derivs)
Segment consBodySegment;
Segment consMobilizerSegment; // mobilizers, not *mobilities*
Segment consQSegment;
Segment consUSegment; // these (u) are *mobilities*
public:
Array_<SBInstancePerConstrainedMobilizerInfo,
ConstrainedMobilizerIndex> constrainedMobilizerInstanceInfo;
// The ConstrainedBodies and ConstrainedMobilizers are set at Topology
// stage, but the particular generalized coordinates q and generalized
// speeds u which are involved can't be determined until Model stage,
// since the associated mobilizers have Model stage options which can
// affect the number and meanings of these variables. These are sorted
// in order of their associated ConstrainedMobilizer, not necessarily
// in order of QIndex or UIndex. Each value appears only once.
Array_<QIndex,ConstrainedQIndex> constrainedQ; // -> subsystem QIndex
Array_<UIndex,ConstrainedUIndex> constrainedU; // -> subsystem UIndex
// Participating mobilities include ALL the mobilities which may be
// involved in any of this Constraint's constraint equations, whether
// from being directly constrained or indirectly as a result of their
// effects on ConstrainedBodies. These are sorted in order of
// increasing QIndex and UIndex, and each QIndex or UIndex appears
// only once.
Array_<QIndex,ParticipatingQIndex> participatingQ; // -> subsystem QIndex
Array_<UIndex,ParticipatingUIndex> participatingU; // -> subsystem UIndex
};
// -----------------------------------------------------------------------------
// INSTANCE CACHE
class SBInstanceCache {
public:
// Instance variables are:
// body mass props; particle masses
// X_BM, X_PF mobilizer transforms
//
// Calculations stored here derive from those states:
// total mass
// central inertia of each rigid body
// principal axes and corresponding principal moments of inertia of
// each rigid body
// reference configuration X_PB when q==0 (usually that means M==F),
// for each rigid body
Real totalMass; // sum of all rigid body and particles masses
Array_<Inertia,MobilizedBodyIndex> centralInertias; // nb
Array_<Vec3,MobilizedBodyIndex> principalMoments; // nb
Array_<Rotation,MobilizedBodyIndex> principalAxes; // nb
Array_<Transform,MobilizedBodyIndex> referenceConfiguration; // nb
int getNumMobilizedBodies() const {return (int)mobodInstanceInfo.size();}
SBInstancePerMobodInfo& updMobodInstanceInfo(MobilizedBodyIndex mbx)
{ return mobodInstanceInfo[mbx]; }
const SBInstancePerMobodInfo& getMobodInstanceInfo(MobilizedBodyIndex mbx) const
{ return mobodInstanceInfo[mbx]; }
Array_<SBInstancePerMobodInfo,MobilizedBodyIndex> mobodInstanceInfo;
int getNumConstraints() const {return (int)constraintInstanceInfo.size();}
SBInstancePerConstraintInfo& updConstraintInstanceInfo(ConstraintIndex cx)
{ return constraintInstanceInfo[cx]; }
const SBInstancePerConstraintInfo& getConstraintInstanceInfo(ConstraintIndex cx) const
{ return constraintInstanceInfo[cx]; }
Array_<SBInstancePerConstraintInfo,ConstraintIndex> constraintInstanceInfo;
// This is a sum over all the mobilizers whose q's are currently prescribed,
// adding the number of q's (generalized coordinates) nq currently being
// used for each of those. An array of size totalNPresQ is allocated in the
// TimeCache to hold the calculated q's (which will be different from the
// actual q's until they are applied). Motions will also provide this many
// prescribed qdots and qdotdots, but we will map those to u's and udots
// before recording them, with nu entries being allocated in each. These
// nq- and nu-sized slots are allocated in order of MobilizedBodyIndex.
int getTotalNumPresQ() const {return (int)presQ.size();}
int getTotalNumZeroQ() const {return (int)zeroQ.size();}
int getTotalNumFreeQ() const {return (int)freeQ.size();}
Array_<QIndex> presQ;
Array_<QIndex> zeroQ;
Array_<QIndex> freeQ; // must be integrated
// This is a sum over all the mobilizers whose u's are current prescribed,
// whether because of non-holonomic (velocity) prescribed motion u=u(t,q),
// or because the q's are prescribed via holonomic (position) prescribed
// motion and the u's are calculated from the qdots. We add the number u's
// (generalized speeds) nu currently being used for each holonomic- or
// nonholonomic-prescribed mobilizer. An array of this size is allocated
// in the PositionCache to hold the calculated u's (which will be
// different from the actual u's until they are applied). Nu-sized slots
// are allocated in order of MobilizedBodyIndex.
int getTotalNumPresU() const {return (int)presU.size();}
int getTotalNumZeroU() const {return (int)zeroU.size();}
int getTotalNumFreeU() const {return (int)freeU.size();}
Array_<UIndex> presU;
Array_<UIndex> zeroU;
Array_<UIndex> freeU; // must be integrated
// This is a sum over all the mobilizers whose udots are currently
// prescribed, adding the number of udots (mobilities) nu from each
// holonomic-, nonholonomic-, or acceleration-prescribed mobilizer. An
// array of this size is allocated in the DynamicsCache, and an entry is
// needed in the prescribed force array in the AccelerationCache as well.
// These nu-sized slots are allocated in order of MobilizedBodyIndex.
int getTotalNumPresUDot() const {return (int)presUDot.size();}
int getTotalNumZeroUDot() const {return (int)zeroUDot.size();}
int getTotalNumFreeUDot() const {return (int)freeUDot.size();}
Array_<UIndex> presUDot;
Array_<UIndex> zeroUDot;
Array_<UIndex> freeUDot; // calculated from forces
// This includes all the mobilizers whose udots are known for any
// reason: Prescribed, Zero, Discrete, or Fast (anything but Free).
// These need slots in the array of calculated prescribed motion
// forces (taus). This maps those tau entries to the mobility at
// which they are generalized forces.
int getTotalNumPresForces() const {return (int)presForce.size();}
Array_<UIndex> presForce;
// Quaternion errors go in qErr also, but after all the physical contraint
// errors. That is, they start at index
// totalNHolonomicConstraintEquationsInUse.
int firstQuaternionQErrSlot;
// These record where in the full System's State our Subsystem's qErr, uErr,
// and udotErr entries begin. That is, this subsystem's segments can be
// found at
// qErr (qErrIndex, nPositionConstraintEquationsInUse
// + nQuaternionsInUse)
// uErr (uErrIndex, nVelocityConstraintEquationsInUse)
// udotErr(udotErrIndex, nAccelerationConstraintEquationsInUse)
int qErrIndex, uErrIndex, udotErrIndex;
// These are the sums over the per-Constraint data above. The number of
// position constraint equations (not counting quaternion normalization
// constraints) is the same as the number of holonomic constraints mHolo.
// The number of velocity constraint equations is mHolo+mNonholo. The
// number of acceleration constraint equations, and thus the number of
// udotErrs and multipliers, is mHolo+mNonholo+mAccOnly.
int totalNHolonomicConstraintEquationsInUse; // sum(mHolo) (#position equations = mHolo)
int totalNNonholonomicConstraintEquationsInUse; // sum(mNonholo) (#velocity equations = mHolo+mNonholo)
int totalNAccelerationOnlyConstraintEquationsInUse; // sum(mAccOnly) (#acceleration eqns = mHolo+mNonholo+mAccOnly)
int totalNConstrainedBodiesInUse;
int totalNConstrainedMobilizersInUse;
int totalNConstrainedQInUse; // q,u from the constrained mobilizers
int totalNConstrainedUInUse;
public:
void allocate(const SBTopologyCache& topo,
const SBModelCache& model)
{
totalMass = SimTK::NaN;
centralInertias.resize(topo.nBodies); // I_CB
principalMoments.resize(topo.nBodies); // (Ixx,Iyy,Izz)
principalAxes.resize(topo.nBodies); // [axx ayy azz]
referenceConfiguration.resize(topo.nBodies); // X0_PB
mobodInstanceInfo.resize(topo.nBodies);
constraintInstanceInfo.resize(topo.nConstraints);
firstQuaternionQErrSlot = qErrIndex = uErrIndex = udotErrIndex = -1;
totalNHolonomicConstraintEquationsInUse = 0;
totalNNonholonomicConstraintEquationsInUse = 0;
totalNAccelerationOnlyConstraintEquationsInUse = 0;
totalNConstrainedBodiesInUse = 0;
totalNConstrainedMobilizersInUse = 0;
totalNConstrainedQInUse = 0;
totalNConstrainedUInUse = 0;
}
};
//.............................. INSTANCE CACHE ................................
// =============================================================================
// TIME CACHE
// =============================================================================
// Here we hold information that is calculated in the SimbodyMatterSubsystem's
// realizeTime() method. Currently that consists only of prescribed q's, which
// must always be defined as functions of time.
class SBTimeCache {
public:
// This holds values from Motion prescribed position (holonomic) calculations.
Array_<Real> presQPool; // Index with PresQPoolIndex
public:
void allocate(const SBTopologyCache& topo,
const SBModelCache& model,
const SBInstanceCache& instance)
{
presQPool.resize(instance.getTotalNumPresQ());
}
};
//............................... TIME CACHE ...................................
// =============================================================================
// TREE POSITION CACHE
// =============================================================================
// Here we hold information that is calculated early in the matter subsystem's
// realizePosition() method. This includes
//
// - mobilizer matrices X_FM, H_FM, X_PB, H_PB_G
// - basic kinematic information X_GB, Phi_PB_G
// - mass properties expressed in Ground (TODO: these should probably be in
// their own cache since they aren't needed for kinematics)
//
// - for constrained bodies, position X_AB of each body in its ancestor A
//
// This cache entry can be calculated after Stage::Time and is guaranteed to
// have been calculated by the end of Stage::Position. The
// SimbodyMatterSubsystem's realizePosition() method will mark this done as
// soon as possible, so that later calculations (constraint position errors,
// prescribed velocities) can access these without a stage violation.
class SBTreePositionCache {
public:
const Transform& getX_FM(MobilizedBodyIndex mbx) const {return bodyJointInParentJointFrame[mbx];}
Transform& updX_FM(MobilizedBodyIndex mbx) {return bodyJointInParentJointFrame[mbx];}
const Transform& getX_PB(MobilizedBodyIndex mbx) const {return bodyConfigInParent[mbx];}
Transform& updX_PB(MobilizedBodyIndex mbx) {return bodyConfigInParent[mbx];}
const Transform& getX_GB(MobilizedBodyIndex mbx) const {return bodyConfigInGround[mbx];}
Transform& updX_GB(MobilizedBodyIndex mbx) {return bodyConfigInGround[mbx];}
const Transform& getX_AB(AncestorConstrainedBodyPoolIndex cbpx) const
{ return constrainedBodyConfigInAncestor[cbpx]; }
Transform& updX_AB(AncestorConstrainedBodyPoolIndex cbpx)
{ return constrainedBodyConfigInAncestor[cbpx]; }
public:
// At model stage, each mobilizer (RBNode) is given a chance to grab
// a segment of this cache entry for its own private use. This includes
// pre-calculated sincos(q) for mobilizers with angular coordinates,
// and all or part of N and NInv for mobilizers for which qdot != u.
// Everything must be filled in by the end of realizePosition() but the
// mobilizer is free to fill in different parts at different times during
// its realizePosition() calculations.
Array_<Real, MobodQPoolIndex> mobilizerQCache;
// CAUTION: our definition of the H matrix is transposed from those used
// by Jain and by Schwieters. Jain would call these H* and Schwieters
// would call them H^T, but we call them H.
// TODO(sherm1) Since each dof gets a SpatialVec, consider making each
// entry a SpatialVec instead to get rid of the 2x in the index.
Array_<Vec3> storageForH_FM; // 2 x ndof (H_FM)
Array_<Vec3> storageForH_PB_G; // 2 x ndof (H_PB_G)
Array_<Transform,MobilizedBodyIndex> bodyJointInParentJointFrame; // nb (X_FM)
Array_<Transform,MobilizedBodyIndex> bodyConfigInParent; // nb (X_PB)
Array_<Transform,MobilizedBodyIndex> bodyConfigInGround; // nb (X_GB)
Array_<PhiMatrix,MobilizedBodyIndex> bodyToParentShift; // nb (phi)
// This contains mass m, p_BBc_G (center of mass location measured from
// B origin, expressed in Ground), and G_Bo_G (unit inertia [gyration]
// matrix about B's origin, expressed in Ground). Note that this body's
// inertia is I_Bo_G = m*G_Bo_G.
Array_<SpatialInertia,MobilizedBodyIndex> bodySpatialInertiaInGround; // nb (Mk_G)
// This is the body center of mass location measured from the ground
// origin and expressed in ground, p_GBc = p_GB + p_BBc_G (above).
Array_<Vec3,MobilizedBodyIndex> bodyCOMInGround; // nb (p_GBc)
// Constrained Body Pool
// For Constraints whose Ancestor body A is not Ground G, we assign pool
// entries for each of their Constrained Bodies (call the total number
// 'nacb') to store the above information but measured and expressed in
// the Ancestor frame rather than Ground.
Array_<Transform> constrainedBodyConfigInAncestor; // nacb (X_AB)
public:
void allocate(const SBTopologyCache& tree,
const SBModelCache& model,
const SBInstanceCache& instance)
{
// Pull out construction-stage information from the tree.
const int nBodies = tree.nBodies;
const int nDofs = tree.nDOFs; // this is the number of u's (nu)
const int maxNQs = tree.maxNQs; // allocate the max # q's we'll ever need
const int nacb = tree.nAncestorConstrainedBodies;
// These contain uninitialized junk. Body-indexed entries get their
// ground elements set appropriately now and forever.
mobilizerQCache.resize(model.totalNQPoolInUse);
storageForH_FM.resize(2*nDofs);
storageForH_PB_G.resize(2*nDofs);
bodyJointInParentJointFrame.resize(nBodies);
bodyJointInParentJointFrame[GroundIndex].setToZero();
bodyConfigInParent.resize(nBodies);
bodyConfigInParent[GroundIndex].setToZero();
bodyConfigInGround.resize(nBodies);
bodyConfigInGround[GroundIndex].setToZero();
bodyToParentShift.resize(nBodies);
bodyToParentShift[GroundIndex].setToZero();
bodySpatialInertiaInGround.resize(nBodies);
bodySpatialInertiaInGround[GroundIndex].setMass(Infinity);
bodySpatialInertiaInGround[GroundIndex].setMassCenter(Vec3(0));
bodySpatialInertiaInGround[GroundIndex].setUnitInertia(UnitInertia(Infinity));
bodyCOMInGround.resize(nBodies);
bodyCOMInGround[GroundIndex] = Vec3(0);
constrainedBodyConfigInAncestor.resize(nacb);
}
};
//.......................... TREE POSITION CACHE ...............................
// =============================================================================
// CONSTRAINED POSITION CACHE
// =============================================================================
// Here we hold information that is part of the matter subsystem's
// realizePosition() calculation but depends on the TreePositionCache having
// already been calculated. This includes:
//
// - desired values of prescribed u's (since those are functions of at most
// time and position)
// - logically, position constraint errors (qerrs), although in fact that
// array is provided as a built-in by the State
//
// This cache entry can be calculated after Stage::Time provided that
// the SBTreePositionCache entry has already been marked valid. We guarantee
// this will have been calculated by Stage::Position.
class SBConstrainedPositionCache {
public:
// qerr cache space is provided directly by the State
// This holds values from all the Motion prescribed velocity (nonholonomic)
// calculations, and those resulting from diffentiating prescribed positions.
Array_<Real> presUPool; // Index with PresUPoolIndex
public:
void allocate(const SBTopologyCache& tree,
const SBModelCache& model,
const SBInstanceCache& instance)
{
presUPool.resize(instance.getTotalNumPresU());
}
};
//........................ CONSTRAINED POSITION CACHE ..........................
// =============================================================================
// COMPOSITE BODY INERTIA CACHE
// =============================================================================
// Composite body inertias R are those that would be felt if all the mobilizers
// had prescribed motion (or were welded in their current configurations). These
// are convenient for inverse dynamics computations and for scaling of
// generalized coordinates and speeds.
//
// Each spatial inertia here is expressed in the Ground frame but measured about
// its body's origin.
//
// Note that each composite body inertia is a rigid-body spatial inertia, not
// the more complicated articulated-body spatial inertia. That means these have
// a scalar mass and well-defined mass center, and a very simple structure which
// can be exploited for speed. There are at most 10 unique elements in a rigid
// body spatial inertia matrix.
//
// Composite body inertias depend only on positions but are often not needed at
// all. So we give them their own cache entry and expect explicit realization
// some time after Position stage, if at all.
class SBCompositeBodyInertiaCache {
public:
Array_<SpatialInertia,MobilizedBodyIndex> compositeBodyInertia; // nb (R)
public:
void allocate(const SBTopologyCache& tree,
const SBModelCache& model,
const SBInstanceCache& instance)
{
// Pull out construction-stage information from the tree.
const int nBodies = tree.nBodies;
compositeBodyInertia.resize(nBodies); // TODO: ground initialization
}
};
//....................... COMPOSITE BODY INERTIA CACHE .........................
// =============================================================================
// ARTICULATED BODY INERTIA CACHE
// =============================================================================
/* These articulated body inertias (ABIs) take into account prescribed motion,
meaning that they are produced by a combination of articulated and rigid
shift operations depending on each mobilizer's current status as "free"
or "prescribed". That means that the articulated inertias here are suited
only for "mixed" dynamics; you can't use them to calculate M^-1*f unless
there is no prescribed motion in the system.
Each articulated body inertia here is expressed in the Ground frame but
measured about its body's origin.
Articulated body inertia matrices, though symmetric and positive
definite, do not have the same simple structure as rigid-body (or composite-
body) spatial inertias. For example, the apparent mass depends on direction.
All 21 elements of this symmetric 6x6 matrix are unique, while there are only
10 unique elements in a rigid body spatial inertia.
Note that although we use some *rigid* body shift operations here, the
results in general are all *articulated* body inertias, because a rigid shift
of an articulated body inertia is still an articulated body inertia. Only if
all mobilizers are prescribed will these be rigid body spatial inertias. For
a discussion of the properties of articulated body inertias, see Section 7.1
(pp. 119-123) of Roy Featherstone's excellent 2008 book, Rigid Body Dynamics
Algorithms.
Intermediate quantities PPlus, D, DI, and G are calculated here which are
separately useful when dealing with "free" mobilized bodies. These quantities
are not calculated for prescribed mobilizers; they will remain NaN in that
case. In particular, this means that the prescribed-mobilizer mass properties
do not have to be invertible, so you can have terminal massless bodies as
long as their motion is always prescribed.
TODO: should D still be calculated? It doesn't require inversion.
ABIs depend only on position kinematics (they are time-independent) but are not
usually needed until Acceleration stage, and we do not want to compute them
earlier because (a) they are expensive, and (b) they require good, invertible
mass properties. Some modelers don't bother with good mass properties since they
have no intention of doing forward dynamics; they will rightfully complain
if they get a singular mass matrix exception in Dynamics stage. So this cache
entry should have depends-on stage Instance, with PositionKinematics as an
additional prerequisite, and computed-by stage Acceleration. However, it can
be realized explicitly any time its stage and prerequisite are valid, such as
after Stage::Position. */
class SBArticulatedBodyInertiaCache {
public:
Array_<ArticulatedInertia,MobodIndex> articulatedBodyInertia; // nb (P)
Array_<ArticulatedInertia,MobodIndex> pPlus; // nb (PPlus)
Vector_<Real> storageForD; // sum(nu[j]^2)
Vector_<Real> storageForDI; // sum(nu[j]^2)
Array_<Vec3> storageForG; // 2 X ndof
public:
void allocate(const SBTopologyCache& tree,
const SBModelCache& model,
const SBInstanceCache& instance)
{
// Pull out construction-stage information from the tree.
const int nBodies = tree.nBodies;
const int nDofs = tree.nDOFs; // this is the number of u's (nu)
const int nSqDofs = tree.sumSqDOFs; // sum(ndof^2) for each joint
const int maxNQs = tree.maxNQs; // allocate the max # q's we'll ever need
articulatedBodyInertia.resize(nBodies); // TODO: ground initialization
pPlus.resize(nBodies); // TODO: ground initialization
storageForD.resize(nSqDofs);
storageForDI.resize(nSqDofs);
storageForG.resize(2*nDofs);
}
};
//....................... ARTICULATED BODY INERTIA CACHE .......................
// =============================================================================
// TREE VELOCITY CACHE
// =============================================================================
// Here we hold information that is calculated early in the matter subsystem's
// realizeVelocity() method. This includes
//
// - mobilizer matrices HDot_FM and HDot_PB_G
// - cross mobilizer velocities V_FM, V_PB
// - basic kinematics V_GB giving body velocities in Ground
// - logically, qdot, but that is provided as a built-in cache entry in State
// - for constrained bodies, V_AB giving body velocities in their ancestor A
// - velocity-dependent dynamics remainder terms: coriolis acceleration and
// gyroscopic forces
//
// This cache entry can be calculated after Stage::Position and is guaranteed to
// have been calculated by the end of Stage::Velocity. The matter subsystem's
// realizeVelocity() method will mark this done as soon as possible, so that
// later calculations (constraint velocity errors) can access these without a
// stage violation.
class SBTreeVelocityCache {
public:
const SpatialVec& getV_FM(MobodIndex mbx) const
{ return mobilizerRelativeVelocity[mbx]; }
SpatialVec& updV_FM(MobodIndex mbx)
{ return mobilizerRelativeVelocity[mbx]; }
const SpatialVec& getV_PB(MobodIndex mbx) const
{ return bodyVelocityInParent[mbx]; }
SpatialVec& updV_PB(MobodIndex mbx)
{ return bodyVelocityInParent[mbx]; }
const SpatialVec& getV_GB(MobodIndex mbx) const
{ return bodyVelocityInGround[mbx]; }
SpatialVec& updV_GB(MobodIndex mbx)
{ return bodyVelocityInGround[mbx]; }
const SpatialVec& getV_AB(AncestorConstrainedBodyPoolIndex cbpx) const
{ return constrainedBodyVelocityInAncestor[cbpx]; }
SpatialVec& updV_AB(AncestorConstrainedBodyPoolIndex cbpx)
{ return constrainedBodyVelocityInAncestor[cbpx]; }
public:
// qdot cache space is supplied directly by the State
Array_<SpatialVec,MobodIndex> mobilizerRelativeVelocity; // nb (V_FM)
Array_<SpatialVec,MobodIndex> bodyVelocityInParent; // nb (V_PB)
Array_<SpatialVec,MobodIndex> bodyVelocityInGround; // nb (V_GB)
// CAUTION: our definition of the H matrix is transposed from those used
// by Jain and by Schwieters.
Array_<Vec3> storageForHDot_FM; // 2 x ndof (HDot_FM)
Array_<Vec3> storageForHDot; // 2 x ndof (HDot_PB_G)
// nb (VB_PB_G=HDot_PB_G*u)
Array_<SpatialVec,MobodIndex> bodyVelocityInParentDerivRemainder;
Array_<SpatialVec,MobodIndex> gyroscopicForces; // nb (b)
Array_<SpatialVec,MobodIndex> mobilizerCoriolisAcceleration; // nb (a)
Array_<SpatialVec,MobodIndex> totalCoriolisAcceleration; // nb (A)
Array_<SpatialVec,MobodIndex> totalCentrifugalForces; // nb (M*A+b)
// Ancestor Constrained Body Pool
// For Constraints whose Ancestor body A is not Ground G, we assign pool
// entries for each of their Constrained Bodies (call the total number
// 'nacb') to store the above information but measured and expressed in the
// Ancestor frame rather than Ground.
Array_<SpatialVec> constrainedBodyVelocityInAncestor; // nacb (V_AB)
public:
void allocate(const SBTopologyCache& tree,
const SBModelCache& model,
const SBInstanceCache& instance)
{
// Pull out construction-stage information from the tree.
const int nBodies = tree.nBodies;
const int nDofs = tree.nDOFs; // this is the number of u's (nu)
const int maxNQs = tree.maxNQs; // allocate max # q's we'll ever need
const int nacb = tree.nAncestorConstrainedBodies;
const SpatialVec SVZero(Vec3(0),Vec3(0));
mobilizerRelativeVelocity.resize(nBodies);
mobilizerRelativeVelocity[GroundIndex] = SVZero;
bodyVelocityInParent.resize(nBodies);
bodyVelocityInParent[GroundIndex] = SVZero;
bodyVelocityInGround.resize(nBodies);
bodyVelocityInGround[GroundIndex] = SVZero;
storageForHDot_FM.resize(2*nDofs);
storageForHDot.resize(2*nDofs);
bodyVelocityInParentDerivRemainder.resize(nBodies);
bodyVelocityInParentDerivRemainder[GroundIndex] = SVZero;
gyroscopicForces.resize(nBodies);