OpenSim  OpenSim 3.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Pages
OpenSim::ModelComponent Class Reference

This defines the abstract ModelComponent class, which is used to add computational components to the underlying SimTK::System (MultibodySystem). More...

#include <ModelComponent.h>

Inheritance diagram for OpenSim::ModelComponent:
OpenSim::Object OpenSim::ActiveForceLengthCurve OpenSim::Body OpenSim::Constraint OpenSim::ContactGeometry OpenSim::Controller OpenSim::Coordinate OpenSim::FiberCompressiveForceCosPennationCurve OpenSim::FiberCompressiveForceLengthCurve OpenSim::FiberForceLengthCurve OpenSim::Force OpenSim::ForceVelocityCurve OpenSim::ForceVelocityInverseCurve OpenSim::GeometryPath OpenSim::Joint OpenSim::Model OpenSim::Probe OpenSim::TendonForceLengthCurve

Classes

struct  CacheInfo
struct  DiscreteVariableInfo
struct  ModelingOptionInfo
struct  StateVariableInfo

Public Member Functions

 ModelComponent ()
 Default constructor.
 ModelComponent (const std::string &aFileName, bool aUpdateFromXMLNode=true) SWIG_DECLARE_EXCEPTION
 Construct ModelComponent from an XML file.
 ModelComponent (SimTK::Xml::Element &aNode)
 Construct ModelComponent from a specific node in an XML document.
 ModelComponent (const ModelComponent &source)
 
Construct ModelComponent with its contents copied from another 

ModelComponent; this is a deep copy so nothing is shared with the source after the copy.

virtual ~ModelComponent ()
 Destructor is virtual to allow concrete model component cleanup.
ModelComponentoperator= (const ModelComponent &aModelComponent)
 Assignment operator to copy contents of an existing component.
const ModelgetModel () const
 Get a const reference to the Model this component is part of.
ModelupdModel ()
 Get a modifiable reference to the Model this component is part of.
virtual void updateDisplayer (const SimTK::State &s)
 In case the ModelComponent has a visual representation (VisualObject), override this method to update it.
virtual int getNumStateVariables () const
 Get the number of "Continuous" state variables maintained by the ModelComponent and its specified subcomponents.
virtual Array< std::string > getStateVariableNames () const
 Get the names of "continuous" state variables maintained by the ModelComponent and its subcomponents.
virtual SimTK::SystemYIndex getStateVariableSystemIndex (const std::string &stateVariableName) const
 Get the System Index of a state variable allocated by this ModelComponent.
ModelComponent State Access methods

Get and set modeling option, state, discrete and/or cache variables in the State

int getModelingOption (const SimTK::State &state, const std::string &name) const
 Get a ModelingOption flag for this ModelComponent by name.
void setModelingOption (SimTK::State &state, const std::string &name, int flag) const
 Set the value of a ModelingOption flag for this ModelComponent.
double getStateVariable (const SimTK::State &state, const std::string &name) const
 Get the value of a state variable allocated by this ModelComponent.
void setStateVariable (SimTK::State &state, const std::string &name, double value) const
 Set the value of a state variable allocated by this ModelComponent by name.
double getDiscreteVariable (const SimTK::State &state, const std::string &name) const
 Get the value of a discrete variable allocated by this ModelComponent by name.
void setDiscreteVariable (SimTK::State &state, const std::string &name, double value) const
 Set the value of a discrete variable allocated by this ModelComponent by name.
template<typename T >
const T & getCacheVariable (const SimTK::State &state, const std::string &name) const
 Get the value of a cache variable allocated by this ModelComponent by name.
template<typename T >
T & updCacheVariable (const SimTK::State &state, const std::string &name) const
 Obtain a writable cache variable value allocated by this ModelComponent by name.
void markCacheVariableValid (const SimTK::State &state, const std::string &name) const
 After updating a cache variable value allocated by this ModelComponent, you can mark its value as valid, which will not change until the realization stage falls below the minimum set at the time the cache variable was created.
void markCacheVariableInvalid (const SimTK::State &state, const std::string &name) const
 Mark a cache variable value allocated by this ModelComponent as invalid.
bool isCacheVariableValid (const SimTK::State &state, const std::string &name) const
 Enables the to monitor the validity of the cache variable value using the returned flag.
template<typename T >
void setCacheVariable (const SimTK::State &state, const std::string &name, T &value) const
 Set cache variable value allocated by this ModelComponent by name.
- Public Member Functions inherited from OpenSim::Object
virtual ~Object ()
 Virtual destructor for cleanup.
virtual Objectclone () const =0
 
Create a new heap-allocated copy of the concrete object to which this 

Object refers.

virtual const std::string & getConcreteClassName () const =0
 
Returns the class name of the concrete %Object-derived class of the

actual object referenced by this Object, as a string.

virtual const VisibleObjectgetDisplayer () const
 Methods to support making the object displayable in the GUI or Visualizer Implemented only in few objects.
virtual VisibleObjectupdDisplayer ()
 get Non const pointer to VisibleObject
bool isEqualTo (const Object &aObject) const
 Equality operator wrapper for use from languages not supporting operator overloading.
Objectoperator= (const Object &aObject)
 
Copy assignment copies he base class fields, including the 

properties.

virtual bool operator== (const Object &aObject) const
 Determine if two objects are equal.
virtual bool operator< (const Object &aObject) const
 
Provide an ordering for objects so they can be put in sorted

containers.

void setName (const std::string &name)
 Set the name of the Object.
const std::string & getName () const
 Get the name of this Object.
void setDescription (const std::string &description)
 Set description, a one-liner summary.
const std::string & getDescription () const
 Get description, a one-liner summary.
const std::string & getAuthors () const
 Get Authors of this Object.
void setAuthors (const std::string &authors)
 Set Authors of this object, call this method in your constructor if needed.
const std::string & getReferences () const
 Get references or publications to cite if using this object.
void setReferences (const std::string &references)
 Set references or publications to cite if using this object.
int getNumProperties () const
 Determine how many properties are stored with this Object.
const AbstractPropertygetPropertyByIndex (int propertyIndex) const
 
Get a const reference to a property by its index number, returned as

an AbstractProperty.

AbstractPropertyupdPropertyByIndex (int propertyIndex)
 
Get a writable reference to a property by its index number, returned as

an AbstractProperty.

bool hasProperty (const std::string &name) const
 
Return true if this %Object has a property of any type with the 

given name, which must not be empty.

const AbstractPropertygetPropertyByName (const std::string &name) const
 
Get a const reference to a property by its name, returned as

an AbstractProperty.

AbstractPropertyupdPropertyByName (const std::string &name)
 
Get a writable reference to a property by its name, returned as

an AbstractProperty.

template<class T >
bool hasProperty () const
 
Return true if this %Object contains an unnamed, one-object property

that contains objects of the given template type T.

template<class T >
const Property< T > & getProperty (const PropertyIndex &index) const
 
Get property of known type Property\<T> as a const reference; 

the property must be present and have the right type.

template<class T >
Property< T > & updProperty (const PropertyIndex &index)
 
Get property of known type Property\<T> as a writable reference;

the property must be present and have the right type.

void setObjectIsUpToDateWithProperties ()
 
When an object is initialized using the current values of its 

properties, it can set a flag indicating that it is up to date.

bool isObjectUpToDateWithProperties () const
 
Returns \c true if any property's value has changed since the last time

setObjectIsUpToDateWithProperties() was called.

void readObjectFromXMLNodeOrFile (SimTK::Xml::Element &objectElement, int versionNumber)
 We're given an XML element from which we are to populate this Object.
virtual void updateFromXMLNode (SimTK::Xml::Element &objectElement, int versionNumber)
 Use this method to deserialize an object from a SimTK::Xml::Element.
virtual void updateXMLNode (SimTK::Xml::Element &parent)
 Serialize this object into the XML node that represents it.
bool getInlined () const
 
Inlined means an in-memory Object that is not associated with

an XMLDocument.

void setInlined (bool aInlined, const std::string &aFileName="")
 
Mark this as inlined or not and optionally provide a file name

to associate with the new XMLDocument for the non-inline case.

std::string getDocumentFileName () const
 
If there is a document associated with this object then return the

file name maintained by the document.

void setAllPropertiesUseDefault (bool aUseDefault)
bool print (const std::string &fileName)
 
Write this %Object into an XML file of the given name; conventionally

the suffix to use is ".osim".

std::string dump (bool dumpName=false)
 dump the XML representation of this Object into an std::string and return it.
void clearObjectIsUpToDateWithProperties ()
 
For testing or debugging purposes, manually clear the "object is up to 

date with respect to properties" flag.

virtual bool isA (const char *type) const
 
The default implementation returns true only if the supplied string

is "Object"; each Object-derived class overrides this to match its own class name.

const std::string & toString () const
 
Wrapper to be used on Java side to display objects in tree; this returns

just the object's name.

PropertySetgetPropertySet ()
 
OBSOLETE: Get a reference to the PropertySet maintained by the 

Object.

const PropertySetgetPropertySet () const

Protected Member Functions

ModelComponent Protected Interface

The interface ensures that deserialization, resolution of inter-connections and dependencies, are performed systematically and prior to system creation, followed by allocation of necessary System resouces.

These methods are virtual and must be implemented by subclasses of ModelComponents. Every implementation of virtual method xxx(args) must begin with the line "Super::xxx(args);" to ensure that the parent class methods execute before the child class method, starting with ModelComponent::xxx() and going down.

virtual void connectToModel (Model &model)
 
Perform any necessary initializations required to connect the 

component into the Model, and check for error conditions.

virtual void addToSystem (SimTK::MultibodySystem &system) const
 
Add appropriate Simbody elements (if needed) to the System 

corresponding to this component and specify needed state resources.

virtual void initStateFromProperties (SimTK::State &state) const
 
Transfer property values or other state-independent initial values

into this component's state variables in the passed-in state argument.

virtual void setPropertiesFromState (const SimTK::State &state)
 
Update this component's property values to match the specified State,

if the component has created any state variable that is intended to correspond to a property.

virtual SimTK::Vector computeStateVariableDerivatives (const SimTK::State &s) const
 
If a model component has allocated any continuous state variables

using the addStateVariable() method, then computeStateVariableDerivatives() must be implemented to provide time derivatives for those states.

virtual void generateDecorations (bool fixed, const ModelDisplayHints &hints, const SimTK::State &state, SimTK::Array_< SimTK::DecorativeGeometry > &appendToThis) const
 
Optional method for generating arbitrary display geometry that reflects

this ModelComponent at the specified state.

ModelComponent System Creation and Access Methods

These methods support implementing concrete ModelComponents.

Add methods can only be called inside of addToSystem() and are useful for creating the underlying SimTK::System level variables that are used for computing values of interest.

Warning
Accessors for System indices are intended for component internal use only.
void includeAsSubComponent (ModelComponent *aComponent)
 Include another ModelComponent as a Subcomponent of this ModelComponent.
void addModelingOption (const std::string &optionName, int maxFlagValue) const
 
Add a modeling option (integer flag stored in the State) for use by 

this ModelComponent.

void addStateVariable (const std::string &stateVariableName, SimTK::Stage invalidatesStage=SimTK::Stage::Dynamics) const
 
Add a continuous system state variable belonging to this ModelComponent,

and assign a name by which to refer to it.

void addDiscreteVariable (const std::string &discreteVariableName, SimTK::Stage invalidatesStage) const
 
Add a system discrete variable belonging to this ModelComponent, give

it a name by which it can be referenced, and declare the lowest Stage that should be invalidated if this variable's value is changed.

template<class T >
void addCacheVariable (const std::string &cacheVariableName, const T &variablePrototype, SimTK::Stage dependsOnStage) const
 
Add a state cache entry belonging to this ModelComponent to hold

calculated values that must be automatically invalidated when certain state values change.

const int getStateIndex (const std::string &name) const
 Get the index of a ModelComponent's continuous state variable in the Subsystem for allocations.
const SimTK::DiscreteVariableIndex getDiscreteVariableIndex (const std::string &name) const
 Get the index of a ModelComponent's discrete variable in the Subsystem for allocations.
const SimTK::CacheEntryIndex getCacheVariableIndex (const std::string &name) const
 Get the index of a ModelComponent's cache variable in the Subsystem for allocations.
- Protected Member Functions inherited from OpenSim::Object
 Object ()
 
 The default constructor is only for use by constructors of 

derived types.

 Object (const std::string &fileName, bool aUpdateFromXMLNode=true) SWIG_DECLARE_EXCEPTION
 
Constructor from a file, to be called from other constructors that 

take a file as input.

 Object (const Object &source)
 
Copy constructor is invoked automatically by derived classes with

default copy constructors; otherwise it must be invoked explicitly.

 Object (SimTK::Xml::Element &aElement)
 
Construct the base class portion of an %Object from a given Xml 

element that describes this Object.

template<class T >
PropertyIndex addProperty (const std::string &name, const std::string &comment, const T &value)
 
Define a new single-value property of known type T, with the given 

name, associated comment, and initial value.

template<class T >
PropertyIndex addOptionalProperty (const std::string &name, const std::string &comment)
 
Add an optional property, meaning it can contain either no value or

a single value.

template<class T >
PropertyIndex addOptionalProperty (const std::string &name, const std::string &comment, const T &value)
 
Add an optional property, meaning it can contain either no value or

a single value.

template<class T >
PropertyIndex addListProperty (const std::string &name, const std::string &comment, int minSize, int maxSize)
 
Define a new list-valued property of known type T, with the given 

name, associated comment, minimum (==0) and maximum (>0) allowable list lengths, and a zero-length initial value.

template<class T , template< class > class Container>
PropertyIndex addListProperty (const std::string &name, const std::string &comment, int minSize, int maxSize, const Container< T > &valueList)
 
Define a new list-valued property as above, but assigning an initial

value via some templatized container class that supports size() and indexing.

PropertyIndex getPropertyIndex (const std::string &name) const
 
Look up a property by name and return its PropertyIndex if it is

found.

template<class T >
PropertyIndex getPropertyIndex () const
 
Look up an unnamed property by the type of object it contains,

and return its PropertyIndex if it is found.

void updateFromXMLDocument ()
 
Use this method only if you're deserializing from a file and the object

is at the top level; that is, primarily in constructors that take a file name as input.

void setDocument (XMLDocument *doc)
 Unconditionally set the XMLDocument associated with this object.
const XMLDocumentgetDocument () const
 
Get a const pointer to the document (if any) associated with this

object.

XMLDocumentupdDocument ()
 
Get a writable pointer to the document (if any) associated with this

object.

Protected Attributes

Model_model
 The model this component belongs to.
- Protected Attributes inherited from OpenSim::Object
PropertySet _propertySet
 
OBSOLETE: Property_Deprecated set for serializable member variables of 

this and derived classes.

Friends

class ModelComponentSet
class ModelComponentMeasure

Additional Inherited Members

- Static Public Member Functions inherited from OpenSim::Object
static void registerType (const Object &defaultObject)
 
Register an instance of a class; if the class is already registered it

will be replaced.

static void renameType (const std::string &oldTypeName, const std::string &newTypeName)
 
Support versioning by associating the current %Object type with an 

old name.

static const ObjectgetDefaultInstanceOfType (const std::string &concreteClassName)
 
Return a pointer to the default instance of the registered (concrete)

Object whose class name is given, or NULL if the type is not registered.

template<class T >
static bool isObjectTypeDerivedFrom (const std::string &concreteClassName)
 
Return true if the given concrete object type represents a subclass of 

the template object type T, and thus could be referenced with a T*.

static ObjectnewInstanceOfType (const std::string &concreteClassName)
 
Create a new instance of the concrete %Object type whose class name is 

given as concreteClassName.

static void getRegisteredTypenames (Array< std::string > &typeNames)
 Retrieve all the typenames registered so far.
template<class T >
static void getRegisteredObjectsOfGivenType (ArrayPtrs< T > &rArray)
 
Return an array of pointers to the default instances of all registered

(concrete) Object types that derive from a given Object-derived type that does not have to be concrete.

static void PrintPropertyInfo (std::ostream &os, const std::string &classNameDotPropertyName)
 
Dump formatted property information to a given output stream, useful

for creating a "help" facility for registered objects.

static void PrintPropertyInfo (std::ostream &os, const std::string &className, const std::string &propertyName)
 
Same as the other signature but the class name and property name are

provided as two separate strings.

static ObjectmakeObjectFromFile (const std::string &fileName)
 
Create an %OpenSim object whose type is based on the tag at the root 

node of the XML file passed in.

static const std::string & getClassName ()
 Return the name of this class as a string; i.e., "Object".
static void setSerializeAllDefaults (bool shouldSerializeDefaults)
 
Static function to control whether all registered objects and

their properties are written to the defaults section of output files rather than only those values for which the default was explicitly overwritten when read in from an input file or set programmatically.

