# Solving optimization problems using Python

The AnyBody Modeling System (AMS) provides a build-in optimization
class `AnyOptStudy`

, and with it you have the opportunity to solve advanced mathematical optimization problems.

**See also:** You can get a taste of how it works in the newly updated tutorial on parameter and optimization studies

## Extending the optimization

Of course there can be situations were you want to do a little more than what the AMS optimization offers. Say you have two seperate models were you wanted to optimize some parameter across the performance in both models? or perhaps you wanted to use a specific algorithm suitable for your exact problem? To solve these kinds of problems, you could perform the optimization process from a third party software.

In this post we will demonstrate how these problems can be solved using Python. This topic is part of a new Anybody Tutorial which describes the content of this post in detail.

As part of the post we will show how to integrate the Scipy optimization package
`Scipy.optimize.minimize`

by running the Anybody 2D bike model from Python, using the AnyPyTools package.

## Optimization example

The process of performing optimization of AMS models through Python can be sketched in four steps:

- Defining a function to call the models using AnyPyTools and extract the designvariables
- Defining a objective function to be either minimized or maximized
- Defining the constraints and bounds of the problem
- Running the optimization

And the whole Python code to complete these four steps could look like this:

## Breaking down the sections

To elaborate a little on the sections, the first part defines the `run_model`

function. This function takes in two arguments and assigns them to the
saddleheight and saddleposition in the AMS model. The function returns the
`Pmet`

value for each timestep in the model.

Details and advanced options of this function and it’s components can be found in the AnyPyTools documentation.

The second part defines the objective function in question. This function takes in a
list of design variable arguments and utilizes the `run_model`

function,
afterwards it integrates the `Pmet`

over the whole time series and returns the
result.

Next up, the constraints and bounds are defined. For this example only a
seat distance constraint is present. The bounds for each of the design
variables is defined in the `bounds`

variable. Lastly, the optimization process is
performed, and here it envokes the SLSQP
algorithm.

For more details and examples of the capabilities of the
`Scipy.optimize`

package, follow this
link.

And there we have it. A full optimization of a AMS model, and a easy template to build other and more advanced optimization processes upon.

**Try it now:** Make sure to try out the full AMS tutorial
here.

This post is hosted on GitHub, feel free to provide feedback here.

## Leave a comment