How to Call a Function in Matlab Again So We Can Plug in

Setting up your Matlab Scripting Environment

These instructions presume that you've already installed OpenSim version iv.0 or later (see Installation Guide for more info). As noted above, OpenSim 4.0 requires 64-bit Matlab.

  1. Launch MATLAB. If y'all're using Windows and you take OpenSim 3.ten configured with Matlab, brand sure to "Run as administrator" (available by right-clicking the MATLAB application in the starting time menu, etc.).
  2. Modify your Current Folder to the OpenSim Matlab Scripts directory. On Windows, past default, this isC:/Users/<username>/Documents/OpenSim/4.0/Code/Matlab.
  3. Run theconfigureOpenSim.g file from the electric current binder. The script will prompt y'all to choose your OpenSim installation directory (nosotros will refer to this as OPENSIM_INSTALL_DIR). On Windows, by default, this isC:/OpenSim 4.0.
  4. When the script finishes, you should see a dialog box notifying you lot if the script succeeded. If the script did not succeed, read the output in the command window for more information.
  5. Windows users: ensure that theOPENSIM_INSTALL_DIR/bin directory (eastward.g., C:/OpenSim 4.0/bin) appears in your system PATH surroundings variable, and that it appears before whatsoever other OpenSim installations you may accept on your PATH. The steps to gear up your path are shown in the animated paradigm below. Double click the paradigm to zoom in. Or run across here for additional assist on setting your PATH environment variable.
  6. Restart MATLAB; the OpenSim libraries will non exist recognized until doing then.
  7. Test that everything is configured correctly: In the control window, run the post-obit:
>>> org.opensim.modeling.opensimCommon.GetVersion()	% This should print the version of OpenSim that you lot'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 arenot deleted, they are simply no longer configured with MATLAB). The configureOpenSim.m file as well backs up whatsoever changes it makes to MATLAB configuration files.

Having trouble? Attempt manual setup...

These manual setup are tailored for Windows and MATLAB 2012b and afterward, with side notes for macOS and MATLAB 2012a and before.

Discover the location where you installed OpenSim (e.g., C:\OpenSim four.0). We volition refer to this directory equallyOPENSIM_INSTALL_DIR. Substitute your specific directory in the instructions below. In the images, we use C:\OpenSim 4.0.

Launch MATLAB

  • If you have MATLAB 2012b or afterward, y'all can launch MATLAB regularly.
  • If you have MATLAB 2012a or earlier, you must run MATLAB equally an administrator: correct-click MATLAB in your First bill of fare, and select Run as administrator.

Tell MATLAB most OpenSim's Java library (.jar)

  • In the MATLAB Command Window, blazon edit(fullfile(prefdir, 'javaclasspath.txt')).
    • For MATLAB 2012a or earlier, type edit classpath.txt instead.
  • Add OPENSIM_INSTALL_DIR\sdk\Java\org-opensim-modeling.jar to the cease of the file.
  • On macOS, use frontward slashes (/) instead of back slashes (\).
  • Remove any entries for previous versions of OpenSim (in either fullfile(prefdir, 'javaclasspath.txt')or classpath.txt, even if y'all have MATLAB 2012b or later).

Tell Matlab well-nigh OpenSim's C++ libraries, which the Java library depends on

  • In the MATLAB Command Window, type edit(fullfile(prefdir, 'javalibrarypath.txt')).
    • For MATLAB 2012a or earlier, type edit librarypath.txt instead.
  • Add OPENSIM_INSTALL_DIR\bin\ to the end of the file.
  • On macOS, use forwards slashes (/) instead of back slashes (\).
  • Remove any entries for previous versions of OpenSim (in either fullfile(prefdir, 'javalibrarypath.txt')or librarypath.txt, even if you have MATLAB 2012b or subsequently).

Add together the OpenSim Utilities directory to MATLAB's PATH variable

  • In the MATLAB Command Window, type pathtool (or editpath in older versions of MATLAB).
  • Click Add together Folder... and select C:\Users\<username>\Documents\OpenSim\4.0\Lawmaking\Matlab\Utilities folder (past default).
    • Remove any entries for previous versions of OpenSim.
  • On macOS, you volition come across forrard slashes (/) instead of back slashes (\).

Delight report any issues you have with the configureOpenSim.m file then that other users need not perform these transmission steps in the future.

Loading OpenSim Libraries

Once yous have set up the OpenSim-Matlab surroundings you must import the OpenSim libraries to be able to have access to the OpenSim classes. Since imported libraries are non Global variables, you must import the libraries at the beginning of all scripts or functions that use OpenSim classes. This included nested functions or classes.

>> import org.opensim.modeling.*		% Import OpenSim Libraries

Finding the Methods Bachelor for a Class in the OpenSim Libraries

Often, information technology is difficult to know exactly what methods are available for an OpenSim class (due east.k., Model, Muscle) so using the API Documentation regularly volition be useful. Nevertheless, you can very quickly get a listing of the bachelor methods and the interfaces to those methods past using the built-in Matlab functions methods and methodsview().

methods() will output a listing of all the methods available for a given OpenSim class to the MATLAB control window. Below is an example of methods you can call on the Model form. A list of methods is printed to the control window (cut off hither since the listing 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 listing of the methods and the method signatures (arguments, return type) for an OpenSim class. When calling methodsview(), a Matlab pop-upwards window will be generated that shows the method names, the arguments you tin 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 y'all know the method name (or the starting time few messages of the method name).  In the GIF beneath, the tab fundamental is pressed after "myModel." is typed to open the tab-completion window.

Utilities

OpenSim provides utility functions for some common tasks. If you have installed OpenSim, these scripts are located in the resource directory (east.g., C:/Users/<username>/Documents/OpenSim/iv.0/Lawmaking/Matlab/Utilities).

File Proper name(south)

Description
osimC3D.m Import data from a C3D file to OpenSim Tables. See the c3dExport.grand instance below for a use case.

osimTableFromStruct.yard
osimTableToStruct.1000

Convert between an OpenSim Tabular array and Matlab Struct.

These utilities catechumen between OpenSim TimeSeriesTables (a new storage format from OpenSIm four.0 for time series data, details below) and Matlab Structs. Be aware that whatever metadata in your Table will exist lost when you convert to a Matlab Struct.

osimVec3FromArray.one thousand
osimVec3ToArray.m
Convert between an OpenSim Vec3 and a Matlab Array.
osimList2MatlabCell.one thousand Get a Matlab cell array populated with an OpenSim's Model's listing (e.g., Body). Encounter the section "Using a model's "Lists" through iterators" beneath for more details and usage.

Instance Scripts

If you accept 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.one thousand Load a C3D file into OpenSim Tables and write out the marker and force data to respective .trc and .mot files.
OpenSimCreateTugOfWarModel.grand
TugOfWar_CompleteRunVisualize.thou
Generate a unproblematic tug of state of war model, run a simulation, and visualize the results.
prescribeMotionInModel.one thousand Create an OpenSim model with coordinates prescribed according to an input motion file. It uses a helper function defined in the script createPrescribedMotionModel.
setupAndRunAnalyzeBatchExample.thousand

Generate OpenSim Setup Files for the Analyze>MuscleAnalysis tool and runs the Clarify tool. You must run setupAndRunIKBatchExample starting time to generate the motion files used in this example.

setupAndRunIKBatchExample.m Run multiple changed kinematics trials for the model Subject01 located in the subfolder "testData/subject01". User must specify the results directory (east.g. "IKResults"), the .osim model (due east.g. "subject01_gait2392_scaled.osim"), and the .trc files (east.g. in folder "MarkerData"). To see the results, load the model and IK output in the GUI.

simpleOptimizerExample.m
simpleOptimizerObjectiveFunction.1000

Run a unproblematic optimization to find the elbow flexion angle where the moment arm of the biceps femoris short head is maximized.
strengthScaler.thou Functionthat loads a model and itsmuscles,then creates a new model where all muscles are scaled past a mutual calibration factor. Takes 3 inputs: 1) the path and proper name of an existing OpenSim model, ii) the path and proper noun of the new model to exist outputted, and 3) the scale cistron. 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 organization's eye of mass.

Reading in and Writing Information to File

Reading from and writing to files has been improved with the introduction of tables and file adapters (available every bit 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

% Define the path to the file  filepath = 'subject01_walk1.trc'; % Use the Vec3 TimeSeriesTable to read the Vec3 blazon data file.  opensimTable = TimeSeriesTableVec3(filepath); % Use the OpenSim Utility office, osimTable2Struct to  % convert the OpenSim table into a Matlab Struct for ease of use. matlabStruct_markerData = osimTableToStruct(opensimTable);
% Define output file name/path filepath = 'myMarkerTrial_01.trc';  % Write the TimeSeriesTableVec3 to file TRCFileAdapter().write(opensimTable,filepath)                        

Double (Scalar) Information

% Define the path to the file filepath = 'subject01_walk1_grf.mot'; % Employ the standard TimeSeriesTable to read the data file.  opensimTable = TimeSeriesTable(filepath); % Use the OpenSim Utility office, osimTable2Struct to  % convert the OpenSim tabular array into a Matlab Struct for ease of use. matlabStruct_grfData = osimTableToStruct(opensimTable);
% Ascertain output file name/path filepath = 'myMarkerTrial_01_grf.mot';  % Write the TimeSeriesTable to file STOFileAdapter().write(opensimTable,filepath)                        

Calculation Geometry Paths to Matlab

OpenSim verifies that Model'due south Geometry mesh files exists when you load a model and whenever y'all later on operate on information technology. If you have a Geometry file divers in your model, and the Geometry path is not set, you will go a alert for each piece of Geometry that tin can't be found, as shown in the epitome below.

These warning can get cumbersome, peculiarly if you are doing batch processing or iterative assay. To terminate the warnings, you have to set the Geometry folder path of OpenSim:ModelVisualizer() in Matlab. Copy and paste the beneath lawmaking 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 non visualizing the model is to remove the geometry from the model. This should but be used if you are doing many model instantiations or initSystem() calls and don't need to visualize the model.

Using a model's "Lists" through iterators

Lists, such every bit BodyList and MuscleList, are useful means to become admission to all components of that type in the model. Access is available through an iterator. Iterators are a unlike way of getting references to objects in the model and Matlab users may be unfamiliar with them. For a give-and-take of iterators, run into this StackOverflow give-and-take.

Iterate over all bodies in a model (even bodies non in the model'due south BodySet)

model = Model("my_model.osim") bodyList = model.getBodyList();      # Get the Model'south BodyList iter = bodyList.begin();             # Start the iterator at the get-go of the listing while ~iter.equals(bodyList.cease())   # Stay in the loop until the iterator reaches the end of the listing     iter.getName()                   # Print proper noun to console     iter.side by side()                      # Movement the iterator to the next torso in the list end

Getting a single reference from a list

We have included a Matlab function— osimList2MatlabCell() — that converts an OpenSim Listing to a Matlab cell array. And so, y'all can apply uncomplicated Matlab methods to get references to objects.

model = Model("my_model.osim") references = osimList2MatlabCell(model,'Body')  % Go a cell array of references to all the bodies in a model Pelvis = references{ane}							% Get the beginning body in the list.

Using PropertyHelper to set Property values for plugin classes

Classes defined in plugins are not bachelor for direct access in Matlab, yet classes that are subclasses of OpenSim "Object" contain properties that can exist accessed and modified using the PropertyHelper class. The exact syntax depends on the basic data blazon of the belongings, for example

prop = obj.getPropertyByName("propertyName") currentValue = PropertyHelper.getValueDouble(prop) PropertyHelper.setValueDouble(newValue, prop)                

Show OpenSim'south log messages in the Matlab Control Window

Applies to OpenSim 4.ii 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)


Additional information

Advanced background information on how MATLAB scripting works...

MATLAB allows i to load and apply Java libraries. OpenSim has a Coffee interface/library (used by the GUI), assuasive u.s.a. to leverage MATLAB's Java capabilities to provide a MATLAB interface to OpenSim.

  1. OpenSim's Java library is located in the file org-opensim-modeling.jar in the OpenSim installation. To allow MATLAB to utilize OpenSim's Java library, the configureOpenSim.1000 file tells MATLAB where this .jar library is located by calculation the path to the .jar file to the javaclasspath.txt file in MATLAB'south preferences directory (determined past running prefdir in MATLAB).
  2. The .jar file depends on OpenSim's C++ library osimJavaJNI.dll (or libosimJavaJNI.dylib on macOS), and the configureOpenSim.m file tells MATLAB the location of this library by adding the appropriate directory to the javalibrarypath.txt file in MATLAB'due south preferences directory.
  3. The osimJavaJNI library depends on OpenSim's other C++ libraries. On Windows, for MATLAB to find these other libraries, the directory containing these libraries must exist on the system PATH. This step is not necessary on macOS.
  4. The MATLAB interface also involves a few pure MATLAB functions in the C:/Users/<username>/Documents/OpenSim/4.0/Lawmaking/Matlab/Utilities folder (by default). The configureOpenSim.m file adds this directory to the MATLAB path.

Troubleshooting

  • OpenSim 4.0 requires 64-bit Matlab.
  • When referring to indexed elements call up that Matlab begins indexing at 1 while OpenSim data structures begin at 0.
  • Errors related to osimJavaJNI non being on the path or "java.lang.NoClassDefFoundError" occur because the OPENSIM_INSTALL_DIR/bin directory is non on the system (Windows) path. Be certain the OPENSIM_INSTALL_DIR/bin directory has been added to the system PATH environment variable. (Note that the system PATH environment variable is distinct from MATLAB's path variable.)
  • If y'all're seeing errors saying failed dependencies with osimJavaJNI.dll, you would need to have Visual Studio redistribution package installed (which would come up with whatsoever Visual Studio installation). You lot can just install the package files without Visual Studio on the Microsoft download site (For instance 32-fleck VS 2010 package is located hither).

pattthibustor.blogspot.com

Source: https://simtk-confluence.stanford.edu:8443/display/OpenSim/Scripting+with+Matlab

0 Response to "How to Call a Function in Matlab Again So We Can Plug in"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel