Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


Note

If using Conda environment we STRONGLY recommend utilizing the conda package directly as a self contained option unrelated to the OpenSim application/GUI. It is the only supported mechanism for versions other than python 3.8. If using Conda please disregard installation instructions on this page and follow the link here https://anaconda.org/opensim-org/opensim

As of 12/2023, python 3.7 is past end of life thus all instructions specific to versions before OpenSim 4.3 (first version built against python 3.8) are moved to a separate section (old OpenSim/Python combinations) near the bottom of this page, we recommend upgrading to the latest OpenSim version available if starting to use the OpenSim API from python.

Table of Contents

Introduction to Python

Python is a widely used general purpose programming language. Python is free and open source, with a large user community that encourages sharing and user contributions. The Python language is very flexible, supporting object-oriented and procedural styles of computing. The Python design philosophy also emphasizes code readability which makes sharing and using code easier than with some other languages. 

Those from scientific and engineering backgrounds who are new to Python should check out the following resources to help get started with the language:

Note on Python versions

...

OpenSim versions and the corresponding python versions used to build distributions: 

...

Table of Contents

Introduction to Python

Python is a widely used general purpose programming language. Python is free and open source, with a large user community that encourages sharing and user contributions. The Python language is very flexible, supporting object-oriented and procedural styles of computing. The Python design philosophy also emphasizes code readability which makes sharing and using code easier than with some other languages. 

Those from scientific and engineering backgrounds who are new to Python should check out the following resources to help get started with the language:

Setting up your Python scripting environment

Conda packages

The fastest way to get started with OpenSim scripting with Python is to install one of our pre-built Conda packages. We highly recommend trying this option first before a manual installation, especially if you have not used Python before.

For information about how to install Conda and create a Python environment, please consult the Conda user guide. Once you have Conda installed and activated in your terminal (or Anaconda prompt), use the following commands to create and activate a new Conda environment.  

Code Block
$ conda create -n opensim_scripting python=3.11 numpy
$ conda activate opensim_scripting

Note that the environement name opensim_scripting can be changed to any environment name you choose.

Once you've created a Conda environment, use the following command to install the latest version of OpenSim that is compatiable with your environment.

Code Block
$ conda install -c opensim-org opensim

The following table summarizes the available packages that can be installed.

OpenSim versionConda packagesIncludes MocoArm64 Mac support
<4.4Not availableN/ANo
4.4, 4.4.13.

...

7, 3.8, 3.

...

9, 3.

...

10, 3.11NoNo
4.5 3.9, 3.10, 3.11NoNo
4.5

...

.

...

13.9, 3.10, 3.11

Setting up your Python scripting environment (if not using conda)

Windows

...

There are a couple options for setting up Python on your Windows machine. You will need the main Python package, as well as NumPy. Alternatively, there are applications such as Anaconda that bundle all the required packages. You can also just set-up Python and the associated packages manually. We have tested both methods, but currently advise you to use Anaconda. Make sure that you get 64-bit Python.

...

...

Manual installation from OpenSim GUI distribution, not using Anaconda:

If not using Anaconda, please proceed to the following section, only execute steps 1, 9-12 below. Note however that you'll need to install numpy on your own.

Using Anaconda with OpenSim 4.3+ and conda  .yml file 

...

  1. Python 3.8
  2. NumPy 1.20.2
  3. Matplotlib
  4. Spyder (Python IDE)

...

Before proceeding, you may need to initialize conda for shell interaction by running (If not done already)

Code Block
C:\> conda init <shell-name>

where <shell-name> is one of the following: cmd.exe (Windows default) or powershell.

Navigate to the location of the Anaconda environment file. For example, if using cmd.exe:

Code Block
C:\> cd "C:\Users\<profile>\Documents\OpenSim\4.3\Code\Python"

Create the environment from the file:

Code Block
C:\> conda env create -f conda_env.yml

Deactivate any existing environments and activate the OpenSim scripting environment. The prefix "opensim_scripting" should now appear in the Anaconda Prompt.

