Simbody  3.3
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
System.h
Go to the documentation of this file.
1 #ifndef SimTK_SimTKCOMMON_SYSTEM_H_
2 #define SimTK_SimTKCOMMON_SYSTEM_H_
3 
4 /* -------------------------------------------------------------------------- *
5  * Simbody(tm): SimTKcommon *
6  * -------------------------------------------------------------------------- *
7  * This is part of the SimTK biosimulation toolkit originating from *
8  * Simbios, the NIH National Center for Physics-Based Simulation of *
9  * Biological Structures at Stanford, funded under the NIH Roadmap for *
10  * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
11  * *
12  * Portions copyright (c) 2006-13 Stanford University and the Authors. *
13  * Authors: Michael Sherman *
14  * Contributors: Peter Eastman *
15  * *
16  * Licensed under the Apache License, Version 2.0 (the "License"); you may *
17  * not use this file except in compliance with the License. You may obtain a *
18  * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. *
19  * *
20  * Unless required by applicable law or agreed to in writing, software *
21  * distributed under the License is distributed on an "AS IS" BASIS, *
22  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
23  * See the License for the specific language governing permissions and *
24  * limitations under the License. *
25  * -------------------------------------------------------------------------- */
26 
27 #include "SimTKcommon/basics.h"
28 #include "SimTKcommon/Simmatrix.h"
31 
32 #include <cassert>
33 
34 namespace SimTK {
35 
36 class DecorativeGeometry;
37 class DefaultSystemSubsystem;
38 class ScheduledEventHandler;
39 class ScheduledEventReporter;
40 class TriggeredEventHandler;
41 class TriggeredEventReporter;
42 class RealizeOptions;
43 class RealizeResults;
44 class ProjectOptions;
45 class ProjectResults;
46 
47 //==============================================================================
48 // SYSTEM
49 //==============================================================================
97 public:
98 class Guts; // local; name is System::Guts
99 
100 
101 //------------------------------------------------------------------------------
124 System& setUpDirection(const CoordinateDirection& up);
125 
133 System& setUseUniformBackground(bool useUniformBackground);
134 
148 System& setDefaultTimeScale(Real tc);
149 
157 System& setDefaultLengthScale(Real lc);
158 
164 void setHasTimeAdvancedEvents(bool); // default=false
165 
167 CoordinateDirection getUpDirection() const;
170 bool getUseUniformBackground() const;
173 Real getDefaultTimeScale() const;
176 Real getDefaultLengthScale() const;
179 bool hasTimeAdvancedEvents() const;
183 //------------------------------------------------------------------------------
192 inline void addEventHandler(ScheduledEventHandler* handler);
195 inline void addEventHandler(TriggeredEventHandler* handler);
198 inline void addEventReporter(ScheduledEventReporter* handler) const;
201 inline void addEventReporter(TriggeredEventReporter* handler) const;
205 //------------------------------------------------------------------------------
234 const State& realizeTopology() const;
235 
250 const State& getDefaultState() const;
253 State& updDefaultState();
254 
273 void realizeModel(State& state) const;
274 
282 void realize(const State& state, Stage stage = Stage::HighestRuntime) const;
286 //------------------------------------------------------------------------------
367 void project(State& state, Real accuracy=-1) const;
368 
384 void projectQ(State& state, Real accuracy=-1) const;
385 
403 void projectU(State& state, Real accuracy=-1) const;
404 
440 void projectQ(State& state, Vector& qErrEst,
441  const ProjectOptions& options, ProjectResults& results) const;
442 
466 void projectU(State& state, Vector& uErrEst,
467  const ProjectOptions& options, ProjectResults& results) const;
468 
469 
487 void prescribe(State& state) const {
488  realize(state, Stage::Time);
489  prescribeQ(state);
490  realize(state, Stage::Position);
491  prescribeU(state);
492 }
493 
512 bool prescribeQ(State& state) const;
513 
529 bool prescribeU(State& state) const;
533 //------------------------------------------------------------------------------
572 void handleEvents(State& state,
573  Event::Cause cause,
574  const Array_<EventId>& eventIds,
575  const HandleEventsOptions& options,
576  HandleEventsResults& results) const;
577 
581 void reportEvents(const State& state,
582  Event::Cause cause,
583  const Array_<EventId>& eventIds) const;
584 
593 void calcEventTriggerInfo(const State& state,
594  Array_<EventTriggerInfo>& triggerInfo) const;
595 
601 void calcTimeOfNextScheduledEvent(const State& state,
602  Real& tNextEvent,
603  Array_<EventId>& eventIds,
604  bool includeCurrentTime) const;
605 
609 void calcTimeOfNextScheduledReport(const State& state,
610  Real& tNextEvent,
611  Array_<EventId>& eventIds,
612  bool includeCurrentTime) const;
616 //------------------------------------------------------------------------------
645 void relax(State& state, Stage stage, Real accuracy=-1) const;
649 //------------------------------------------------------------------------------
670 void multiplyByN(const State& state, const Vector& u,
671  Vector& dq) const;
673 void multiplyByNTranspose(const State& state, const Vector& fq,
674  Vector& fu) const;
676 void multiplyByNPInv(const State& state, const Vector& dq,
677  Vector& u) const;
679 void multiplyByNPInvTranspose(const State& state, const Vector& fu,
680  Vector& fq) const;
684 //------------------------------------------------------------------------------
694 void resetAllCountersToZero();
695 
696  // Realization
697 
701 int getNumRealizationsOfThisStage(Stage) const;
702 
706 int getNumRealizeCalls() const;
707 
708  // Prescribed motion
709 
711 int getNumPrescribeQCalls() const;
713 int getNumPrescribeUCalls() const;
714 
715  // Projection
716 
719 int getNumProjectQCalls() const;
721 int getNumFailedProjectQCalls() const;
724 int getNumQProjections() const;
727 int getNumQErrorEstimateProjections() const;
728 
731 int getNumProjectUCalls() const;
733 int getNumFailedProjectUCalls() const;
736 int getNumUProjections() const;
739 int getNumUErrorEstimateProjections() const;
740 
741  // Event handling and reporting
742 
746 int getNumHandlerCallsThatChangedStage(Stage) const;
747 
750 int getNumHandleEventCalls() const;
751 
754 int getNumReportEventCalls() const;
758 //------------------------------------------------------------------------------
765 System() : guts(0) { }
767 System(const System&);
769 System& operator=(const System&);
772 ~System();
773 
775 const String& getName() const;
777 const String& getVersion() const;
778 
781 SubsystemIndex adoptSubsystem(Subsystem& child);
782 
784 int getNumSubsystems() const;
786 const Subsystem& getSubsystem(SubsystemIndex) const;
788 Subsystem& updSubsystem(SubsystemIndex);
791 const DefaultSystemSubsystem& getDefaultSubsystem() const;
794 DefaultSystemSubsystem& updDefaultSubsystem();
795 
799 inline operator const Subsystem&() const; // implemented below
803 inline operator Subsystem&();
804 
809 bool systemTopologyHasBeenRealized() const;
810 
818 StageVersion getSystemTopologyCacheVersion() const;
819 
825 void setSystemTopologyCacheVersion(StageVersion topoVersion) const;
826 
836 void invalidateSystemTopologyCache() const;
837 
845 void calcDecorativeGeometryAndAppend(const State&, Stage,
847 
848 
851 bool isSameSystem(const System& otherSystem) const;
852 
853 
857 const Guts& getSystemGuts() const {assert(guts); return *guts;}
861 Guts& updSystemGuts() {assert(guts); return *guts;}
862 
866 void adoptSystemGuts(System::Guts* g);
867 
869 explicit System(System::Guts* g) : guts(g) { }
871 bool hasGuts() const {return guts!=0;}
872 
874 bool isOwnerHandle() const;
876 bool isEmptyHandle() const;
879 private:
880 friend class Guts;
881 // This is the only data member in this class. Also, any class derived from
882 // System must have *NO* data members at all (data goes in the Guts class).
883 Guts* guts;
884 };
885 
886 
896 public:
897  explicit DefaultSystemSubsystem(System& sys);
898  void addEventHandler(ScheduledEventHandler* handler);
899  void addEventHandler(TriggeredEventHandler* handler);
900  void addEventReporter(ScheduledEventReporter* handler) const;
901  void addEventReporter(TriggeredEventReporter* handler) const;
902  EventId createEventId(SubsystemIndex subsys, const State& state) const;
903  void findSubsystemEventIds
904  (SubsystemIndex subsys, const State& state,
905  const Array_<EventId>& allEvents,
906  Array_<EventId>& eventsForSubsystem) const;
907  // don't let doxygen see this private class
909  class Guts;
911 private:
912  const Guts& getGuts() const;
913  Guts& updGuts();
914 };
915 
917 { updDefaultSubsystem().addEventHandler(handler); }
919 { updDefaultSubsystem().addEventHandler(handler); }
924 
925 inline System::operator const Subsystem&() const {return getDefaultSubsystem();}
926 inline System::operator Subsystem&() {return updDefaultSubsystem();}
927 
928 
929 //==============================================================================
930 // PROJECT OPTIONS and PROJECT RESULTS
931 //==============================================================================
936 public:
937  enum Option {
939  None = 0x0000,
944  LocalOnly = 0x0001,
948  DontThrow = 0x0002,
951  UseInfinityNorm = 0x0004,
955  ForceProjection = 0x0008,
960  };
961 
967  explicit ProjectOptions(Real accuracy)
968  { clear(); setRequiredAccuracy(accuracy); }
971  explicit ProjectOptions(Option opt)
972  { clear(); setOption(opt); }
973 
978  { optionSet=0; setAccuracyDefaults(); return *this; }
979 
985  requiredAccuracy = accuracy > 0 ? accuracy
987  return *this;
988  }
989 
993  assert(0 < overshoot && overshoot <= 1);
994  desiredOvershoot = overshoot;
995  return *this;
996  }
997 
1001  assert(limit > 0);
1002  projectionLimit = limit;
1003  return *this;
1004  }
1005 
1009  { optionSet &= ~(unsigned)opt; return *this; }
1012  { optionSet |= (unsigned)opt; return *this; }
1013 
1015  Real getRequiredAccuracy() const {return requiredAccuracy;}
1018  Real getOvershootFactor() const {return desiredOvershoot;}
1020  Real getProjectionLimit() const {return projectionLimit;}
1021 
1022  bool isOptionSet(Option opt) const {return (optionSet&(unsigned)opt) != 0;}
1023 
1024  static Real getDefaultRequiredAccuracy() {return Real(1e-4);}
1025  static Real getDefaultOvershootFactor() {return Real(0.1);} //i.e., 1e-5
1026 
1027  // Set operators: not, or, and, set difference
1029  { optionSet |= opts.optionSet; return *this; }
1031  { optionSet &= opts.optionSet; return *this; }
1033  { optionSet &= ~opts.optionSet; return *this; }
1034 
1035  ProjectOptions& operator|=(Option opt) {setOption(opt); return *this;}
1036  ProjectOptions& operator-=(Option opt) {clearOption(opt); return *this;}
1037 
1038 private:
1039  Real requiredAccuracy;
1040  Real desiredOvershoot; // try for accuracy*overshoot
1041  Real projectionLimit; // abort if initial norm is worse than this
1042  unsigned optionSet;
1043 
1044  void setAccuracyDefaults() {
1045  requiredAccuracy = getDefaultRequiredAccuracy();
1046  desiredOvershoot = getDefaultOvershootFactor();
1047  projectionLimit = Infinity; // we'll try from however far away
1048  }
1049 };
1050 
1053 public:
1055 
1056  enum Status {
1058  Invalid = -1,
1070  };
1071 
1075  m_exitStatus = Invalid;
1076  m_anyChangeMade = m_projectionLimitExceeded = false;
1077  m_numIterations = 0;
1078  m_worstError = -1;
1079  m_normOnEntrance = m_normOnExit = NaN;
1080  return *this;
1081  }
1082  bool isValid() const {return m_exitStatus != Invalid;}
1083  Status getExitStatus() const {return m_exitStatus;}
1084 
1085  bool getAnyChangeMade() const {assert(isValid());return m_anyChangeMade;}
1086  int getNumIterations() const {assert(isValid());return m_numIterations;}
1087  Real getNormOnEntrance() const {assert(isValid());return m_normOnEntrance;}
1088  Real getNormOnExit() const {assert(isValid());return m_normOnExit;}
1090  { assert(isValid());return m_worstError; }
1092  { assert(isValid());return m_projectionLimitExceeded; }
1093 
1095  { m_exitStatus=status; return *this; }
1097  { m_anyChangeMade=changeMade; return *this; }
1099  { m_projectionLimitExceeded=limitExceeded; return *this; }
1100  ProjectResults& setNumIterations(int numIterations)
1101  { m_numIterations=numIterations; return *this; }
1102  ProjectResults& setNormOnEntrance(Real norm, int worstError)
1103  { m_normOnEntrance=norm; m_worstError=worstError; return *this; }
1105  { m_normOnExit=norm; return *this; }
1106 private:
1107  Status m_exitStatus;
1108  bool m_anyChangeMade;
1109  bool m_projectionLimitExceeded;
1110  int m_numIterations;
1111  int m_worstError; // index of worst error on entrance
1112  Real m_normOnEntrance; // in selected rms or infinity norm
1113  Real m_normOnExit;
1114 };
1115 
1116 
1117 
1118 //==============================================================================
1119 // REALIZE OPTIONS and REALIZE RESULTS
1120 //==============================================================================
1123  unsigned int optionSet;
1124  explicit RealizeOptions(unsigned o) : optionSet(o) { }
1125 public:
1126 
1127  enum Option {
1128  None = 0x00,
1129  DontThrow = 0x01
1130  };
1131 
1132 
1133  RealizeOptions() : optionSet(0) { }
1134 
1135  // This is an implicit conversion
1136  RealizeOptions(Option opt) : optionSet((unsigned)opt) { }
1137 
1138  // Implicit conversion to bool when needed
1139  operator bool() const {return optionSet != 0;}
1140  bool isEmpty() const {return optionSet==0;}
1141 
1142  bool isOptionSet(Option opt) const {return (optionSet&(unsigned)opt) != 0;}
1143  void clear() {optionSet=0;}
1144  void clearOption(Option opt) {optionSet &= ~(unsigned)opt;}
1145  void setOption (Option opt) {optionSet |= (unsigned)opt;}
1146 
1147  // Set operators: or, and
1148  RealizeOptions& operator|=(RealizeOptions opts) {optionSet |= opts.optionSet; return *this;}
1149  RealizeOptions& operator&=(RealizeOptions opts) {optionSet &= opts.optionSet; return *this;}
1150 
1151  RealizeOptions& operator|=(Option opt) {setOption(opt); return *this;}
1152  RealizeOptions& operator-=(Option opt) {clearOption(opt); return *this;}
1153 };
1154 
1157 };
1158 
1159 
1160 
1161 
1162 } // namespace SimTK
1163 
1164 #endif // SimTK_SimTKCOMMON_SYSTEM_H_
DefaultSystemSubsystem & updDefaultSubsystem()
Get writable access to the default subsystem which is present in every system.
ScheduledEventReporter is a subclass of EventReporter for events that occur at a particular time that...
Definition: EventReporter.h:72
System(System::Guts *g)
Constructor for internal use only.
Definition: System.h:869
ScheduledEventHandler is a subclass of EventHandler for events that occur at a particular time that i...
Definition: EventHandler.h:84
Definition: System.h:1129
bool isOptionSet(Option opt) const
Definition: System.h:1142
The abstract parent of all Subsystems.
Definition: Subsystem.h:61
ProjectResults()
Definition: System.h:1054
#define SimTK_SimTKCOMMON_EXPORT
Definition: SimTKcommon/include/SimTKcommon/internal/common.h:202
Normally a project() method will return immediately after evaluating the norm if it is already at or ...
Definition: System.h:955
A project() method is free to use an out-of-date Jacobian when solving the nonlinear system...
Definition: System.h:959
ProjectResults & setNumIterations(int numIterations)
Definition: System.h:1100
ProjectOptions & operator|=(const ProjectOptions &opts)
Definition: System.h:1028
ProjectOptions & operator-=(const ProjectOptions &opts)
Definition: System.h:1032
RealizeOptions & operator|=(RealizeOptions opts)
Definition: System.h:1148
(NOT USED YET) Results for advanced users of realize() methods.
Definition: System.h:1156
ProjectOptions(Real accuracy)
This constructor allows the default accuracy to be overridden while leaving all other options at thei...
Definition: System.h:967
bool isEmpty() const
Definition: System.h:1140
Definition: Stage.h:68
int getNumIterations() const
Definition: System.h:1086
ProjectOptions & operator&=(const ProjectOptions &opts)
Definition: System.h:1030
void addEventHandler(ScheduledEventHandler *handler)
Definition: System.h:1128
A CoordinateDirection is a CoordinateAxis plus a direction indicating the positive or negative direct...
Definition: CoordinateAxis.h:246
Status getExitStatus() const
Definition: System.h:1083
ProjectOptions(Option opt)
This constructor creates default options except one setting one non-default Option.
Definition: System.h:971
This class is basically a glorified enumerated type, type-safe and range checked but permitting conve...
Definition: Stage.h:50
bool getAnyChangeMade() const
Definition: System.h:1085
Real getOvershootFactor() const
Return the factor by which a project() method should try to do better than the required accuracy...
Definition: System.h:1018
void addEventReporter(ScheduledEventReporter *handler) const
Add a ScheduledEventReporter to this System, which takes over ownership of the event reporter object...
Definition: System.h:920
ProjectOptions & setProjectionLimit(Real limit)
Project will fail immediately if the initial norm is greater than the projection limit, with status FailureToConverge.
Definition: System.h:1000
ProjectResults & clear()
Restore this object to its default-constructed state, with the return status set to Invalid...
Definition: System.h:1074
ProjectOptions & clear()
Restore this object to its default-constructed state (no options selected, default accuracy and overs...
Definition: System.h:977
static Real getDefaultOvershootFactor()
Definition: System.h:1025
System()
Default constructor creates an empty handle.
Definition: System.h:765
ProjectResults & setNormOnExit(Real norm)
Definition: System.h:1104
void addEventReporter(ScheduledEventReporter *handler) const
Guts & updSystemGuts()
Obtain a writable reference to the System::Guts object to which this handle refers.
Definition: System.h:861
This is the handle class for the hidden State implementation.
Definition: State.h:264
const Real NaN
This is the IEEE "not a number" constant for this implementation of the default-precision Real type; ...
Results for advanced users of project() methods.
Definition: System.h:1052
These are all the possible causes for events.
Definition: Event.h:123
static Real getDefaultRequiredAccuracy()
Definition: System.h:1024
int getWorstErrorOnEntrance() const
Definition: System.h:1089
bool getProjectionLimitExceeded() const
Definition: System.h:1091
Options for the advanced project() methods.
Definition: System.h:935
This object has not been filled in yet and holds no results.
Definition: System.h:1058
Option
Definition: System.h:1127
The project() was successful either because no projection was necessary or projection was able to ach...
Definition: System.h:1061
ProjectResults & setProjectionLimitExceeded(bool limitExceeded)
Definition: System.h:1098
The SimTK::Array_<T> container class is a plug-compatible replacement for the C++ standard template l...
Definition: Array.h:50
Option
Definition: System.h:937
(NOT USED YET) Options for the advanced realize() methods.
Definition: System.h:1122
bool isValid() const
Definition: System.h:1082
Normally failure to meet the accuracy requirements throws an exception.
Definition: System.h:948
const Guts & getSystemGuts() const
Obtain a const reference to the System::Guts object to which this handle refers.
Definition: System.h:857
RealizeOptions()
Definition: System.h:1133
ProjectOptions & operator-=(Option opt)
Definition: System.h:1036
Spatial configuration available.
Definition: Stage.h:58
ProjectOptions & setRequiredAccuracy(Real accuracy)
The norm of the constraint errors must be driven to below this value for a project() to be considered...
Definition: System.h:984
The abstract parent of all Subsystem "Guts" implementation classes.
Definition: SubsystemGuts.h:42
bool isOptionSet(Option opt) const
Definition: System.h:1022
const DefaultSystemSubsystem & getDefaultSubsystem() const
Get read-only access to the default subsystem which is present in every system.
float norm(const conjugate< float > &c)
Definition: conjugate.h:775
The Newton iterations were diverging.
Definition: System.h:1069
This option says we expect the state to be close to a solution already and restricts projection to mo...
Definition: System.h:944
RealizeOptions & operator-=(Option opt)
Definition: System.h:1152
void addEventHandler(ScheduledEventHandler *handler)
Add a ScheduledEventHandler to this System, which takes over ownership of the event handler object...
Definition: System.h:916
ProjectResults & setAnyChangeMade(bool changeMade)
Definition: System.h:1096
const Real Infinity
This is the IEEE positive infinity constant for this implementation of the default-precision Real typ...
ProjectResults & setExitStatus(Status status)
Definition: System.h:1094
RealizeOptions & operator&=(RealizeOptions opts)
Definition: System.h:1149
Use the stricter infinity (max absolute value) norm rather than the default RMS norm to determine whe...
Definition: System.h:951
SimTK::String is a plug-compatible std::string replacement (plus some additional functionality) inten...
Definition: String.h:62
Real getRequiredAccuracy() const
Return the current value for the required accuracy option.
Definition: System.h:1015
This is the declaration for the System::Guts class, the abstract object to which a System handle poin...
Definition: SystemGuts.h:71
Status
Definition: System.h:1056
TriggeredEventHandler is a subclass of EventHandler for events that occur when some condition is sati...
Definition: EventHandler.h:109
ProjectOptions & setOption(Option opt)
Set a particular option.
Definition: System.h:1011
This is the base class that serves as the parent of all SimTK System objects; most commonly Simbody's...
Definition: System.h:96
void clear()
Definition: System.h:1143
void clearOption(Option opt)
Definition: System.h:1144
bool hasGuts() const
Return true if this System handle is not empty.
Definition: System.h:871
ProjectOptions()
Default constructor sets options to their default values.
Definition: System.h:963
Provide a unique integer type for identifying Subsystems.
This is a concrete Subsystem that is part of every System. It provides a variety of services for the ...
Definition: System.h:895
Real getProjectionLimit() const
Return the maximum norm we're allowed to attempt to correct.
Definition: System.h:1020
Real getNormOnEntrance() const
Definition: System.h:1087
Results returned by the handleEvent() method.
Definition: Event.h:341
A new time has been realized.
Definition: Stage.h:57
This is the header which should be included in user programs that would like to make use of all the S...
Take all defaults.
Definition: System.h:939
TriggeredEventReporter is a subclass of EventReporter for events that occur when some condition is sa...
Definition: EventReporter.h:96
Includes internal headers providing declarations for the basic SimTK Core classes.
ProjectOptions & setOvershootFactor(Real overshoot)
Project will attempt to reach accuracy*overshoot but settle for just accuracy.
Definition: System.h:992
Real getNormOnExit() const
Definition: System.h:1088
ProjectOptions & clearOption(Option opt)
Remove a given option from the set.
Definition: System.h:1008
RealizeOptions(Option opt)
Definition: System.h:1136
RealizeOptions & operator|=(Option opt)
Definition: System.h:1151
ProjectOptions & operator|=(Option opt)
Definition: System.h:1035
int StageVersion
This is the type to use for Stage version numbers.
Definition: State.h:154
void prescribe(State &state) const
Set values for prescribed positions q and velocities u.
Definition: System.h:487
ProjectResults & setNormOnEntrance(Real norm, int worstError)
Definition: System.h:1102
void setOption(Option opt)
Definition: System.h:1145
Options for the handleEvent() method.
Definition: Event.h:265
Projection converged but was unable to achieve the required accuracy.
Definition: System.h:1064
This is a class to represent unique IDs for events in a type-safe way.