static bool getSerializeAllDefaults ()
 Report the value of the "serialize all defaults" flag.
static bool isKindOf (const char *type)
 
Returns true if the passed-in string is "Object"; each %Object-derived

class defines a method of this name for its own class name.

static void setDebugLevel (int newLevel)
 Set the debug level to get verbose output.
static int getDebugLevel ()
 Get current setting of debug level.
static ObjectSafeCopy (const Object *aObject)
 
Use the clone() method to duplicate the given object unless the pointer

is null in which case null is returned.

static void RegisterType (const Object &defaultObject)
 OBSOLETE alternate name for registerType().
static void RenameType (const std::string &oldName, const std::string &newName)
 OBSOLETE alternate name for renameType().
- Static Public Attributes inherited from OpenSim::Object
static const std::string DEFAULT_NAME
 Name used for default objects when they are serialized.

Detailed Description

This defines the abstract ModelComponent class, which is used to add computational components to the underlying SimTK::System (MultibodySystem).

It specifies the interface that components must satisfy in order to be part of the system and provides a series of helper methods for adding variables (state, discrete, cache, ...) to the underlying system. As such, ModelComponent handles all of the bookkeeping of system indices and provides convenience access to variable values via their names as strings.

The MultibodySystem and its State are defined by Simbody (ref ...). Briefly, a System can be thought of the equations that define the mathematical behavior of a model. The State is a collection of all the variables that uniquely define the unknowns in the system equations. These would be joint coordinates, their speeds, accelerations as well other variables that govern system dynamics (e.g. muscle activation and fiber-length variables that dictate muscle force). These variables are called continuous state variables in Simbody, but are more simply referred to as StateVariables in OpenSim. ModelComponent provides services to define and access its StateVariables and specify their dynamics (derivatives with respect to time) that are automatically and simultaneously integrated with the MultibodySystem dynamics.

There are other types of "State" variables such as a flag (or option) that enables a component to be disabled or for a muscle force to be overridden and and these are identified as ModelingOptions since they fundamentally change the modeled dynamics of the component. ModelComponent provides services that enable developers of components to define additional ModelingOptions.

Often a component requires input from an outside source (precomputed data from a file, another program, or interaction from a user) in which case these variables do not have dynamics (differential eqns.) known to the component, but are necessary to describe the dynamical "state" of the system. An example, is a throttle component (a "controller" that provides an actuator (e.g. a motor) with a control signal (a voltage or current)) which it gets direct input from the user (via a joystick, key press, etc..). The throttle controls the motor torque output and therefore the behavior of the model. The input by the user to the throttle the motor (the controls) is necesary to specify the model dynamics at any instant and therefore are considered part of the State in Simbody as Discrete State Variables. In OpenSim they are simplify referred to as DiscreteVariables. The ModelComponent provides services to enable developers of components to define and access its DiscreteVariables.

Fast and efficient simulations also require computationally expensive calculations to be performed only when necessary. Often the result of a expensive calculation can be reused many times over, while the variables it is dependent on remain fixed. The concept of holding onto these values is called caching and the variables that hold these values are call CacheVariables. It is important to note, that cache variables are not state variables. Cache variables can always be recomputed excactly from the State. OpenSim uses the Simbody infrastructure to manage cache variables and their validity. ModelComponent provides a simplified interface to define and access CacheVariables.

Many modeling and simulation codes put the onus on users and component creators to manage the validity of cache variables, which is likely to lead to undetectable errors where cache values are stale (calculated based on past state variable values). Simbody, on the other hand, provides a more strict infrastructure to make it easy to exploit the efficiencies of caching while reducing the risks of validity errors. To do this, Simbody employs the concept of computational stages. To "realize" a model's system to a particular stage is to perform all the computations necessary to evaluate the cached quantities up to and including the stage specified. Simbody utilizes nine realization stages (SimTK::Stage::)

  1. Topology finalize System with "slots" for most variables (above)
  2. Model specify modeling choices
  3. Instance specify modifiable model parameters
  4. Time compute time dependent quantities
  5. Position compute position dependent quantities
  6. Velocity compute velocity dependent quantities
  7. Dynamics compute system applied forces and dependent quantities
  8. Acceleration compute system accelerations and all other derivatives
  9. Report compute quantities for reporting/output

The ModelComponent interface is automatically invoked by the System and its realizations. Component users and most developers need not concern themselves with Topology, Model or Instance stages. That interaction is managed by ModelComponent when component creators implement addToSystem() and use the services provided ModelComponent. Component creators do need to determine and specify stage dependencies for Discrete and CacheVariables that they add to their components. For example, the throttle controller reads its value from user input and it is valid for all calculations as long as time does not change. If the simulation (via numerical integration) steps forward (or backward for a trial step) and updates the state, the control from a previous state (time) should be invalid and an error generated for trying to access the DiscreteVariable for the control value. To do this one specifies the "dependsOn" stage (e.g. SimTK::Stage::Time) for a DiscreteVariable when the variable is added to the ModelComponent. If the control is fixed (not changing with time) then the lowest valid stage could just be Instance.

Similar principles apply to CacheVariables, which requires a "lowestValid" stage to be specified when a CacheVariable is added to the component. In this case, the cache variable augments the State (unlike a discrete state variable, which is a part of the State) for the convenience of not recomputing a value unless necesary. Accessing the cache variable at a stage lower than the lowestValid specified will trigger an exception. It is up to the component to update the value of the cache variable. ModelComponent provides methods to check if the cache is valid, update its value and mark as valid.

All components: Bodies, Joints, Coordinates, Constraints, Forces, Controllers, .. and even Model itself, are ModelComponents. Each component is "connected" to a SimTK::Subsystem and by default this is the System's DefaultSubsystem.

The primary responsibility of a ModelComponent is to add its computational representation(s) to the underlying SimTK::System by implementing addToSystem().

Additional methods provide support for adding modeling options, state and cache variables.

Public methods enable access to component variables via their names.

Author
Ajay Seth

Constructor & Destructor Documentation

OpenSim::ModelComponent::ModelComponent ( )

Default constructor.

OpenSim::ModelComponent::ModelComponent ( const std::string &  aFileName,
bool  aUpdateFromXMLNode = true 
)

Construct ModelComponent from an XML file.

OpenSim::ModelComponent::ModelComponent ( SimTK::Xml::Element &  aNode)
explicit

Construct ModelComponent from a specific node in an XML document.

OpenSim::ModelComponent::ModelComponent ( const ModelComponent source)

Construct ModelComponent with its contents copied from another 

ModelComponent; this is a deep copy so nothing is shared with the source after the copy.

virtual OpenSim::ModelComponent::~ModelComponent ( )
inlinevirtual

Destructor is virtual to allow concrete model component cleanup.

Member Function Documentation

template<class T >
void OpenSim::ModelComponent::addCacheVariable ( const std::string &  cacheVariableName,
const T &  variablePrototype,
SimTK::Stage  dependsOnStage 
) const
inlineprotected

Add a state cache entry belonging to this ModelComponent to hold

calculated values that must be automatically invalidated when certain state values change.

Cache entries contain values whose computations depend on state variables and provide convenience and/or efficiency by holding on to them in memory (cache) to avoid recomputation. Once the state changes, the cache values automatically become invalid and has to be recomputed based on the current state before it can be referenced again. Any attempt to reference an invalid cache entry results in an exception being thrown.

Cache entry validity is managed by computation Stage, rather than by dependence on individual state variables. Changing a variables whose "invalidates" stage is the same or lower as the one specified as the "depends on" stage here cause the cache entry to be invalidated. For example, a body's momementum, which is dependent on position and velocity states, should have Stage::Velocity as its dependsOnStage. Then if a Velocity stage variable or lower (e.g. Position stage) changes, then the cache is invalidated. But, if a Dynamics stage variable (or above) is changed, the velocity remains valid so the cache entry does not have to be recomputed.

Parameters
[in]cacheVariableNameThe name you are assigning to this cache entry. Must be unique within this model component.
[in]variablePrototypeAn object defining the type of value, and a default value of that type, to be held in this cache entry. Can be a simple int or an elaborate class, as long as it has deep copy semantics.
[in]dependsOnStageThis is the highest computational stage on which this cache entry's value computation depends. State changes at this level or lower will invalidate the cache entry.
void OpenSim::ModelComponent::addDiscreteVariable ( const std::string &  discreteVariableName,
SimTK::Stage  invalidatesStage 
) const
protected

Add a system discrete variable belonging to this ModelComponent, give

it a name by which it can be referenced, and declare the lowest Stage that should be invalidated if this variable's value is changed.

void OpenSim::ModelComponent::addModelingOption ( const std::string &  optionName,
int  maxFlagValue 
) const
protected

Add a modeling option (integer flag stored in the State) for use by 

this ModelComponent.

Each modeling option is identified by its own optionName, specified here. Modeling options enable the model component to be configured differently in order to represent different operating modes. For example, if two modes of operation are necessary (mode off and mode on) then specify optionName, "mode" with maxFlagValue = 1. Subsequent gets will return 0 or 1 and set will only accept 0 and 1 as acceptable values. Changing the value of a model option invalidates Stage::Instance and above in the State, meaning all calculations involving time, positions, velocity, and forces are invalidated.

void OpenSim::ModelComponent::addStateVariable ( const std::string &  stateVariableName,
SimTK::Stage  invalidatesStage = SimTK::Stage::Dynamics 
) const
protected

Add a continuous system state variable belonging to this ModelComponent,

and assign a name by which to refer to it.

Changing the value of this state variable will automatically invalidate everything at and above its invalidatesStage, which is normally Stage::Dynamics meaning that there are forces that depend on this variable. If you define one or more of these variables you must also override computeStateVariableDerivatives() to provide time derivatives for them.

virtual void OpenSim::ModelComponent::addToSystem ( SimTK::MultibodySystem &  system) const
protectedvirtual

Add appropriate Simbody elements (if needed) to the System 

corresponding to this component and specify needed state resources.

addToSystem() is called when the Simbody System is being created to represent a completed Model for computation. That is, connectToModel() will already have been invoked on all components before any addToSystem() call is made. Helper methods for adding modeling options, state variables and their derivatives, discrete variables, and cache entries are available and can be called within addToSystem() only.

Note that this method is const; you must not modify your model component or the containing model during this call. Any modifications you need should instead be performed in connectToModel(), which is non-const. One exception is that you may need to record access information for resources you create in the system, such as an index number. You should declare those data members mutable so that you can set them here.

If you override this method, be sure to invoke the base class method first, using code like this:

void MyComponent::addToSystem(SimTK::MultibodySystem& system) const {
Super::addToSystem(system); // invoke parent class method
// ... your code goes here
}
Parameters
[in,out]systemThe System being created.
See Also
addModelingOption(), addStateVariable(), addDiscreteVariables(), addCacheVariable()

