<NME> Component.h <BEF> #ifndef OPENSIM_COMPONENT_H_ #define OPENSIM_COMPONENT_H_ /* -------------------------------------------------------------------------- * * OpenSim: Component.h * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ajay Seth * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ /** @file * This file defines the abstract Component 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, * Component handles all of the bookkeeping for variable indices and * provides convenience access via variable names. Furthermore, a component * embodies constructs of inputs, outputs and connections that are useful in * composing computational systems. * * A component may contain one or more underlying Simbody multibody system * elements (MobilizedBody, Constraint, Force, or Measure) which are part of * a SimTK::Subsystem. A SimTK::Subsystem is where new variables are * allocated. A Component, by default, uses the System's DefaultSubsystem. * for allocating new variables. */ // INCLUDES #include "ComponentList.h" #include "ComponentPath.h" #include "Logger.h" #include "OpenSim/Common/Array.h" #include "OpenSim/Common/ComponentOutput.h" #include "OpenSim/Common/ComponentSocket.h" #include "OpenSim/Common/Object.h" #include "simbody/internal/MultibodySystem.h" #include <unordered_map> #include <OpenSim/Common/osimCommonDLL.h> namespace OpenSim { class Model; class ModelDisplayHints; //============================================================================== /// Component Exceptions //============================================================================== class ComponentHasNoName : public Exception { public: ComponentHasNoName(const std::string& file, size_t line, const std::string& func, const std::string& componentConcreteClassName) : Exception(file, line, func) { std::string msg = componentConcreteClassName; msg += " was constructed with no name.\n"; msg += "Please assign a valid name and try again."; addMessage(msg); } }; class InvalidComponentName : public Exception { public: InvalidComponentName(const std::string& file, size_t line, const std::string& func, const std::string& thisName, const std::string& invalidChars, const std::string& componentConcreteClassName) : Exception(file, line, func) { std::string msg = "Component '" + thisName + "' of type " + componentConcreteClassName + " contains invalid characters of: '" + invalidChars + "'."; addMessage(msg); } }; class ComponentNotFoundOnSpecifiedPath : public ComponentNotFound { public: ComponentNotFoundOnSpecifiedPath(const std::string& file, size_t line, const std::string& func, const std::string& toFindName, const std::string& toFindClassName, const std::string& thisName) : ComponentNotFound(file, line, func) { std::string msg = "Component '" + thisName; msg += "' could not find '" + toFindName; msg += "' of type " + toFindClassName + ". "; msg += "Make sure a component exists at this path and that it is of "; msg += "the correct type."; addMessage(msg); } }; class ComponentIsAnOrphan : public Exception { public: ComponentIsAnOrphan(const std::string& file, size_t line, const std::string& func, const std::string& thisName, const std::string& componentConcreteClassName) : Exception(file, line, func) { std::string msg = "Component '" + thisName + "' of type " + componentConcreteClassName + " has no owner and is not the root.\n" + "Verify that finalizeFromProperties() has been invoked on the " + "root Component or that this Component is not a clone, which has " + "not been added to another Component."; addMessage(msg); } }; class SubcomponentsWithDuplicateName : public Exception { public: SubcomponentsWithDuplicateName(const std::string& file, size_t line, const std::string& func, const std::string& thisName, const std::string& duplicateName) : Exception(file, line, func) { std::string msg = "Component '" + thisName + "' has subcomponents " + "with duplicate name '" + duplicateName + "'. " "Please supply unique names for immediate subcomponents."; addMessage(msg); } }; class ComponentIsRootWithNoSubcomponents : public Exception { public: ComponentIsRootWithNoSubcomponents(const std::string& file, size_t line, const std::string& func, const std::string& thisName, const std::string& componentConcreteClassName) : Exception(file, line, func) { std::string msg = "Component '" + thisName + "' of type " + componentConcreteClassName + " is the root but has no " + "subcomponents listed.\n" + "Verify that finalizeFromProperties() was called on this " "Component to identify its subcomponents."; addMessage(msg); } }; class ComponentAlreadyPartOfOwnershipTree : public Exception { public: ComponentAlreadyPartOfOwnershipTree(const std::string& file, size_t line, const std::string& func, const std::string& compName, const std::string& thisName) : Exception(file, line, func) { std::string msg = "Component '" + compName; msg += "' already owned by tree to which '" + thisName; msg += "' belongs. Clone the component to adopt a fresh copy."; addMessage(msg); } }; class ComponentHasNoSystem : public Exception { public: ComponentHasNoSystem(const std::string& file, size_t line, const std::string& func, const Object& obj) : Exception(file, line, func, obj) { std::string msg = "Component has no underlying System.\n"; msg += "You must call initSystem() on the top-level Component "; msg += "(i.e. Model) first."; addMessage(msg); } }; class SocketNotFound : public Exception { public: SocketNotFound(const std::string& file, size_t line, const std::string& func, const Object& obj, const std::string& socketName) : Exception(file, line, func, obj) { std::string msg = "no Socket '" + socketName; msg += "' found for this Component."; addMessage(msg); } }; class InputNotFound : public Exception { public: InputNotFound(const std::string& file, size_t line, const std::string& func, const Object& obj, const std::string& inputName) : Exception(file, line, func, obj) { std::string msg = "no Input '" + inputName; msg += "' found for this Component."; addMessage(msg); /** Destructor is virtual to allow concrete Component to cleanup. **/ virtual ~Component() {} /** Update Component's internal data members based on properties. Marks the Component as up to date with its properties. */ void finalizeFromProperties(); /** * The abstract Component class defines the interface used to add computational * elements 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, Component * handles all of the bookkeeping of system indices and provides convenience * access to variable values (incl. derivatives) via their names as strings. * * # Component's Interfaces * ## System and State * * The MultibodySystem and its State are defined by Simbody (ref ...). Briefly, * a System represents the mathematical equations that specify the behavior * of a computational model. The State is a collection of all the variables /** Set Component's properties given a state. */ void setPropertiesFromState(const SimTK::State& state); /** * Get the underlying MultibodySystem that this component is connected to. */ * that are automatically and simultaneously integrated with the MultibodySystem * dynamics. Common operations to integrate, take the max or min, or to delay a * signal, etc. require internal variables to perform their calculations and * these are also held in the State. Simbody provides the infrastructure to * ensure that calculations are kept up-to-date with the state variable values. * * There are other types of "State" variables such as a flag (or options) that * enables a component to be disabled or for a muscle force to be overridden and * and these are identified as <em>ModelingOptions</em> since they may change * the modeled dynamics of the component. Component provides services * that enable developers of components to define additional ModelingOptions. * * ## Discrete variables * * 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 like a voltage or current) which it gets as 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 OpenSim they are simply referred to as DiscreteVariables. The Component * provides services to enable developers of components to define and access its * DiscreteVariables. * * ## Cache variables * * Fast and efficient simulations also require computationally expensive * calculations to be performed only when necessary. Often the result of an */ Array<std::string> getStateVariableNames() const; /** @name Component Connector Access methods Access Connectors of this component in a generic way and also by name. */ * define and access CacheVariables. * * ## Stages * * 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" (or compute) a model's system to a * particular stage requires cached quantities up to and including the stage to * to computed/specified. Simbody utilizes nine realization stages * (<tt>SimTK::Stage::</tt>) * * -# \c Topology finalize System with "slots" for most variables (above) * -# \c %Model specify modeling choices * -# \c Instance specify modifiable model parameters * -# \c Time compute time dependent quantities * -# \c Position compute position dependent quantities * -# \c Velocity compute velocity dependent quantities * -# \c Dynamics compute system applied forces and dependent quantities * -# \c Acceleration compute system accelerations and all other derivatives * -# \c Report compute quantities for reporting/output * * The Component interface is automatically invoked by the System and its * realizations. Component users and most developers need not concern themselves * with \c Topology, \c %Model or \c Instance stages. That interaction is managed * by Component when component creators implement extendAddToSystem() and use the * services provided by Component. 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. <tt>SimTK::Stage::Time</tt>) for a DiscreteVariable * when the variable is added to the Component. 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 <tt>Stage::Position</tt> * 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. * Component provides methods to check if the cache is valid, update its value * and then to mark it as valid. * * ## The interface of this class * * The primary responsibility of a Component is to add its computational * representation(s) to the underlying SimTK::System by implementing * extendAddToSystem(). * * Additional methods provide support for adding modeling options, state and * cache variables. * * Public methods enable access to component variables via their names. * * ## Subcomponents * * A %Component can have any number of %Components within it; we call these * subcomponents. Subcomponents can also contain their own subcomponents as * well. There are three categories of subcomponents, which vary in whether * they are *configurable* and *fixed in number*: * * - **property subcomponents** Any Property in a Component that is of type * Component is a subcomponent. This includes list properties and Set%s. This * is the most common category of subcomponent, and its distinguishing * feature is that these subcomponents are *configurable* by the user of this * component. These subcomponents appear in the XML for this component, and * can be modified in XML or through the API. They are also not fixed in * number; users can add more property subcomponents to an existing * component (though it is possible to enforce a fixed number by using * one-value properties or limiting the size of a list property). The bodies, * joints, forces, etc. in a Model's BodySet, JointSet, ForceSet, etc. are * all examples of property subcomponents. This category of subcomponent is * the most similar to what was available pre-v4.0. * - **member subcomponents** These are *not* configurable by the user of this * Component, and can only be modified by this Component. You can * still access member subcomponents through the API, but only the component * containing the subcomponents can modify them. Any Component class can have * any number of member subcomponents, but this number is *fixed* for every * instance of the component. * - **adopted subcomponents** These are *not* configurable (does not appear in * XML) and *not* fixed in number. For example, a component can decide, * based on other aspects of the model, that it needs to create a new * subcomponent. This can be done using adopted subcomponents. * * Also, any specific Component can end up in any of these three categories. * That is, if you have a MySpecialForce Component, any other Component can * have it as a property subcomponent, a member subcomponent, or as an adopted * subcomponent. * * @author Ajay Seth, Michael Sherman, Chris Dembia */ class OSIMCOMMON_API Component : public Object { OpenSim_DECLARE_ABSTRACT_OBJECT(Component, Object); protected: //============================================================================== // PROPERTIES //============================================================================== OpenSim_DECLARE_LIST_PROPERTY(components, Component, "List of components that this component owns and serializes."); public: //============================================================================== // METHODS //============================================================================== /** Default constructor **/ Component(); /** Construct Component from an XML file. **/ Component(const std::string& aFileName, bool aUpdateFromXMLNode = true) SWIG_DECLARE_EXCEPTION; /** Construct Component from a specific node in an XML document. **/ explicit Component(SimTK::Xml::Element& aNode); /** Use default copy constructor and assignment operator. */ Component(const Component&) = default; Component& operator=(const Component&) = default; /** Destructor is virtual to allow concrete Component to cleanup. **/ virtual ~Component() = default; /** @name Component Structural Interface The structural 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 can be extended by virtual methods that form the Component Extension Interface (e.g. #extendFinalizeFromProperties) that can be implemented by subclasses of Components. Component ensures that the corresponding calls are propagated to all of its subcomponents.*/ ///@{ /** Define a Component's internal data members and structure according to its properties. This includes its subcomponents as part of the component ownership tree and identifies its owner (if present) in the tree. finalizeFromProperties propagates to all of the component's subcomponents prior to invoking the virtual extendFinalizeFromProperties() on itself. Note that if the Component has already been added to a System (result of addToSystem(); e.g., Model::initSystem()) when finalizeFromProperties() is called, then finalizeFromProperties() disassociates the component from that System.*/ void finalizeFromProperties(); /** Satisfy the Component's connections specified by its Sockets and Inputs. Locate Components and their Outputs to satisfy the connections in an aggregate Component (e.g. Model), which is the root of a tree of Components. */ void finalizeConnections(Component& root); /** Disconnect/clear this Component from its aggregate component. Empties all component's sockets and sets them as disconnected.*/ void clearConnections(); /** Have the Component add itself to the underlying computational System */ void addToSystem(SimTK::MultibodySystem& system) const; /** Initialize Component's state variable values from its properties */ void initStateFromProperties(SimTK::State& state) const; /** %Set Component's properties given a state. */ void setPropertiesFromState(const SimTK::State& state); // End of Component Structural Interface (public non-virtual). ///@} /** Optional method for generating arbitrary display geometry that reflects this %Component at the specified \a state. This will be called once to obtain ground- and body-fixed geometry (with \a fixed=\c true), and then once per frame (with \a fixed=\c false) to generate on-the-fly geometry such as rubber band lines, force arrows, labels, or debugging aids. Please note that there is a precondition that the state passed in to generateDecorations be realized to Stage::Position. If your component can visualize quantities realized at Velocity, Dynamics or Acceleration stages, then you must check that the stage has been realized before using/requesting stage dependent values. It is forbidden to realize the model to a higher stage within generateDecorations, because this can trigger costly side- effects such as evaluating all model forces even when performing a purely kinematic study. If you override this method, be sure to invoke the base class method first, using code like this: @code void MyComponent::generateDecorations (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 // can render velocity dependent quanities if stage is Velocity or higher if(state.getSystemStage() >= Stage::Velocity) { // draw velocity vector for model COM } // can render computed forces if stage is Dynamics or higher if(state.getSystemStage() >= Stage::Dynamics) { // change the length of a force arrow based on the force in N } } @endcode @param[in] fixed If \c true, generate only geometry that is fixed to a PhysicalFrame, configuration, and velocity. Otherwise generate only such dependent geometry. @param[in] hints See 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. @param[in] state The State for which geometry should be produced. See below for more information. @param[in,out] appendToThis %Array to which generated geometry should be \e appended via the \c push_back() method. When called with \a fixed=\c 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 \a state through Instance stage. When called with \a fixed=\c false, you may consult any relevant value in \a state. However, to avoid unnecessary computation, OpenSim guarantees only that \a state will have been realized through Position stage; if you need anything higher than that (reaction forces, for example) you should make sure the \a state is realized through Acceleration stage. **/ virtual void generateDecorations (bool fixed, const ModelDisplayHints& hints, const SimTK::State& state, SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const {}; /** * Get the underlying MultibodySystem that this component is connected to. * Make sure you have called Model::initSystem() prior to accessing the System. * Throws an Exception if the System has not been created or the Component * has not added itself to the System. * @see hasSystem(). */ const SimTK::MultibodySystem& getSystem() const { // This method is inlined because it is called *a lot* at runtime OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem); return _system.getRef(); } /** * Check if this component has an underlying MultibodySystem. * Returns false if the System has not been created OR if this * Component has not added itself to the System. */ bool hasSystem() const { return !_system.empty(); } /** Does the provided component already exist anywhere in the ownership * tree (not just subcomponents of this component)? */ bool isComponentInOwnershipTree(const Component* component) const; /** * Add a Component (as a subcomponent) of this component. * This component takes ownership of the subcomponent and it will be * serialized (appear in XML) as part of this component. Specifically, * it will appear in the `<components>` list for this Component. * If the subcomponent is already owned by this component or exists * in the same hierarchy (tree) as this component, an Exception * is thrown. * @note addComponent is intended to replace existing addBody(), addJoint, * ... on Model or the requirement for specific add###() methods to * subcomponents to a Component. * * Typical usage is: @code // Start with an empty Model (which is a Component) Model myModel; // Create any Component type on the heap Body* newBody = new Body(); // Customize the Component by setting its properties newBody->setName("newBody"); newBody->setMass(10.0); newBody->setMassCenter(SimTK::Vec3(0)); // ... // Now add it to your model, which will take ownership of it myModel.addComponent(newBody); // // Keep creating and adding new components, like Joints, Forces, etc.. @endcode * * @throws ComponentAlreadyPartOfOwnershipTree * @param subcomponent is the Component to be added. */ void addComponent(Component* subcomponent); /** * Get an iterator through the underlying subcomponents that this component is * composed of. The hierarchy of Components/subComponents forms a tree. * The order of the Components is that of tree preorder traversal so that a * component is traversed before its subcomponents. * * @code{.cpp} * for (const auto& muscle : model.getComponentList<Muscle>()) { * muscle.get_max_isometric_force(); * } * @endcode * * The returned ComponentList does not permit modifying any components; if * you want to modify the components, see updComponentList(). * * @tparam T A subclass of Component (e.g., Body, Muscle). */ template <typename T = Component> ComponentList<const T> getComponentList() const { static_assert(std::is_base_of<Component, T>::value, "Template argument must be Component or a derived class."); initComponentTreeTraversal(*this); return ComponentList<const T>(*this); } /** Similar to getComponentList(), except the resulting list allows one to modify the components. For example, you could use this method to change the max isometric force of all muscles: @code{.cpp} for (auto& muscle : model.updComponentList<Muscle>()) { muscle.set_max_isometric_force(...); } @endcode @note Do NOT use this method to add (or remove) (sub)components from any component. The tree structure of the components should not be altered through this ComponentList. @tparam T A subclass of Component (e.g., Body, Muscle). */ template <typename T = Component> ComponentList<T> updComponentList() { static_assert(std::is_base_of<Component, T>::value, "Template argument must be Component or a derived class."); initComponentTreeTraversal(*this); clearObjectIsUpToDateWithProperties(); return ComponentList<T>(*this); } /** * Uses getComponentList<T>() to count the number of underlying * subcomponents of the specified type. * * @tparam T A subclass of Component (e.g., Body, Muscle). */ template <typename T = Component> unsigned countNumComponents() const { unsigned count = 0u; const auto compList = getComponentList<T>(); auto it = compList.begin(); while (it != compList.end()) { ++count; ++it; } return count; } /** Class that permits iterating over components/subcomponents (but does * not actually contain the components themselves). */ template <typename T> friend class ComponentList; /** Class to iterate over ComponentList returned by getComponentList(). */ template <typename T> friend class ComponentListIterator; /** Get the complete (absolute) pathname for this Component to its ancestral * Component, which is the root of the tree to which this Component belongs. * For example: a Coordinate Component would have an absolute path name * like: `/arm26/elbow_r/flexion`. Accessing a Component by its * absolutePathName from root is guaranteed to be unique. The * absolutePathName is generated on-the-fly by traversing the ownership tree * and, therefore, calling this method is not "free". */ std::string getAbsolutePathString() const; /** Return a ComponentPath of the absolute path of this Component. * Note that this has more overhead than calling `getName()` because * it traverses up the tree to generate the absolute pathname (and its * computational cost is thus a function of depth). Consider other * options if this is repeatedly called and efficiency is important. * For instance, `getAbsolutePathString()` is faster if you only * need the path as a string. */ ComponentPath getAbsolutePath() const; /** Get the relative path of this Component with respect to another * Component, as a string. */ std::string getRelativePathString(const Component& wrt) const; /** Get the relative path of this Component with respect to another * Component. */ ComponentPath getRelativePath(const Component& wrt) const; /** Query if there is a component (of any type) at the specified * path name. For example, * @code * bool exists = model.hasComponent("right_elbow/elbow_flexion"); * @endcode * checks if `model` has a subcomponent "right_elbow," which has a * subcomponent "elbow_flexion." */ bool hasComponent(const std::string& pathname) const { return hasComponent<Component>(pathname); } /** Query if there is a component of a given type at the specified * path name. For example, * @code * bool exists = model.hasComponent<Coordinate>("right_elbow/elbow_flexion"); * @endcode * checks if `model` has a subcomponent "right_elbow," which has a * subcomponent "elbow_flexion," and that "elbow_flexion" is of type * Coordinate. This method cannot be used from scripting; see the * non-templatized hasComponent(). */ template <class C = Component> bool hasComponent(const std::string& pathname) const { static_assert(std::is_base_of<Component, C>::value, "Template parameter 'C' must be derived from Component."); const C* comp = this->template traversePathToComponent<C>({pathname}); return comp != nullptr; } /** * Get a unique subcomponent of this Component by its path name and type 'C'. * Throws ComponentNotFoundOnSpecifiedPath exception if the component at * that path name location does not exist OR it is not of the correct type. * For example, * @code * auto& coord = model.getComponent<Coordinate>("right_elbow/elbow_flexion"); * @endcode * returns coord which is a Coordinate named "elbow_flexion" from a Joint * named "right_elbow" given it is a child of the Component (Model) model. * If unsure of a Component's path or whether or not it exists in the model, * use printComponentsMatching() or hasComponent(). * * This template function cannot be used in Python/Java/MATLAB; see the * non-templatized getComponent(). * * @param pathname a pathname of a Component of interest * @return const reference to component of type C at * @throws ComponentNotFoundOnSpecifiedPath if no component exists */ template <class C = Component> const C& getComponent(const std::string& pathname) const { return getComponent<C>(ComponentPath(pathname)); } template <class C = Component> const C& getComponent(const ComponentPath& pathname) const { static_assert(std::is_base_of<Component, C>::value, "Template parameter 'CompType' must be derived from Component."); const C* comp = this->template traversePathToComponent<C>(pathname); if (comp) { return *comp; } // Only error cases remain OPENSIM_THROW(ComponentNotFoundOnSpecifiedPath, pathname.toString(), C::getClassName(), getName()); } /** Similar to the templatized getComponent(), except this returns the * component as the generic Component type. This can be used in * Python/Java/MATLAB. Here is an example of using this in MATLAB: * @code * coord = model.getComponent('right_elbow/elbow_flexion') * coord.getNumConnectees() % okay; this is a Component method. * coord.getDefaultClamped() % inaccessible; method on Coordinate. * Coordinate.safeDownCast(coord).getDefaultClamped() % now accessible. * @endcode * * %Exception: in Python, you will get the concrete type (in most cases): * @code{.py} * coord = model.getComponent('right_elbow/elbow_flexion') * coord.getDefaultClamped() # works; no downcasting necessary. * @endcode */ const Component& getComponent(const std::string& pathname) const { return getComponent<Component>(pathname); } /** Get a writable reference to a subcomponent. Use this method * to edit the properties and connections of the subcomponent. * Note: the method will mark this Component as out-of-date with * its properties and will require finalizeFromProperties() to be * invoked directly or indirectly (by finalizeConnections() or * Model::initSystem()) * @param name the pathname of the Component of interest * @return Component the component of interest * @throws ComponentNotFoundOnSpecifiedPath if no component exists * @see getComponent() */ template <class C = Component> C& updComponent(const std::string& name) { return updComponent<C>(ComponentPath(name)); } template <class C = Component> C& updComponent(const ComponentPath& name) { clearObjectIsUpToDateWithProperties(); return *const_cast<C*>(&(this->template getComponent<C>(name))); } /** Similar to the templatized updComponent(), except this returns the * component as the generic Component type. As with the non-templatized * getComponent(), though, this will give the concrete type in Python in * most cases. * @see getComponent() */ Component& updComponent(const std::string& pathname) { constructOutputs(); } /** @name Component 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 Components. @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 Component::xxx() and going down. The base class implementations here do two things: (1) take care of any needs of the %Component base class itself, and then (2) ensure that the corresponding calls are made to any subcomponents that have been specified by derived %Component objects, via calls to the addComponent() method. So assuming that your concrete %Component and all intermediate classes from * /leg_model/left_hip/rotation * @endverbatim * * @returns The number of matches. */ unsigned printComponentsMatching(const std::string& substring) const; /** * Get the number of "continuous" state variables maintained by the * Component and its subcomponents. * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ int getNumStateVariables() const; /** * Get the names of "continuous" state variables maintained by the Component * and its subcomponents. * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ Array<std::string> getStateVariableNames() const; /** @name Component Socket Access methods Access Sockets of this component by name. */ //@{ /** Get the number of Sockets in this Component. */ int getNumSockets() const { return int(_socketsTable.size()); } /** Collect and return the names of the sockets in this component. You * can use this to iterate through the sockets: * @code * for (std::string name : comp.getSocketNames()) { * const AbstractSocket& socket = getSocket(name); * } * @endcode */ std::vector<std::string> getSocketNames() const { std::vector<std::string> names; for (const auto& it : _socketsTable) { names.push_back(it.first); } return names; } /** * Get the "connectee" object that the Component's Socket * is bound to. Guaranteed to be valid only after the Component * has been connected (that is connect() has been invoked). * If the Socket has not been connected, an exception is thrown. * * This method is for getting the concrete connectee object, and is not * available in scripting. If you want generic access to the connectee as an * Object, use the non-templated version. /** Invoke connect() on the (sub)components of this Component.*/ void componentsConnect(Component& root) const; /** Opportunity to remove connection related information. If you override this method, be sure to invoke the base class method first, using code like this : * @code * const PhysicalFrame& frame = joint.getConnectee<PhysicalFrame>("parent_frame"); * frame.getMobilizedBody(); * @endcode */ } @endcode */ //virtual void extendDisconnect() {}; /** Add appropriate Simbody elements (if needed) to the System corresponding to this component and specify needed state resources. } /** Get the connectee as an Object. This means you will not have * access to the methods on the concrete connectee. This is the method you * must use in MATLAB to access the connectee. * * Example: * @code{.cpp} * const Object& obj = joint.getConnectee("parent_frame"); * obj.getName(); // method on Object works. * obj.getMobilizedBody(); // error: not available. * @endcode * * In MATLAB, if you want the concrete type, you need to downcast the * Object. Here is an example where you know the "parent_frame" is a Body: * @code * f = joint.getConnectee('parent_frame'); * m = Body.safeDownCast(f).getMass(); * @endcode * * Exception: in Python, you will get the concrete type (in most cases): * @code{.py} * f = joint.getConnectee("parent_frame"); * m = f.getMass() # works (if the parent frame is a body) * @endcode */ const Object& getConnectee(const std::string& name) const { const AbstractSocket& socket = getSocket(name); OPENSIM_THROW_IF_FRMOBJ(!socket.isConnected(), Exception, "Socket '" + name + "' not connected."); return socket.getConnecteeAsObject(); } /** Get an AbstractSocket for the given socket name. This * lets you get information about the connection (like if the socket is * connected), but does not give you access to the socket's connectee. * For that, use getConnectee(). * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Socket (to tell it which * component it's in) before providing it to you. * * <b>C++ example</b> * @code{.cpp} * model.getComponent("/path/to/component").getSocket("socketName"); * @endcode */ const AbstractSocket& getSocket(const std::string& name) const { auto it = _socketsTable.find(name); if (it != _socketsTable.end()) { // The following allows one to use a Socket immediately after // copying the component; // e.g., myComponent.clone().getSocket("a").getConnecteePath(). // Since we use the default copy constructor for Component, // the copied AbstractSocket cannot know its new owner // immediately after copying. if (!it->second->hasOwner()) { // The `this` pointer must be non-const because the Socket // will want to be able to modify the connectee path property. const_cast<AbstractSocket*>(it->second.get())->setOwner( const_cast<Self&>(*this)); } return it->second.getRef(); } OPENSIM_THROW_FRMOBJ(SocketNotFound, name); } /** Get a writable reference to the AbstractSocket for the given * socket name. Use this method to connect the Socket to something. * * <b>C++ example</b> * @code * joint.updSocket("parent_frame").connect(model.getGround()); * @endcode * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Socket (to tell it which * component it's in) before providing it to you. */ AbstractSocket& updSocket(const std::string& name) { return const_cast<AbstractSocket&>(getSocket(name)); } /** * Get a const reference to the concrete Socket provided by this * Component by name. * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Socket (to tell it which * component it's in) before providing it to you. * * @param name the name of the Socket * @return const reference to the (Abstract)Socket */ template<typename T> const Socket<T>& getSocket(const std::string& name) const { return Socket<T>::downcast(getSocket(name)); } /** * Get a writable reference to the concrete Socket provided by this * Component by name. * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Socket (to tell it which * component it's in) before providing it to you. * * @param name the name of the Socket * @return const reference to the (Abstract)Socket */ template<typename T> Socket<T>& updSocket(const std::string& name) { return const_cast<Socket<T>&>(getSocket<T>(name)); } //@} end of Component Socket Access methods /** @name Component Inputs and Outputs Access methods Access inputs and outputs by name and iterate over all outputs. */ //@{ /** Access the number of Inputs that this component has. */ int getNumInputs() const { return int(_inputsTable.size()); } /** Access the number of Outputs that this component has. */ int getNumOutputs() const { return int(_outputsTable.size()); } const std::string& name, double deriv) const; // End of Model Component Basic Interface (protected virtuals). //@} /** @name Component 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 /** Collect and return the names of Outputs in this component as an * std::vector. */ std::vector<std::string> getOutputNames() const { std::vector<std::string> names; for (const auto& entry : getOutputs()) { names.push_back(entry.first); } return names; } /** * Get an Input provided by this Component by name. * * <b>C++ example:</b> get an Input from a Component in the model * @code{.cpp} * model.getComponent("/path/to/component").getInput("inputName"); * @endcode * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Input (to tell it which * component it's in) before providing it to you. * * @param name the name of the Input * @return const reference to the AbstractInput */ const AbstractInput& getInput(const std::string& name) const { auto it = _inputsTable.find(name); if (it != _inputsTable.end()) { // The following allows one to use an Input immediately after // copying the component; // e.g., myComponent.clone().getInput("a").getConnecteePath(). // Since we use the default copy constructor for Component, // the copied AbstractSocket (base class of AbstractInput) // cannot know its new owner immediately after copying. if (!it->second->hasOwner()) { // The `this` pointer must be non-const because the Socket // will want to be able to modify the connectee_name property. const_cast<AbstractInput*>(it->second.get())->setOwner( const_cast<Self&>(*this)); } return it->second.getRef(); } OPENSIM_THROW_FRMOBJ(InputNotFound, name); } /** * Get a writable reference to an Input provided by this Component by name. * * <b>C++ example:</b> get a writable reference to an Input of a * Component in a model * @code{.cpp} * model.updComponent("/path/to/component").updInput("inputName"); * @endcode * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Input (to tell it which * component it's in) before providing it to you. * @param name the name of the Input * @return reference to the AbstractInput */ AbstractInput& updInput(const std::string& name) { return *const_cast<AbstractInput *>(&getInput(name)); } /** * Get a concrete Input that you can directly ask for its values. * * @internal If you have not yet called finalizeFromProperties() on this * component, this function will update the Input (to tell it which * component it's in) before providing it to you. * * @param name the name of the Input * @throws Exception if an Input with the given name does not exist. * @throws std::bad_cast if the provided type T is incorrect for the given name. */ template<typename T> const Input<T>& getInput(const std::string& name) const { return dynamic_cast<const Input<T>&>(getInput(name)); } /** * Get the Output provided by this Component by name. * * <b>C++ example:</b> get an Output from a Component in a model * @code{.cpp} * model.getComponent("/path/to/component").getOutput("outputName"); * @endcode * * @param name the name of the Output * @return const reference to the AbstractOutput */ const AbstractOutput& getOutput(const std::string& name) const { auto it = _outputsTable.find(name); if (it != _outputsTable.end()) { return it->second.getRef(); } OPENSIM_THROW_FRMOBJ(OutputNotFound, name); } /** * Get a writable reference to an Output provided by this Component by name. * * <b>C++ example:</b> get a writable reference to an Output of a * Component in a model * @code{.cpp} * model.updComponent("/path/to/component").updOutput("outputName"); * @endcode * @param name the name of the Output * @return reference to the AbstractOutput */ AbstractOutput& updOutput(const std::string& name) { return *const_cast<AbstractOutput *>(&getOutput(name)); } /** Define OutputConstIterator for convenience */ typedef std::map<std::string, SimTK::ClonePtr<AbstractOutput>>:: const_iterator OutputConstIterator; /** Iterate through all Outputs of this component. The intent is to use * this in a loop as such: * @code * for (const auto& entry : comp.getOutputs()) { * const std::string& name = entry.first; * const AbstractOutput* output = entry.second.get(); * std::cout << output->getTypeName() << std::endl; * } * @endcode * This provides access to the outputs as AbstractOutput%s, not as the * concrete type. This also does not permit modifying the outputs. * * Not available in Python/Java/MATLAB; use getOutputNames() and * getOutput() instead. */ SimTK::IteratorRange<OutputConstIterator> getOutputs() const { return {_outputsTable.cbegin(), _outputsTable.cend()}; } //@} end of Component Inputs and Outputs Access methods /** @name Component State Access methods Get and set modeling option, input and output values, state variable, discrete and/or cache variables in the State. */ //@{ /** * Get a ModelingOption flag for this Component by name. * The flag is an integer corresponding to the index of modelingOptionNames used * add the modeling option to the component. @see addModelingOption * * @param state the State in which to set the modeling option * @param name the name (string) of the modeling option of interest * @return flag integer value for modeling option */ int getModelingOption(const SimTK::State& state, const std::string& name) const; /** * %Set the value of a ModelingOption flag for this Component. * 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. * * @param state the State in which to set the flag * @param name the name (string) of the modeling option of interest * @param flag the desired flag (int) value specifying the modeling option */ void setModelingOption(SimTK::State& state, const std::string& name, int flag) const; /** * Get the Input value that this component is dependent on. * Checks if Input is connected, otherwise it will throw an * exception. You can only call this method for non-list inputs. * For list inputs, you must get the input using getInput(), * from which you can ask for its values. * * @param state the State for which to set the value * @param name the name of the input * @return T const Input value */ template<typename T> const T& getInputValue(const SimTK::State& state, const std::string& name) const { // get the input and check if it is connected. const AbstractInput& in = getInput(name); // TODO could maybe remove this check and have the Input do it. Or, // here, we could catch Input's exception and give a different message. if (in.isConnected()) { return (Input<T>::downcast(in)).getValue(state); } else { std::stringstream msg; msg << "Component::getInputValue: ERR- Input '" << name << "' not connected.\n " << "for component '" << getName() << "' of type "<< getConcreteClassName(); throw Exception(msg.str(), __FILE__, __LINE__); } } /** * Get the Output value provided by this Component by name. * * @param state the State for which to set the value * @param name the name of the cache variable * @return T const Output value */ template<typename T> const T& getOutputValue(const SimTK::State& state, const std::string& name) const { return (Output<T>::downcast(getOutput(name))).getValue(state); } /** * Get the value of a state variable allocated by this Component. * * To connect this StateVariable as an input to another component (such as * a Reporter), use getOutput(name); each state variable has a * corresponding Output: * @code * foo.getInput("input1").connect(bar.getOutput(name)); * @endcode * * @param state the State for which to get the value * @param name the name (string) of the state variable of interest * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ double getStateVariableValue(const SimTK::State& state, const std::string& name) const; /** * Get the value of a state variable allocated by this Component. * * To connect this StateVariable as an input to another component (such as * a Reporter), use getOutput(name); each state variable has a * corresponding Output: * * @code * foo.getInput("input1").connect(bar.getOutput(name)); * @endcode * * @param state the State for which to get the value * @param name path to the state variable of interest * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ double getStateVariableValue(const SimTK::State& state, const ComponentPath& path) const; /** * %Set the value of a state variable allocated by this Component by name. * * @param state the State for which to set the value * @param name the name of the state variable * @param value the value to set * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ void setStateVariableValue(SimTK::State& state, const std::string& name, double value) const; /** * Get all values of the state variables allocated by this Component. * Includes state variables allocated by its subcomponents. * * @param state the State for which to get the value * @return Vector of state variable values of length getNumStateVariables() * in the order returned by getStateVariableNames() * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ SimTK::Vector getStateVariableValues(const SimTK::State& state) const; /** * %Set all values of the state variables allocated by this Component. * Includes state variables allocated by its subcomponents. Note, this * method simply sets the values on the input State. If other conditions * must be met (such as satisfying kinematic constraints for Coordinates, * or fiber and tendon equilibrium for muscles) you must invoke the * appropriate methods on Model (e.g. assemble() to satisfy constraints or * equilibrateMuscles()) to satisfy these conditions starting from the * State values provided by setStateVariableValues. * * @param state the State whose values are set * @param values Vector of state variable values of length * getNumStateVariables() in the order returned by * getStateVariableNames() * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ void setStateVariableValues(SimTK::State& state, const SimTK::Vector& values) const; /** * Get the value of a state variable derivative computed by this Component. * * @param state the State for which to get the derivative value * @param name the name (string) of the state variable of interest * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ double getStateVariableDerivativeValue(const SimTK::State& state, const std::string& name) const; /** * Get the value of a discrete variable allocated by this Component by name. * * @param state the State from which to get the value * @param name the name of the state variable * @return value the discrete variable value * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ double getDiscreteVariableValue(const SimTK::State& state, const std::string& name) const; /** * %Set the value of a discrete variable allocated by this Component by name. * * @param state the State for which to set the value * @param name the name of the discrete variable * @param value the value to set * @throws ComponentHasNoSystem if this Component has not been added to a * System (i.e., if initSystem has not been called) */ void setDiscreteVariableValue(SimTK::State& state, const std::string& name, double value) const; /** * A cache variable containing a value of type T. * * - A `CacheVariable` is a handle to the cache variable's value and * validity * * - Derived classes may declare `CacheVariable` members (ideally, * as `private` members), which grants them strongly-typed access * to cache variable values * * - `CacheVariable` should be initialized with * `Component::addCacheVariable`; usually, in the * `Component::extendAddToSystem` method. A cache variable's value * will not be valid until after `Component::realizeTopology` is * called * * @tparam T * Type of data held in the cache variable */ template<class T> class CacheVariable { private: std::string name; // this is initialized in Component::getCacheVariableIndex. It enhances // performance by skipping using `name` to perform runtime map lookups. mutable SimTK::ResetOnCopy<SimTK::CacheEntryIndex> maybeUninitIndex{ SimTK::InvalidIndex }; friend class Component; explicit CacheVariable(std::string _name) : name{std::move(_name)} { } public: // A default constructor is required for user-facing impl. because // derived classes might not be able to fully initialize an instance // at construction time (e.g. via member initialization). // // Usage of a partially-initialized CacheVariable is invalid. The way // that this is dealt with is by checking for errors at runtime: // // - CacheVariable will default-initialize with a name of "", which is // disallowed by `Component::addCacheVariable`. Therefore, if a // CacheVariable instance has an empty name, it was not initialized. // // - The index is default-initialized, and copy constructed, with an // invalid (erroring) index, so derived classes can't alias // cache variables by copying this class around. CacheVariable() = default; }; protected: /** * Add a state cache entry belonging to this Component 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 momentum, which is dependent on position and velocity * states, should have Stage::Velocity as its \a 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. * * @param[in] name * The name you are assigning to this cache entry. Must be unique within * this model component. * * @param[in] variablePrototype * An object defining the type of value, and a default value of that type, * to be
{'commit': 'diff --git a/OpenSim/Common/Component.h b/OpenSim/Common/Component.h\nindex cb7b47b31..79b87f099 100644\n--- a/OpenSim/Common/Component.h\n+++ b/OpenSim/Common/Component.h\n@@ -216,6 +216,20 @@ public:\n     /** Destructor is virtual to allow concrete Component to cleanup. **/\n     virtual ~Component() {}\n \n+\n+    /** @name Component Structural Interface\n+    The structural interface ensures that deserialization, resolution of \n+    inter-connections, and handling of dependencies are performed systematically\n+    and prior to system creation, followed by allocation of necessary System\n+    resources. These methods can be extended by virtual methods that form the\n+    Component Extension Interface (e.g. #extendFinalizeFromProperties) \n+    that can be implemented by subclasses of Components.\n+\n+    Component ensures that the corresponding calls are propogated to all of its\n+    (sub)components. */\n+\n+    //@{\n+\n     /** Update Component\'s internal data members based on properties.\n         Marks the Component as up to date with its properties. */\n     void finalizeFromProperties();\n@@ -237,6 +251,9 @@ public:\n     /** Set Component\'s properties given a state. */\n     void setPropertiesFromState(const SimTK::State& state);\n \n+    // End of Component Structural Interface (public non-virtual).\n+    //@} \n+\n     /**\n      * Get the underlying MultibodySystem that this component is connected to.\n      */\n@@ -275,6 +292,7 @@ public:\n      */\n     Array<std::string> getStateVariableNames() const;\n \n+\n     /** @name Component Connector Access methods\n         Access Connectors of this component in a generic way and also by name.\n     */\n@@ -805,20 +823,18 @@ template <class T> friend class ComponentMeasure;\n         constructOutputs();\n     }\n \n-    /** @name           Component Basic Interface\n+    /** @name  Component Extension Interface\n     The interface ensures that deserialization, resolution of inter-connections,\n     and handling of dependencies are performed systematically and prior to \n     system creation, followed by allocation of necessary System resources. These \n     methods are virtual and may be implemented by subclasses of \n     Components. \n     \n-    @note Every implementation of virtual method xxx(args) must begin\n-    with the line "Super::xxx(args);" to ensure that the parent class methods\n-    execute before the child class method, starting with Component::xxx()\n-    and going down. \n+    @note Every implementation of virtual extend method xxx(args) must begin\n+    with the line "Super::extend<xxx>(args);" to ensure that the parent class\n+    is called before the child class method.\n     \n-    The base class implementations here do two things: (1) take care of any\n-    needs of the %Component base class itself, and then (2) ensure that the \n+    The base class implementations ensures that the \n     corresponding calls are made to any subcomponents that have been specified \n     by derived %Component objects, via calls to the addComponent() method. \n     So assuming that your concrete %Component and all intermediate classes from\n@@ -880,6 +896,7 @@ template <class T> friend class ComponentMeasure;\n     /** Invoke connect() on the (sub)components of this Component.*/\n     void componentsConnect(Component& root) const;\n \n+    ///@cond\n     /** Opportunity to remove connection related information. \n     If you override this method, be sure to invoke the base class method first,\n     using code like this :\n@@ -891,7 +908,7 @@ template <class T> friend class ComponentMeasure;\n     }\n     @endcode  */\n     //virtual void extendDisconnect() {};\n-\n+    ///@endcond\n \n     /** Add appropriate Simbody elements (if needed) to the System \n     corresponding to this component and specify needed state resources. \n@@ -1029,10 +1046,10 @@ template <class T> friend class ComponentMeasure;\n                             const std::string& name, double deriv) const;\n \n \n-    // End of Model Component Basic Interface (protected virtuals).\n+    // End of Component Extension Interface (protected virtuals).\n     //@} \n \n-    /** @name           Component Advanced Interface\n+    /** @name  Component Advanced Interface\n     You probably won\'t need to override methods in this section. These provide\n     a way for you to perform computations ("realizations") that must be \n     scheduled in carefully-ordered stages as described in the class description\n', 'commit_subject': 'Update to comments.', 'repo_name': 'opensim-org/opensim-core', 'committer': {'name': 'Ajay Seth', 'email': 'b506629e4698a937c5166aa6069ad6008e969ba5@stanford.edu', 'time_sec': '1415318632', 'tz_offset': '-480', 'date': {'seconds': '1415318632'}}, 'commit_tree': '977d81700c1d068d651e04a980359b8e210ab75a', 'commit_message': 'Update to comments.\n', 'language_name': 'Python', 'license': 'apache-2.0', 'hunks': '@@ -216,6 +216,20 @@ public:\n     /** Destructor is virtual to allow concrete Component to cleanup. **/\n     virtual ~Component() {}\n \n+\n+    /** @name Component Structural Interface\n+    The structural interface ensures that deserialization, resolution of \n+    inter-connections, and handling of dependencies are performed systematically\n+    and prior to system creation, followed by allocation of necessary System\n+    resources. These methods can be extended by virtual methods that form the\n+    Component Extension Interface (e.g. #extendFinalizeFromProperties) \n+    that can be implemented by subclasses of Components.\n+\n+    Component ensures that the corresponding calls are propogated to all of its\n+    (sub)components. */\n+\n+    //@{\n+\n     /** Update Component\'s internal data members based on properties.\n         Marks the Component as up to date with its properties. */\n     void finalizeFromProperties();\n@@ -237,6 +251,9 @@ public:\n     /** Set Component\'s properties given a state. */\n     void setPropertiesFromState(const SimTK::State& state);\n \n+    // End of Component Structural Interface (public non-virtual).\n+    //@} \n+\n     /**\n      * Get the underlying MultibodySystem that this component is connected to.\n      */\n@@ -275,6 +292,7 @@ public:\n      */\n     Array<std::string> getStateVariableNames() const;\n \n+\n     /** @name Component Connector Access methods\n         Access Connectors of this component in a generic way and also by name.\n     */\n@@ -805,20 +823,18 @@ template <class T> friend class ComponentMeasure;\n         constructOutputs();\n     }\n \n-    /** @name           Component Basic Interface\n+    /** @name  Component Extension Interface\n     The interface ensures that deserialization, resolution of inter-connections,\n     and handling of dependencies are performed systematically and prior to \n     system creation, followed by allocation of necessary System resources. These \n     methods are virtual and may be implemented by subclasses of \n     Components. \n     \n-    @note Every implementation of virtual method xxx(args) must begin\n-    with the line "Super::xxx(args);" to ensure that the parent class methods\n-    execute before the child class method, starting with Component::xxx()\n-    and going down. \n+    @note Every implementation of virtual extend method xxx(args) must begin\n+    with the line "Super::extend<xxx>(args);" to ensure that the parent class\n+    is called before the child class method.\n     \n-    The base class implementations here do two things: (1) take care of any\n-    needs of the %Component base class itself, and then (2) ensure that the \n+    The base class implementations ensures that the \n     corresponding calls are made to any subcomponents that have been specified \n     by derived %Component objects, via calls to the addComponent() method. \n     So assuming that your concrete %Component and all intermediate classes from\n@@ -880,6 +896,7 @@ template <class T> friend class ComponentMeasure;\n     /** Invoke connect() on the (sub)components of this Component.*/\n     void componentsConnect(Component& root) const;\n \n+    ///@cond\n     /** Opportunity to remove connection related information. \n     If you override this method, be sure to invoke the base class method first,\n     using code like this :\n@@ -891,7 +908,7 @@ template <class T> friend class ComponentMeasure;\n     }\n     @endcode  */\n     //virtual void extendDisconnect() {};\n-\n+    ///@endcond\n \n     /** Add appropriate Simbody elements (if needed) to the System \n     corresponding to this component and specify needed state resources. \n@@ -1029,10 +1046,10 @@ template <class T> friend class ComponentMeasure;\n                             const std::string& name, double deriv) const;\n \n \n-    // End of Model Component Basic Interface (protected virtuals).\n+    // End of Component Extension Interface (protected virtuals).\n     //@} \n \n-    /** @name           Component Advanced Interface\n+    /** @name  Component Advanced Interface\n     You probably won\'t need to override methods in this section. These provide\n     a way for you to perform computations ("realizations") that must be \n     scheduled in carefully-ordered stages as described in the class description\n', 'addition_count': 27, 'deletion_count': 10, 'src_file': 'a/OpenSim/Common/Component.h', 'tgt_file': 'b/OpenSim/Common/Component.h', 'file_extension': '.h', 'before_file': '#ifndef OPENSIM_COMPONENT_H_\n#define OPENSIM_COMPONENT_H_\n/* -------------------------------------------------------------------------- *\n *                             OpenSim: Component.h                           *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *\n * See http://opensim.stanford.edu and the NOTICE file for more information.  *\n * OpenSim is developed at Stanford University and supported by the US        *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *\n * through the Warrior Web program.                                           *\n *                                                                            *\n * Copyright (c) 2005-2017 Stanford University and the Authors                *\n * Author(s): Ajay Seth                                                       *\n *                                                                            *\n * Licensed under the Apache License, Version 2.0 (the "License"); you may    *\n * not use this file except in compliance with the License. You may obtain a  *\n * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *\n *                                                                            *\n * Unless required by applicable law or agreed to in writing, software        *\n * distributed under the License is distributed on an "AS IS" BASIS,          *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *\n * See the License for the specific language governing permissions and        *\n * limitations under the License.                                             *\n * -------------------------------------------------------------------------- */\n\n/** @file\n * This file defines the abstract Component class, which is used to add\n * computational components to the underlying SimTK::System (MultibodySystem).\n * It specifies the interface that components must satisfy in order to be part\n * of the system and provides a series of helper methods for adding variables\n * (state, discrete, cache, ...) to the underlying system. As such,\n * Component handles all of the bookkeeping for variable indices and\n * provides convenience access via variable names. Furthermore, a component\n * embodies constructs of inputs, outputs and connections that are useful in\n * composing computational systems.\n *\n * A component may contain one or more underlying Simbody multibody system\n * elements (MobilizedBody, Constraint, Force, or Measure) which are part of\n * a SimTK::Subsystem. A SimTK::Subsystem is where new variables are\n * allocated. A Component, by default, uses the System\'s DefaultSubsystem.\n * for allocating new variables.\n */\n\n// INCLUDES\n#include "ComponentList.h"\n#include "ComponentPath.h"\n#include "Logger.h"\n#include "OpenSim/Common/Array.h"\n#include "OpenSim/Common/ComponentOutput.h"\n#include "OpenSim/Common/ComponentSocket.h"\n#include "OpenSim/Common/Object.h"\n#include "simbody/internal/MultibodySystem.h"\n#include <unordered_map>\n\n#include <OpenSim/Common/osimCommonDLL.h>\n\nnamespace OpenSim {\n\nclass Model;\nclass ModelDisplayHints;\n\n//==============================================================================\n/// Component Exceptions\n//==============================================================================\nclass ComponentHasNoName : public Exception {\npublic:\n    ComponentHasNoName(const std::string& file,\n        size_t line,\n        const std::string& func,\n        const std::string& componentConcreteClassName) :\n        Exception(file, line, func) {\n        std::string msg = componentConcreteClassName;\n        msg += " was constructed with no name.\\n";\n        msg += "Please assign a valid name and try again.";\n        addMessage(msg);\n    }\n};\n\nclass InvalidComponentName : public Exception {\npublic:\n    InvalidComponentName(const std::string& file,\n        size_t line,\n        const std::string& func,\n        const std::string& thisName,\n        const std::string& invalidChars,\n        const std::string& componentConcreteClassName) :\n        Exception(file, line, func) {\n        std::string msg = "Component \'" + thisName + "\' of type " +\n            componentConcreteClassName + " contains invalid characters of: \'" +\n            invalidChars + "\'.";\n        addMessage(msg);\n    }\n};\n\nclass ComponentNotFoundOnSpecifiedPath : public ComponentNotFound {\npublic:\n    ComponentNotFoundOnSpecifiedPath(const std::string& file,\n        size_t line,\n        const std::string& func,\n        const std::string& toFindName,\n        const std::string& toFindClassName,\n        const std::string& thisName) :\n        ComponentNotFound(file, line, func) {\n        std::string msg = "Component \'" + thisName;\n        msg += "\' could not find \'" + toFindName;\n        msg += "\' of type " + toFindClassName + ". ";\n        msg += "Make sure a component exists at this path and that it is of ";\n        msg += "the correct type.";\n        addMessage(msg);\n    }\n};\n\nclass ComponentIsAnOrphan : public Exception {\npublic:\n    ComponentIsAnOrphan(const std::string& file,\n        size_t line,\n        const std::string& func,\n        const std::string& thisName,\n        const std::string& componentConcreteClassName) :\n        Exception(file, line, func) {\n        std::string msg = "Component \'" + thisName + "\' of type " +\n            componentConcreteClassName + " has no owner and is not the root.\\n" +\n            "Verify that finalizeFromProperties() has been invoked on the " +\n            "root Component or that this Component is not a clone, which has " +\n            "not been added to another Component.";\n        addMessage(msg);\n    }\n};\n\nclass SubcomponentsWithDuplicateName : public Exception {\npublic:\n    SubcomponentsWithDuplicateName(const std::string& file,\n        size_t line,\n        const std::string& func,\n        const std::string& thisName,\n        const std::string& duplicateName) :\n        Exception(file, line, func) {\n        std::string msg = "Component \'" + thisName + "\' has subcomponents " +\n            "with duplicate name \'" + duplicateName + "\'. "\n            "Please supply unique names for immediate subcomponents.";\n        addMessage(msg);\n    }\n};\n\nclass ComponentIsRootWithNoSubcomponents : public Exception {\npublic:\n    ComponentIsRootWithNoSubcomponents(const std::string& file,\n        size_t line,\n        const std::string& func,\n        const std::string& thisName,\n        const std::string& componentConcreteClassName) :\n        Exception(file, line, func) {\n        std::string msg = "Component \'" + thisName + "\' of type " +\n            componentConcreteClassName + " is the root but has no " +\n            "subcomponents listed.\\n" +\n            "Verify that finalizeFromProperties() was called on this "\n            "Component to identify its subcomponents.";\n        addMessage(msg);\n    }\n};\n\nclass ComponentAlreadyPartOfOwnershipTree : public Exception {\npublic:\n    ComponentAlreadyPartOfOwnershipTree(const std::string& file,\n                                        size_t line,\n                                        const std::string& func,\n                                        const std::string& compName,\n                                        const std::string& thisName) :\n        Exception(file, line, func) {\n        std::string msg = "Component \'" + compName;\n        msg += "\' already owned by tree to which \'" + thisName;\n        msg += "\' belongs. Clone the component to adopt a fresh copy.";\n        addMessage(msg);\n    }\n};\n\nclass ComponentHasNoSystem : public Exception {\npublic:\n    ComponentHasNoSystem(const std::string& file,\n                         size_t line,\n                         const std::string& func,\n                         const Object& obj) :\n        Exception(file, line, func, obj) {\n        std::string msg = "Component has no underlying System.\\n";\n        msg += "You must call initSystem() on the top-level Component ";\n        msg += "(i.e. Model) first.";\n        addMessage(msg);\n    }\n};\n\nclass SocketNotFound : public Exception {\npublic:\n    SocketNotFound(const std::string& file,\n                   size_t line,\n                   const std::string& func,\n                   const Object& obj,\n                   const std::string& socketName) :\n        Exception(file, line, func, obj) {\n        std::string msg = "no Socket \'" + socketName;\n        msg += "\' found for this Component.";\n        addMessage(msg);\n    }\n};\n\nclass InputNotFound : public Exception {\npublic:\n    InputNotFound(const std::string& file,\n                  size_t line,\n                  const std::string& func,\n                  const Object& obj,\n                  const std::string& inputName) :\n        Exception(file, line, func, obj) {\n        std::string msg = "no Input \'" + inputName;\n        msg += "\' found for this Component.";\n        addMessage(msg);\n    /** Destructor is virtual to allow concrete Component to cleanup. **/\n    virtual ~Component() {}\n\n    /** Update Component\'s internal data members based on properties.\n        Marks the Component as up to date with its properties. */\n    void finalizeFromProperties();\n/**\n * The abstract Component class defines the interface used to add computational\n * elements to the underlying SimTK::System (MultibodySystem). It specifies\n * the interface that components must satisfy in order to be part of the system\n * and provides a series of helper methods for adding variables\n * (state, discrete, cache, ...) to the underlying system. As such, Component\n * handles all of the bookkeeping of system indices and provides convenience\n * access to variable values (incl. derivatives) via their names as strings.\n *\n * # Component\'s Interfaces\n * ## System and State\n *\n * The MultibodySystem and its State are defined by Simbody (ref ...). Briefly,\n * a System represents the mathematical equations that specify the behavior\n * of a computational model. The State is a collection of all the variables\n    /** Set Component\'s properties given a state. */\n    void setPropertiesFromState(const SimTK::State& state);\n\n    /**\n     * Get the underlying MultibodySystem that this component is connected to.\n     */\n * that are automatically and simultaneously integrated with the MultibodySystem\n * dynamics. Common operations to integrate, take the max or min, or to delay a\n * signal, etc. require internal variables to perform their calculations and\n * these are also held in the State. Simbody provides the infrastructure to\n * ensure that calculations are kept up-to-date with the state variable values.\n *\n * There are other types of "State" variables such as a flag (or options) that\n * enables a component to be disabled or for a muscle force to be overridden and\n * and these are identified as <em>ModelingOptions</em> since they may change\n * the modeled dynamics of the component. Component provides services\n * that enable developers of components to define additional ModelingOptions.\n *\n * ## Discrete variables\n *\n * Often a component requires input from an outside source (precomputed data\n * from a file, another program, or interaction from a user) in which case these\n * variables do not have dynamics (differential eqns.) known to the component,\n * but are necessary to describe the dynamical "state" of the system. An example,\n * is a throttle component (a "controller" that provides an actuator, e.g. a\n * motor, with a control signal like a voltage or current) which it gets as direct\n * input from the user (via a joystick, key press, etc..). The throttle controls\n * the motor torque output and therefore the behavior of the model. The input by\n * the user to the throttle the motor (the controls) is necessary to specify the\n * model dynamics at any instant and therefore are considered part of the State.\n * In OpenSim they are simply referred to as DiscreteVariables. The Component\n * provides services to enable developers of components to define and access its\n * DiscreteVariables.\n *\n * ## Cache variables\n *\n * Fast and efficient simulations also require computationally expensive\n * calculations to be performed only when necessary. Often the result of an\n     */\n    Array<std::string> getStateVariableNames() const;\n\n    /** @name Component Connector Access methods\n        Access Connectors of this component in a generic way and also by name.\n    */\n * define and access CacheVariables.\n *\n * ## Stages\n *\n * Many modeling and simulation codes put the onus on users and component\n * creators to manage the validity of cache variables, which is likely to lead\n * to undetectable errors where cache values are stale (calculated based on past\n * state variable values). Simbody, on the other hand, provides a more strict\n * infrastructure to make it easy to exploit the efficiencies of caching while\n * reducing the risks of validity errors. To do this, Simbody employs the concept\n * of computational stages to "realize" (or compute) a model\'s system to a\n * particular stage requires cached quantities up to and including the stage to\n * to computed/specified. Simbody utilizes nine realization stages\n * (<tt>SimTK::Stage::</tt>)\n *\n * -# \\c Topology       finalize System with "slots" for most variables (above)\n * -# \\c %Model         specify modeling choices\n * -# \\c Instance       specify modifiable model parameters\n * -# \\c Time           compute time dependent quantities\n * -# \\c Position       compute position dependent quantities\n * -# \\c Velocity       compute velocity dependent quantities\n * -# \\c Dynamics       compute system applied forces and dependent quantities\n * -# \\c Acceleration   compute system accelerations and all other derivatives\n * -# \\c Report         compute quantities for reporting/output\n *\n * The Component interface is automatically invoked by the System and its\n * realizations. Component users and most developers need not concern themselves\n * with \\c Topology, \\c %Model or \\c Instance stages. That interaction is managed\n * by Component when component creators implement extendAddToSystem() and use the\n * services provided by Component. Component creators do need to determine and\n * specify stage dependencies for Discrete and CacheVariables that they add to\n * their components. For example, the throttle controller reads its value from\n * user input and it is valid for all calculations as long as time does not\n * change. If the simulation (via numerical integration) steps forward (or\n * backward for a trial step) and updates the state, the control from a previous\n * state (time) should be invalid and an error generated for trying to access\n * the DiscreteVariable for the control value. To do this one specifies the\n * "invalidates" stage (e.g. <tt>SimTK::Stage::Time</tt>) for a DiscreteVariable\n * when the variable is added to the Component. A subsequent change to that\n * variable will invalidate all state cache entries at that stage or higher. For\n * example, if a DiscreteVariable is declared to invalidate <tt>Stage::Position</tt>\n * then changing it will invalidate cache entries that depend on positions,\n * velocities, forces, and accelerations.\n *\n * Similar principles apply to CacheVariables, which requires a "dependsOn" stage to\n * be specified when a CacheVariable is added to the component. In this case,\n * the cache variable "shadows" the State (unlike a DiscreteVariable, which is a\n * part of the State) holding already-computed state-dependent values so that\n * they do not need to be recomputed until the state changes.\n * Accessing the CacheVariable in a State whose current stage is lower than\n * that CacheVariable\'s specified dependsOn stage will trigger an exception.\n * It is up to the component to update the value of the cache variable.\n * Component provides methods to check if the cache is valid, update its value\n * and then to mark it as valid.\n *\n * ## The interface of this class\n *\n * The primary responsibility of a Component is to add its computational\n * representation(s) to the underlying SimTK::System by implementing\n * extendAddToSystem().\n *\n * Additional methods provide support for adding modeling options, state and\n * cache variables.\n *\n * Public methods enable access to component variables via their names.\n *\n * ## Subcomponents\n *\n * A %Component can have any number of %Components within it; we call these\n * subcomponents. Subcomponents can also contain their own subcomponents as\n * well. There are three categories of subcomponents, which vary in whether\n * they are *configurable* and *fixed in number*:\n *\n * - **property subcomponents** Any Property in a Component that is of type\n *   Component is a subcomponent. This includes list properties and Set%s. This\n *   is the most common category of subcomponent, and its distinguishing\n *   feature is that these subcomponents are *configurable* by the user of this\n *   component. These subcomponents appear in the XML for this component, and\n *   can be modified in XML or through the API. They are also not fixed in\n *   number; users can add more property subcomponents to an existing\n *   component (though it is possible to enforce a fixed number by using\n *   one-value properties or limiting the size of a list property). The bodies,\n *   joints, forces, etc. in a Model\'s BodySet, JointSet, ForceSet, etc. are\n *   all examples of property subcomponents. This category of subcomponent is\n *   the most similar to what was available pre-v4.0.\n * - **member subcomponents** These are *not* configurable by the user of this\n *   Component, and can only be modified by this Component. You can\n *   still access member subcomponents through the API, but only the component\n *   containing the subcomponents can modify them. Any Component class can have\n *   any number of member subcomponents, but this number is *fixed* for every\n *   instance of the component.\n * - **adopted subcomponents** These are *not* configurable (does not appear in\n *   XML) and *not* fixed in number. For example, a component can decide,\n *   based on other aspects of the model, that it needs to create a new\n *   subcomponent. This can be done using adopted subcomponents.\n *\n * Also, any specific Component can end up in any of these three categories.\n * That is, if you have a MySpecialForce Component, any other Component can\n * have it as a property subcomponent, a member subcomponent, or as an adopted\n * subcomponent.\n *\n * @author Ajay Seth, Michael Sherman, Chris Dembia\n */\nclass OSIMCOMMON_API Component : public Object {\nOpenSim_DECLARE_ABSTRACT_OBJECT(Component, Object);\n\nprotected:\n//==============================================================================\n// PROPERTIES\n//==============================================================================\n\n    OpenSim_DECLARE_LIST_PROPERTY(components, Component,\n        "List of components that this component owns and serializes.");\n\npublic:\n//==============================================================================\n// METHODS\n//==============================================================================\n    /** Default constructor **/\n    Component();\n\n    /** Construct Component from an XML file. **/\n    Component(const std::string& aFileName,\n        bool aUpdateFromXMLNode = true) SWIG_DECLARE_EXCEPTION;\n\n    /** Construct Component from a specific node in an XML document. **/\n    explicit Component(SimTK::Xml::Element& aNode);\n\n    /** Use default copy constructor and assignment operator. */\n    Component(const Component&) = default;\n    Component& operator=(const Component&) = default;\n\n    /** Destructor is virtual to allow concrete Component to cleanup. **/\n    virtual ~Component() = default;\n\n    /** @name Component Structural Interface\n    The structural interface ensures that deserialization, resolution of\n    inter-connections, and handling of dependencies are performed systematically\n    and prior to system creation, followed by allocation of necessary System\n    resources. These methods can be extended by virtual methods that form the\n    Component Extension Interface (e.g. #extendFinalizeFromProperties)\n    that can be implemented by subclasses of Components.\n\n    Component ensures that the corresponding calls are propagated to all of its\n    subcomponents.*/\n\n    ///@{\n\n    /** Define a Component\'s internal data members and structure according to\n        its properties. This includes its subcomponents as part of the component\n        ownership tree and identifies its owner (if present) in the tree.\n        finalizeFromProperties propagates to all of the component\'s subcomponents\n        prior to invoking the virtual extendFinalizeFromProperties() on itself.\n        Note that if the Component has already been added to a System (result of\n        addToSystem(); e.g., Model::initSystem()) when finalizeFromProperties()\n        is called, then finalizeFromProperties() disassociates the component from\n        that System.*/\n    void finalizeFromProperties();\n\n    /** Satisfy the Component\'s connections specified by its Sockets and Inputs.\n        Locate Components and their Outputs to satisfy the connections in an\n        aggregate Component (e.g. Model), which is the root of a tree of\n        Components. */\n    void finalizeConnections(Component& root);\n\n    /** Disconnect/clear this Component from its aggregate component. Empties\n        all component\'s sockets and sets them as disconnected.*/\n    void clearConnections();\n\n    /** Have the Component add itself to the underlying computational System */\n    void addToSystem(SimTK::MultibodySystem& system) const;\n\n    /** Initialize Component\'s state variable values from its properties */\n    void initStateFromProperties(SimTK::State& state) const;\n\n    /** %Set Component\'s properties given a state. */\n    void setPropertiesFromState(const SimTK::State& state);\n\n    // End of Component Structural Interface (public non-virtual).\n    ///@}\n\n    /** Optional method for generating arbitrary display geometry that reflects\n    this %Component at the specified \\a state. This will be called once to\n    obtain ground- and body-fixed geometry (with \\a fixed=\\c true), and then\n    once per frame (with \\a fixed=\\c false) to generate on-the-fly geometry such\n    as rubber band lines, force arrows, labels, or debugging aids.\n\n    Please note that there is a precondition that the state passed in to\n    generateDecorations be realized to Stage::Position. If your component can\n    visualize quantities realized at Velocity, Dynamics or Acceleration stages,\n    then you must check that the stage has been realized before using/requesting\n    stage dependent values. It is forbidden to realize the model to a higher\n    stage within generateDecorations, because this can trigger costly side-\n    effects such as evaluating all model forces even when performing a purely\n    kinematic study.\n\n    If you override this method, be sure to invoke the base class method first,\n    using code like this:\n    @code\n    void MyComponent::generateDecorations\n       (bool                                        fixed,\n        const ModelDisplayHints&                    hints,\n        const SimTK::State&                         state,\n        SimTK::Array_<SimTK::DecorativeGeometry>&   appendToThis) const\n    {\n        // invoke parent class method\n        Super::generateDecorations(fixed,hints,state,appendToThis);\n        // ... your code goes here\n        // can render velocity dependent quanities if stage is Velocity or higher\n        if(state.getSystemStage() >= Stage::Velocity) {\n            // draw velocity vector for model COM\n        }\n        // can render computed forces if stage is Dynamics or higher\n        if(state.getSystemStage() >= Stage::Dynamics) {\n            // change the length of a force arrow based on the force in N\n        }\n    }\n    @endcode\n\n    @param[in]      fixed\n        If \\c true, generate only geometry that is fixed to a PhysicalFrame,\n        configuration, and velocity. Otherwise generate only such dependent\n        geometry.\n    @param[in]      hints\n        See documentation for ModelDisplayHints; you may want to alter the\n        geometry you generate depending on what you find there. For example,\n        you can determine whether the user wants to see debug geometry.\n    @param[in]      state\n        The State for which geometry should be produced. See below for more\n        information.\n    @param[in,out]  appendToThis\n        %Array to which generated geometry should be \\e appended via the\n        \\c push_back() method.\n\n    When called with \\a fixed=\\c true only modeling options and parameters\n    (Instance variables) should affect geometry; time, position, and velocity\n    should not. In that case OpenSim will already have realized the \\a state\n    through Instance stage. When called with \\a fixed=\\c false, you may\n    consult any relevant value in \\a state. However, to avoid unnecessary\n    computation, OpenSim guarantees only that \\a state will have been realized\n    through Position stage; if you need anything higher than that (reaction\n    forces, for example) you should make sure the \\a state is realized through\n    Acceleration stage. **/\n    virtual void generateDecorations\n            (bool                                       fixed,\n            const ModelDisplayHints&                    hints,\n            const SimTK::State&                         state,\n            SimTK::Array_<SimTK::DecorativeGeometry>&   appendToThis) const {};\n\n    /**\n     * Get the underlying MultibodySystem that this component is connected to.\n     * Make sure you have called Model::initSystem() prior to accessing the System.\n     * Throws an Exception if the System has not been created or the Component\n     * has not added itself to the System.\n     * @see hasSystem().  */\n    const SimTK::MultibodySystem& getSystem() const\n    {\n        // This method is inlined because it is called *a lot* at runtime\n\n        OPENSIM_THROW_IF_FRMOBJ(!hasSystem(), ComponentHasNoSystem);\n        return _system.getRef();\n    }\n\n    /**\n    * Check if this component has an underlying MultibodySystem.\n    * Returns false if the System has not been created OR if this\n    * Component has not added itself to the System.  */\n    bool hasSystem() const { return !_system.empty(); }\n\n    /** Does the provided component already exist anywhere in the ownership\n     * tree (not just subcomponents of this component)? */\n    bool isComponentInOwnershipTree(const Component* component) const;\n\n    /**\n    * Add a Component (as a subcomponent) of this component.\n    * This component takes ownership of the subcomponent and it will be\n    * serialized (appear in XML) as part of this component. Specifically,\n    * it will appear in the `<components>` list for this Component.\n    * If the subcomponent is already owned by this component or exists\n    * in the same hierarchy (tree) as this component, an Exception\n    * is thrown.\n    * @note addComponent is intended to replace existing addBody(), addJoint,\n    *       ... on Model or the requirement for specific add###() methods to\n    *       subcomponents to a Component.\n    *\n    * Typical usage is:\n    @code\n        // Start with an empty Model (which is a Component)\n        Model myModel;\n        // Create any Component type on the heap\n        Body* newBody = new Body();\n        // Customize the Component by setting its properties\n        newBody->setName("newBody");\n        newBody->setMass(10.0);\n        newBody->setMassCenter(SimTK::Vec3(0));\n        // ...\n        // Now add it to your model, which will take ownership of it\n        myModel.addComponent(newBody);\n        //\n        // Keep creating and adding new components, like Joints, Forces, etc..\n    @endcode\n    *\n    * @throws ComponentAlreadyPartOfOwnershipTree\n    * @param subcomponent is the Component to be added. */\n    void addComponent(Component* subcomponent);\n\n    /**\n     * Get an iterator through the underlying subcomponents that this component is\n     * composed of. The hierarchy of Components/subComponents forms a tree.\n     * The order of the Components is that of tree preorder traversal so that a\n     * component is traversed before its subcomponents.\n     *\n     * @code{.cpp}\n     * for (const auto& muscle : model.getComponentList<Muscle>()) {\n     *     muscle.get_max_isometric_force();\n     * }\n     * @endcode\n     *\n     * The returned ComponentList does not permit modifying any components; if\n     * you want to modify the components, see updComponentList().\n     *\n     * @tparam T A subclass of Component (e.g., Body, Muscle).\n     */\n    template <typename T = Component>\n    ComponentList<const T> getComponentList() const {\n        static_assert(std::is_base_of<Component, T>::value,\n                "Template argument must be Component or a derived class.");\n        initComponentTreeTraversal(*this);\n        return ComponentList<const T>(*this);\n    }\n\n    /** Similar to getComponentList(), except the resulting list allows one to\n    modify the components. For example, you could use this method to change\n    the max isometric force of all muscles:\n\n    @code{.cpp}\n    for (auto& muscle : model.updComponentList<Muscle>()) {\n        muscle.set_max_isometric_force(...);\n    }\n    @endcode\n\n    @note Do NOT use this method to add (or remove) (sub)components from any\n    component. The tree structure of the components should not be altered\n    through this ComponentList.\n\n    @tparam T A subclass of Component (e.g., Body, Muscle). */\n    template <typename T = Component>\n    ComponentList<T> updComponentList() {\n        static_assert(std::is_base_of<Component, T>::value,\n                "Template argument must be Component or a derived class.");\n        initComponentTreeTraversal(*this);\n        clearObjectIsUpToDateWithProperties();\n        return ComponentList<T>(*this);\n    }\n\n    /**\n     * Uses getComponentList<T>() to count the number of underlying\n     * subcomponents of the specified type.\n     *\n     * @tparam T A subclass of Component (e.g., Body, Muscle).\n     */\n    template <typename T = Component>\n    unsigned countNumComponents() const {\n        unsigned count = 0u;\n        const auto compList = getComponentList<T>();\n        auto it = compList.begin();\n        while (it != compList.end()) {\n            ++count;\n            ++it;\n        }\n        return count;\n    }\n\n    /** Class that permits iterating over components/subcomponents (but does\n     * not actually contain the components themselves). */\n    template <typename T>\n    friend class ComponentList;\n    /** Class to iterate over ComponentList returned by getComponentList(). */\n    template <typename T>\n    friend class ComponentListIterator;\n\n\n    /** Get the complete (absolute) pathname for this Component to its ancestral\n     * Component, which is the root of the tree to which this Component belongs.\n     * For example: a Coordinate Component would have an absolute path name\n     * like: `/arm26/elbow_r/flexion`. Accessing a Component by its\n     * absolutePathName from root is guaranteed to be unique. The\n     * absolutePathName is generated on-the-fly by traversing the ownership tree\n     * and, therefore, calling this method is not "free". */\n    std::string getAbsolutePathString() const;\n\n    /** Return a ComponentPath of the absolute path of this Component.\n     * Note that this has more overhead than calling `getName()` because\n     * it traverses up the tree to generate the absolute pathname (and its\n     * computational cost is thus a function of depth). Consider other\n     * options if this is repeatedly called and efficiency is important.\n     * For instance, `getAbsolutePathString()` is faster if you only\n     * need the path as a string. */\n    ComponentPath getAbsolutePath() const;\n\n    /** Get the relative path of this Component with respect to another\n     * Component, as a string. */\n    std::string getRelativePathString(const Component& wrt) const;\n\n    /** Get the relative path of this Component with respect to another\n     * Component. */\n    ComponentPath getRelativePath(const Component& wrt) const;\n\n    /** Query if there is a component (of any type) at the specified\n     * path name. For example,\n     * @code\n     * bool exists = model.hasComponent("right_elbow/elbow_flexion");\n     * @endcode\n     * checks if `model` has a subcomponent "right_elbow," which has a\n     * subcomponent "elbow_flexion." */\n    bool hasComponent(const std::string& pathname) const {\n        return hasComponent<Component>(pathname);\n    }\n\n    /** Query if there is a component of a given type at the specified\n     * path name. For example,\n     * @code\n     * bool exists = model.hasComponent<Coordinate>("right_elbow/elbow_flexion");\n     * @endcode\n     * checks if `model` has a subcomponent "right_elbow," which has a\n     * subcomponent "elbow_flexion," and that "elbow_flexion" is of type\n     * Coordinate. This method cannot be used from scripting; see the\n     * non-templatized hasComponent(). */\n    template <class C = Component>\n    bool hasComponent(const std::string& pathname) const {\n        static_assert(std::is_base_of<Component, C>::value,\n            "Template parameter \'C\' must be derived from Component.");\n        const C* comp = this->template traversePathToComponent<C>({pathname});\n        return comp != nullptr;\n    }\n\n    /**\n     * Get a unique subcomponent of this Component by its path name and type \'C\'.\n     * Throws ComponentNotFoundOnSpecifiedPath exception if the component at\n     * that path name location does not exist OR it is not of the correct type.\n     * For example,\n     * @code\n     *    auto& coord = model.getComponent<Coordinate>("right_elbow/elbow_flexion");\n     * @endcode\n     * returns coord which is a Coordinate named "elbow_flexion" from a Joint\n     * named "right_elbow" given it is a child of the Component (Model) model.\n     * If unsure of a Component\'s path or whether or not it exists in the model,\n     * use printComponentsMatching() or hasComponent().\n     *\n     * This template function cannot be used in Python/Java/MATLAB; see the\n     * non-templatized getComponent().\n     *\n     * @param  pathname        a pathname of a Component of interest\n     * @return const reference to component of type C at\n     * @throws ComponentNotFoundOnSpecifiedPath if no component exists\n     */\n    template <class C = Component>\n    const C& getComponent(const std::string& pathname) const {\n        return getComponent<C>(ComponentPath(pathname));\n    }\n    template <class C = Component>\n    const C& getComponent(const ComponentPath& pathname) const {\n        static_assert(std::is_base_of<Component, C>::value,\n            "Template parameter \'CompType\' must be derived from Component.");\n\n        const C* comp = this->template traversePathToComponent<C>(pathname);\n        if (comp) {\n            return *comp;\n        }\n\n        // Only error cases remain\n        OPENSIM_THROW(ComponentNotFoundOnSpecifiedPath, pathname.toString(),\n                                                       C::getClassName(),\n                                                       getName());\n    }\n\n    /** Similar to the templatized getComponent(), except this returns the\n     * component as the generic Component type. This can be used in\n     * Python/Java/MATLAB. Here is an example of using this in MATLAB:\n     * @code\n     * coord = model.getComponent(\'right_elbow/elbow_flexion\')\n     * coord.getNumConnectees() % okay; this is a Component method.\n     * coord.getDefaultClamped() % inaccessible; method on Coordinate.\n     * Coordinate.safeDownCast(coord).getDefaultClamped() % now accessible.\n     * @endcode\n     *\n     * %Exception: in Python, you will get the concrete type (in most cases):\n     * @code{.py}\n     * coord = model.getComponent(\'right_elbow/elbow_flexion\')\n     * coord.getDefaultClamped() # works; no downcasting necessary.\n     * @endcode\n     */\n    const Component& getComponent(const std::string& pathname) const {\n        return getComponent<Component>(pathname);\n    }\n\n    /** Get a writable reference to a subcomponent. Use this method\n    * to edit the properties and connections of the subcomponent.\n    * Note: the method will mark this Component as out-of-date with\n    * its properties and will require finalizeFromProperties() to be\n    * invoked directly or indirectly (by finalizeConnections() or\n    * Model::initSystem())\n    * @param name       the pathname of the Component of interest\n    * @return Component the component of interest\n    * @throws ComponentNotFoundOnSpecifiedPath if no component exists\n    * @see getComponent()\n    */\n    template <class C = Component>\n    C& updComponent(const std::string& name) {\n        return updComponent<C>(ComponentPath(name));\n    }\n    template <class C = Component>\n    C& updComponent(const ComponentPath& name) {\n        clearObjectIsUpToDateWithProperties();\n        return *const_cast<C*>(&(this->template getComponent<C>(name)));\n    }\n\n    /** Similar to the templatized updComponent(), except this returns the\n     * component as the generic Component type. As with the non-templatized\n     * getComponent(), though, this will give the concrete type in Python in\n     * most cases.\n     * @see getComponent()\n     */\n    Component& updComponent(const std::string& pathname) {\n        constructOutputs();\n    }\n\n    /** @name           Component Basic Interface\n    The interface ensures that deserialization, resolution of inter-connections,\n    and handling of dependencies are performed systematically and prior to \n    system creation, followed by allocation of necessary System resources. These \n    methods are virtual and may be implemented by subclasses of \n    Components. \n    \n    @note Every implementation of virtual method xxx(args) must begin\n    with the line "Super::xxx(args);" to ensure that the parent class methods\n    execute before the child class method, starting with Component::xxx()\n    and going down. \n    \n    The base class implementations here do two things: (1) take care of any\n    needs of the %Component base class itself, and then (2) ensure that the \n    corresponding calls are made to any subcomponents that have been specified \n    by derived %Component objects, via calls to the addComponent() method. \n    So assuming that your concrete %Component and all intermediate classes from\n     * /leg_model/left_hip/rotation\n     * @endverbatim\n     *\n     * @returns The number of matches. */\n    unsigned printComponentsMatching(const std::string& substring) const;\n\n    /**\n     * Get the number of "continuous" state variables maintained by the\n     * Component and its subcomponents.\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    int getNumStateVariables() const;\n\n    /**\n     * Get the names of "continuous" state variables maintained by the Component\n     * and its subcomponents.\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    Array<std::string> getStateVariableNames() const;\n\n\n    /** @name Component Socket Access methods\n        Access Sockets of this component by name. */\n    //@{\n    /** Get the number of Sockets in this Component. */\n    int getNumSockets() const {\n        return int(_socketsTable.size());\n    }\n\n    /** Collect and return the names of the sockets in this component. You\n     * can use this to iterate through the sockets:\n     * @code\n     * for (std::string name : comp.getSocketNames()) {\n     *     const AbstractSocket& socket = getSocket(name);\n     * }\n     * @endcode */\n    std::vector<std::string> getSocketNames() const {\n        std::vector<std::string> names;\n        for (const auto& it : _socketsTable) {\n            names.push_back(it.first);\n        }\n        return names;\n    }\n\n    /**\n    * Get the "connectee" object that the Component\'s Socket\n    * is bound to. Guaranteed to be valid only after the Component\n    * has been connected (that is connect() has been invoked).\n    * If the Socket has not been connected, an exception is thrown.\n    *\n    * This method is for getting the concrete connectee object, and is not\n    * available in scripting. If you want generic access to the connectee as an\n    * Object, use the non-templated version.\n    /** Invoke connect() on the (sub)components of this Component.*/\n    void componentsConnect(Component& root) const;\n\n    /** Opportunity to remove connection related information. \n    If you override this method, be sure to invoke the base class method first,\n    using code like this :\n    * @code\n    * const PhysicalFrame& frame = joint.getConnectee<PhysicalFrame>("parent_frame");\n    * frame.getMobilizedBody();\n    * @endcode\n    */\n    }\n    @endcode  */\n    //virtual void extendDisconnect() {};\n\n\n    /** Add appropriate Simbody elements (if needed) to the System \n    corresponding to this component and specify needed state resources. \n    }\n\n    /** Get the connectee as an Object. This means you will not have\n    * access to the methods on the concrete connectee. This is the method you\n    * must use in MATLAB to access the connectee.\n    *\n    * Example:\n    * @code{.cpp}\n    * const Object& obj = joint.getConnectee("parent_frame");\n    * obj.getName(); // method on Object works.\n    * obj.getMobilizedBody(); // error: not available.\n    * @endcode\n    *\n    * In MATLAB, if you want the concrete type, you need to downcast the\n    * Object. Here is an example where you know the "parent_frame" is a Body:\n    * @code\n    * f = joint.getConnectee(\'parent_frame\');\n    * m = Body.safeDownCast(f).getMass();\n    * @endcode\n    *\n    * Exception: in Python, you will get the concrete type (in most cases):\n    * @code{.py}\n    * f = joint.getConnectee("parent_frame");\n    * m = f.getMass() # works (if the parent frame is a body)\n    * @endcode\n    */\n    const Object& getConnectee(const std::string& name) const {\n        const AbstractSocket& socket = getSocket(name);\n        OPENSIM_THROW_IF_FRMOBJ(!socket.isConnected(), Exception,\n                "Socket \'" + name + "\' not connected.");\n        return socket.getConnecteeAsObject();\n    }\n\n    /** Get an AbstractSocket for the given socket name. This\n     * lets you get information about the connection (like if the socket is\n     * connected), but does not give you access to the socket\'s connectee.\n     * For that, use getConnectee().\n     *\n     * @internal If you have not yet called finalizeFromProperties() on this\n     * component, this function will update the Socket (to tell it which\n     * component it\'s in) before providing it to you.\n     *\n     * <b>C++ example</b>\n     * @code{.cpp}\n     * model.getComponent("/path/to/component").getSocket("socketName");\n     * @endcode\n     */\n    const AbstractSocket& getSocket(const std::string& name) const {\n        auto it = _socketsTable.find(name);\n\n        if (it != _socketsTable.end()) {\n            // The following allows one to use a Socket immediately after\n            // copying the component;\n            // e.g., myComponent.clone().getSocket("a").getConnecteePath().\n            // Since we use the default copy constructor for Component,\n            // the copied AbstractSocket cannot know its new owner\n            // immediately after copying.\n            if (!it->second->hasOwner()) {\n                // The `this` pointer must be non-const because the Socket\n                // will want to be able to modify the connectee path property.\n                const_cast<AbstractSocket*>(it->second.get())->setOwner(\n                        const_cast<Self&>(*this));\n            }\n            return it->second.getRef();\n        }\n\n        OPENSIM_THROW_FRMOBJ(SocketNotFound, name);\n    }\n\n    /** Get a writable reference to the AbstractSocket for the given\n     * socket name. Use this method to connect the Socket to something.\n     *\n     * <b>C++ example</b>\n     * @code\n     * joint.updSocket("parent_frame").connect(model.getGround());\n     * @endcode\n     *\n     * @internal If you have not yet called finalizeFromProperties() on this\n     * component, this function will update the Socket (to tell it which\n     * component it\'s in) before providing it to you.\n     */\n    AbstractSocket& updSocket(const std::string& name) {\n        return const_cast<AbstractSocket&>(getSocket(name));\n    }\n\n    /**\n    * Get a const reference to the concrete Socket provided by this\n    * Component by name.\n    *\n    * @internal If you have not yet called finalizeFromProperties() on this\n    * component, this function will update the Socket (to tell it which\n    * component it\'s in) before providing it to you.\n    *\n    * @param name       the name of the Socket\n    * @return const reference to the (Abstract)Socket\n    */\n    template<typename T>\n    const Socket<T>& getSocket(const std::string& name) const {\n        return Socket<T>::downcast(getSocket(name));\n    }\n\n    /**\n    * Get a writable reference to the concrete Socket provided by this\n    * Component by name.\n    *\n    * @internal If you have not yet called finalizeFromProperties() on this\n    * component, this function will update the Socket (to tell it which\n    * component it\'s in) before providing it to you.\n    *\n    * @param name       the name of the Socket\n    * @return const reference to the (Abstract)Socket\n    */\n    template<typename T> Socket<T>& updSocket(const std::string& name) {\n        return const_cast<Socket<T>&>(getSocket<T>(name));\n    }\n    //@} end of Component Socket Access methods\n\n    /** @name Component Inputs and Outputs Access methods\n        Access inputs and outputs by name and iterate over all outputs.\n    */\n    //@{\n\n    /** Access the number of Inputs that this component has. */\n    int getNumInputs() const {\n        return int(_inputsTable.size());\n    }\n\n    /** Access the number of Outputs that this component has. */\n    int getNumOutputs() const {\n        return int(_outputsTable.size());\n    }\n                            const std::string& name, double deriv) const;\n\n\n    // End of Model Component Basic Interface (protected virtuals).\n    //@} \n\n    /** @name           Component Advanced Interface\n    You probably won\'t need to override methods in this section. These provide\n    a way for you to perform computations ("realizations") that must be \n    scheduled in carefully-ordered stages as described in the class description\n\n    /** Collect and return the names of Outputs in this component as an\n     * std::vector. */\n    std::vector<std::string> getOutputNames() const {\n        std::vector<std::string> names;\n        for (const auto& entry : getOutputs()) {\n            names.push_back(entry.first);\n        }\n        return names;\n    }\n\n    /**\n    * Get an Input provided by this Component by name.\n    *\n    * <b>C++ example:</b> get an Input from a Component in the model\n    * @code{.cpp}\n    * model.getComponent("/path/to/component").getInput("inputName");\n    * @endcode\n    *\n    * @internal If you have not yet called finalizeFromProperties() on this\n    * component, this function will update the Input (to tell it which\n    * component it\'s in) before providing it to you.\n    *\n    * @param name   the name of the Input\n    * @return       const reference to the AbstractInput\n    */\n    const AbstractInput& getInput(const std::string& name) const\n    {\n        auto it = _inputsTable.find(name);\n\n        if (it != _inputsTable.end()) {\n            // The following allows one to use an Input immediately after\n            // copying the component;\n            // e.g., myComponent.clone().getInput("a").getConnecteePath().\n            // Since we use the default copy constructor for Component,\n            // the copied AbstractSocket (base class of AbstractInput)\n            // cannot know its new owner immediately after copying.\n            if (!it->second->hasOwner()) {\n\n                // The `this` pointer must be non-const because the Socket\n                // will want to be able to modify the connectee_name property.\n                const_cast<AbstractInput*>(it->second.get())->setOwner(\n                        const_cast<Self&>(*this));\n            }\n            return it->second.getRef();\n        }\n\n        OPENSIM_THROW_FRMOBJ(InputNotFound, name);\n    }\n\n    /**\n    * Get a writable reference to an Input provided by this Component by name.\n    *\n    * <b>C++ example:</b> get a writable reference to an Input of a\n    * Component in a model\n    * @code{.cpp}\n    * model.updComponent("/path/to/component").updInput("inputName");\n    * @endcode\n    *\n    * @internal If you have not yet called finalizeFromProperties() on this\n    * component, this function will update the Input (to tell it which\n    * component it\'s in) before providing it to you.\n\n    * @param name   the name of the Input\n    * @return       reference to the AbstractInput\n    */\n    AbstractInput& updInput(const std::string& name)\n    {\n        return *const_cast<AbstractInput *>(&getInput(name));\n    }\n\n\n    /**\n    * Get a concrete Input that you can directly ask for its values.\n    *\n    * @internal If you have not yet called finalizeFromProperties() on this\n    * component, this function will update the Input (to tell it which\n    * component it\'s in) before providing it to you.\n    *\n    * @param name   the name of the Input\n    * @throws Exception if an Input with the given name does not exist.\n    * @throws std::bad_cast if the provided type T is incorrect for the given name.\n    */\n    template<typename T>\n    const Input<T>& getInput(const std::string& name) const {\n        return dynamic_cast<const Input<T>&>(getInput(name));\n    }\n\n    /**\n    * Get the Output provided by this Component by name.\n    *\n    * <b>C++ example:</b> get an Output from a Component in a model\n    * @code{.cpp}\n    * model.getComponent("/path/to/component").getOutput("outputName");\n    * @endcode\n    *\n    * @param name   the name of the Output\n    * @return       const reference to the AbstractOutput\n    */\n    const AbstractOutput& getOutput(const std::string& name) const\n    {\n        auto it = _outputsTable.find(name);\n\n        if (it != _outputsTable.end()) {\n            return it->second.getRef();\n        }\n\n        OPENSIM_THROW_FRMOBJ(OutputNotFound, name);\n    }\n\n    /**\n    * Get a writable reference to an Output provided by this Component by name.\n    *\n    * <b>C++ example:</b> get a writable reference to an Output of a\n    * Component in a model\n    * @code{.cpp}\n    * model.updComponent("/path/to/component").updOutput("outputName");\n    * @endcode\n\n    * @param name   the name of the Output\n    * @return       reference to the AbstractOutput\n    */\n    AbstractOutput& updOutput(const std::string& name)\n    {\n        return *const_cast<AbstractOutput *>(&getOutput(name));\n    }\n\n    /** Define OutputConstIterator for convenience */\n    typedef std::map<std::string, SimTK::ClonePtr<AbstractOutput>>::\n        const_iterator OutputConstIterator;\n\n    /** Iterate through all Outputs of this component. The intent is to use\n     * this in a loop as such:\n     * @code\n     * for (const auto& entry : comp.getOutputs()) {\n     *     const std::string& name = entry.first;\n     *     const AbstractOutput* output = entry.second.get();\n     *     std::cout << output->getTypeName() << std::endl;\n     * }\n     * @endcode\n     * This provides access to the outputs as AbstractOutput%s, not as the\n     * concrete type. This also does not permit modifying the outputs.\n     *\n     * Not available in Python/Java/MATLAB; use getOutputNames() and\n     * getOutput() instead.\n     */\n    SimTK::IteratorRange<OutputConstIterator> getOutputs() const {\n        return {_outputsTable.cbegin(), _outputsTable.cend()};\n    }\n    //@} end of Component Inputs and Outputs Access methods\n\n\n\n    /** @name Component State Access methods\n        Get and set modeling option, input and output values, state variable,\n        discrete and/or cache variables in the State.\n     */\n    //@{\n\n    /**\n     * Get a ModelingOption flag for this Component by name.\n     * The flag is an integer corresponding to the index of modelingOptionNames used\n     * add the modeling option to the component. @see addModelingOption\n    *\n     * @param state  the State in which to set the modeling option\n     * @param name   the name (string) of the modeling option of interest\n     * @return flag  integer value for modeling option\n    */\n    int getModelingOption(const SimTK::State& state, const std::string& name) const;\n\n    /**\n     * %Set the value of a ModelingOption flag for this Component.\n     * if the integer value exceeds the number of option names used to\n     * define the options, an exception is thrown. The SimTK::State\n     * Stage will be reverted back to Stage::Instance.\n     *\n     * @param state  the State in which to set the flag\n     * @param name   the name (string) of the modeling option of interest\n     * @param flag   the desired flag (int) value specifying the modeling option\n     */\n    void setModelingOption(SimTK::State& state, const std::string& name, int flag) const;\n\n    /**\n    * Get the Input value that this component is dependent on.\n    * Checks if Input is connected, otherwise it will throw an\n    * exception. You can only call this method for non-list inputs.\n    * For list inputs, you must get the input using getInput(),\n    * from which you can ask for its values.\n    *\n    * @param state      the State for which to set the value\n    * @param name       the name of the input\n    * @return T         const Input value\n    */\n    template<typename T> const T&\n        getInputValue(const SimTK::State& state, const std::string& name) const {\n        // get the input and check if it is connected.\n        const AbstractInput& in = getInput(name);\n        // TODO could maybe remove this check and have the Input do it. Or,\n        // here, we could catch Input\'s exception and give a different message.\n        if (in.isConnected()) {\n            return (Input<T>::downcast(in)).getValue(state);\n        }\n\n        else {\n        std::stringstream msg;\n            msg << "Component::getInputValue: ERR- Input \'" << name << "\' not connected.\\n "\n                << "for component \'" << getName() << "\' of type "<< getConcreteClassName();\n        throw Exception(msg.str(), __FILE__, __LINE__);\n        }\n    }\n\n    /**\n    * Get the Output value provided by this Component by name.\n    *\n    * @param state      the State for which to set the value\n    * @param name       the name of the cache variable\n    * @return T         const Output value\n    */\n    template<typename T> const T&\n        getOutputValue(const SimTK::State& state, const std::string& name) const\n    {\n        return (Output<T>::downcast(getOutput(name))).getValue(state);\n    }\n\n\n    /**\n     * Get the value of a state variable allocated by this Component.\n     *\n     * To connect this StateVariable as an input to another component (such as\n     * a Reporter), use getOutput(name); each state variable has a\n     * corresponding Output:\n     *  @code\n     *  foo.getInput("input1").connect(bar.getOutput(name));\n     *  @endcode\n     *\n     * @param state   the State for which to get the value\n     * @param name    the name (string) of the state variable of interest\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    double getStateVariableValue(const SimTK::State& state, const std::string& name) const;\n\n    /**\n     * Get the value of a state variable allocated by this Component.\n     *\n     * To connect this StateVariable as an input to another component (such as\n     * a Reporter), use getOutput(name); each state variable has a\n     * corresponding Output:\n     *\n     *  @code\n     *  foo.getInput("input1").connect(bar.getOutput(name));\n     *  @endcode\n     *\n     * @param state   the State for which to get the value\n     * @param name    path to the state variable of interest\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    double getStateVariableValue(const SimTK::State& state, const ComponentPath& path) const;\n\n    /**\n     * %Set the value of a state variable allocated by this Component by name.\n     *\n     * @param state  the State for which to set the value\n     * @param name   the name of the state variable\n     * @param value  the value to set\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    void setStateVariableValue(SimTK::State& state, const std::string& name, double value) const;\n\n\n    /**\n     * Get all values of the state variables allocated by this Component.\n     * Includes state variables allocated by its subcomponents.\n     *\n     * @param state   the State for which to get the value\n     * @return Vector of state variable values of length getNumStateVariables()\n     *                in the order returned by getStateVariableNames()\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    SimTK::Vector getStateVariableValues(const SimTK::State& state) const;\n\n    /**\n     * %Set all values of the state variables allocated by this Component.\n     * Includes state variables allocated by its subcomponents. Note, this\n     * method simply sets the values on the input State. If other conditions\n     * must be met (such as satisfying kinematic constraints for Coordinates,\n     * or fiber and tendon equilibrium for muscles) you must invoke the\n     * appropriate methods on Model (e.g. assemble() to satisfy constraints or\n     * equilibrateMuscles()) to satisfy these conditions starting from the\n     * State values provided by setStateVariableValues.\n     *\n     * @param state   the State whose values are set\n     * @param values  Vector of state variable values of length\n     *                getNumStateVariables() in the order returned by\n     *                getStateVariableNames()\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    void setStateVariableValues(SimTK::State& state,\n                                const SimTK::Vector& values) const;\n\n    /**\n     * Get the value of a state variable derivative computed by this Component.\n     *\n     * @param state   the State for which to get the derivative value\n     * @param name    the name (string) of the state variable of interest\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    double getStateVariableDerivativeValue(const SimTK::State& state,\n        const std::string& name) const;\n\n    /**\n     * Get the value of a discrete variable allocated by this Component by name.\n     *\n     * @param state   the State from which to get the value\n     * @param name    the name of the state variable\n     * @return value  the discrete variable value\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    double getDiscreteVariableValue(const SimTK::State& state,\n                                    const std::string& name) const;\n\n    /**\n     * %Set the value of a discrete variable allocated by this Component by name.\n     *\n     * @param state  the State for which to set the value\n     * @param name   the name of the discrete variable\n     * @param value  the value to set\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    void setDiscreteVariableValue(SimTK::State& state, const std::string& name,\n                                  double value) const;\n\n    /**\n     * A cache variable containing a value of type T.\n     *\n     * - A `CacheVariable` is a handle to the cache variable\'s value and\n     *   validity\n     *\n     * - Derived classes may declare `CacheVariable` members (ideally,\n     *   as `private` members), which grants them strongly-typed access\n     *   to cache variable values\n     *\n     * - `CacheVariable` should be initialized with\n     *   `Component::addCacheVariable`; usually, in the\n     *   `Component::extendAddToSystem` method. A cache variable\'s value\n     *   will not be valid until after `Component::realizeTopology` is\n     *   called\n     *\n     * @tparam T\n     *   Type of data held in the cache variable\n     */\n    template<class T>\n    class CacheVariable {\n    private:\n        std::string name;\n\n        // this is initialized in Component::getCacheVariableIndex. It enhances\n        // performance by skipping using `name` to perform runtime map lookups.\n        mutable SimTK::ResetOnCopy<SimTK::CacheEntryIndex> maybeUninitIndex{\n            SimTK::InvalidIndex\n        };\n\n        friend class Component;\n\n        explicit CacheVariable(std::string _name) : name{std::move(_name)} {\n        }\n\n    public:\n        // A default constructor is required for user-facing impl. because\n        // derived classes might not be able to fully initialize an instance\n        // at construction time (e.g. via member initialization).\n        //\n        // Usage of a partially-initialized CacheVariable is invalid. The way\n        // that this is dealt with is by checking for errors at runtime:\n        //\n        // - CacheVariable will default-initialize with a name of "", which is\n        //   disallowed by `Component::addCacheVariable`. Therefore, if a\n        //   CacheVariable instance has an empty name, it was not initialized.\n        //\n        // - The index is default-initialized, and copy constructed, with an\n        //   invalid (erroring) index, so derived classes can\'t alias\n        //   cache variables by copying this class around.\n        CacheVariable() = default;\n    };\n\nprotected:\n    /**\n     * Add a state cache entry belonging to this Component to hold\n     * calculated values that must be automatically invalidated when certain\n     * state values change. Cache entries contain values whose computations depend\n     * on state variables and provide convenience and/or efficiency by holding on\n     * to them in memory (cache) to avoid recomputation. Once the state changes,\n     * the cache values automatically become invalid and has to be\n     * recomputed based on the current state before it can be referenced again.\n     * Any attempt to reference an invalid cache entry results in an exception\n     * being thrown.\n     *\n     * Cache entry validity is managed by computation Stage, rather than by\n     * dependence on individual state variables. Changing a variables whose\n     * "invalidates" stage is the same or lower as the one specified as the\n     * "depends on" stage here cause the cache entry to be invalidated. For\n     * example, a body\'s momentum, which is dependent on position and velocity\n     * states, should have Stage::Velocity as its \\a dependsOnStage. Then if a\n     * Velocity stage variable or lower (e.g. Position stage) changes, then the\n     * cache is invalidated. But, if a Dynamics stage variable (or above) is\n     * changed, the velocity remains valid so the cache entry does not have to be\n     * recomputed.\n     *\n     * @param[in]      name\n     *   The name you are assigning to this cache entry. Must be unique within\n     *   this model component.\n     *\n     * @param[in]      variablePrototype\n     *   An object defining the type of value, and a default value of that type,\n     *   to be held in this cache entry. Can be a simple int or an elaborate\n     *   class, as long as it has deep copy semantics.\n     * @param[in]      dependsOnStage\n     *   This is the highest computational stage on which this cache entry\'s\n     *   value computation depends. State changes at this level or lower will\n     *   invalidate the cache entry.\n     */\n    template <class T>\n    CacheVariable<T> addCacheVariable(std::string name,\n                                      T variablePrototype,\n                                      SimTK::Stage dependsOnStage) const\n    {\n        if (name.empty()) {\n            OPENSIM_THROW_FRMOBJ(Exception, "Cannot create a cache variable with an empty name");\n        }\n\n        // edge-case: there is already a cache variable with the same name allocated.\n        //            This is disallowed--and probably a development error--because it\n        //            might result in horrible edge cases such as two cachevars indirectly\n        //            aliasing eachother at run-time.\n        if (this->_namedCacheVariables.find(name) != this->_namedCacheVariables.end()) {\n            std::stringstream msg;\n            msg << "Cannot create a cache variable with the name \'" << name << "\' because another cache variable with that name already exists";\n            OPENSIM_THROW_FRMOBJ(Exception, msg.str());\n        }\n\n        this->_namedCacheVariables.emplace(\n                name,\n                StoredCacheVariable{\n                    new SimTK::Value<T>(std::move(variablePrototype)),\n                    dependsOnStage\n                });\n\n        return CacheVariable<T>{std::move(name)};\n    }\n\npublic:\n    /**\n     * Get the index of a Component\'s cache variable in the Subsystem for allocations.\n     *\n     * @tparam T\n     *   Type of value held in the cache variable\n     * @param cv\n     *   A CacheVariable<T>, as allocated by Component::addCacheVariable\n     * @return\n     *   A valid SimTK::CacheEntryIndex, which callers can use with Simbody methods\n     *   (e.g. markCacheValueRealized)\n     */\n    template<class T>\n    SimTK::CacheEntryIndex getCacheVariableIndex(const CacheVariable<T>& cv) const {\n        // cheap: index previously initialized, just return that\n        if (cv.maybeUninitIndex.isValid()) {\n            return cv.maybeUninitIndex;\n        }\n\n        // expensive: perform index lookup and initialize it\n\n        if (cv.name.empty()) {\n            OPENSIM_THROW_FRMOBJ(Exception, "Cannot get cache variable index: the cache variable has no name: has it been initialized with Component::addCacheVariable?");\n        }\n\n        // getCacheVariableIndex asserts whether the returned index is valid or not,\n        // so this assignment will set the index to something valid, making subsequent\n        // calls use the cheap path (above).\n        cv.maybeUninitIndex = this->getCacheVariableIndex(cv.name);\n\n        return cv.maybeUninitIndex;\n    }\n\n    /**\n     * Get the index of a Component\'s cache variable in the Subsystem for allocations.\n     *\n     * @tparam T\n     *   Type of value held in the cache variable\n     * @param name\n     *   Name of the cache variable, as provided to Component::addCacheVariable\n     * @return\n     *   A valid SimTK::CacheEntryIndex, which callers can use with simbody methods\n     *   (e.g. markCacheValueRealized)\n     */\n    SimTK::CacheEntryIndex getCacheVariableIndex(const std::string& name) const;\n\nprivate:\n    template<class T, class K>\n    const T& getCacheVariableValueGeneric(const SimTK::State& state, const K& key) const\n    {\n        const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();\n        const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(key);\n        const SimTK::AbstractValue& v = subsystem.getCacheEntry(state, idx);\n        return SimTK::Value<T>::downcast(v).get();\n    }\n\npublic:\n    /**\n     * Get the value of a cache variable allocated by this Component by name.\n     *\n     * @param state\n     *     the State from which to get the value\n     * @param name\n     *     the name of the cache variable\n     * @return T\n     *     A const reference to the cache variable\'s value\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<class T>\n    const T& getCacheVariableValue(const SimTK::State& state, const std::string& name) const\n    {\n        return getCacheVariableValueGeneric<T>(state, name);\n    }\n\n    /**\n     * Get the value of a cache variable allocated by this Component.\n     *\n     * @param state\n     *     the State from which to get the value\n     * @param cv\n     *     the cache variable\n     * @return T\n     *     A const reference to the cache variable\'s value\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<class T>\n    const T& getCacheVariableValue(const SimTK::State& state, const CacheVariable<T>& cv) const\n    {\n        return getCacheVariableValueGeneric<T>(state, cv);\n    }\n\nprivate:\n    template<typename T, typename K>\n    void setCacheVariableValueGeneric(const SimTK::State& state, const K& key, T value) const\n    {\n        const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();\n        const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(key);\n        SimTK::AbstractValue& valWrapper = subsystem.updCacheEntry(state, idx);\n\n        T& currentVal = SimTK::Value<T>::downcast(valWrapper).upd();\n        currentVal = std::move(value);\n        subsystem.markCacheValueRealized(state, idx);\n    }\n\npublic:\n    /**\n     * Set the value of a cache variable, identified by `name`, to a new value\n     * and mark the cache variable as valid.\n     *\n     * @param state\n     *     the State in which to store the new value\n     * @param k\n     *     the name of the cache variable\n     * @param value\n     *     the new value for this cache variable\n     * @return T\n     *     A const reference to the cache variable\'s new value\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<typename T>\n    void setCacheVariableValue(const SimTK::State& state, const std::string& k, T value) const\n    {\n      setCacheVariableValueGeneric<T>(state, k, std::move(value));\n    }\n\n    /**\n     * Set the value of a cache variable to a new value and mark the cache variable\n     * as valid.\n     *\n     * @param state\n     *     the State in which to store the new value\n     * @param cv\n     *     the cache variable to update\n     * @param value\n     *     the new value for the cache variable\n     * @return T\n     *     a const reference to the cache variable\'s new value\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<typename T>\n    void setCacheVariableValue(const SimTK::State& state, const CacheVariable<T>& cv, T value) const\n    {\n        setCacheVariableValueGeneric<T>(state, cv, std::move(value));\n    }\n\nprivate:\n    template<typename T, typename K>\n    T& updCacheVariableValueGeneric(const SimTK::State& state, const K& key) const {\n        const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();\n        const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(key);\n        SimTK::AbstractValue& valWrapper = subsystem.updCacheEntry(state, idx);\n        return SimTK::Value<T>::downcast(valWrapper).upd();\n    }\n\npublic:\n    /**\n     * Returns a mutable reference to the value of a cache variable identified by `name`.\n     *\n     * Note: do not forget to mark the cache variable as valid after updating.\n     *       Otherwise, it will force a re-computation of the value if the\n     *       computation method is monitoring the validity of the cache value.\n     *\n     * @param state\n     *     the State in which to set the value\n     * @param name\n     *     the name of the cache variable\n     * @return value\n     *     modifiable reference to the cache variable\'s value\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<typename T>\n    T& updCacheVariableValue(const SimTK::State& state, const std::string& name) const\n    {\n        return updCacheVariableValueGeneric<T>(state, name);\n    }\n\n    /**\n     * Returns a mutable reference to the value of a cache variable.\n     *\n     * Note: do not forget to mark the cache variable as valid after updating.\n     *       Otherwise, it will force a re-computation of the value if the\n     *       computation method is monitoring the validity of the cache value.\n     *\n     * @param state\n     *     the State in which to set the value\n     * @param cv\n     *     the cache variable\n     * @return value\n     *     modifiable reference to the cache variable\'s value\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to the System (i.e., if initSystem has not been called)\n     */\n    template<typename T>\n    T& updCacheVariableValue(const SimTK::State& state, const CacheVariable<T>& cv) const\n    {\n        return updCacheVariableValueGeneric<T>(state, cv);\n    }\n\n    /**\n     * Returns true if the cache variable, identified by `name`, is valid.\n     *\n     * This method enables callers to monitor the validity of the cache variable,\n     * which enables the caller to decide whether to update the cache variable\'s\n     * value (or not). When computing an update is costly, use this method to check\n     * whether computing the value is necessary.\n     *\n     * @param state\n     *     the State in which the cache variable\'s value resides\n     * @param name\n     *     the name of the cache variable\n     * @return bool\n     *     whether the cache variable\'s value is valid or not\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    bool isCacheVariableValid(const SimTK::State& state, const std::string& name) const;\n\n    /**\n     * Returns true if the cache variable is valid.\n     *\n     * This method enables callers to monitor the validity of the cache variable,\n     * which enables the caller to decide whether to update the cache variable\'s\n     * value (or not). When computing an update is costly, use this method to check\n     * whether computing the value is necessary.\n     *\n     * @param state\n     *     the State in which the cache variable\'s value resides\n     * @param cv\n     *     the cache variable\n     * @return bool\n     *     whether the cache variable\'s value is valid or not\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<class T>\n    bool isCacheVariableValid(const SimTK::State& state, const CacheVariable<T>& cv) const {\n        const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();\n        const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(cv);\n        return subsystem.isCacheValueRealized(state, idx);\n    }\n\n    /**\n     * Marks the value of a cache variable, identified by `name`, as valid.\n     *\n     * Upon marking a cache variable\'s value as valid, the cache variable will remain\n     * valid until either:\n     *\n     * - the realization stage falls below the minimum realization stage set\n     *   when the cache variable was initialized with `Component::addCacheVariable`\n     *\n     * - the cache variable is explicitly invalidated by calling\n     *   `Component::markCacheVariableInvalid`\n     *\n     * This method causes `Component::isCacheVariableValid` to return true.\n     * `Component::isCacheVariableValid` is commonly used by value-getting\n     * methods to decide on whether to return the value as-is or recompute the\n     * value. Therefore, if a cache variable is not marked as valid then the\n     * cache variable\'s value may be recomputed more than necessary, which may\n     * be costly.\n     *\n     * @param state\n     *     the State in which the cache variable\'s value resides\n     * @param name\n     *     the name of the cache variable\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    void markCacheVariableValid(const SimTK::State& state, const std::string& name) const;\n\n    /**\n     * Marks the value of a cache variable as valid.\n     *\n     * Upon marking a cache variable\'s value as valid, the cache variable will remain\n     * valid until either:\n     *\n     * - the realization stage falls below the minimum realization stage set\n     *   when the cache variable was initialized with `Component::addCacheVariable`\n     *\n     * - the cache variable is explicitly invalidated by calling\n     *   `Component::markCacheVariableInvalid`\n     *\n     * This method causes `Component::isCacheVariableValid` to return true.\n     * `Component::isCacheVariableValid` is commonly used by value-getting\n     * methods to decide on whether to return the value as-is or recompute the\n     * value. Therefore, if a cache variable is not marked as valid then the\n     * cache variable\'s value may be recomputed more than necessary, which may\n     * be costly.\n     *\n     * @param state\n     *     the State in which the cache variable\'s value resides\n     * @param cv\n     *     the cache variable\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem\n     *     has not been called)\n     */\n    template<typename T>\n    void markCacheVariableValid(const SimTK::State& state, const CacheVariable<T>& cv) const {\n        const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();\n        const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(cv);\n        subsystem.markCacheValueRealized(state, idx);\n    }\n\n    /**\n     * Marks the value of a cache variable, identified by `name`, as invalid.\n     *\n     * Upon marking a cache variable\'s value as invalid, it will remain invalid\n     * until `Component::markCacheVariableValid` is called (or a method which\n     * uses that, such as `Component::setCacheVariableValue`, is called).\n     *\n     * - Cache variables are automatically marked as invalid when the realization stage\n     *   falls below the minimum realization stage set when the cache variable was\n     *   initialized with `Component::addCacheVariable`.\n     *\n     * - Cache variables *may* be indirectly marked as invalid by other methods. For\n     *   example, a component-added state variable may invalidate a cache variable at\n     *   a lower stage. Concretely:\n     *\n     *   - A (hypothetical) component has a `length` state variable\n     *   - There are cache variables that are computed from `length` (e.g.\n     *   `strain`)\n     *   - So changing the `length` may invalidate the `strain` indirectly\n     *     (depending on how the state variable is handled)\n     *\n     * @param state\n     *     the State in which the cache variable\'s value resides\n     * @param name\n     *     the name of the cache variable\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    void markCacheVariableInvalid(const SimTK::State& state, const std::string& name) const;\n\n    /**\n     * Marks the value of a cache variable as invalid.\n     *\n     * Upon marking a cache variable\'s value as invalid, it will remain invalid\n     * until `Component::markCacheVariableValid` is called (or a method which\n     * uses that, such as `Component::setCacheVariableValue`, is called).\n     *\n     * - Cache variables are automatically marked as invalid when the realization stage\n     *   falls below the minimum realization stage set when the cache variable was\n     *   initialized with `Component::addCacheVariable`.\n     *\n     * - Cache variables *may* be indirectly marked as invalid by other methods. For\n     *   example, a component-added state variable may invalidate a cache variable at\n     *   a lower stage. Concretely:\n     *\n     *   - A (hypothetical) component has a `length` state variable\n     *   - There are cache variables that are computed from `length` (e.g.\n     *   `strain`)\n     *   - So changing the `length` may invalidate the `strain` indirectly (depending on\n     *     how the state variable is handled)\n     *\n     * @param state\n     *     the State in which the cache variable\'s value resides\n     * @param cv\n     *     the cache variable\n     * @throws ComponentHasNoSystem\n     *     if this Component has not been added to a System (i.e., if initSystem has not been called)\n     */\n    template<class T>\n    void markCacheVariableInvalid(const SimTK::State& state, const CacheVariable<T>& cv) const {\n        const SimTK::DefaultSystemSubsystem& subsystem = this->getDefaultSubsystem();\n        const SimTK::CacheEntryIndex idx = this->getCacheVariableIndex(cv);\n        subsystem.markCacheValueNotRealized(state, idx);\n    }\n\n    // End of Model Component State Accessors.\n    //@}\n\n    /** @name Print information to the console */\n    /// @{\n    /** List all subcomponents by name and recurse into these components to\n    list their subcomponents, and so on.                                      */\n    void printSubcomponentInfo() const;\n\n    /** List all the Sockets of this component and whether or not they are\n    connected. Also list the connectee paths for sockets that are connected. */\n    void printSocketInfo() const;\n\n    /** List all the inputs of this component and whether or not they are\n    connected. Also list the (desired) connectee paths for the inputs.       */\n    void printInputInfo() const;\n\n    template<typename C>\n    void printSubcomponentInfo() const {\n\n        ComponentList<const C> compList = getComponentList<C>();\n\n        // Step through compList once to determine if there are any\n        // subcomponents and to find the longest concrete class name.\n        const std::string concreteClassName = this->getConcreteClassName();\n        unsigned numSubcomponents = 0;\n        size_t maxlen = concreteClassName.length();\n        for (const C& thisComp : compList) {\n            ++numSubcomponents;\n            auto len = thisComp.getConcreteClassName().length();\n            maxlen = std::max(maxlen, len);\n        }\n\n        if (numSubcomponents == 0) {\n            log_cout("Component \'{}\' has no subcomponents.", getName());\n            return;\n        }\n        maxlen += 6; //padding\n\n        std::string className = SimTK::NiceTypeName<C>::namestr();\n        // Remove "OpenSim::", etc. if it exists.\n        const std::size_t colonPos = className.rfind(":");\n        if (colonPos != std::string::npos)\n            className = className.substr(colonPos+1,\n                                         className.length()-colonPos);\n\n        log_cout("Class name and absolute path name for descendants of \'{}\'"\n                 "that are of type {}:\\n", getName(), className);\n\n        log_cout("{:>{}}  {}", concreteClassName, maxlen,\n                getAbsolutePathString());\n\n        // Step through compList again to print.\n        for (const C& thisComp : compList) {\n            const std::string thisClass = thisComp.getConcreteClassName();\n            auto path = thisComp.getAbsolutePath();\n            log_cout(fmt::format(\n                    "{:>{}}  {}/{}",\n                    fmt::format("[{}]", thisClass),\n                    maxlen,\n                    std::string((path.getNumPathLevels() - 1) * 4, \' \'),\n                    path.getComponentName()));\n        }\n        log_cout("");\n    }\n\n    /** Print outputs of this component and optionally, those of all\n    subcomponents.                                                            */\n    void printOutputInfo(const bool includeDescendants = true) const;\n    /// @}\n\nprotected:\n    class StateVariable;\n    //template <class T> friend class ComponentSet;\n    // Give the ComponentMeasure access to the realize() methods.\n    template <class T> friend class ComponentMeasure;\n\n#ifndef SWIG\n    /// @class MemberSubcomponentIndex\n    /// Unique integer type for local member subcomponent indexing\n    SimTK_DEFINE_UNIQUE_INDEX_TYPE(MemberSubcomponentIndex);\n\n    /** Construct a subcomponent as a data member of this Component. All Component\n        interface calls are automatically invoked on its subcomponents. */\n    template<class C=Component>\n    MemberSubcomponentIndex constructSubcomponent(const std::string& name) {\n        C* component = new C();\n        component->setName(name);\n        component->setOwner(*this);\n        _memberSubcomponents.push_back(SimTK::ClonePtr<Component>(component));\n        return MemberSubcomponentIndex(_memberSubcomponents.size()-1);\n    }\n    template<class C = Component>\n    const C& getMemberSubcomponent(MemberSubcomponentIndex ix) const {\n        const C* comp = dynamic_cast<const C*>(_memberSubcomponents[ix].get());\n        if(comp)\n            return *comp;\n\n        throw Exception("Component::getMemberSubcomponent() - Incorrect type requested.");\n    }\n    template<class C = Component>\n    C& updMemberSubcomponent(MemberSubcomponentIndex ix) {\n        C* comp = dynamic_cast<C*>(_memberSubcomponents[ix].upd());\n        if (comp)\n            return *comp;\n\n        throw Exception("Component::updMemberSubcomponent() - Incorrect type requested.");\n    }\n#endif //SWIG\n\n    /**\n    * Adopt a component as a subcomponent of this Component. Component\n    * methods (e.g. addToSystem(), initStateFromProperties(), ...) are\n    * automatically invoked on subcomponents when called on this Component.\n    * Realization is also performed automatically on subcomponents. All\n    * subcomponents are owned, therefore this Component also takes ownership.\n    */\n    void adoptSubcomponent(Component* subcomponent);\n\n    /** Get the number of Subcomponents immediately owned by this Component */\n    size_t getNumImmediateSubcomponents() const {\n        return getNumMemberSubcomponents() + getNumPropertySubcomponents()\n            + getNumAdoptedSubcomponents();\n    }\n\n    /** Get the number of Subcomponents that are data members of this Component */\n    size_t getNumMemberSubcomponents() const;\n    /** Get the number of Subcomponents that are properties of this Component */\n    size_t getNumPropertySubcomponents() const;\n    /** Get the number of Subcomponents adopted by this Component */\n    size_t getNumAdoptedSubcomponents() const;\n\n    /** Access this Component\'s immediate subcomponents (not those owned by\n        subcomponents) */\n    std::vector<SimTK::ReferencePtr<const Component>>\n        getImmediateSubcomponents() const;\n\n    /** @name  Component Extension Interface\n    The interface ensures that deserialization, resolution of inter-connections,\n    and handling of dependencies are performed systematically and prior to\n    system creation, followed by allocation of necessary System resources. These\n    methods are virtual and may be implemented by subclasses of\n    Components.\n\n    @note Every implementation of virtual extend method xxx(args) must begin\n    with the line "Super::extend<xxx>(args);" to ensure that the parent class\n    is called before the child class method.\n\n    The base class implementations ensures that the corresponding calls are made\n    to any subcomponents which are owned by this Component. Ownership is\n    established by the subcomponent being a data member (not serialized), a\n    property (serialized), or created and adopted based on other settings\n    or options that arise from the properties. For example, a Model (Component)\n    may have to split a body and add a Weld constraint to handle a closed\n    loop specified by Joints that are properties of the Model. The new Body and\n    Weld (components) are created and adopted as part of connecting the model to\n    form a valid multibody tree.\n\n    So assuming that your concrete %Component and all intermediate classes from\n    which it derives properly follow the requirement of calling the Super class\n    method first, the order of operations enforced here for a call to a single\n    method will be\n      -# %Component base class computations\n      -# calls to that same method for intermediate %Component-derived\n         objects\' computations, in order down from %Component, and\n      -# call to that method for the bottom-level concrete class.\n      -# finally calls to that same method for \\e all subcomponents\n    You should consider this ordering when designing a %Component.  **/\n\n    ///@{\n\n    /** Perform any secondary operations, e.g. to investigate the component or\n    to insert it into a particular internal list (for grouping), after adding\n    the subcomponent to this component. This is intended primarily for composites\n    like Model to have more control over the handling of a component being added\n    to it.\n\n    If you override this method, be sure to invoke the base class method first,\n    using code like this :\n    @code\n    void MyComponent::extendAddComponent(Component* subcomponent) {\n        Super::extendAddComponent(); // invoke parent class method\n        // ... your code goes here\n        // ... initialize any internal data structures\n    }\n    @endcode   */\n    virtual void extendAddComponent(Component* subcomponent) {};\n\n    /** Perform any time-invariant calculations, data structure initializations,\n    or other configuration based on the component\'s properties to form a\n    functioning (but not yet connected) component. For example, each property\n    should be checked to ensure that its value is within an acceptable range.\n    When this method returns, the component will be marked as being up-to-date\n    with its properties. Do not perform any configuration that depends on the\n    SimTK::MultibodySystem; it is not available at this point.\n\n    If you override this method, be sure to invoke the base class method first,\n    using code like this:\n        @code\n        void MyComponent::extendFinalizeFromProperties() {\n            Super::extendFinalizeFromProperties(); // invoke parent class method\n            // ... your code goes here\n            // ... catch invalid property values\n            // ... initialize any internal data structures\n        }\n        @endcode   */\n    virtual void extendFinalizeFromProperties() {};\n\n    /** Perform any necessary initializations required to connect the component\n    (and it subcomponents) to other components and mark the connection status.\n    Provides a check for error conditions. connect() is invoked on all components\n    to form a directed acyclic graph of the multibody system, prior to creating the\n    Simbody MultibodySystem to represent it computationally. It may also be invoked\n    at times just for its error-checking side effects.\n\n    The "root" Component argument is the root node of the directed graph composed\n    of all the subcomponents (and their subcomponents and so on ...) and their\n    interconnections. This should yield a fully connected root component. For\n    ModelComponents this is the Model component. But a Model can be connected to\n    an environment or world component with several other models, by choosing the\n    environment/world as the root.\n\n    If you override this method, be sure to invoke the base class method first,\n    using code like this:\n    @code\n    void MyComponent::extendFinalizeConnections(Component& root) {\n        Super::extendFinalizeConnections(root); // invoke parent class method\n        // ... your code goes here\n    }\n    @endcode   */\n    virtual void extendFinalizeConnections(Component& root) {};\n\n    /** Build the tree of Components from this component through its descendants.\n    This method is invoked whenever a ComponentList<C> is requested. Note that\n    all components must have been added to the model (or its subcomponents),\n    otherwise it will not be included in the tree and will not be found for\n    iteration or for connection. The implementation populates the _nextComponent\n    ReferencePtr with a pointer to the next Component in tree pre-order traversal.\n\n    @throws ComponentIsRootWithNoSubcomponents if the Component is the root and\n            yet has no subcomponents.\n    */\n    void initComponentTreeTraversal(const Component &root) const;\n\n    ///@cond\n    /** Opportunity to remove connection-related information.\n    If you override this method, be sure to invoke the base class method first,\n        using code like this:\n        @code\n        void MyComponent::disconnect(Component& root) {\n        // disconnect your subcomponents and your Super first\n        Super::extendDisconnect();\n            //your code to wipe out your connection-related information\n    }\n    @endcode  */\n    //virtual void extendDisconnect() {};\n    ///@endcond\n\n    /** Add appropriate Simbody elements (if needed) to the System\n    corresponding to this component and specify needed state resources.\n    extendAddToSystem() is called when the Simbody System is being created to\n    represent a completed system (model) for computation. That is, connect()\n    will already have been invoked on all components before any addToSystem()\n    call is made. Helper methods for adding modeling options, state variables\n    and their derivatives, discrete variables, and cache entries are available\n    and can be called within extendAddToSystem() only.\n\n    Note that this method is const; you may not modify your model component\n    or the containing model during this call. Any modifications you need should\n    instead be performed in finalizeFromProperties() or at the latest connect(),\n    which are non-const. The only exception is that you may need to record access\n    information for resources you create in the \\a system, such as an index number.\n    For most Components, OpenSim base classes either provide convenience methods\n    or handle indices automatically. Otherwise, you must declare indices as mutable\n    data members so that you can set them here.\n\n    If you override this method, be sure to invoke the base class method at the\n    beginning, using code like this:\n    @code\n    void MyComponent::extendAddToSystem(SimTK::MultibodySystem& system) const {\n        // Perform any additions to the system required by your Super\n        Super::extendAddToSystem(system);\n        // ... your code goes here\n    }\n    @endcode\n\n    This method assumes that this Component\'s addToSystem will be invoked before\n    its subcomponents. If you need your subcomponents to be added to the system,\n    first (e.g. require of a Force to be anchored to a SimTK::MobilizedBody\n    specified by subcomponents) then you must implement:\n        extendAddToSystemAfterSubcomponents().\n    It is possible to implement both method to add system elements before and then\n    after your subcomponents have added themselves. Caution is required that\n    Simbody elements are not added twice especially when order is unimportant.\n\n    @param[in,out] system   The MultibodySystem being added to.\n\n    @see addModelingOption(), addStateVariable(), addDiscreteVariables(),\n         addCacheVariable() **/\n    virtual void extendAddToSystem(SimTK::MultibodySystem& system) const {};\n\n    /** Add appropriate Simbody elements (if needed) to the System after your\n    component\'s subcomponents have had a chance to add themselves to the system.\n\n    If you override this method, be sure to invoke the base class method at the\n    beginning, using code like this:\n    @code\n    void MyComponent::\n        extendAddToSystemAfterSubcomponents(SimTK::MultibodySystem& system) const {\n        // Perform any additions to the system required by your Super\n        Super::extendAddToSystemAfterSubcomponents(system);\n        // ... your code goes here\n    }\n    @endcode\n\n    @param[in,out] system   The MultibodySystem being added to.\n\n    @see extendAddToSystem() **/\n    virtual void\n        extendAddToSystemAfterSubcomponents(SimTK::MultibodySystem& system)\n                                                                      const {};\n\n    /** Transfer property values or other state-independent initial values\n    into this component\'s state variables in the passed-in \\a state argument.\n    This is called after a SimTK::System and State have been created for the\n    Model (that is, after extendAddToSystem() has been called on all components).\n    You should override this method if your component has properties\n    (serializable values) that can affect initial values for your state\n    variables. You can also perform any other state-independent calculations\n    here that result in state initial conditions.\n\n    If you override this method, be sure to invoke the base class method first,\n    using code like this:\n    @code\n    void MyComponent::extendInitStateFromProperties(SimTK::State& state) const {\n        Super::extendInitStateFromProperties(state); // invoke parent class method\n        // ... your code goes here\n    }\n    @endcode\n\n    @param      state\n        The state that will receive the new initial conditions.\n\n    @see extendSetPropertiesFromState() **/\n    virtual void extendInitStateFromProperties(SimTK::State& state) const {};\n\n    /** Update this component\'s property values to match the specified State,\n    if the component has created any state variable that is intended to\n    correspond to a property. Thus, state variable values can persist as part\n    of the model component and be serialized as a property.\n\n    If you override this method, be sure to invoke the base class method first,\n    using code like this:\n    @code\n    void MyComponent::extendSetPropertiesFromState(const SimTK::State& state) {\n        Super::extendSetPropertiesFromState(state); // invoke parent class method\n        // ... your code goes here\n    }\n    @endcode\n\n    @param      state\n        The State from which values may be extracted to set persistent\n        property values.\n\n    @see extendInitStateFromProperties() **/\n    virtual void extendSetPropertiesFromState(const SimTK::State& state) {};\n\n    /** If a model component has allocated any continuous state variables\n    using the addStateVariable() method, then %computeStateVariableDerivatives()\n    must be implemented to provide time derivatives for those states.\n    Override to set the derivatives of state variables added to the system\n    by this component. (also see extendAddToSystem()). If the component adds states\n    and computeStateVariableDerivatives is not implemented by the component,\n    an exception is thrown when the system tries to evaluate its derivatives.\n\n    Implement like this:\n    @code\n    void computeStateVariableDerivatives(const SimTK::State& state) const {\n\n        // Let the parent class set the derivative values for the\n        // the state variables that it added.\n        Super::computeStateVariableDerivatives(state)\n\n        // Compute derivative values for states allocated by this component\n        // as a function of the state.\n        double deriv = ...\n\n        // Then set the derivative value by state variable name\n        setStateVariableDerivativeValue(state, "<state_variable_name>", deriv);\n    }\n    @endcode\n\n    For subclasses, it is highly recommended that you first call\n    Super::computeStateVariableDerivatives(state) to preserve the derivative\n    computation of the parent class and to only specify the derivatives of the state\n    variables added by name. One does have the option to override all the derivative\n    values for the parent by accessing the derivatives by their state variable name.\n    This is necessary, for example, if a newly added state variable is coupled to the\n    dynamics (derivatives) of the states variables that were added by the parent.\n    **/\n    virtual void computeStateVariableDerivatives(const SimTK::State& s) const;\n\n    /**\n     * %Set the derivative of a state variable by name when computed inside of\n     * this Component\'s computeStateVariableDerivatives() method.\n     *\n     * @param state  the State for which to set the value\n     * @param name   the name of the state variable\n     * @param deriv  the derivative value to set\n     */\n    void setStateVariableDerivativeValue(const SimTK::State& state,\n                            const std::string& name, double deriv) const;\n\n\n    // End of Component Extension Interface (protected virtuals).\n    ///@}\n\n    /** @name           Component Advanced Interface\n    You probably won\'t need to override methods in this section. These provide\n    a way for you to perform computations ("realizations") that must be\n    scheduled in carefully-ordered stages as described in the class description\n    above. The typical operation will be that the given SimTK::State provides\n    you with the inputs you need for your computation, which you will then\n    write into some element of the state cache, where later computations can\n    pick it up.\n\n    @note Once again it is crucial that, if you override a method here,\n    you invoke the superclass method as the <em>first line</em> in your\n    implementation, via a call like "Super::extendRealizePosition(state);". This\n    will ensure that all necessary base class computations are performed, and\n    that subcomponents are handled properly.\n\n    @warning Currently the realize() methods here are invoked early in the\n    sequence of realizations at a given stage, meaning that you will not be\n    able to access other computations at that same stage.\n    TODO: Should defer calls to these until at least kinematic realizations\n    at the same stage have been performed.\n\n    @see Simbody documentation for more information about realization.\n    **/\n    //@{\n    /** Obtain state resources that are needed unconditionally, and perform\n    computations that depend only on the system topology. **/\n    virtual void extendRealizeTopology(SimTK::State& state) const;\n    /** Obtain and name state resources (like state variables allocated by\n    an underlying Simbody component) that may be needed, depending on modeling\n    options. Also, perform any computations that depend only on topology and\n    selected modeling options. **/\n    virtual void extendRealizeModel(SimTK::State& state) const;\n    /** Perform computations that depend only on instance variables, like\n    lengths and masses. **/\n    virtual void extendRealizeInstance(const SimTK::State& state) const;\n    /** Perform computations that depend only on time and earlier stages. **/\n    virtual void extendRealizeTime(const SimTK::State& state) const;\n    /** Perform computations that depend only on position-level state\n    variables and computations performed in earlier stages (including time). **/\n    virtual void extendRealizePosition(const SimTK::State& state) const;\n    /** Perform computations that depend only on velocity-level state\n    variables and computations performed in earlier stages (including position,\n    and time). **/\n    virtual void extendRealizeVelocity(const SimTK::State& state) const;\n    /** Perform computations (typically forces) that may depend on\n    dynamics-stage state variables, and on computations performed in earlier\n    stages (including velocity, position, and time), but not on other forces,\n    accelerations, constraint multipliers, or reaction forces. **/\n    virtual void extendRealizeDynamics(const SimTK::State& state) const;\n    /** Perform computations that may depend on applied forces. **/\n    virtual void extendRealizeAcceleration(const SimTK::State& state) const;\n    /** Perform computations that may depend on anything but are only used\n    for reporting and cannot affect subsequent simulation behavior. **/\n    virtual void extendRealizeReport(const SimTK::State& state) const;\n    //@} end of Component Advanced Interface\n\n\n    /** @name     Component System Creation and Access Methods\n     * These methods support implementing concrete Components. Add methods\n     * can only be called inside of extendAddToSystem() and are useful for creating\n     * the underlying SimTK::System level variables that are used for computing\n     * values of interest.\n     * @warning Accessors for System indices are intended for component internal use only.\n     **/\n\n    //@{\n\n    /** Add a modeling option (integer flag stored in the State) for use by\n    this Component. Each modeling option is identified by its own\n    \\a optionName, specified here. Modeling options enable the model\n    component to be configured differently in order to represent different\n    operating modes. For example, if two modes of operation are necessary (mode\n    off and mode on) then specify optionName, "mode" with maxFlagValue = 1.\n    Subsequent gets will return 0 or 1 and set will only accept 0 and 1 as\n    acceptable values. Changing the value of a model option invalidates\n    Stage::Instance and above in the State, meaning all calculations involving\n    time, positions, velocity, and forces are invalidated. **/\n    void addModelingOption(const std::string&  optionName,\n                           int                 maxFlagValue) const;\n\n\n    /** Add a continuous system state variable belonging to this Component,\n    and assign a name by which to refer to it. Changing the value of this state\n    variable will automatically invalidate everything at and above its\n    \\a invalidatesStage, which is normally Stage::Dynamics meaning that there\n    are forces that depend on this variable. If you define one or more\n    of these variables you must also override computeStateVariableDerivatives()\n    to provide time derivatives for them. Note, all corresponding system\n    indices are automatically determined using this interface. As an advanced\n    option you may choose to hide the state variable from being accessed outside\n    of this component, in which case it is considered to be "hidden".\n    You may also want to create an Output for this state variable; see\n    #OpenSim_DECLARE_OUTPUT_FOR_STATE_VARIABLE for more information. Reporters\n    should use such an Output to get the StateVariable\'s value (instead of using\n    getStateVariableValue()).\n\n    @param[in] stateVariableName     string value to access variable by name\n    @param[in] invalidatesStage      the system realization stage that is\n                                     invalidated when variable value is changed\n    @param[in] isHidden              flag (bool) to optionally hide this state\n                                     variable from being accessed outside this\n                                     component as an Output\n    */\n    void addStateVariable(const std::string&  stateVariableName,\n         const SimTK::Stage& invalidatesStage=SimTK::Stage::Dynamics,\n         bool isHidden = false) const;\n\n    /** The above method provides a convenient interface to this method, which\n    automatically creates an \'AddedStateVariable\' and allocates resources in the\n    SimTK::State for this variable.  This interface allows the creator to\n    add/expose state variables that are allocated by underlying Simbody\n    components and specify how the state variable value is accessed by\n    implementing a concrete StateVariable and adding it to the component using\n    this method.\n    You may also want to create an Output for this state variable; see\n    #OpenSim_DECLARE_OUTPUT_FOR_STATE_VARIABLE for more information. Reporters\n    should use such an Output to get the StateVariable\'s value (instead of\n    using getStateVariableValue()).\n    */\n    void addStateVariable(Component::StateVariable*  stateVariable) const;\n\n    /** Add a system discrete variable belonging to this Component, give\n    it a name by which it can be referenced, and declare the lowest Stage that\n    should be invalidated if this variable\'s value is changed. **/\n    void addDiscreteVariable(const std::string& discreteVariableName,\n                             SimTK::Stage       invalidatesStage) const;\n\n    /**\n     * Get writable reference to the MultibodySystem that this component is\n     * connected to.\n     */\n    SimTK::MultibodySystem& updSystem() const;\n\n    /** Get the index of a Component\'s continuous state variable in the Subsystem for\n        allocations. This method is intended for derived Components that may need direct\n        access to its underlying Subsystem.*/\n    int getStateIndex(const std::string& name) const;\n\n   /**\n     * Get the System Index of a state variable allocated by this Component.\n     * Returns an InvalidIndex if no state variable with the name provided is\n     * found.\n     * @param stateVariableName   the name of the state variable\n     */\n    SimTK::SystemYIndex\n        getStateVariableSystemIndex(const std::string& stateVariableName) const;\n\n   /**\n     * Get the index of a Component\'s discrete variable in the Subsystem for\n     * allocations. This method is intended for derived Components that may need\n     * direct access to its underlying Subsystem.\n     */\n    const SimTK::DiscreteVariableIndex\n    getDiscreteVariableIndex(const std::string& name) const;\n\n    // End of System Creation and Access Methods.\n    //@}\n\npublic:\n\n    /** Find a Component to which this Component is an ancestor---in other\n    words, a Component that is directly owned by this Component or is owned\n    by one of its sub-components, sub-sub-components, etc. The Component can\n    be found by type (by specifying a template argument) and either path or\n    name.\n\n    Here is an example of searching for a component of any type with the name\n    \'elbow_flexion\':\n    @code{.cpp}\n    if (const Component* found =\n            model.findComponent(ComponentPath("elbow_flexion"))) {\n        std::cout << found.getName() << std::endl;\n    }\n    @endcode\n\n    Here, we require that \'elbow_flexion\' is of type Coordinate.\n    @code{.cpp}\n    if (const Coordinate* found =\n            model.findComponent<Coordinate>(ComponentPath("elbow_flexion"))) {\n        std::cout << "Coordinate " << found.getName() << std::endl;\n    }\n    @endcode\n\n    The search can be sped up considerably if the path or even partial path\n    name is known. For example, "forearm/elbow/elbow_flexion" will find\n    the Coordinate component of the elbow joint that connects the forearm body\n    in linear time (linear search for name at each component level). Whereas\n    supplying "elbow_flexion" requires a tree search. Returns nullptr (None in\n    Python, empty array in Matlab) if Component of that specified name cannot\n    be found.\n\n    NOTE: If the component name is ambiguous, an exception is thrown. To\n    disambiguate, more information must be provided, such as the template\n    argument to specify the type and/or a path rather than just the name. */\n    template<class C = Component>\n    const C* findComponent(const ComponentPath& pathToFind) const {\n        const std::string name = pathToFind.toString();\n        std::string msg = getConcreteClassName() + "\'" + getName() +\n                          "\'::findComponent() ";\n        if (name.empty()) {\n            msg += "cannot find a nameless subcomponent.";\n            throw Exception(msg);\n        }\n\n        ComponentPath thisAbsPath = getAbsolutePath();\n\n        const C* found = NULL;\n        if (thisAbsPath == pathToFind) {\n            found = dynamic_cast<const C*>(this);\n            if (found)\n                return found;\n        }\n\n        std::vector<const C*> foundCs;\n\n        std::string subname = pathToFind.getComponentName();\n        std::string thisName = this->getName();\n        if (thisName == subname) {\n            if ( (found = dynamic_cast<const C*>(this)) )\n                foundCs.push_back(found);\n        }\n\n        ComponentList<const C> compsList = this->template getComponentList<C>();\n\n        for (const C& comp : compsList) {\n            // if a child of this Component, one should not need\n            // to specify this Component\'s absolute path name\n            ComponentPath compAbsPath = comp.getAbsolutePath();\n            ComponentPath thisAbsPathPlusSubname = getAbsolutePath();\n            thisAbsPathPlusSubname.pushBack(subname);\n            if (compAbsPath == thisAbsPathPlusSubname) {\n                foundCs.push_back(&comp);\n                break;\n            }\n\n            // otherwise, we just have a type and name match\n            // which we may need to support for compatibility with older models\n            // where only names were used (not path or type)\n            // TODO replace with an exception -aseth\n            std::string compName = comp.getName();\n            if (compName == subname) {\n                foundCs.push_back(&comp);\n                // TODO Revisit why the exact match isn\'t found when\n                // when what appears to be the complete path.\n                log_debug("{} Found \'{}\' as a match for: Component \'{}\' of "\n                          "type {}, but it is not on the specified path.",\n                          msg, compAbsPath.toString(),\n                          comp.getConcreteClassName());\n                //throw Exception(details, __FILE__, __LINE__);\n            }\n        }\n\n        if (foundCs.size() == 1) {\n            //unique type and name match!\n            return foundCs[0];\n        }\n\n        // Only error cases remain\n        // too many components of the right type with the same name\n        if (foundCs.size() > 1) {\n            msg += "Found multiple \'" + name + "\'s of type " +\n                foundCs[0]->getConcreteClassName() + ".";\n            throw Exception(msg, __FILE__, __LINE__);\n        }\n\n        // Not found\n        return nullptr;\n    }\n\n    /** Same as findComponent(const ComponentPath&), but accepting a string (a\n    path or just a name) as input. */\n    template<class C = Component>\n    const C* findComponent(const std::string& pathToFind) const {\n        return findComponent<C>(ComponentPath(pathToFind));\n    }\n\nprotected:\n\n    template<class C>\n    const C* traversePathToComponent(ComponentPath path) const\n    {\n        // Get rid of all the ".."\'s that are not at the front of the path.\n        path.trimDotAndDotDotElements();\n\n        // Move up either to the root component or just enough to resolve all\n        // the ".."\'s.\n        size_t iPathEltStart = 0u;\n        const Component* current = this;\n        if (path.isAbsolute()) {\n            current = &current->getRoot();\n        } else {\n            while (iPathEltStart < path.getNumPathLevels() &&\n                    path.getSubcomponentNameAtLevel(iPathEltStart) == "..") {\n                // The path sends us up farther than the root.\n                if (!current->hasOwner()) return nullptr;\n                current = &current->getOwner();\n                ++iPathEltStart;\n            }\n        }\n\n        using RefComp = SimTK::ReferencePtr<const Component>;\n\n        // Skip over the root component name.\n        for (size_t i = iPathEltStart; i < path.getNumPathLevels(); ++i) {\n            // At this depth in the tree, is there a component whose name\n            // matches the corresponding path element?\n            const auto& currentPathElement =\n                path.getSubcomponentNameAtLevel(i);\n            const auto& currentSubs = current->getImmediateSubcomponents();\n            const auto it = std::find_if(currentSubs.begin(), currentSubs.end(),\n                    [currentPathElement](const RefComp& sub)\n                    { return sub->getName() == currentPathElement; });\n            if (it != currentSubs.end())\n                current = it->get();\n            else\n                return nullptr;\n        }\n        if (const C* comp = dynamic_cast<const C*>(current))\n            return comp;\n        return nullptr;\n    }\n\npublic:\n#ifndef SWIG // StateVariable is protected.\n    /**\n     * Get a StateVariable anywhere in the Component tree, given a\n     * StateVariable path.\n     *\n     * The StateVariable doesn\'t need to be in a subcomponent of this\n     * component; it could be located in a different branch of the Component\n     * tree (in such a case, the specified path might begin with "../").\n     *\n     * This returns nullptr if a StateVariable does not exist at the specified\n     * path or if the path is invalid.\n     *\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    const StateVariable* traverseToStateVariable(\n            const std::string& pathName) const;\n\n    /**\n     * Get a StateVariable anywhere in the Component tree, given a\n     * StateVariable path.\n     *\n     * The StateVariable doesn\'t need to be in a subcomponent of this\n     * component; it could be located in a different branch of the Component\n     * tree (in such a case, the specified path might begin with "../").\n     *\n     * This returns nullptr if a StateVariable does not exist at the specified\n     * path or if the path is invalid.\n     *\n     * @throws ComponentHasNoSystem if this Component has not been added to a\n     *         System (i.e., if initSystem has not been called)\n     */\n    const StateVariable* traverseToStateVariable(\n            const ComponentPath& path) const;\n#endif\n\n    /// @name Access to the owning component (advanced).\n    /// @{\n    /** Access the owner of this Component.\n     * An exception is thrown if the %Component has no owner; in this case, the\n     * component is the root component, or is orphaned.\n     * @see hasOwner() */\n    const Component& getOwner() const;\n\n    /** (For advanced users) Check if this %Component has an owner.\n     * A component may not have an owner if it:\n     * (1) is the root component, or\n     * (2) has not been added to another component */\n    bool hasOwner() const;\n\n    /** Obtain the root %Component, which is this component if it is orphaned.\n     */\n    const Component& getRoot() const;\n\nprotected:\n    /** %Set this %Component\'s reference to its owning %Component */\n    void setOwner(const Component& owner);\n\n    /// @}\n\n    /** @name Internal methods for constructing Sockets, Outputs, Inputs\n     * To declare Socket%s, Output%s, and Input%s for your component,\n     * use the following macros within your class declaration (ideally at\n     * the top near property declarations):\n     *\n     *  - #OpenSim_DECLARE_SOCKET\n     *  - #OpenSim_DECLARE_OUTPUT\n     *  - #OpenSim_DECLARE_LIST_OUTPUT\n     *  - #OpenSim_DECLARE_OUTPUT_FOR_STATE_VARIABLE\n     *  - #OpenSim_DECLARE_INPUT\n     *  - #OpenSim_DECLARE_LIST_INPUT\n     *\n     * The methods below are used in those macros, and you should not use these\n     * methods yourself.\n     */\n    /// @{\n    /**\n    * Construct a specialized Socket for this Component\'s dependence on\n    * another Component. It serves as a placeholder for the Component and its\n    * type and enables the Component to automatically traverse its dependencies\n    * and provide a meaningful message if the provided Component is\n    * incompatible or non-existent. This function also creates a Property in\n    * this component to store the connectee path for this socket; the\n    * propertyComment argument is the comment to use for that Property. */\n    template <typename T>\n    PropertyIndex constructSocket(const std::string& name,\n                                     const std::string& propertyComment) {\n        OPENSIM_THROW_IF(_socketsTable.count(name), Exception,\n            getConcreteClassName() + " already has a socket named \'"\n            + name + "\'.");\n\n        // This property is accessed / edited by the Socket class. It is\n        // not easily accessible to users.\n        // TODO does putting the addProperty here break the ability to\n        // create a custom-copy-ctor version of all of this?\n        // TODO property type should be ComponentPath or something like that.\n        PropertyIndex propIndex = this->template addProperty<std::string>(\n                "socket_" + name , propertyComment, "");\n        // We must create the Property first: the Socket needs the property\'s\n        // index in order to access the property later on.\n        _socketsTable[name].reset(\n            new Socket<T>(name, propIndex, SimTK::Stage::Topology, *this));\n        return propIndex;\n    }\n\n#ifndef SWIG // SWIG can\'t parse the const at the end of the second argument.\n    /** Construct an output for a member function of the same component.\n        The following must be true about componentMemberFunction, the function\n        that returns the output:\n\n           -# It is a member function of \\a this component.\n           -# The member function is const.\n           -# It takes only one input, which is `const SimTK::State&`\n           -# The function returns the computed quantity *by value* (e.g.,\n              `double computeQuantity(const SimTK::State&) const`).\n\n        You must also provide the stage on which the output depends.\n\n        You can ask outputs for their value only after you call\n        `finalizeFromProperties()`.\n\n       @see constructOutputForStateVariable()\n     */\n    template <typename T, typename CompType = Component>\n    bool constructOutput(const std::string& name,\n            T (CompType::*const memFunc)(const SimTK::State&) const,\n            const SimTK::Stage& dependsOn = SimTK::Stage::Acceleration) {\n        // The `const` in `CompType::*const componentMemberFunction` means this\n        // function can\'t assign componentMemberFunction to some other function\n        // pointer. This is unlikely, since that function would have to match\n        // the same template parameters (T and CompType).\n        static_assert(std::is_base_of<Component, CompType>::value,\n            "Template parameter \'CompType\' must be derived from Component.");\n\n        // This lambda takes a pointer to a component, downcasts it to the\n        // appropriate derived type, then calls the member function of the\n        // derived type. Thank you, klshrinidhi!\n        // TODO right now, the assignment to result within the lambda is\n        // making a copy! We can fix this using a reference pointer.\n        auto outputFunc = [memFunc] (const Component* comp,\n                const SimTK::State& s, const std::string&, T& result) -> void {\n            result = std::mem_fn(memFunc)(dynamic_cast<const CompType*>(comp), s);\n        };\n        return constructOutput<T>(name, outputFunc, dependsOn);\n    }\n    /** This variant handles component member functions that return the\n     * output value by const reference (const T&).\n     * @warning ONLY use this with member functions that fetch quantities that\n     * are stored within the passed-in SimTK::State. The function cannot return\n     * local variables. */\n    template <typename T, typename CompType = Component>\n    bool constructOutput(const std::string& name,\n            const T& (CompType::*const memFunc)(const SimTK::State&) const,\n            const SimTK::Stage& dependsOn = SimTK::Stage::Acceleration) {\n        static_assert(std::is_base_of<Component, CompType>::value,\n            "Template parameter \'CompType\' must be derived from Component.");\n\n        // This lambda takes a pointer to a component, downcasts it to the\n        // appropriate derived type, then calls the member function of the\n        // derived type. Thank you, klshrinidhi!\n        auto outputFunc = [memFunc] (const Component* comp,\n                const SimTK::State& s, const std::string&, T& result) -> void {\n            result = std::mem_fn(memFunc)(dynamic_cast<const CompType*>(comp), s);\n        };\n        return constructOutput<T>(name, outputFunc, dependsOn);\n    }\n    /** Construct an output that can have multiple channels. You add Channels\n    to this Output in extendFinalizeFromProperties() using\n    AbstractOutput::addChannel(). The member function\n    you provide must take the name of the channel whose value is requested. */\n    template <typename T, typename CompType>\n    bool constructListOutput(const std::string& name,\n             T (CompType::*const memFunc)(const SimTK::State&,\n                                          const std::string& channel) const,\n            const SimTK::Stage& dependsOn = SimTK::Stage::Acceleration) {\n        // The `const` in `CompType::*const componentMemberFunction` means this\n        // function can\'t assign componentMemberFunction to some other function\n        // pointer. This is unlikely, since that function would have to match\n        // the same template parameters (T and CompType).\n        static_assert(std::is_base_of<Component, CompType>::value,\n            "Template parameter \'CompType\' must be derived from Component.");\n\n        // This lambda takes a pointer to a component, downcasts it to the\n        // appropriate derived type, then calls the member function of the\n        // derived type. Thank you, klshrinidhi!\n        auto outputFunc = [memFunc] (const Component* comp,\n                const SimTK::State& s, const std::string& channel, T& result) -> void {\n            result = std::mem_fn(memFunc)(\n                    dynamic_cast<const CompType*>(comp), s, channel);\n        };\n        return constructOutput<T>(name, outputFunc, dependsOn, true);\n    }\n#endif\n\n    /** Construct an Output for a StateVariable. While this method is a\n     * convenient way to construct an Output for a StateVariable, it is\n     * inefficient because it uses a string lookup. To create a more efficient\n     * Output, create a member variable that returns the state variable\n     * directly; see the implementations of Coordinate::getValue() or\n     * Muscle::getActivation() for examples.\n     *\n     * @param name Name of the output, which must be the same as the name of\n     * the corresponding state variable. */\n    bool constructOutputForStateVariable(const std::string& name);\n\n    /** Construct an Input (socket) for this Component\'s dependence on an\n     * Output signal.  It is a placeholder for the Output and its type and\n     * enables the Component to automatically traverse its dependencies and\n     * provide a meaningful message if the provided Output is incompatible or\n     * non-existent. This also specifies at what stage the output must be valid\n     * for the component to consume it as an input.  If the Output\'s\n     * dependsOnStage is above the Input\'s requiredAtStage, an Exception is\n     * thrown because the output cannot satisfy the Input\'s requirement.\n     * This function also creates a Property in this component to store the\n     * connectee paths for this input; the\n     * propertyComment argument is the comment to use for that Property. */\n    template <typename T>\n    PropertyIndex constructInput(const std::string& name, bool isList,\n            const std::string& propertyComment,\n            const SimTK::Stage& requiredAtStage = SimTK::Stage::Instance) {\n\n        OPENSIM_THROW_IF(_inputsTable.count(name), Exception,\n            getConcreteClassName() + " already has an input named \'"\n            + name + "\'.");\n\n        PropertyIndex propIndex;\n        // This property is accessed / edited by the AbstractSocket class.\n        // It is not easily accessible to users.\n        // TODO property type should be OutputPath or ChannelPath.\n        if (isList) {\n            propIndex = this->template addListProperty<std::string>(\n                    "input_" + name, propertyComment,\n                    0, std::numeric_limits<int>::max());\n        } else {\n            propIndex = this->template addProperty<std::string>(\n                    "input_" + name, propertyComment, "");\n        }\n        // We must create the Property first: the Input needs the property\'s\n        // index in order to access the property later on.\n        _inputsTable[name].reset(\n                new Input<T>(name, propIndex, requiredAtStage, *this));\n        return propIndex;\n    }\n    /// @}\n\n    /// For internal use. Update absolute connectee paths in all sockets and\n    /// inputs in the subcomponent by prepending the absolute path of the\n    /// subcomponent. To be used when adding subcomponent to another component.\n    static void prependComponentPathToConnecteePath(Component& subcomponent);\n\nprivate:\n    //Mark components that are properties of this Component as subcomponents of\n    //this Component. This happens automatically upon construction of the\n    //component. If a Component property is added programmatically, then one must\n    //also mark it by calling markAsPropertySubcomponent() with that component.\n    void markPropertiesAsSubcomponents();\n\n    // Internal use: mark as a subcomponent, a component that is owned by this\n    // Component by virtue of being one of its properties.\n    void markAsPropertySubcomponent(const Component* subcomponent);\n\n    /// Invoke finalizeFromProperties() on the (sub)components of this Component.\n    void componentsFinalizeFromProperties() const;\n\n    /// Invoke connect() on the (sub)components of this Component.\n    void componentsFinalizeConnections(Component& root);\n\n    /// Base Component must create underlying resources in computational System.\n    void baseAddToSystem(SimTK::MultibodySystem& system) const;\n\n    /// Invoke addToSystem() on the (sub)components of this Component.\n    void componentsAddToSystem(SimTK::MultibodySystem& system) const;\n\n    /// Invoke initStateFromProperties() on (sub)components of this Component\n    void componentsInitStateFromProperties(SimTK::State& state) const;\n\n    /// Invoke setPropertiesFromState() on (sub)components of this Component\n    void componentsSetPropertiesFromState(const SimTK::State& state);\n\n    /** Used internally to construct outputs. Creating the functions for\n     outputs is potentially error-prone if the function binds to (or\n     captures) a pointer to a class. When the component is copied, the\n     pointer bound to the function is also copied and points to the original\n     object. This is unlikely to be the intended behavior. For this reason,\n     this variant of constructOutput should be used with care.\n    */\n    template <typename T>\n    bool constructOutput(const std::string& name,\n            const std::function<void (const Component*,\n                                      const SimTK::State&,\n                                      const std::string& channel, T&)> outputFunction,\n            const SimTK::Stage& dependsOn = SimTK::Stage::Acceleration,\n            bool isList = false) {\n\n        OPENSIM_THROW_IF(_outputsTable.count(name), Exception,\n            getConcreteClassName() + " already has an output named \'"\n            + name + "\'.");\n\n        _outputsTable[name].reset(\n                new Output<T>(name, outputFunction, dependsOn, isList));\n        return true;\n    }\n\n    // Get the number of continuous states that the Component added to the\n    // underlying computational system. It includes the number of built-in states\n    // exposed by this component. It represents the number of state variables\n    // managed by this Component.\n    int getNumStateVariablesAddedByComponent() const\n    {   return (int)_namedStateVariableInfo.size(); }\n    Array<std::string> getStateVariableNamesAddedByComponent() const;\n\n    const SimTK::DefaultSystemSubsystem& getDefaultSubsystem() const\n        {   return getSystem().getDefaultSubsystem(); }\n    SimTK::DefaultSystemSubsystem& updDefaultSubsystem() const\n        {   return updSystem().updDefaultSubsystem(); }\n\n    // Clear all modeling options, continuous and discrete state variables,\n    // and cache variable allocated by this Component\n    void clearStateAllocations();\n\n    // Reset by clearing underlying system indices.\n    void reset();\n\n    void warnBeforePrint() const override;\n\nprotected:\n    //Derived Components must create concrete StateVariables to expose their state\n    //variables. When exposing state variables allocated by the underlying Simbody\n    //component (MobilizedBody, Constraint, Force, etc...) use its interface to\n    //implement the virtual methods below. Otherwise, if the Component is adding its\n    //own state variables using the addStateVariable() helper, then an\n    //AddedStateVariable implements the interface and automatically handles state\n    //variable access.\n    class StateVariable {\n        friend void Component::addStateVariable(StateVariable* sv) const;\n    public:\n        StateVariable() : name(""), owner(nullptr),\n            subsysIndex(SimTK::InvalidIndex), varIndex(SimTK::InvalidIndex),\n            sysYIndex(SimTK::InvalidIndex), hidden(true) {}\n        explicit StateVariable(const std::string& name, //state var name\n            const Component& owner,     //owning component\n            SimTK::SubsystemIndex sbsix,//subsystem for allocation\n            int varIndex,               //variable\'s index in subsystem\n            bool hide = false)          //state variable is hidden or not\n            : name(name), owner(&owner),\n            subsysIndex(sbsix), varIndex(varIndex),\n            sysYIndex(SimTK::InvalidIndex), hidden(hide)  {}\n\n        virtual ~StateVariable() {}\n\n        const std::string& getName() const { return name; }\n        const Component& getOwner() const { return *owner; }\n\n        const int& getVarIndex() const { return varIndex; }\n        // return the index of the subsystem used to make resource allocations\n        const SimTK::SubsystemIndex& getSubsysIndex() const { return subsysIndex; }\n        // return the index in the global list of continuous state variables, Y\n        const SimTK::SystemYIndex& getSystemYIndex() const { return sysYIndex; }\n\n        bool isHidden() const { return hidden; }\n        void hide()  { hidden = true; }\n        void show()  { hidden = false; }\n\n        void setVarIndex(int index) { varIndex = index; }\n        void setSubsystemIndex(const SimTK::SubsystemIndex& sbsysix) {\n            subsysIndex = sbsysix;\n        }\n\n        //Concrete Components implement how the state variable value is evaluated\n        virtual double getValue(const SimTK::State& state) const = 0;\n        virtual void setValue(SimTK::State& state, double value) const = 0;\n        virtual double getDerivative(const SimTK::State& state) const = 0;\n        // The derivative a state should be a cache entry and thus does not\n        // change the state\n        virtual void setDerivative(const SimTK::State& state, double deriv) const = 0;\n\n    private:\n        std::string name;\n        SimTK::ReferencePtr<const Component> owner;\n\n        // Identify which subsystem this state variable belongs to, which should\n        // be determined and set at creation time\n        SimTK::SubsystemIndex subsysIndex;\n        // The local variable index in the subsystem also provided at creation\n        // (e.g. can be QIndex, UIndex, or Zindex type)\n        int  varIndex;\n        // Once allocated a state in the system will have a global index\n        // and that can be stored here as well\n        SimTK::SystemYIndex sysYIndex;\n\n        // flag indicating if state variable is hidden to the outside world\n        bool hidden;\n    };\n\n    /// Helper method to enable Component makers to specify the order of their\n    /// subcomponents to be added to the System during addToSystem(). It is\n    /// highly unlikely that you will need to reorder the subcomponents of your\n    /// custom component. This ability is primarily intended for Model (and\n    /// other top-level) components that have the responsibility of creating a\n    /// valid SimTK::MultibodySystem. MultibodySystem (Simbody) elements such as\n    /// MobilizedBodies must be added sequentially to form a Multibody tree.\n    /// SimTK::Constraints and SimTK::Forces must be applied to MobilizedBodies\n    /// that are already present in the MultibodySystem. The Model component\n    /// handles this order for you and should handle user-defined Components\n    /// without any issues. You should rarely need to use this method yourself.\n    /// If needed, use this method in extendFinalizeConnections() of your\n    /// Component (or within your extendConnectToModel() for ModelComponents) to\n    /// set the order of your subcomponents. For example, Model orders\n    /// subcomponents according to the Multibody tree and adds bodies and joints\n    /// in order starting from Ground and growing outward. If the subcomponent\n    /// already appears in the ordered list setting it later in the list has no\n    /// effect. The list remains unique. NOTE: If you do need to set the order\n    /// of your subcomponents, you must do so for all your immediate\n    /// subcomponents, otherwise those components not in the ordered list will\n    /// not be added to the System.\n    void setNextSubcomponentInSystem(const Component& sub) const;\n\n    /// resetSubcomponentOrder clears this Component\'s list of ordered\n    /// subcomponents (but otherwise leaves subcomponents untouched). You can\n    /// form the ordered list using setNextSubcomponentInSystem() above.\n    void resetSubcomponentOrder() {\n        _orderedSubcomponents.clear();\n    }\n\n    /// Handle a change in XML syntax for Sockets.\n    void updateFromXMLNode(SimTK::Xml::Element& node, int versionNumber)\n            override;\n\nprivate:\n\n    // Reference to the owning Component of this Component. It is not the\n    // previous in the tree, but is the Component one level up that owns this\n    // one.\n    SimTK::ReferencePtr<const Component> _owner;\n\n    // Reference pointer to the successor of the current Component in Pre-order traversal\n    mutable SimTK::ReferencePtr<const Component> _nextComponent;\n\n    // Reference pointer to the system that this component belongs to.\n    SimTK::ReferencePtr<SimTK::MultibodySystem> _system;\n\n    // propertiesTable maintained by Object\n\n    // Table of Component\'s structural Sockets indexed by name.\n    std::map<std::string, SimTK::ClonePtr<AbstractSocket>> _socketsTable;\n\n    // Table of Component\'s Inputs indexed by name.\n    std::map<std::string, SimTK::ClonePtr<AbstractInput>> _inputsTable;\n\n    // Table of Component\'s Outputs indexed by name.\n    std::map<std::string, SimTK::ClonePtr<AbstractOutput> > _outputsTable;\n\n    // Underlying SimTK custom measure ComponentMeasure, which implements\n    // the realizations in the subsystem by calling private concrete methods on\n    // the Component. Every model component has one of these, allocated\n    // in its extendAddToSystem() method, and placed in the System\'s default\n    // subsystem.\n    SimTK::ResetOnCopy<SimTK::MeasureIndex> _simTKcomponentIndex;\n\n    // list of subcomponents that are contained in this Component\'s properties\n    SimTK::ResetOnCopy<SimTK::Array_<SimTK::ReferencePtr<Component>>>\n        _propertySubcomponents;\n    // Keep fixed list of data member Components upon construction\n    SimTK::Array_<SimTK::ClonePtr<Component> > _memberSubcomponents;\n    // Hold onto adopted components\n    SimTK::Array_<SimTK::ClonePtr<Component> > _adoptedSubcomponents;\n\n    // A flat list of subcomponents (immediate and otherwise) under this\n    // Component. This list must be populated prior to addToSystem(), and is\n    // used strictly to specify the order in which addToSystem() is invoked\n    // on its subcomponents. The order is necessary for the construction\n    // of Simbody elements (e.g. MobilizedBodies, Constraints, Forces,\n    // Measures, ...) which cannot be added to the SimTK::MultibodySystem in\n    // arbitrary order. In the case of MobilizedBodies, for example, the parent\n    // MobilizedBody must be part of the system before the child can be added.\n    // OpenSim::Model performs the mapping from User specifications to the\n    // system order required by the SimTK::MultibodySystem.\n    // If the Component does not reset the list, it is by default the ownership\n    // tree order of its subcomponents.\n    mutable std::vector<SimTK::ReferencePtr<const Component> > _orderedSubcomponents;\n\n    // Structure to hold modeling option information. Modeling options are\n    // integers 0..maxOptionValue. At run time we keep them in a Simbody\n    // discrete state variable that invalidates Model stage if changed.\n    struct ModelingOptionInfo {\n        ModelingOptionInfo() : maxOptionValue(-1) {}\n        explicit ModelingOptionInfo(int maxOptVal)\n        :   maxOptionValue(maxOptVal) {}\n        // Model\n        int                             maxOptionValue;\n        // System\n        SimTK::DiscreteVariableIndex    index;\n    };\n\n    // Class for handling state variable added (allocated) by this Component\n    class AddedStateVariable : public StateVariable {\n        public:\n        // Constructors\n        AddedStateVariable() : StateVariable(),\n            invalidatesStage(SimTK::Stage::Empty)  {}\n\n        /** Convenience constructor for defining a Component added state variable */\n        explicit AddedStateVariable(const std::string& name, //state var name\n                        const Component& owner,       //owning component\n                        SimTK::Stage invalidatesStage,//stage this variable invalidates\n                        bool hide=false) :\n                    StateVariable(name, owner,\n                            SimTK::SubsystemIndex(SimTK::InvalidIndex),\n                            SimTK::InvalidIndex, hide),\n                        invalidatesStage(SimTK::Stage::Empty) {}\n\n        //override virtual methods\n        double getValue(const SimTK::State& state) const override;\n        void setValue(SimTK::State& state, double value) const override;\n\n        double getDerivative(const SimTK::State& state) const override;\n        void setDerivative(const SimTK::State& state, double deriv) const override;\n\n        private: // DATA\n        // Changes in state variables trigger recalculation of appropriate cache\n        // variables by automatically invalidating the realization stage specified\n        // upon allocation of the state variable.\n        SimTK::Stage    invalidatesStage;\n    };\n\n    // Structure to hold related info about discrete variables\n    struct StateVariableInfo {\n        StateVariableInfo() {}\n        explicit StateVariableInfo(Component::StateVariable* sv, int order) :\n        stateVariable(sv), order(order) {}\n\n        // Need empty copy constructor because default compiler generated\n        // will fail since it cannot copy a unique_ptr!\n        StateVariableInfo(const StateVariableInfo&) {}\n        // Now handle assignment by moving ownership of the unique pointer\n        StateVariableInfo& operator=(const StateVariableInfo& svi) {\n            if(this != &svi){\n                //assignment has to be const but cannot swap const\n                //want to keep unique pointer to guarantee no multiple reference\n                //so use const_cast to swap under the covers\n                StateVariableInfo* mutableSvi = const_cast<StateVariableInfo *>(&svi);\n                stateVariable.swap(mutableSvi->stateVariable);\n            }\n            order = svi.order;\n            return *this;\n        }\n\n        // State variable\n        std::unique_ptr<Component::StateVariable> stateVariable;\n        // order of allocation\n        int order;\n    };\n\n    // Structure to hold related info about discrete variables\n    struct DiscreteVariableInfo {\n        DiscreteVariableInfo() {}\n        explicit DiscreteVariableInfo(SimTK::Stage invalidates)\n        :   invalidatesStage(invalidates) {}\n        // Model\n        SimTK::Stage                    invalidatesStage;\n        // System\n        SimTK::DiscreteVariableIndex    index;\n    };\n\n    /**\n    * A cache variable, as stored internally by Component.\n    */\n    struct StoredCacheVariable {\n        SimTK::ClonePtr<SimTK::AbstractValue> value;\n        SimTK::Stage dependsOnStage;\n\n        // initialized by Component::extendRealizeTopology\n        SimTK::ResetOnCopy<SimTK::CacheEntryIndex> maybeUninitIndex{\n            SimTK::InvalidIndex\n        };\n\n        StoredCacheVariable(SimTK::AbstractValue* _value,\n                            SimTK::Stage _dependsOnStage) :\n            value{_value},\n            dependsOnStage{_dependsOnStage} {\n       }\n\n       SimTK::CacheEntryIndex index() const {\n           if (this->maybeUninitIndex.isValid()) {\n               return this->maybeUninitIndex;\n           } else {\n               OPENSIM_THROW(Exception, "StoredCacheVariable::get: failed because this->index == SimTK::InvalidIndex: this can happen if Component::extendRealizeTopology has not been called");\n           }\n       }\n    };\n\n    // Map names of modeling options for the Component to their underlying\n    // SimTK indices.\n    // These are mutable here so they can ONLY be modified in extendAddToSystem().\n    // This is not an API bug. The purpose of these maps is to automate the\n    // bookkeeping of component variables (state variables and cache entries) with\n    // their index in the computational system. The earliest time we have a valid\n    // index is when we ask the system to allocate the resources and that only\n    // happens in extendAddToSystem. Furthermore, extendAddToSystem may not\n    // alter the Component in any way that would affect its behavior- that is\n    // why it is const!\n    // The setting of the variable indices is not in the public interface and is\n    // not polymorphic.\n\n\n    mutable std::map<std::string, ModelingOptionInfo> _namedModelingOptionInfo;\n    // Map names of continuous state variables of the Component to their\n    // underlying SimTK indices.\n    mutable std::map<std::string, StateVariableInfo> _namedStateVariableInfo;\n    // Map names of discrete variables of the Component to their underlying\n    // SimTK indices.\n    mutable std::map<std::string, DiscreteVariableInfo> _namedDiscreteVariableInfo;\n    // Map names of cache entries of the Component to their individual\n    // cache information.\n    mutable SimTK::ResetOnCopy<std::unordered_map<std::string, StoredCacheVariable>> _namedCacheVariables;\n\n    // Check that the list of _allStateVariables is valid\n    bool isAllStatesVariablesListValid() const;\n\n    // Array of all state variables for fast access during simulation\n    mutable SimTK::Array_<SimTK::ReferencePtr<const StateVariable> >\n                                                            _allStateVariables;\n    // A handle the System associated with the above state variables\n    mutable SimTK::ReferencePtr<const SimTK::System> _statesAssociatedSystem;\n\n//==============================================================================\n};  // END of class Component\n//==============================================================================\n//==============================================================================\n\n// Implement methods for ComponentListIterator\n/// ComponentListIterator<T> pre-increment operator, advances the iterator to\n/// the next valid entry.\ntemplate <typename T>\nComponentListIterator<T>& ComponentListIterator<T>::operator++() {\n    if (_node==nullptr)\n        return *this;\n    // If _node has children then successor is first child\n    // move _node to point to it\n    if (_node->_memberSubcomponents.size() > 0) {\n        _node = _node->_memberSubcomponents[0].get();\n    }\n    else if (_node->_propertySubcomponents.size() > 0) {\n        _node = _node->_propertySubcomponents[0].get();\n    }\n    else if (_node->_adoptedSubcomponents.size() > 0) {\n        _node = _node->_adoptedSubcomponents[0].get();\n    }\n    // If processing a subtree under _root we stop when our successor is the same\n    // as the successor of _root as this indicates we\'re leaving the _root\'s subtree.\n    else if (_node->_nextComponent.get() == _root->_nextComponent.get())\n        _node = nullptr;\n    else // move on to the next component we computed earlier for the full tree\n        _node = _node->_nextComponent.get();\n    advanceToNextValidComponent(); // make sure we have a _node of type T after advancing\n    return *this;\n}\n\n/// Internal method to advance iterator to next valid component.\ntemplate <typename T>\nvoid ComponentListIterator<T>::advanceToNextValidComponent() {\n    // Advance _node to next valid (of type T) if needed\n    // Similar logic to operator++ but applies _filter->isMatch()\n    while (_node != nullptr && (dynamic_cast<const T*>(_node) == nullptr ||\n                                !_filter.isMatch(*_node) ||\n                                (_node == _root))){\n        if (_node->_memberSubcomponents.size() > 0) {\n            _node = _node->_memberSubcomponents[0].get();\n        }\n        else if (_node->_propertySubcomponents.size() > 0) {\n            _node = _node->_propertySubcomponents[0].get();\n        }\n        else if (_node->_adoptedSubcomponents.size() > 0) {\n            _node = _node->_adoptedSubcomponents[0].get();\n        }\n        else {\n            if (_node->_nextComponent.get() == _root->_nextComponent.get()){ // end of subtree under _root\n                _node = nullptr;\n                continue;\n            }\n            _node = _node->_nextComponent.get();\n        }\n    }\n    return;\n}\n\n\nclass ConnecteeNotSpecified : public Exception {\npublic:\n    ConnecteeNotSpecified(const std::string& file,\n                          size_t line,\n                          const std::string& func,\n                          const AbstractSocket& socket,\n                          const Component& owner) :\n    Exception(file, line, func) {\n        std::string msg = "Connectee for Socket \'" + socket.getName() +\n                "\' of type " + socket.getConnecteeTypeName() + " in " +\n                owner.getConcreteClassName() + " at " +\n                owner.getAbsolutePathString() + " is unspecified. "\n                "If this model was built programmatically, perhaps "\n                "finalizeConnections() was not called before "\n                "printing.";\n        addMessage(msg);\n    }\n};\n\ntemplate<class C>\nconst C& Socket<C>::getConnectee() const {\n    if (!isConnected()) {\n        std::string msg = "Socket " + getName() + " of type " +\n                          C::getClassName() + " in " +\n                          getOwner().getAbsolutePathString() + " of type " +\n                          getOwner().getConcreteClassName() + " is not connected.";\n        OPENSIM_THROW(Exception, msg);\n    }\n    return connectee.getRef();\n}\n\ntemplate<class C>\nvoid Socket<C>::findAndConnect(const ComponentPath& connectee) {\n    const auto* comp =\n            getOwner().getRoot().template findComponent<C>(connectee);\n    OPENSIM_THROW_IF(!comp, ComponentNotFound, connectee.toString(),\n                     getConnecteeTypeName(),\n                     getOwner().getAbsolutePathString());\n    connect(*comp);\n}\n\ntemplate<class C>\nvoid Socket<C>::finalizeConnection(const Component& root) {\n\n    // If the reference to the connectee is set, use that. Otherwise, use the\n    // connectee path property.\n    if (isConnected()) {\n        const auto& comp = *connectee;\n        const auto& rootOfConnectee = comp.getRoot();\n        const auto& myRoot = getOwner().getRoot();\n        OPENSIM_THROW_IF(&myRoot != &rootOfConnectee, Exception,\n            "Socket<" + getConnecteeTypeName() + "> \'" + getName() +\n            "\' in " + getOwner().getConcreteClassName() + " at " +\n            getOwner().getAbsolutePathString() + " cannot connect to " +\n            comp.getConcreteClassName() + " at " +\n            comp.getAbsolutePathString() + ": components do not have the same "\n            "root component. Did you intend to add \'" +\n            rootOfConnectee.getName() + "\' to \'" + myRoot.getName() + "\'?");\n\n        ComponentPath connecteePath = connectee->getRelativePath(getOwner());\n        // If the relative path starts with ".." then use an absolute path\n        // instead.\n        if (connecteePath.getNumPathLevels() > 1 &&\n                connecteePath.getSubcomponentNameAtLevel(0) == "..")\n            connecteePath = connectee->getAbsolutePath();\n        updConnecteePathProp().setValue(0, connecteePath.toString());\n\n    } else {\n        const auto connecteePath = getConnecteePath();\n        OPENSIM_THROW_IF(connecteePath.empty(), ConnecteeNotSpecified,\n                        *this, getOwner());\n\n        ComponentPath path(connecteePath);\n        const C* comp = nullptr;\n        if (path.isAbsolute()) {\n            comp = &root.template getComponent<C>(path);\n        } else {\n            comp = &getOwner().template getComponent<C>(path);\n        }\n        connectInternal(*comp);\n    }\n}\n\ntemplate<class T>\nvoid Input<T>::connect(const AbstractOutput& output,\n                       const std::string& alias) {\n    const auto* outT = dynamic_cast<const Output<T>*>(&output);\n    if (!outT) {\n        std::stringstream msg;\n        msg << "Type mismatch between Input and Output: Input \'" << getName()\n            << "\' of type " << getConnecteeTypeName()\n            << " cannot connect to Output \'" << output.getPathName()\n            << "\' of type " << output.getTypeName() << ".";\n        OPENSIM_THROW(Exception, msg.str());\n    }\n\n    if (!isListSocket() && outT->getChannels().size() > 1) {\n        OPENSIM_THROW(Exception,\n            "Non-list input \'" + getName() +\n            "\' cannot connect to output \'" + output.getPathName() +\n            " with more than 1 channel");\n    }\n\n    // For a non-list socket, there will only be one channel.\n    for (const auto& chan : outT->getChannels()) {\n        registerChannel(chan.second, alias);\n    }\n}\n\ntemplate<class T>\nvoid Input<T>::connect(const AbstractChannel& channel,\n                       const std::string& alias) {\n    registerChannel(channel, alias);\n}\n\ntemplate<class T>\nvoid Input<T>::finalizeConnection(const Component& root) {\n\n    _connectees.clear();\n    _aliases.clear();\n    if (!_registeredChannels.empty()) {\n        clearConnecteePath();\n        OPENSIM_THROW_IF(!isListSocket() && getChannels().size() > 1,\n                         Exception,\n                         "Cannot connect single-value input to multiple channels.");\n        for (const auto& reg : _registeredChannels) {\n            const Output<T>& output = std::get<0>(reg).getRef();\n            std::string channelName = std::get<1>(reg);\n            const AbstractChannel& channel = output.getChannel(channelName);\n            const std::string& alias = std::get<2>(reg);\n            connectInternal(channel, std::get<2>(reg));\n        }\n\n        int i = -1;\n        for (const auto& chan : getChannels()) {\n\n            const auto& rootOfConnectee =\n                    chan->getOutput().getOwner().getRoot();\n            const auto& myRoot = getOwner().getRoot();\n            OPENSIM_THROW_IF(&myRoot != &rootOfConnectee, Exception,\n                "Input<" + getConnecteeTypeName() + "> \'" + getName() +\n                "\' in " + getOwner().getConcreteClassName() + " at " +\n                getOwner().getAbsolutePathString() + " cannot connect to " +\n                "Channel " + chan->getPathName() + ": components do not have "\n                "the same root component. Did you intend to add \'" +\n                rootOfConnectee.getName() + "\' to \'" + myRoot.getName() + "\'?");\n\n            ++i;\n            // Update the connectee path as\n            // <OwnerPath>/<Output><:Channel><(annotation)>\n            const auto& outputOwner = chan->getOutput().getOwner();\n            ComponentPath path = outputOwner.getRelativePath(getOwner());\n            // If the relative path starts with ".." then use an absolute path\n            // instead.\n            if (path.getNumPathLevels() > 1 &&\n                    path.getSubcomponentNameAtLevel(0) == "..")\n                path = outputOwner.getAbsolutePath();\n\n            auto pathStr = composeConnecteePath(path.toString(),\n                                                chan->getOutput().getName(),\n                                                chan->getOutput().isListOutput()\n                                                ?\n                                                chan->getChannelName() :\n                                                "",\n                                                _aliases[i]);\n\n            if (isListSocket())\n                updConnecteePathProp().appendValue(pathStr);\n            else\n                updConnecteePathProp().setValue(pathStr);\n        }\n    } else {\n        if (!isListSocket() && getConnecteePath().empty()) return;\n        std::string compPathStr, outputName, channelName, alias;\n        for (unsigned ix = 0; ix < getNumConnectees(); ++ix) {\n            parseConnecteePath(getConnecteePath(ix),\n                               compPathStr, outputName, channelName, alias);\n            ComponentPath compPath(compPathStr);\n            const AbstractOutput* output = nullptr;\n\n            if (compPath.isAbsolute()) { //absolute path string\n                if (compPathStr.empty()) {\n                    output = &root.getOutput(outputName);\n                } else {\n                    output = &root.getComponent(compPathStr).getOutput(\n                            outputName);\n                }\n            } else { // relative path string\n                const Component* comp = nullptr;\n                if (compPathStr.empty()) {\n                    comp = &getOwner();\n                } else {\n                    comp = &getOwner().getComponent(compPathStr);\n                }\n                // comp should never be null at this point.\n                OPENSIM_THROW_IF(!comp, Exception, "Internal error: "\n                                 "could not find component \'" +\n                                 compPathStr + ".");\n                output = &comp->getOutput(outputName);\n            }\n            const auto& channel = output->getChannel(channelName);\n            connectInternal(channel, alias);\n        }\n    }\n}\n\n\n} // end of namespace OpenSim\n\n#endif // OPENSIM_COMPONENT_H_\n\n', 'message': 'Update to comments.\n', 'author_name': 'Ajay Seth', 'lang': 'h'}