These instructions assume that you've already installed OpenSim version 4.0 or later (see Installation Guide for more info). As noted above, OpenSim 4.0 requires 64-bit Matlab.
>>> org.opensim.modeling.opensimCommon.GetVersion() % This should print the version of OpenSim that you've configured with MATLAB |
The configureOpenSim.m file will detect any installations of OpenSim that were previously configured with MATLAB, and will "remove" them from MATLAB (the other OpenSim installations are not deleted, they are simply no longer configured with MATLAB). The configureOpenSim.m file also backs up any changes it makes to MATLAB configuration files.
These manual setup are tailored for Windows and MATLAB 2012b and later, with side notes for macOS and MATLAB 2012a and earlier. Find the location where you installed OpenSim (e.g., C:\OpenSim 4.0). We will refer to this directory as OPENSIM_INSTALL_DIR. Substitute your specific directory in the instructions below. In the images, we use C:\OpenSim 4.0. Launch MATLAB
Tell MATLAB about OpenSim's Java library (.jar)
Tell Matlab about OpenSim's C++ libraries, which the Java library depends on
Add the OpenSim Utilities directory to MATLAB's PATH variable
Please report any issues you have with the configureOpenSim.m file so that other users need not perform these manual steps in the future. |
>> import org.opensim.modeling.* % Import OpenSim Libraries |
Often, it is difficult to know exactly what methods are available for an OpenSim class (e.g., Model, Muscle) and so using the API Documentation regularly will be useful. However, you can very quickly get a list of the available methods and the interfaces to those methods by using the built-in Matlab functions methods and methodsview().
methods() will output a list of all the methods available for a given OpenSim class to the MATLAB command window. Below is an example of methods you can call on the Model class. A list of methods is printed to the command window (cut off here since the list is very long).
>> methods(Model) Methods for class Model: LoadOpenSimLibrary getDefaultSubsystem notifyAll Model getDescription overrideAllActuators PrintPropertyInfo getDiscreteVariableValue postScale RegisterType getDisplayHints preScale RenameType getDocumentFileName print SafeCopy getDocumentFileVersion printBasicInfo addAnalysis getFilePath printComponentsMatching addBody getForceSet printControlStorage addComponent getForceSubsystem printDetailedInfo addConstraint getForceUnits printInputInfo addContactGeometry getFrameList printOutputInfo addController getFunctionClassNames printSocketInfo addForce getGravity printSubcomponentInfo addJoint getGravityForce readObjectFromXMLNodeOrFile ... ... ... |
methodsview() is useful to get a list of the methods and the method signatures (arguments, return type) for an OpenSim class. When calling methodsview(), a Matlab pop-up window will be generated that shows the method names, the arguments you can input, and the return type.
>> myModel = Model() >> methodsview(myModel) |
Tab-completion can be used to get quick access to a method name and is most useful when you know the method name (or the first few letters of the method name). In the GIF below, the tab key is pressed after "myModel." is typed to open the tab-completion window.
OpenSim provides utility functions for some common tasks. If you have installed OpenSim, these scripts are located in the resources directory (e.g., C:/Users/<username>/Documents/OpenSim/4.0/Code/Matlab/Utilities).
File Name(s) | Description |
---|---|
osimC3D.m | Import data from a C3D file to OpenSim Tables. See the c3dExport.m example below for a use case. |
osimTableFromStruct.m | Convert between an OpenSim Table and Matlab Struct. These utilities convert between OpenSim TimeSeriesTables (a new storage format from OpenSIm 4.0 for time series data, details below) and Matlab Structs. Be aware that any metadata in your Table will be lost when you convert to a Matlab Struct. |
osimVec3FromArray.m osimVec3ToArray.m | Convert between an OpenSim Vec3 and a Matlab Array. |
osimList2MatlabCell.m | Get a Matlab cell array populated with an OpenSim's Model's list (e.g., Body). See the section "Using a model's "Lists" through iterators" below for more details and usage. |
If you have installed OpenSim, these scripts are located in the resources directory (e.g., C:/Users/<username>/Documents/OpenSim/4.0/Code/Matlab).
File Name(s) | Description |
---|---|
c3dExport.m | Load a C3D file into OpenSim Tables and write out the marker and force data to corresponding .trc and .mot files. |
OpenSimCreateTugOfWarModel.m TugOfWar_CompleteRunVisualize.m | Generate a simple tug of war model, run a simulation, and visualize the results. |
prescribeMotionInModel.m | Create an OpenSim model with coordinates prescribed according to an input motion file. It uses a helper function defined in the script createPrescribedMotionModel. |
setupAndRunAnalyzeBatchExample.m | Generate OpenSim Setup Files for the Analyze>MuscleAnalysis tool and runs the Analyze tool. You must run setupAndRunIKBatchExample first to generate the motion files used in this example. |
setupAndRunIKBatchExample.m | Run multiple inverse kinematics trials for the model Subject01 located in the subfolder "testData/subject01". User must specify the results directory (e.g. "IKResults"), the .osim model (e.g. "subject01_gait2392_scaled.osim"), and the .trc files (e.g. in folder "MarkerData"). To see the results, load the model and IK output in the GUI. |
simpleOptimizerExample.m | Run a simple optimization to find the elbow flexion angle where the moment arm of the biceps femoris short head is maximized. |
strengthScaler.m | Functionthat loads a model and itsmuscles,then creates a new model where all muscles are scaled by a common scale factor. Takes 3 inputs: 1) the path and name of an existing OpenSim model, 2) the path and name of the new model to be outputted, and 3) the scale factor. If no input model names are given, the user is prompted to choose a model to scale and all muscle strengths are doubled. |
wiringInputsAndOutputsWithTableReporter.m | Create a Reporter and wire the Inputs and Outputs necessary to report the system's center of mass. |
Reading from and writing to files has been improved with the introduction of tables and file adapters (available as of OpenSim 4.0). The code blocks below demonstrate how to read and write vector and scalar (double) data from and to a file.
Reading Data from file | Writing Data to File | ||
---|---|---|---|
Vec3 (Vector) Data
|
| ||
Double (Scalar) Data
|
|
OpenSim verifies that Model's Geometry mesh files exists when you load a model and whenever you subsequently operate on it. If you have a Geometry file defined in your model, and the Geometry path is not set, you will get a warning for each piece of Geometry that can't be found, as shown in the image below.
These warning can get cumbersome, especially if you are doing batch processing or iterative analysis. To stop the warnings, you have to set the Geometry folder path of OpenSim:ModelVisualizer() in Matlab. Copy and paste the below code and update the path to your local OpenSim Geometry directory.
>>> path='/Users/username/Applications/OpenSim 4.0/OpenSim 4.0.app/Contents/Resources/OpenSim/Geometry'; >>> ModelVisualizer.addDirToGeometrySearchPaths(path); |
Alternatively, a 'workaround' that if you are not visualizing the model is to remove the geometry from the model. This should only be used if you are doing many model instantiations or initSystem() calls and don't need to visualize the model.
Lists, such as BodyList and MuscleList, are useful ways to get access to all components of that type in the model. Access is available through an iterator. Iterators are a different way of getting references to objects in the model and Matlab users may be unfamiliar with them. For a discussion of iterators, see this StackOverflow discussion.
Iterate over all bodies in a model (even bodies not in the model's BodySet)
model = Model("my_model.osim") bodyList = model.getBodyList(); # Get the Model's BodyList iter = bodyList.begin(); # Start the iterator at the beginning of the list while ~iter.equals(bodyList.end()) # Stay in the loop until the iterator reaches the end of the list iter.getName() # Print name to console iter.next() # Move the iterator to the next body in the list end |
Getting a single reference from a list
We have included a Matlab function— osimList2MatlabCell() — that converts an OpenSim List to a Matlab cell array. Then, you can use simple Matlab methods to get references to objects.
model = Model("my_model.osim") references = osimList2MatlabCell(model,'Body') % Get a cell array of references to all the bodies in a model Pelvis = references{1} % Get the first body in the list. |
Classes defined in plugins are not available for direct access in Matlab, however classes that are subclasses of OpenSim "Object" contain properties that can be accessed and modified using the PropertyHelper class. The exact syntax depends on the basic data type of the property, for example
prop = obj.getPropertyByName("propertyName") currentValue = PropertyHelper.getValueDouble(prop) PropertyHelper.setValueDouble(newValue, prop) |
Applies to OpenSim 4.2 and above. |
Some versions of Matlab do not show OpenSim's log messages by default. To see these messages in the Matlab Command Window, run the following command:
myMatlabLog = JavaLogSink() Logger.addSink(myMatlabLog) |
MATLAB allows one to load and use Java libraries. OpenSim has a Java interface/library (used by the GUI), allowing us to leverage MATLAB's Java capabilities to provide a MATLAB interface to OpenSim.
|
Next: Scripting in Python Previous: Scripting in the GUI |