Reimplemented in OpenSim::Model, OpenSim::Millard2012AccelerationMuscle, OpenSim::Millard2012EquilibriumMuscle, OpenSim::FiberCompressiveForceCosPennationCurve, OpenSim::Muscle, OpenSim::Thelen2003Muscle, OpenSim::Coordinate, OpenSim::Joint, OpenSim::CMC, OpenSim::Actuator, OpenSim::CoordinateLimitForce, OpenSim::Probe, OpenSim::ContDerivMuscle_Deprecated, OpenSim::GeometryPath, OpenSim::Body, OpenSim::Delp1990Muscle_Deprecated, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::PointToPointSpring, OpenSim::CorrectionController, OpenSim::Force, OpenSim::Ligament, OpenSim::ActivationFiberLengthMuscle, OpenSim::Controller, OpenSim::ControlSetController, OpenSim::RollingOnSurfaceConstraint, OpenSim::WeldConstraint, OpenSim::SpringGeneralizedForce, OpenSim::ConstantDistanceConstraint, OpenSim::CoordinateCouplerConstraint, OpenSim::PointOnLineConstraint, OpenSim::PointConstraint, OpenSim::HuntCrossleyForce, OpenSim::EllipsoidJoint, OpenSim::Actuator_, OpenSim::BallJoint, OpenSim::FreeJoint, OpenSim::SliderJoint, OpenSim::UniversalJoint, OpenSim::PinJoint, OpenSim::WeldJoint, and OpenSim::ElasticFoundationForce.

virtual SimTK::Vector OpenSim::ModelComponent::computeStateVariableDerivatives ( const SimTK::State &  s) const
inlineprotectedvirtual

If a model component has allocated any continuous state variables

using the addStateVariable() method, then computeStateVariableDerivatives() must be implemented to provide time derivatives for those states.

Override to return a Vector of the same size as the number of state variables defined and in order added to the system (also

See Also
addToSystem()). Default returns empty (no derivatives are defined). Implement like this:
SimTK::Vector computeStateVariableDerivatives(const SimTK::State& s) const {
// Collect derivatives from parent class and above first.
SimTK::Vector derivs = Super::computeStateVariableDerivatives(s);
const int n = derivs.size();
derivs.resizeKeep(n + myNumStateVariables); // grow
for (int i=0; i < myNumStateVariables; ++i)
derivs[n+i] = ...; // i'th state variable derivative
return derivs;
}
TODO: Subcomponents are not handled here.

Reimplemented in OpenSim::Millard2012AccelerationMuscle, OpenSim::Millard2012EquilibriumMuscle, OpenSim::ContDerivMuscle_Deprecated, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::Delp1990Muscle_Deprecated, and OpenSim::ActivationFiberLengthMuscle.

virtual void OpenSim::ModelComponent::connectToModel ( Model model)
protectedvirtual

Perform any necessary initializations required to connect the 

component into the Model, and check for error conditions.

connectToModel() is invoked on all components to complete construction of a Model, prior to creating a Simbody System to represent it computationally. It may also be invoked at times just for its error-checking side effects.

If you override this method, be sure to invoke the base class method first, using code like this:

void MyComponent::connectToModel(Model& model) {
Super::connectToModel(model); // invoke parent class method
// ... your code goes here
}

Note that this method is expected to check for modeling errors and should throw an OpenSim::Exception if there is something wrong. For example, if your model component references another object by name, you should verify that it exists in the supplied Model, which is not guaranteed since components may be independently instantiated or constructed from XML files.

Parameters
[in,out]modelThe Model currently being constructed to which this ModelComponent should be connected.

Reimplemented in OpenSim::Model, OpenSim::Millard2012AccelerationMuscle, OpenSim::Millard2012EquilibriumMuscle, OpenSim::FiberCompressiveForceCosPennationCurve, OpenSim::Muscle, OpenSim::PrescribedForce, OpenSim::Coordinate, OpenSim::Joint, OpenSim::CMC, OpenSim::CoordinateLimitForce, OpenSim::ExternalForce, OpenSim::Probe, OpenSim::ContDerivMuscle_Deprecated, OpenSim::ContactGeometry, OpenSim::GeometryPath, OpenSim::Body, OpenSim::Delp1990Muscle_Deprecated, OpenSim::PathActuator, OpenSim::PointToPointSpring, OpenSim::CorrectionController, OpenSim::Ligament, OpenSim::Schutte1993Muscle_Deprecated, OpenSim::Controller, OpenSim::ControlSetController, OpenSim::RollingOnSurfaceConstraint, OpenSim::SpringGeneralizedForce, OpenSim::WeldConstraint, OpenSim::Constraint, OpenSim::ConstantDistanceConstraint, OpenSim::CoordinateCouplerConstraint, OpenSim::PointOnLineConstraint, OpenSim::PointConstraint, OpenSim::UnilateralConstraint, OpenSim::EllipsoidJoint, OpenSim::BallJoint, OpenSim::FreeJoint, OpenSim::SliderJoint, OpenSim::UniversalJoint, OpenSim::PinJoint, and OpenSim::WeldJoint.

virtual void OpenSim::ModelComponent::generateDecorations ( bool  fixed,
const ModelDisplayHints hints,
const SimTK::State &  state,
SimTK::Array_< SimTK::DecorativeGeometry > &  appendToThis 
) const
inlineprotectedvirtual

Optional method for generating arbitrary display geometry that reflects

this ModelComponent at the specified state.

This will be called once to obtain ground- and body-fixed geometry (with fixed=true), and then once per frame (with fixed=false) to generate on-the-fly geometry such as rubber band lines, force arrows, labels, or debugging aids.

If you override this method, be sure to invoke the base class method first, using code like this:

(bool fixed,
const ModelDisplayHints& hints,
const SimTK::State& state,
SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const
{
// invoke parent class method
Super::generateDecorations(fixed,hints,state,appendToThis);
// ... your code goes here
}
Parameters
[in]fixedIf true, generate only geometry that is independent of time, configuration, and velocity. Otherwise generate only such dependent geometry.
[in]hintsSee documentation for ModelDisplayHints; you may want to alter the geometry you generate depending on what you find there. For example, you can determine whether the user wants to see debug geometry.
[in]stateThe State for which geometry should be produced. See below for more information.
[in,out]appendToThisArray to which generated geometry should be appended via the push_back() method.

When called with fixed=true only modeling options and parameters (Instance variables) should affect geometry; time, position, and velocity should not. In that case OpenSim will already have realized the state through Instance stage. When called with fixed=false, you may consult any relevant value in state. However, to avoid unnecessary computation, OpenSim guarantees only that state will have been realized through Position stage; if you need anything higher than that (reaction forces, for example) you should make sure the state is realized through Acceleration stage.

Reimplemented in OpenSim::Model.

template<typename T >
const T& OpenSim::ModelComponent::getCacheVariable ( const SimTK::State &  state,
const std::string &  name 
) const
inline

Get the value of a cache variable allocated by this ModelComponent by name.

Parameters
statethe State for which to set the value
namethe name of the cache variable
Returns
T const reference to the cache variable's value
const SimTK::CacheEntryIndex OpenSim::ModelComponent::getCacheVariableIndex ( const std::string &  name) const
protected

Get the index of a ModelComponent's cache variable in the Subsystem for allocations.

This method is intended for derived ModelComponents that may need direct access to its underlying Subsystem.

double OpenSim::ModelComponent::getDiscreteVariable ( const SimTK::State &  state,
const std::string &  name 
) const

Get the value of a discrete variable allocated by this ModelComponent by name.

Parameters
statethe State for which to set the value
namethe name of the state variable
Returns
value the discrete variable value
const SimTK::DiscreteVariableIndex OpenSim::ModelComponent::getDiscreteVariableIndex ( const std::string &  name) const
protected

Get the index of a ModelComponent's discrete variable in the Subsystem for allocations.

This method is intended for derived ModelComponents that may need direct access to its underlying Subsystem.

const Model& OpenSim::ModelComponent::getModel ( ) const

Get a const reference to the Model this component is part of.

int OpenSim::ModelComponent::getModelingOption ( const SimTK::State &  state,
const std::string &  name 
) const

Get a ModelingOption flag for this ModelComponent by name.

The flag is an integer corresponding to the index of modelingOptionNames used add the modeling option to the component.

See Also
addModelingOption
Parameters
statethe State in which to set the modeling option
namethe name (string) of the modeling option of interest
Returns
flag integer value for modeling option
virtual int OpenSim::ModelComponent::getNumStateVariables ( ) const
virtual

Get the number of "Continuous" state variables maintained by the ModelComponent and its specified subcomponents.

Reimplemented in OpenSim::Model, OpenSim::Coordinate, OpenSim::GeometryPath, OpenSim::Body, and OpenSim::Constraint.

const int OpenSim::ModelComponent::getStateIndex ( const std::string &  name) const
protected

Get the index of a ModelComponent's continuous state variable in the Subsystem for allocations.

This method is intended for derived ModelComponents that may need direct access to its underlying Subsystem.

double OpenSim::ModelComponent::getStateVariable ( const SimTK::State &  state,
const std::string &  name 
) const

Get the value of a state variable allocated by this ModelComponent.

Parameters
statethe State for which to get the value
namethe name (string) of the state variable of interest

Reimplemented in OpenSim::Model.

virtual Array<std::string> OpenSim::ModelComponent::getStateVariableNames ( ) const
virtual
virtual SimTK::SystemYIndex OpenSim::ModelComponent::getStateVariableSystemIndex ( const std::string &  stateVariableName) const
virtual

Get the System Index of a state variable allocated by this ModelComponent.

Returns an InvalidIndex if no state variable with the name provided is found.

Parameters
stateVariableNamethe name of the state variable

Reimplemented in OpenSim::Model, OpenSim::Millard2012AccelerationMuscle, OpenSim::Millard2012EquilibriumMuscle, OpenSim::Coordinate, OpenSim::ActivationFiberLengthMuscle_Deprecated, and OpenSim::ActivationFiberLengthMuscle.

void OpenSim::ModelComponent::includeAsSubComponent ( ModelComponent aComponent)
protected

Include another ModelComponent as a Subcomponent of this ModelComponent.

ModelComponent methods (e.g. addToSystem(), initStateFromProperties(), ...) are therefore invoked on Subcomponents when called on the parent. Realization is also performed automatically on subcomponents. This ModelComponent does not take ownership of the subcomponent.

virtual void OpenSim::ModelComponent::initStateFromProperties ( SimTK::State &  state) const
inlineprotectedvirtual

Transfer property values or other state-independent initial values

into this component's state variables in the passed-in state argument.

This is called after a SimTK::System and State have been created for the Model (that is, after addToSystem() has been called on all components). You should override this method if your component has properties (serializable values) that can affect initial values for your state variables. You can also perform any other state-independent calculations here that result in state initial conditions.

If you override this method, be sure to invoke the base class method first, using code like this:

void MyComponent::initStateFromProperties(SimTK::State& state) const {
Super::initStateFromProperties(state); // invoke parent class method
// ... your code goes here
}
Parameters
stateThe state that will receive the new initial conditions.
See Also
setPropertiesFromState()

Reimplemented in OpenSim::Model, OpenSim::Millard2012AccelerationMuscle, OpenSim::Millard2012EquilibriumMuscle, OpenSim::FiberCompressiveForceCosPennationCurve, OpenSim::Muscle, OpenSim::Coordinate, OpenSim::Joint, OpenSim::GeometryPath, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::CorrectionController, OpenSim::Ligament, OpenSim::ActivationFiberLengthMuscle, OpenSim::RollingOnSurfaceConstraint, OpenSim::ControlSetController, OpenSim::Force, OpenSim::Constraint, OpenSim::EllipsoidJoint, OpenSim::BallJoint, and OpenSim::FreeJoint.

bool OpenSim::ModelComponent::isCacheVariableValid ( const SimTK::State &  state,
const std::string &  name 
) const
inline

Enables the to monitor the validity of the cache variable value using the returned flag.

For components performing a costly evaluation, use this method to force a re-evaluation cache variable value only when necessary (returns false).

Parameters
statethe State in which the cache value resides
namethe name of the cache variable
Returns
bool whether the cache variable value is valid or not
void OpenSim::ModelComponent::markCacheVariableInvalid ( const SimTK::State &  state,
const std::string &  name 
) const
inline

Mark a cache variable value allocated by this ModelComponent as invalid.

When the system realization drops to below the lowest valid stage, cache variables are automatically marked as invalid. There are instances when component added state variables require invalidating a cache at a lower stage. For example, a component may have a length state variable which should invalidate calculations involving it and other positions when the state variable is set. Changing the component state variable automatically invalidates Dynamics and higher realizations, but to force realizations at Position and Velocity requires setting the lowest valid stage to Position and marking the cache variable as invalid whenver the length state variable value is set/changed.

Parameters
statethe State containing the cache variable
namethe name of the cache variable
void OpenSim::ModelComponent::markCacheVariableValid ( const SimTK::State &  state,
const std::string &  name 
) const
inline

After updating a cache variable value allocated by this ModelComponent, you can mark its value as valid, which will not change until the realization stage falls below the minimum set at the time the cache variable was created.

If not marked as valid, the evaluation method monitoring this flag will force a re-evaluation rather that just reading the value from the cache.

Parameters
statethe State containing the cache variable
namethe name of the cache variable
ModelComponent& OpenSim::ModelComponent::operator= ( const ModelComponent aModelComponent)

Assignment operator to copy contents of an existing component.

template<typename T >
void OpenSim::ModelComponent::setCacheVariable ( const SimTK::State &  state,
const std::string &  name,
T &  value 
) const
inline

Set cache variable value allocated by this ModelComponent by name.

All cache entries are lazily evaluated (on a need basis) so a set also marks the cache as valid.

Parameters
statethe State for which to set the value
namethe name of the state variable
valuethe variable's cache new value to set
void OpenSim::ModelComponent::setDiscreteVariable ( SimTK::State &  state,
const std::string &  name,
double  value 
) const

Set the value of a discrete variable allocated by this ModelComponent by name.

Parameters
statethe State for which to set the value
namethe name of the dsicrete variable
valuethe value to set
void OpenSim::ModelComponent::setModelingOption ( SimTK::State &  state,
const std::string &  name,
int  flag 
) const

Set the value of a ModelingOption flag for this ModelComponent.

if the integer value exceeds the number of option names used to define the options, an exception is thrown. The SimTK::State Stage will be reverted back to Stage::Instance.

Parameters
statethe State in which to set the flag
namethe name (string) of the modeling option of interest
flagthe desired flag (integer) value specifying the modeling option
virtual void OpenSim::ModelComponent::setPropertiesFromState ( const SimTK::State &  state)
inlineprotectedvirtual

Update this component's property values to match the specified State,

if the component has created any state variable that is intended to correspond to a property.

Thus, state variable values can persist as part of the model component and be serialized as a property.

If you override this method, be sure to invoke the base class method first, using code like this:

void MyComponent::setPropertiesFromState(const SimTK::State& state) {
Super::setPropertiesFromState(state); // invoke parent class method
// ... your code goes here
}
Parameters
stateThe State from which values may be extracted to set persistent property values.
See Also
initStateFromProperties()

Reimplemented in OpenSim::Model, OpenSim::Millard2012AccelerationMuscle, OpenSim::Millard2012EquilibriumMuscle, OpenSim::FiberCompressiveForceCosPennationCurve, OpenSim::Muscle, OpenSim::Coordinate, OpenSim::Joint, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::Force, OpenSim::RollingOnSurfaceConstraint, OpenSim::ActivationFiberLengthMuscle, OpenSim::Constraint, OpenSim::EllipsoidJoint, OpenSim::BallJoint, and OpenSim::FreeJoint.

void OpenSim::ModelComponent::setStateVariable ( SimTK::State &  state,
const std::string &  name,
double  value 
) const

Set the value of a state variable allocated by this ModelComponent by name.

Parameters
statethe State for which to set the value
namethe name of the state variable
valuethe value to set
virtual void OpenSim::ModelComponent::updateDisplayer ( const SimTK::State &  s)
inlinevirtual

In case the ModelComponent has a visual representation (VisualObject), override this method to update it.

This is typically done by recomputing anchor points and positions based on transforms obtained from current state.

Reimplemented in OpenSim::GeometryPath, OpenSim::PathActuator, OpenSim::Ligament, and OpenSim::PointToPointSpring.

template<typename T >
T& OpenSim::ModelComponent::updCacheVariable ( const SimTK::State &  state,
const std::string &  name 
) const
inline

Obtain a writable cache variable value allocated by this ModelComponent by name.

Do not forget to mark the cache value as valid after updating, otherwise it will force a reevaluation if the evaluation method is monitoring the validity of the cache value.

Parameters
statethe State for which to set the value
namethe name of the state variable
Returns
value modifiable reference to the cache variable's value
Model& OpenSim::ModelComponent::updModel ( )

Get a modifiable reference to the Model this component is part of.

Friends And Related Function Documentation

friend class ModelComponentMeasure
friend
friend class ModelComponentSet
friend

Member Data Documentation

Model* OpenSim::ModelComponent::_model
protected

The model this component belongs to.


The documentation for this class was generated from the following file: