Go to start of banner

# Dynamic Walking Challenge: Go the Distance!

## Overview

In this exercise you will use the OpenSim software to simulate and design a dynamic walker.  As a starting point, you will be given a five-segment dynamic walker model and an arena with obstacles.  The goal of the exercise is to maximize the distance the walker can travel on an increasingly challenging terrain by adjusting the model's parameters and adding new model components.  You will learn to use the OpenSim graphical user interface (GUI) and Matlab scripting commands to add model components, adjust component properties, and visualize dynamic simulations, and make plots of your simulation results.

## Acknowledgements

The original exercise was created by Daniel A. Jacobs.  Ajay Seth, Chris Dembia, Jen Hicks, Ajay Seth, Tom Uchida contributed to the scripts library used in this example.

## I. Getting Started

2. Download the archive of starter files (top of page) and unzip them to your working directory.
3. Follow the setup instructions on Scripting with Matlab to get your Matlab environment ready for scripting. Both 32-bit and 64-bit are supported, but the set-up for 64-bit requires a few extra steps.

## II. Explore the OpenSim GUI and Model

In this section, you will familiarize yourself with the OpenSim GUI and explore the editable properties of the walker and environment.  You will use the GUI to examine the bodies, joints, and contact geometry that make up the model.  The starting model is simple; it includes two legs with knees and spherical feet.  In the following sections, you will learn how to add bodies and joints and adjust the model properties to create your own robust walker.  The model of of the walker and the environment includes the following elements:

• A long platform, declined at 10 degrees with obstacles welded to it.
• A pelvis segment, connected to the platform by two slider joints.
• Two thigh segments, offset from the pelvis laterally and connected to the pelvis by pin joints.
• Two shank segments connected to the thighs by pin joints.
• A contact geometry set, consisting of contact spheres and a contact half space (plane), which are used to generate contact forces.
• Contact forces, which compute the applied body forces due to the interaction of contact geometries.
• Coordinate limit forces, which enforce the desired range of motion of the joints.

#### A. Launch the OpenSim Program

You can launch OpenSim 3.1 from the Windows Start menu. If you used default installation settings, simply select Windows>All Programs>OpenSim 3.1>OpenSim. You will see multiple information panels and an empty main View.  The can learn more about the Graphical User Interface in the OpenSim User's Guide.

#### B. Explore the model components

1. In the OpenSim GUI, select File>Open Model... to open the file DynamicWalkerStarter/DW2013_WalkerModelTerrain.osim. Alternatively, you can drag the model file onto the view window in the GUI.
2. The View panel is used to control the model's visual display.  By dragging the mouse, the view can be rotated (with the left mouse button), translated (with the middle mouse button), and zoomed (with the right mouse button).
3. In the Navigator panel on the left side of the screen, use the + icon to expand the list of model components.  Explore the individual components in the model by clicking on them in the Navigator Panel
4. As you click on each component, scroll through the component's properties in the Property Editor panel underneath the Navigator panel.
5. The Coordinates panel lists the current values of the model's generalized coordinates.
1. The values of the coordinates (in meters or degrees) can be changed with the sliders or by entering a value in the left text box.
2. The initial coordinate speeds (in meters/second or radians/second) are used as the initial conditions forward simulations. These can be set in the speed text box on the right hand side of each row.
3. The value of a coordinate can be locked by toggling the lock icon.
4. To reset the model to the default pose, select Poses>Default.  You can also uses the Poses menu to change the default pose and add custom poses.

#### Questions

1. How many degrees of freedom does the model have?
2. What are the lengths of the long axes of the thigh and shank segments? (Hint: The length is set by successive joints e.g., thigh-to-pelvis and shank-to-thigh pin joint locations as measured in the thigh).
3. What is the ratio of the thigh mass to shank mass in the model?

## III. Simulate and Visualize the Walker

In this section, you will run a dynamic simulation of the model, visualize the resulting motion, plot the output, and save a movie of the motion using the OpenSim GUI.

#### A. Run the Forward Tool

1. Before you run the forward tool, go to the Coordinates tab in the left panel and choose a set of initial coordinate values and coordinate velocities for your simulation.
2. Select Tools>Forward Dynamics from the top menu in the GUI
3. In the Time Pane, set the Time Range to Process from 0 to 2 seconds
4. In the Output Pane, append a directory called FWD to the currently listed directory (e.g. C:\OpenSimProject\DynamicWalker\FWD).  You can leave all the other settings at their default value.
5. To quickly set up future runs of the forward tool, save your settings to a file (e.g., Setup_Forward.xml) by clicking the Save... button
6. Click the Run button to begin the simulation.
7. Close the tool.

#### B. Visualize the motion

After running the forward tool, three storage files (.sto) are written to the output directory specified with the time history of the control signals and the model states.  The model state histories, which for this model contain the coordinate values and velocities, are automatically loaded into the program (Results) and can be accessed in the Navigator panel under Motions.

1. If you wish to run several motions with different starting conditions, make sure to Rename the motion from the default name Results by right clicking on the item in the Navigator (e.g. Default_Results).

At the top middle section of the GUI, the blue movie controls can be used to playback and visualize the results.  On the left hand side, the playback speed can be adjusted with the arrow icons or by entering a value in the textbox.  In the center, you can use the control icons to play a movie forward or backwards, either continuously, or frame-by-frame.

1. Hit the blue play button to visualize the results from your forward simulation.

#### C. Create a movie in the GUI

1. In the Navigator panel under Motions, double click a motion to make it the current motion (bold name).
2. On the right side of the view window, click the video camera icon (third from the bottom). This will turn the camera icon orange and a dialog will appear.
3. Type in your desired name for your movie file and hit the Open button.
4. Set the time and speed of your motion using the view controls
5. Play the resulting motion (Note: you can pause the movie before completion if you want a specific interval). You can pause and rotate the model and play again to get a movie with two views of the walker.
6. Click the video camera icon again.  This will end the capture and turn the camera icon blue again.

Note: The size of the movie is based on the current size of the view screen.  At each time interval, as selected by the movie playback speed, a frame is saved to the movie file.  For smaller files, adjust the main window and increase the play speed accordingly.

#### D. Plot in GUI

The GUI has a Plotter tool for plotting results. We'll plot the coordinate velocities for the right leg of the model.

1. Select Tools>Plot from the top menu in the GUI
2. In the bottom panel, select Y-Quantity... and select the Results(deg.) file which was created by the forward tool.
3. In the Select Motion Quantity window, select the generalized coordinate velocities for the right hip (RHip_rz_u) and the right knee (RKnee_rz_u) and hit OK.
4. In the bottom panel, select X-Quantity... and select time.
5. In the bottom right hit Add to plot the data.

More information regarding the plotting tool is available by hitting the help button in the GUI or by going to the help page here.

#### E. Iteratively modify the model to maximize walking distance

The following is a partial list of the common parameters you can change:

1. Modify the mass and inertia parameters of the bodies.
1. The mass and inertia properties of the body can be accessed through the Navigator panel.  Open the bodies group by clicking on the + icon and selecting a body from the list.  In the properties window you can select the mass, the mass_center location, and the six unique elements of the inertia matrix for the body.
2. By convention, the mass_center is the location of the mass center from the body origin measured in the body reference frame and the inertia values are the inertia of the body about the body center of mass measured in the body reference frame.
2. Modify the segment length in the joints.
1. Access the joint properties in the Joints set in the Navigator panel.  The length of the segment is set by the adjacent joints (e.g., to change the length of the right thigh segment you will need to change the RThighToPelvis and the RShankToRThigh location parameters. Read more about OpenSim joints on the OpenSim Models page or in the OpenSim Doxygen.
3. Modify the initial starting conditions by entering the initial coordinate values and the initial coordinate speeds in the Coordinate panel..

Notes:

• In the above configuration of the Forward Tool, the initial conditions of the system will be taken from the listed values in the Coordinates panel.
• Changing the joint locations to length the segments will not change the visual object in the GUI.  To change the visual object, open the Body set, click on the body, and click on ... for the Displayer element in the Properties panel.
• Use the keyboard shortcuts (Ctrl+Z for undo, Ctrl+Y for redo) or the orange and blue arced arrows in the Top Left section of the GUI to manage your model changes.

#### Questions

1. What are some reasons why the model is not taking many steps? How might you improve the model to stabilize the gait?

## IV. Extending the Model with the Matlab Scripting interface

The base model has trouble maintaining knee extension during stance.  In this section, you will use the Matlab scripting interface to extend the base model in two ways.  First, you will create a custom force component to build a permanent magnet model that will always act to extend the knee.  Second, you will add a more substantial foot to the model based on a CAD .obj file. Before getting started:

1. Make sure you've setup the OpenSim Matlab interface by following the instructions for Scripting with Matlab.
2. The scripts assume that you've set your working directory in Matlab to DynamicWalkingConference/MatlabScripts

#### A. Add a Magnet Force around the Knee Joint in Matlab

With the base dynamic walker model, the knee often flexes during the stance phase.  One way to maintain knee extension during the stance phase is to add a magnet force around the knee which will contribute to extension of the knee.

OpenSim provides a library of actuators, from simple springs up to efficient muscle models.  In this example, a magnet force is realized with a general purpose force element called an ExpressionBasedPointToPointForce.  The ExpressionBasedPointToPointForce calculates the relative distance (d) between two points and its time derivative (ddot) and allows the user to specify the mathematical expression for the force using the variables d and ddot. The force function can be written as a string and the parser understands expressions with C-mathematical operations such as +,-,*,/ and common functions such as exp, pow, sqrt, sin, cos, and tan.  NOTE: a limitation is that the expression may not contain whitespace.

Your starter archive includes the partial script AddExpressionPointToPointForceMagnets.m.  In order to complete the script, you will need to set the bodies and locations of the two magnets for each knee.  You will also need to write the expression for the magnet forces.   The areas where you will need to enter code are marked with ( ***** WRITE YOUR CODE HERE: ... *****).  For reference, the completed file (AddExpressionPointToPointForceMagnets.m) is in the reference folder of the starter archive.

The magnet forces will be calculated as  f = \frac{c}{d^2} where the constant, c, is 0.01 Nm^{2}

1. Complete the script for adding the magnet force at the knee. See the doxygen for the OpenSim Model (e.g. to see how to get a handle to a particular body) and ExpressionBasedPointToPointForce for reference.
2. Visualize and simulate using the OpenSim GUI or using one of the help scripts in section V below. Does this increase the number of steps the walker can take?

Click To Expand Code for AddExpressionPointToPointForceMagnets.m

#### B.  Add a custom foot object

Another way to add an extension moment during stance is to add a more substantial foot with a large radius of curvature.  During stance, the contact forces create a moment on the lower leg which acts to extend the knee.  By moving the contact point further ahead on the foot, the moment on the foot created by the ground contact forces can be used to inhibit knee flexion in stance.

OpenSim comes with a large library of geometry files for visualizing elements of the human skeletal system, as well as simple generic shapes such as, spheres, cylinders, and boxes .  If the base library is not sufficient for your model, it is easy to add additional geometry files .  This section demonstrates how to add a custom foot object using the Matlab scripting interface.  OpenSim can import model files with the following extensions: .vtp, .stl and .obj.  By default, OpenSim looks for object files in the model's local directory on in the Models directory in the OpenSim installation directory (e.g., (<OpenSim_Home>\Models)

Your starter archive comes with an .obj of simple cylindrical foot design.  The object files were created in the open source 3d CAD program Blender.  The AddCustomFeet.m script in the starter archive adds ContactMesh component using the .obj file and creates an ElasticFoundationForce component to represent the contact between the foot and the ground.

In your starter archive, the script AddCustomFeet.m file is a partial script.  In order to add custom feet to the model, you will need to define four Vec3 objects to represent the location and orientation of the WeldJoint between the parent shank body and the child foot body.   The areas where you will need to enter code are marked with (  ***** WRITE YOUR CODE HERE: *****).  For reference, the completed file (AddCustomFootComplete.m) is in the reference folder of the starter archive.

The WeldJoint should be specified as follows:

• Location in the Parent Frame : 0.05, -0.2, 0 m
• Orientation in the Parent Frame: 0, 0, 0 rad
• Location in the Child Frame : 0, 0, 0 m
• Orientation in the Child Frame: 0, 0, 0 rad

Use the variable names (locationInParent, orientationInParent, locationInChild, and orientationInChild), which are the arguments of the WeldJoint constructor functions.

1. Complete the script for adding the feet to tne walker model. See the doxygen sections on Body, WeldJoint, ContactMesh, ElasticFoundationForce for reference.
2. Visualize and simulate using the OpenSim GUI or using one of the help scripts in section V below. Does this increase the number of steps the walker can take?

Click To Expand Code for AddCustomFoot.m

## V. Design your own Walker Model

The starter archive includes many example scripts to help you iteratively design your walker model. These scripts are designed for convenience and to demonstrate key parts of the functionality of the Matlab scripting interface.  You can access the documentation for each function by using Matlab's internal help interface (e.g., help RunForwardTool).  You can use tab completion to access available methods for OpenSim modeling library objects. The following is a list of the scripts we've provided and links to the doxygen page of the key OpenSim classes used in each script.

### A. Scripts Quick Reference

###### Main Workflow Examples:
Script NameDescriptionRelated Functions/Classes
DesignMainStarter.m
The starting point for design iteration.  The script loads a model, adjusts initial conditions, runs and visualizes a forward dynamic simulation using Matlab's integrator and plots the results.IntegrateOpenSimPlant, PlotOpenSimData
DesignMainStarterWithControls.mThe starting point for running a model with controls. This builds upon DesignMainStarter, but additionally passes to IntegrateOpenSimPlant a handle to a function that specifies actuator controls during the simulation. OpenSimPlantControlsFunction
CompareTwoModels.m
A sample client script that sets up two models with the same set of initial conditions and compares the results via plot.

IntegrateOpenSimPlant, PlotOpenSimData

###### Interfacing with Matlab Examples:
Script NameDescriptionRelated Functions/Classes
IntergateOpenSimPlant.m
This function runs (and optionally visualizes) a forward simulation using one of Matlab's integrators. The script creates a plant function which returns state derivatives given a model and state values.  This plant function can then be passed to any of the built-in integration tools in Matlab. The function IntegrateOpenSimPlant allows you to quickly run a simulation from the default values of the model in a single line.  The output values are placed in a Matlab structure object which can be used with the Matlab function PlotOpensimData.  This function requires OpenSimPlantFunction from the MatlabScripts folder.
OpenSimPlantControlsFunction.mThe function calculates a set of control values which are input to OpenSim muscles and actuators. DesignMainStarterWithControls
OpenSimPlantFunction.mThis function creates an interface which calculates the state derivatives for an OpenSim Model object and a OpenSim State object. This function can be passed to a Matlab integrator sch as ode15s.
PlotOpenSimData.mThis function creates plots from the Matlab structures created by IntegrateOpenSimPlant.m and ReadOpenSimData.m. The functions IntegrateOpenSimPlant and ReadOpenSimData each return matlab structures of the resulting data.  The function PlotOpenSimData can be used to quickly assemble plots from the passed in arguments.
ReadOpenSimData.mThis function creates a formatted Matlab structure from OpenSim storage (.sto) files and OpenSim/SIMM motion (.mot) files. This structure can be used with the script function PlotOpensimData.
RunForwardTool.m

This function runs a forward simulation using OpenSim's Forward Tool. In this script, we use the base model and call the forward tool with settings similar to the instructions in Section II Part A.  Here, we load an additional Analysis called a ForceReporter which outputs to a file the forces and torques applied the force on each body.

ForceReporter, ForwardTool

### B. Model Building Examples

Script NameDescriptionRelated Functions/Classes
AddClutchedPathSpring.mAdds a clutched path spring to the model.  The clutch is set based on length.ClutchedPathSpring

Adds a coordinate actuator to the model.CoordinateActuator
CreateWalkingModelAndEnvironment.mCreates the basic walking model with obstacles.Body, WeldJoint, SliderJoint, PinJoint, ContactSphere, ContactHalfSpace, HuntCrossleyForce, CoordinateLimitForce

Tips and Tricks:

• There is a large number of model components available for your model, please refer to the 3.1 Beta Doxygen online documentation for more information on model components and their methods.
• The introductory page for the Matlab scripting interface is located here.
• In Matlab, you can use the command methodsview('classname') or methodsview(OpenSimObject) to get a list of available functions. You can also use tab completion to see the available methosds for an OpenSim object.
• You can quickly load models and motions from your output states files by dragging and dropping them onto the view window of the OpenSim GUI.
• If you want to walk without any environment obstacle forces, you can disable the force by right clicking on ObstacleForces in the Force Set in the Navigator pane and selecting Disable.
• Inside the Matlab GUI, you can type help <function-name> for any of the Matlab scripts presented here.

## References:

1. Millard, M., Uchida, T., Seth, A., Delp, S.L. (2013) Flexing computational muscle: modeling and simulation of musculotendon dynamics. ASME Journal of Biomechanical Engineering, 135(2):021005.