Code Block
(base) C:\> conda deactivate
C:\> conda activate opensim_scripting
(opensim_scripting) C:\>

...

First, run the following script:

Code Block
(opensim_scripting) C:\> python setup_win_python38.py

Install OpenSim by running

Code Block
(opensim_scripting) C:\> python -m pip install .

...

Once installation completes, test the configuration by checking the timestamp from running 

Code Block
(opensim_scripting) C:\> python
>>> import opensim as osim
>>> osim.GetVersionAndDate()
>>> quit()

in the Anaconda Prompt. Test that the visualizer is working by running the following

Code Block
(opensim_scripting) C:\> cd "C:\Users\<PROFILE_NAME_HERE>\Documents\OpenSim\4.3\Code\Python\Moco"
(opensim_scripting) C:\> python exampleSlidingMass.py

You should see a visualizer window appear with a sliding mass animation. Hit ESC twice to close the window. If you get an error about loading DLL failure check that PATH has been updated correctly before relaunching the shell.

Scripting can be performed by using a text editor and running the scripts from the Anaconda Prompt via "python <script_name>.py". However, if you prefer using an interactive development environment (IDE) similar to Matlab, we've included the Spyder IDE in the Anaconda environment. Launch Spyder by simply running

Code Block
(opensim_scripting) C:\> spyder

Having trouble?

...

  1. You are trying to use 32-bit Python with 64-bit OpenSim libraries. If you are using 64-bit OpenSim libraries, make sure to use 64-bit python.
  2. OpenSim's DLLs are not on your PATH. In a command window, you could achieve this with a command like "set PATH=C:\OpenSim 4.0\bin;%PATH%"

Mac

...

There are 2 possible architectures on OSX: arm64 and intel x86_64. There're conda packages for both, however the GUI distribution includes ONLY x86_64 build with Python 3.8. MacOS comes with some version of Python, but you may also want to obtain Python through Homebrew or the Anaconda Python distribution. Note that the Python package that comes with the OpenSim GUI distribution was built to use the Python that comes with macOS, and it will not work with Homebrew's Python or with Anaconda Python; in the latter cases, you must compile OpenSim from the source code.

Navigate to the location of the opensim python package within the OpenSim installation. If you are using OpenSim's GUI distribution, this location is likely /Applications/OpenSim 4.x/sdk/Python. If you built OpenSim from source, this location is likely OPENSIM_INSTALL_DIR>/lib/python3.x/site-packages if using Python ). Perform the following (modifying the path below if necessary):

Code Block
$ cd /Applications/OpenSim 4.0/sdk/Python
$ sudo python setup.py install

The OpenSim libraries must be on your DYLD_LIBRARY_PATH:

Code Block
$ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/lib

You can place the above `export` commands in your `~/.bash_profile` file so that they are set whenever you open up a new terminal.

You should be ready to use the Python wrapping now. Try the following from any directory:

Code Block
$ python
...
>>> import opensim
>>> m = opensim.Model()

Step-by-step instructions when using Anaconda with OpenSim 4.3+

...

  1. Python 3.8
  2. NumPy 1.20.2
  3. Matplotlib
  4. Spyder (Python IDE)

...

Before proceeding, you may need to initialize conda for shell interaction by running

Code Block
$ conda init <shell-name>

where <shell-name> is one of the following: bash (macOS default), fish, zsh, tcsh, or xonsh.

Navigate to the location of the Anaconda environment file:

Code Block
$ cd /Users/<profile>/Documents/OpenSim/4.3/Code/Python

Create the environment from the file:

Code Block
$ conda env create -f conda_env.yml

Deactivate any existing environments and activate the OpenSim scripting environment. The prefix "opensim_scripting" should now appear in the terminal (it may appear on the right side of the screen).

Code Block
(base) $ conda deactivate 
$ conda activate opensim_scripting
(opensim_scripting) $

...

Install OpenSim by running

Code Block
(opensim_scripting) $ python -m pip install .

You may need to update the DYLD_LIBRARY_PATH to include the OpenSim and Simbody libraries:

Code Block
(opensim_scripting) $ export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:<YOUR_INSTALL_DIRECTORY_HERE>/sdk/lib" 
(opensim_scripting) $ export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:<YOUR_INSTALL_DIRECTORY_HERE>/sdk/Simbody/lib"

...

Once installation completes, test the configuration by checking the timestamp from running 

Code Block
(opensim_scripting) $ python
>>> import opensim as osim
>>> osim.GetVersionAndDate()
>>> quit()

in the terminal. Test that the visualizer is working by running the following

Code Block
(opensim_scripting) $ cd "/Users/<PROFILE_NAME_HERE>/Documents/OpenSim/4.3/Code/Python/Moco"
(opensim_scripting) $ python exampleSlidingMass.py

You should see a visualizer window appear with a sliding mass animation. Hit ESC twice to close the window. If you get an error about loading DLL failure check that PATH has been updated correctly before relaunching the shell.

Scripting can be performed by using a text editor and running the scripts from the Anaconda Prompt via "python <script_name>.py". However, if you prefer using an interactive development environment (IDE) similar to Matlab, we've included the Spyder IDE in the Anaconda environment. Launch Spyder by simply running

Code Block
(opensim_scripting) $ spyder

Ubuntu

...

We assume that you will use Python through the terminal. Open a new terminal window.

Code Block
$ sudo apt-get install python-setuptools

Navigate to the sdk/python folder in your OpenSim installation. Assuming that OpenSim is installed into directory OPENSIM_INSTALL_DIR (by executing make install), perform the following:

Code Block
$ cd <OPENSIM_INSTALL_DIR>/lib/python3.x/site-packages
$ sudo python setup.py install

The OpenSim libraries must be on your LD_LIBRARY_PATH:

Code Block
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/lib

You can place the above `export` commands in your `~/.bashrc` file so that they are set whenever you open up a new terminal.

You should be ready to use the Python wrapping now. Try the following from any directory:

Code Block
$ python
...
>>> import opensim
>>> m = opensim.Model()

Old OpenSim/Python combinations

Windows:

Add a folder to PYTHONPATH variable (needed for OpenSim 4.2)

...

Image Removed

Insert OpenSim Python directory into PYTHONPATH

Edit your PYTHONPATH environment variable to include <OPENSIM_INSTALL_DIRECTORY>\sdk\Python is in system variable PYTHONPATH, where OPENSIM_INSTALL_DIRECTORY is the directory where you installed the current version of OpenSim (e.g. C:\OpenSim 4.0). Delete any other OpenSim Path entries. If PYTHONPATH doesn't exit, you can add the variable using the "New..." button. For instructions, see https://www.java.com/en/download/help/path.xml

Mac:

...

Needed for OpenSim 4.2: You must also add OpenSim's python folder to PYTHONPATH, also by adding the following to the `~/.bashrc` file:

Code Block
export PYTHONPATH=<OPENSIM_INSTALL_DIR>/sdk/Python:$PYTHONPATH

Ubuntu:

...

Needed for OpenSim 4.2: You must also add OpenSim's python folder to PYTHONPATH, also by adding the following to the `~/.bashrc` file:

Code Block
export PYTHONPATH=<OPENSIM_INSTALL_DIR>/sdk/Python:$PYTHONPATH

Available Example Scripts

Scripts can are located in the OpenSim distribution in the sdk/Scripts/Python folder. 

...

Script Name

...

YesYes

To install a specific version, find the package name matching the version you want in the list of packages hosted on Anaconda.org. For example, to install OpenSim 4.4 into a Python 3.10 environment (which requires NumPy 1.21), you would use the following command.

Code Block
$ conda install -c opensim-org opensim=4.4=py310np121

OpenSim Conda packages that include Moco are available for OpenSim 4.4, 4.4.1, and 4.5, but only for Windows. Use the following command to install these packages.

Code Block
$ conda install -c opensim-org opensim-moco

If possible, we recommend using the Conda packages with the latest OpenSim version which includes Moco and all of the latest features in the OpenSim API. 

Manual installation (OpenSim 4.3 or later)

It is possible to manually install the OpenSim Python bindings, but this approach comes with a few caveats:

  1.  If installing from a GUI distribution with OpenSim 4.3 or later, only Python 3.8 is supported.
  2. While it is not necessary to use Conda to create a Python environment, you must use a 64-bit version of Python.
  3. If you want to create a manual installation with a different version of Python, you must build the Python bindings from source.

The following instructions will refer to a directory <OPENSIM_INSTALL_DIR>, where you installed some version of OpenSim. On Windows this might look like C:\OpenSim 4.X, and on MacOS it might look like /Applications/OpenSim 4.X. The installation directory can be identified by the subfolders "bin" and "sdk". If you built from source on Mac or Linux, where the installation directory might use a Unix-like folder structure with subfolders "lib", "libexec", and "share".

To install, first navigate to the location of the OpenSim Python package within the OpenSim installation. If you are using OpenSim's GUI distribution, this location is <OPENSIM_INSTALL_DIR>/sdk/Python. If you built OpenSim from source on Mac or Linux, this location is likely <OPENSIM_INSTALL_DIR>/lib/python3.x/site-packages.

If on Windows, you may need to run the following command when using OpenSim 4.3 or later with Python 3.8. (If setup_win_python38.py does not exist in your distribution, then you can skip this step.)

Code Block
$ python setup_win_python38.py

To install the OpenSim Python bindings on all platforms, run the following command. Note that if you have a Conda environment activated, this command with install OpenSim as a package into your Conda environment.

Code Block
$ python -m pip install .

On Windows, you will likely need to set the Path environment variable to point to the "bin" folder in your OpenSim installation. To do this:

  1. Press the Windows key and search for "Edit the system environment variables". Click the top search result.
  2. Click "Environment Variables..." in the bottom right corner. Look for Path under "System variables".
  3. Highlight the Path entry and click "Edit...".
  4. Add a new entry with value <OPENSIM_INSTALL_DIR>/bin and move it to the top of the list.
  5. Restart your terminal for the change to Path to take effect before testing your Python installation.

On Mac, you may need to update the DYLD_LIBRARY_PATH environment variable to point to the OpenSim and Simbody libraries. 

Code Block
$ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/sdk/lib
$ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/sdk/Simbody/lib

You can place export commands in your ~/.bashrc file (or other terminal configuration file) so that they are set whenever you open up a new terminal.

Similarly on Linux, you may need to updated LD_LIBRARY_PATH.

Code Block
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/sdk/lib
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/sdk/Simbody/lib

Installing older OpenSim and Python versions (OpenSim 4.2 or earlier)

While we strongly recommend upgrading to a recent version of OpenSim and using the install instructions above, for legacy purposes, you may expand the following section to install older versions of OpenSim and Python.

Expand

As of December 2023, Python 3.7 is past end of life. Therefore, installation instructions for versions prior to OpenSim 4.3 are different.

For OpenSim 4.2 or earlier, you may need to set the PYTHONPATH environment variable. To do this on Windows:

  1. Press the Windows key and search for "Edit the system environment variables". Click the top search result.
  2. Click "Environment Variables..." in the bottom right corner. Look for PYTHONPATH under "System variables".
  3. If it exists, highlight it and click "Edit...". If not, click "New..." to create a new variable. Set the value to <OPENSIM_INSTALL_DIR>\sdk\Python.

On Mac or Linux, you can set PYTHONPATH via the terminal, or in your ~/.bashrc file (or other terminal configuration file).

Code Block
$ export PYTHONPATH=<OPENSIM_INSTALL_DIR>/sdk/Python:$PYTHONPATH


First, navigate to <OPENSIM_INSTALL_DIR>/sdk/Python.

To install on Windows, run the following command. Note that your terminal might need to be in Administrator mode.

Code Block
$ python setup.py install


To install on Mac, run the following commands.

Code Block
$ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/lib
$ sudo python setup.py install


To install on Linux, instead navigate to <OPENSIM_INSTALL_DIR>/lib/python3.x/site-packages, since we assume you built and installed from source. Run the following commands.

Code Block
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<OPENSIM_INSTALL_DIR>/lib
$ sudo python setup.py instal


Testing your installation 

After activating your Conda environment (or manually installed Python environment), run the following commands to test your OpenSim installation.

Code Block
$ python
>>> import opensim as osim
>>> osim.GetVersionAndDate()

Troubleshooting

  1. You are trying to use 32-bit Python with 64-bit OpenSim libraries. If you are using 64-bit OpenSim libraries, make sure to use 64-bit python.
  2. OpenSim's DLLs are not on your PATH. In a command window, you could achieve this with a command like "set PATH=C:\OpenSim 4.0\bin;%PATH%"
  3. There are 2 possible architectures on OSX: arm64 and intel x86_64. There're conda packages for both, however the GUI distribution includes ONLY x86_64 build with Python 3.8. MacOS comes with some version of Python, but you may also want to obtain Python through Homebrew or the Anaconda Python distribution. Note that the Python package that comes with the OpenSim GUI distribution was built to use the Python that comes with macOS, and it will not work with Homebrew's Python or with Anaconda Python; in the latter cases, you must compile OpenSim from the source code.


Example Scripts

Scripts can are located wherever you installed the resources that come packaged OpenSim distribution (i.e., the folder you choose after opening the GUI the first time after installation). For example, on Windows the <RESOURCES_DIR> might be C:\Users\username\Documents\OpenSim\4.X

The scripts below are located at <RESOURCES_DIR>\Code\Python. Additional scripts containing Moco examples can be found under <RESOURCES_DIR>\Code\Python\Moco.

Script Name

Description
build_simple_arm_model.pyThis script generates a simple arm model, runs a simulation, and visualizes the results.
wiring_inputs_and_outputs_with_TableReporter.pyThis script shows how to write model outputs (the position of a body) to a data file.
dynamic_walker_example_optimization.pyThis script shows how to run an optimization with the dynamic walker model.
posthoc_StatesTrajectory_example.pyThis script shows how to use a StatesTrajectory to analyze a simulation.
numpy_conversions.pyThis script shows how to convert NumPy arrays to and from OpenSim's Vector and Matrix classes.
extend_OpenSim_Vec3_class.pyThis script demonstrates how to extend the Vec3 class.

Jupyter Notebooks

You can find a series of OpenSim scripting tutorials written using Jupyter notebooks here. These notebooks leverage Google Colab, a service for hosting interactive Jupyter notebooks in the cloud, and condacolab, a package that enables creating Conda environments in Google Colab. 

Pythonic extensions of the OpenSim API

We have add some pythonic aspects to our Python interface. All examples assume that you have already imported the opensim package ("import opensim").

Initializing a Vector from a Python list

Code Block
languagepy
v = opensim.Vector([6, 7, 8, 9])
rv = opensim.RowVector([1, 2, 5])

Accessing elements of VecX and Vector using brackets

Code Block
languagepy
v = opensim.Vec3(1, 2, 3)
v[0] = 1.5 + v[1]
w = opensim.Vector(5, 1.5)
w[0] = 3 * w[1]

Printing the contents of a VecX or Vector

Code Block
languagepy
>>> v = opensim.Vec3(1, 2, 3)
>>> print v
~[1,2,3]

Getting the length of a VecX or Vector

You can use the built-in python function len() on VecX (e.g., Vec3) and Vector:

Code Block
languagepy
w = opensim.Vector(5)
if len(w) < 5:
    raise Exception()

Iterate over elements of any Set

There are two iterators: one that treats the Set like a python list, and another that treats the Set like a python dict:

Code Block
languagepy
model = opensim.Model("my_model.osim")
for force in model.getForceSet():
    print(force.getName())
for name, muscle in model.getMuscles():
    print(name, muscle.get_max_isometric_force())

Iterate over all bodies in a model (even bodies not in the model's BodySet)

Code Block
languagepy
model = opensim.Model("my_model.osim")
for body in model.getBodyList():
    print(body.getName())


...