OpenSim  OpenSim 3.1
 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::Body OpenSim::Constraint OpenSim::ContactGeometry OpenSim::Controller OpenSim::Coordinate OpenSim::Force OpenSim::GeometryPath OpenSim::Joint OpenSim::Model OpenSim::Probe

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) const
 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, const 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 true if no 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 Basic Interface

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

These methods are virtual and may be implemented by subclasses of ModelComponents.

Note
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.

The base class implementations here do two things: (1) take care of any needs of the ModelComponent base class itself, and then (2) ensure that the corresponding calls are made to any subcomponents that have been specified by derived ModelComponent objects, via calls to the includeAsSubComponent() method. So assuming that your concrete ModelComponent and all intermediate classes from which it derives properly follow the requirement of calling the Super class method first, the order of operations enforced here for a call to a single method will be

  1. ModelComponent base class computations
  2. calls to that same method for all subcomponents
  3. calls to that same method for intermediate ModelComponent-derived objects' computations, in order down from ModelComponent, and
  4. finally a call to that method for the bottom-level concrete class.

You should consider this ordering when designing a ModelComponent. In particular the fact that all your subcomponents will be invoked before you are may be surprising.

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 Advanced Interface

You probably won't need to override methods in this section.

These provide a way for you to perform computations ("realizations") that must be scheduled in carefully-ordered stages as described in the class description above. The typical operation will be that the given SimTK::State provides you with the inputs you need for your computation, which you will then write into some element of the state cache, where later computations can pick it up.

Note
Once again it is crucial that, if you override a method here, you invoke the superclass method as the first line in your implementation, via a call like "Super::realizePosition(state);". This will ensure that all necessary base class computations are performed, and that subcomponents are handled properly.
Warning
Currently the realize() methods here are invoked early in the sequence of realizations at a given stage, meaning that you will not be able to access other computations at that same stage.
Bug:
Should defer calls to these until at least kinematic realizations at the same stage have been performed.
See Also
Simbody documentation for more information about realization.
virtual void realizeTopology (SimTK::State &state) const
 Obtain state resources that are needed unconditionally, and perform computations that depend only on the system topology.
virtual void realizeModel (SimTK::State &state) const
 Obtain state resources that may be needed, depending on modeling options, and perform computations that depend only on topology and selected modeling options.
virtual void realizeInstance (const SimTK::State &state) const
 Perform computations that depend only on instance variables, like lengths and masses.
virtual void realizeTime (const SimTK::State &state) const
 Perform computations that depend only on time and earlier stages.
virtual void realizePosition (const SimTK::State &state) const
 Perform computations that depend only on position-level state variables and computations performed in earlier stages (including time).
virtual void realizeVelocity (const SimTK::State &state) const
 Perform computations that depend only on velocity-level state variables and computations performed in earlier stages (including position, and time).
virtual void realizeDynamics (const SimTK::State &state) const
 Perform computations (typically forces) that may depend on dynamics-stage state variables, and on computations performed in earlier stages (including velocity, position, and time), but not on other forces, accelerations, constraint multipliers, or reaction forces.
virtual void realizeAcceleration (const SimTK::State &state) const
 Perform computations that may depend on applied forces.
virtual void realizeReport (const SimTK::State &state) const
 Perform computations that may depend on anything but are only used for reporting and cannot affect subsequent simulation behavior.
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 necessary 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 "invalidates" stage (e.g. SimTK::Stage::Time) for a DiscreteVariable when the variable is added to the ModelComponent. A subsequent change to that variable will invalidate all state cache entries at that stage or higher. For example, if a DiscreteVariable is declared to invalidate Stage::Position then changing it will invalidate cache entries that depend on positions, velocities, forces, and accelerations.

Similar principles apply to CacheVariables, which requires a "dependsOn" stage to be specified when a CacheVariable is added to the component. In this case, the cache variable "shadows" the State (unlike a DiscreteVariable, which is a part of the State) holding already-computed state-dependent values so that they do not need to be recomputed until the state changes. Accessing the CacheVariable in a State whose current stage is lower than that CacheVariable's specified dependsOn stage 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::Muscle, OpenSim::Thelen2003Muscle, OpenSim::Coordinate, OpenSim::Joint, OpenSim::CMC, OpenSim::Actuator, OpenSim::CoordinateLimitForce, OpenSim::Probe, OpenSim::GeometryPath, OpenSim::ExpressionBasedPointToPointForce, OpenSim::ContDerivMuscle_Deprecated, OpenSim::PathSpring, OpenSim::Body, OpenSim::Delp1990Muscle_Deprecated, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::Ligament, OpenSim::CorrectionController, OpenSim::ActivationFiberLengthMuscle, OpenSim::Force, OpenSim::PointToPointSpring, OpenSim::ClutchedPathSpring, OpenSim::Controller, OpenSim::ControlSetController, OpenSim::HuntCrossleyForce, OpenSim::SpringGeneralizedForce, OpenSim::CoordinateCouplerConstraint, OpenSim::RollingOnSurfaceConstraint, OpenSim::WeldConstraint, OpenSim::ConstantDistanceConstraint, OpenSim::PointConstraint, OpenSim::PointOnLineConstraint, OpenSim::EllipsoidJoint, OpenSim::Actuator_, OpenSim::BallJoint, OpenSim::GimbalJoint, OpenSim::FreeJoint, OpenSim::UniversalJoint, OpenSim::PinJoint, OpenSim::WeldJoint, OpenSim::PlanarJoint, OpenSim::SliderJoint, and OpenSim::ElasticFoundationForce.

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

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;
}
This method is invoked from the base class realizeAcceleration() method.

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

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::Muscle, OpenSim::Thelen2003Muscle, OpenSim::PrescribedForce, OpenSim::Coordinate, OpenSim::Joint, OpenSim::CMC, OpenSim::CoordinateLimitForce, OpenSim::ExternalForce, OpenSim::Probe, OpenSim::GeometryPath, OpenSim::ExpressionBasedPointToPointForce, OpenSim::ContDerivMuscle_Deprecated, OpenSim::ContactGeometry, OpenSim::PathSpring, OpenSim::Body, OpenSim::PathActuator, OpenSim::Delp1990Muscle_Deprecated, OpenSim::Ligament, OpenSim::ActivationFiberLengthMuscle, OpenSim::CorrectionController, OpenSim::ActuatorPowerProbe, OpenSim::PointToPointSpring, OpenSim::ActuatorForceProbe, OpenSim::PrescribedController, OpenSim::Schutte1993Muscle_Deprecated, OpenSim::ControlSetController, OpenSim::Controller, OpenSim::SpringGeneralizedForce, OpenSim::CoordinateCouplerConstraint, OpenSim::RollingOnSurfaceConstraint, OpenSim::WeldConstraint, OpenSim::ConstantDistanceConstraint, OpenSim::Constraint, OpenSim::PointConstraint, OpenSim::UnilateralConstraint, OpenSim::EllipsoidJoint, OpenSim::PointOnLineConstraint, OpenSim::BallJoint, OpenSim::GimbalJoint, OpenSim::FreeJoint, OpenSim::UniversalJoint, OpenSim::PinJoint, OpenSim::WeldJoint, OpenSim::PlanarJoint, and OpenSim::SliderJoint.

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

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, OpenSim::ExpressionBasedBushingForce, OpenSim::FunctionBasedBushingForce, OpenSim::GeometryPath, and OpenSim::EllipsoidJoint.

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::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
protectedvirtual

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::Muscle, OpenSim::Thelen2003Muscle, OpenSim::Coordinate, OpenSim::Joint, OpenSim::GeometryPath, OpenSim::PathSpring, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::CorrectionController, OpenSim::ActivationFiberLengthMuscle, OpenSim::ControlSetController, OpenSim::Force, OpenSim::RollingOnSurfaceConstraint, OpenSim::Constraint, OpenSim::EllipsoidJoint, OpenSim::BallJoint, OpenSim::GimbalJoint, 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.

virtual void OpenSim::ModelComponent::realizeAcceleration ( const SimTK::State &  state) const
protectedvirtual

Perform computations that may depend on applied forces.

virtual void OpenSim::ModelComponent::realizeDynamics ( const SimTK::State &  state) const
protectedvirtual

Perform computations (typically forces) that may depend on dynamics-stage state variables, and on computations performed in earlier stages (including velocity, position, and time), but not on other forces, accelerations, constraint multipliers, or reaction forces.

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

virtual void OpenSim::ModelComponent::realizeInstance ( const SimTK::State &  state) const
protectedvirtual

Perform computations that depend only on instance variables, like lengths and masses.

virtual void OpenSim::ModelComponent::realizeModel ( SimTK::State &  state) const
protectedvirtual

Obtain state resources that may be needed, depending on modeling options, and perform computations that depend only on topology and selected modeling options.

virtual void OpenSim::ModelComponent::realizePosition ( const SimTK::State &  state) const
protectedvirtual

Perform computations that depend only on position-level state variables and computations performed in earlier stages (including time).

virtual void OpenSim::ModelComponent::realizeReport ( const SimTK::State &  state) const
protectedvirtual

Perform computations that may depend on anything but are only used for reporting and cannot affect subsequent simulation behavior.

virtual void OpenSim::ModelComponent::realizeTime ( const SimTK::State &  state) const
protectedvirtual

Perform computations that depend only on time and earlier stages.

virtual void OpenSim::ModelComponent::realizeTopology ( SimTK::State &  state) const
protectedvirtual

Obtain state resources that are needed unconditionally, and perform computations that depend only on the system topology.

virtual void OpenSim::ModelComponent::realizeVelocity ( const SimTK::State &  state) const
protectedvirtual

Perform computations that depend only on velocity-level state variables and computations performed in earlier stages (including position, and time).

template<typename T >
void OpenSim::ModelComponent::setCacheVariable ( const SimTK::State &  state,
const std::string &  name,
const 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 in which to store the new value
namethe name of the cache variable
valuethe new value for this cache variable
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)
protectedvirtual

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::Muscle, OpenSim::Thelen2003Muscle, OpenSim::Coordinate, OpenSim::Joint, OpenSim::ActivationFiberLengthMuscle_Deprecated, OpenSim::Force, OpenSim::ActivationFiberLengthMuscle, OpenSim::RollingOnSurfaceConstraint, OpenSim::Constraint, OpenSim::EllipsoidJoint, OpenSim::BallJoint, OpenSim::GimbalJoint, 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

Reimplemented in OpenSim::Model.

virtual void OpenSim::ModelComponent::updateDisplayer ( const SimTK::State &  s) const
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::PathSpring, OpenSim::GeometryPath, OpenSim::PathActuator, and OpenSim::Ligament.

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: