Scripting environments like Matlab, Python and the OpenSim GUI shell allow users to interact with the classes of the OpenSim API (see Introduction to the OpenSim API). There are many example scripts that are located in the OpenSim scripting folder, available with the distribution to help you get started. This page is resources of some of the common calls that you will make in the scripting environment of your choice.
Beginner Scripting Resources
- Run the example scripts found in the distribution.
- As you run the example scripts, find the related Classes and Methods in Doxygen
- The structure for classes can often be found in OpenSim's files (.xml or .osim). For example, Setup_Scale.xml shows the hierarchy of the ScaleTool.
- Use the OpenSim Search bar to search for a Class or Method in the documentation, on the forum or on the Doxygen pages.
- If you are having trouble with a Class or Method, ask a question on the OpenSim forum.
Inline Method and Type getting
These are inline commands that help you find the methods available for a class
|methodsview('Model') or methodsview(osimModel)||GUI, Matlab||Examine the methods available for a class (e.g. Model) or for an existing object that you've created (e.g. osimModel)|
|type(aObject)||GUI, Python||Prints the full qualified type of aObject|
|Up/Down Arrows at the command prompt||GUI, Interactive Python||Recalls past commands entered at the prompt|
|Tab completion||Matlab, Interactive Python||Define an OpenSim model or object then use tab completion in Matlab to see the available methods|
|dir(aObject)||Python||Returns a list of methods available on aObject|
Packages and Libraries
Packages and libraries are collections of classes and methods (see Introduction to the OpenSim API for background) that have a well-defined interface and can be imported into your programming environment to utilize. These can be packages to browse files, read and write files, do mathematics operations, and run simulations. The commands below are common packages or libraries you will find useful.
|java.swing||GUI||Swing is the generic GUI kit for Java, allows for I/O and creating windows if needed. Examples of usage can be found here.|
|java.lang||GUI||Lang is the Java language core libraries e.g String, Math, etc. To use particular libraries (for example Math), do "from java.lang import Math"|
|java.io||GUI||IO is the package in Java that's used to perform input/output operations including file reading/writing.|
|org.opensim.modeling||GUI and Matlab||Modeling classes from the OpenSim API. This package is automatically imported in the GUI Shell. In Matlab, excute command import org.opensim.modeling.* to avoid having to type org.opensim.modeling.'Class'|
|org.opensim.utils||GUI||Provides some convenient file browsing options|
Creating New Objects
Creation of objects is performed by the constructor method of the Class. We can create an object and populate its properties, or pass the class a correctly formatted xml file.
Note: 'path' indicates your system path to the file (i.e., C:/Users/<username>/Documents/OpenSim/4.0/Models/...).
Note: Delete "modeling." from code for Matlab.
|Action||Class Information||Default construction (Scripting shell)||XML construction (Scripting shell)|
|Marker set object||OpenSim::MarkerSet||markerSet = modeling.MarkerSet()||markerSet = modeling.MarkerSet([path 'markerSet.xml'])|
|Marker data object||OpenSim::MarkerData||markerData = modeling.MarkerData()||markerData = modeling.MarkerData([path 'walkingData.trc'])|
|Scaling tool object||OpenSim::ScaleTool||scaleTool = modeling.ScaleTool()||scaleTool = modeling.ScaleTool([path 'scale_setup.xml'])|
|Inverse Dynamics analysis object||OpenSIm::InverseDynamicsTool||idTool = modeling.InverseDynamicsTool()||idTool = modeling.InverseDynamicsTool([path 'ID_setup.xml'])|
|Control Set||OpenSim:ControlSet||controlSet = modeling.ControlSet()||controlSet = modeling.ControlSet([path 'controls.mot'])|
Loading, Creating, and Initializing Models
Loading models and dealing with model states is very common. Below are the methods for loading, copying and initializing a model
|Action||GUI Command||Matlab/Python Command|
|Loads the specified model in the GUI||loadModel(modelFileName)|
|Creates a handle to the current model in the GUI||myModel = getCurrentModel()|
|Load a model from file (Create Model Object)||myModel = modeling.Model(modelFileName)||myModel = Model('gait2354.osim')|
|Creates a copy of myModel.||myModelCopy = modeling.Model(myModel)||myModelCopy = Model(myModel)|
|Initialize the model and get the default state||myState = myModel.initSystem()||myState = myModel.initSystem()|
Exploring and Editing Models and Model Components
You can use the functionality of the OpenSim API to access the properties of a model and change their values. For examples, refer to the distributed scripts muscleScaler and alterTendonSlackLength. The OpenSim API Doxygen lists all of the available functions. For example, executing the following commands in the GUI scripting shell, sets and gets the name of the current model.
You should generally avoid adding and removing objects from a model that is "live" in the OpenSim GUI. Instead you should make a copy of the model, make additions and deletions, then reload in the GUI.
The API also allows you to access and edit the components of an OpenSim model, like its bodies, muscles, and joints. Some properties have custom "get" and "set" functions - see the respective classes for details.
|Action||Class Information||Getting a Handle to a Set||Reference an Object by index||Get object from a name||Alternative 'long path'|
|Body Set||OpenSim::BodySet||bodySet= myModel.getBodySet()||rightFemur = bodySet().get(1)||rightFemur = bodySet().get("femur_r")||rightFemur =myModel.getBodySet().get("femur_r")|
|Joint Set||OpenSim::JointSet||jointSet = myModel.getJointSet()||rightHip = jointSet ().get(7)||rightHip = jointSet().("hip_r")||rightHip = myModel.getJointSet().("hip_r")|
|Coordinate Set||OpenSim::CoordinateSet||cordSet= myModel.getCoordinateSet()||hip_coord = cordSet().get(4)||hip_coord = cordSet().get("hip_flexion_r")||hip_coord = cordSet().get("hip_flexion_r")|
|Muscle Set||Muscles||muscleSet= myModel.getMuscles()||recFemR = muscleSet().get(3)||rec_fem_r = recFemRt().get("'recFem_r")||rec_fem_r= myModel.getMuscles().get("'recFem_r")|
|Path Point of a Muscle||OpenSim; PathPoint||pathPoints = myModel.getMuscles().get("'recFem_r").getGeometryPath().getPathPointSet()||recFemPathPoint1 = pathPoints.get(0)||recFemPathPoint1 = pathPoints.get("rect_fem_r-P1")||recFemPathPoint1 = myModel.getMuscles().get("'recFem_r").getGeometryPath().getPathPointSet()|
Once a Handle to the component has been created you can edit its properties and methods.
|Get the optimal fiber length||OpenSim::Muscle::getOptimalFiberLength	()||recFemFiberLength = RectusFemoris.getOptimalFiberLength()|
|Set the optimal fiber length||OpenSim::Muscle::setOptimalFiberLength()||RectusFemoris.setOptimalFiberLength(0.23)|
|Set the tendon slack length||OpenSim::Muscle::setTendonSlackLength()||RectusFemoris.setTendonSlackLength(0.2105)|
|Get the muscle maximum isometric force||OpenSim::Muscle::getMaxIsometricForce()||recFemMaxForce = RectusFemoris.getMaxIsometricForce()|
You may need to downcast an object from an abstract class (e.g., Muscle) to a derived class (e.g., Thelen2003Muscle) in order to gain access to its properties and methods. Here is an example:
Using the Tools
Tools contain a number of grouped Methods that allow you to run a study. For example, to scale a Model to match experimental data the ScaleTool groups GenericModelMaker(), ModelScaler() and MarkerPlacer() together. The AnalyzeTool() can group StaticOptimization() and MuscleAnalysis() together to output muscle states of a Static Optimization.
|Command or Class||Platform||Action|
|getScriptsDir()||GUI||Returns the path of your scripts directory|
|java.io.File||GUI||A representation of file and directory pathnames that allows you to easily create files and directories, get all the files in a given directory, and more. Read more here: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html|
|getInstallDir()||GUI||Returns the path of your OpenSim Install directory|
|getResourcesDir()||GUI||Returns the path of your resources directory containg models and code examples (e.g., 'C/Users/<username>/Documents/OpenSim/4.0').|
|os.chdir(NewWorkingDirectoryName)||GUI, Python||Changes the working directory of the scripting shell (default is your OpenSim installation directory) to the directory specified by NewWorkingDirectoryName. You need to import the python os package before using it (i.e. import os).|
|execfile("ScriptFileName")||GUI, Python||Executes a script. Can be used in shell or as part of script. File name can be absolute path to file or relative to the current directory.|
Working with Vectors, Matrices, and Other SimTK Classes
We've exposed the most commonly used SimTK classes. In particular:
modeling.Vec3(double e0, double e1, double e2)
|All||Creates a Simtk Vec3 object (a vector of length 3). If passed only one argument (double e) all elements will be set to e.|
|modeling.Vector(int length, double e)||All||Creates a Simtk Vector with specified length. All elements are set to e.|
modeling.Mat33(double e0, ... , double e8)
|All||Creates a Simtk Mat33 object (a 3x3 matrix). If passed only one argument (double e), the diagonal elements will be set to e and other elements set to zero.|
See doxygen link at right for additional constructors
|All||Creates a Simtk Inertia object. All constructors are available except symmetric matrix constructors.|
|modeling.State()||All||Creates a Simtk State object. See the doxygen link for more information.|
Creates a Simtk Stage object, optionally realized to level l. See the doxygen link for more information.
- For Simbody doxygen links above Vec3P corresponds to a modeling.Vec3 object and RealP corresponds to a double value.
- To see the available methods for these objects, use methodsview() or tab completion (Matlab only).
- You can find more information in the SimTK Basics section of the User's Guide. Note that only the SimTK classes listed above are available through scripting.
- You can also find more information in the section below on Handling C++ Templates.
In many cases the function you're trying to call takes an argument type different from the object you have already. This is true even moving data between Matlab and Java objects, and between objects in the SimTK namespace and those in the OpenSim namespace. In particular, many OpenSim methods return an ArrayDouble (Array<double) and you would prefer to convert the array to a different type. The following set of convenience methods are "Adaptors" intended to help you pass data around between OpenSim objects and low level SimTK objects.
For Matlab, leave off "modeling". For Python, change "modeling" to "opensim".
|modeling.ArrayDouble.createVec3([0.0,0.05,0.35])||All||Creates a SimTK::Vec3|
|All||returns SimTK::Vec3 populated from ArrayDouble of size 3.|
|modeling.ArrayDouble.getAsVector()||All||return SimTK::Vector populated from ArrayDouble|
|modeling.ArrayDouble.populateFromVector(SimTK::Vector aVector)||All||populate an ArrayDouble from the passed in SimTK Vector|
|modeling.ArrayDouble.getValuesFromVec3(SimTK::Vec3 vec3)||All||returns an ArrayDouble populated from the passed in SimTK Vec3|
When referring to indexed elements remember that Matlab begins indexing at 1 while OpenSim data structures begin at 0.
Advanced Multibody Calculations with Simbody
In 4.0, you can perform advanced multibody calculations in scripting via the SimbodyMatterSubsystem inside the OpenSim Model (model.getMatterSubsystem()). The SimbodyMatterSubsystem class allows you to compute the mass matrix, Jacobians, inverse dynamics moments, etc.
Class Templates (Vec3(), Array<double>, Vector() )
A summary of Templatized Class use in scripting can be found on the Scripting Versions of OpenSim C++ API Calls page.
Templates are advanced C++ constructs that are used extensively throughout the OpenSim API and Simbody API. If you see notation like Array<double> in the doxygen or C++ code that you are trying to replicate, this means you're working with a templatized class and, to use that class in scripting, will need to find its appropriate mapping in the scripting environment. For more information, and a easy to use ummary of the C++ to scripting mappings, see the Scripting Versions of OpenSim C++ API Calls page.
Obtaining Position and Velocity Information
For more information regarding multibody system states, refer to the SimTK Simulation Concepts documentation in the Developer's Guide.
In order to obtain simulation position or velocity state information you must have a State object in hand.
Now you can use methods on Body objects (actually, from the Frame class) to obtain the location or velocity of a point in the ground frame.
Using the Simbody Visualizer
You can use the visualizer from Simbody in Matlab and Python. To do so call the "setUseVisualizer" method and pass in the parameter "true", and when you run the simulation the Simbody Visualizer GUI will pop up. The example of usage is described in "TugOfWar_CompleteRunVisualizer.m"
There are several examples in the Matlab scripts and GUI scripts that show how to perform batch processing by calling the OpenSim API (e.g. Analyze, IK). We encourage you to use this approach rather than using Matlab's xml parsing tools. To read more about why this is the case, please see the scripting FAQ:
- Java File IO: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html
- Using Java in Jython: http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html
- Jython Swing examples: http://wiki.python.org/jython/SwingExamples