{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"active-ipynb",
"remove-input",
"remove-output"
]
},
"outputs": [],
"source": [
"# This cell is mandatory in all Dymos documentation notebooks.\n",
"missing_packages = []\n",
"try:\n",
" import openmdao.api as om\n",
"except ImportError:\n",
" if 'google.colab' in str(get_ipython()):\n",
" !python -m pip install openmdao[notebooks]\n",
" else:\n",
" missing_packages.append('openmdao')\n",
"try:\n",
" import dymos as dm\n",
"except ImportError:\n",
" if 'google.colab' in str(get_ipython()):\n",
" !python -m pip install dymos\n",
" else:\n",
" missing_packages.append('dymos')\n",
"try:\n",
" import pyoptsparse\n",
"except ImportError:\n",
" if 'google.colab' in str(get_ipython()):\n",
" !pip install -q condacolab\n",
" import condacolab\n",
" condacolab.install_miniconda()\n",
" !conda install -c conda-forge pyoptsparse\n",
" else:\n",
" missing_packages.append('pyoptsparse')\n",
"if missing_packages:\n",
" raise EnvironmentError('This notebook requires the following packages '\n",
" 'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Modeling Dynamic Systems with Dymos\n",
"\n",
"```{admonition} Things you'll learn through this example\n",
"- How to define a basic Dymos ODE system.\n",
"- How to explicitly propagate the system from some initial state.\n",
"```\n",
"\n",
"Dymos is a library for modeling dynamic systems and performing optimal\n",
"control with the [OpenMDAO](https://github.com/OpenMDAO/OpenMDAO) framework.\n",
"Dynamic systems are typically defined by some set of ordinary\n",
"differential equations (the ODE) which governs their behavior.\n",
"\n",
"Consider a simple damped harmonic oscillator.\n",
"\n",
"![Damped harmonic oscillator free-body diagram](figures/spring_mass_damper.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\\begin{align}\n",
" \\ddot{x} &= -\\frac{kx}{m} - \\frac{c \\dot{x}}{m}\n",
"\\end{align}\n",
"\n",
"Converting this to a first order system results in an ODE system with two states:\n",
"\n",
"\\begin{align}\n",
" \\dot{x} &= v \\\\\n",
" \\dot{v} &= -\\frac{kx}{m} - \\frac{c \\dot{x}}{m}\n",
"\\end{align}\n",
"\n",
"## The OpenMDAO model of the ODE\n",
"\n",
"In Dymos, the ODE is an OpenMDAO System (a Component, or a Group of components).\n",
"The following ExplicitComponent computes the velocity rate for the damped harmonic oscillator.\n",
"\n",
"More detail on the workings of an ExplicitComponent can be found in the OpenMDAO documentation. In summary, an ExplicitComponent used as part of an ODE in Dymos should override the following methods:\n",
"\n",
"- **initialize**: Called at setup, and used to define options for the component. **ALL** Dymos ODE components should have the property `num_nodes`, which defines the number of points at which the outputs are simultaneously computed.\n",
"- **setup**: Used to add inputs and outputs to the component, and declare which outputs (and indices of outputs) are dependent on each of the inputs.\n",
"- **compute**: Used to compute the outputs, given the inputs.\n",
"- **compute_partials**: Used to compute the derivatives of the outputs w.r.t. each of the inputs analytically. This method may be omitted if finite difference or complex-step approximations are used, though analytic is recommended."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import openmdao.api as om\n",
"\n",
"\n",
"class OscillatorODE(om.ExplicitComponent):\n",
" \"\"\"\n",
" A Dymos ODE for a damped harmonic oscillator.\n",
" \"\"\"\n",
"\n",
" def initialize(self):\n",
" self.options.declare('num_nodes', types=int)\n",
"\n",
" def setup(self):\n",
" nn = self.options['num_nodes']\n",
"\n",
" # Inputs\n",
" self.add_input('x', shape=(nn,), desc='displacement', units='m')\n",
" self.add_input('v', shape=(nn,), desc='velocity', units='m/s')\n",
" self.add_input('k', shape=(nn,), desc='spring constant', units='N/m')\n",
" self.add_input('c', shape=(nn,), desc='damping coefficient', units='N*s/m')\n",
" self.add_input('m', shape=(nn,), desc='mass', units='kg')\n",
"\n",
" # self.add_output('x_dot', val=np.zeros(nn), desc='rate of change of displacement', units='m/s')\n",
" self.add_output('v_dot', val=np.zeros(nn), desc='rate of change of velocity', units='m/s**2')\n",
"\n",
" self.declare_partials(of='*', wrt='*', method='fd')\n",
"\n",
" def compute(self, inputs, outputs):\n",
" x = inputs['x']\n",
" v = inputs['v']\n",
" k = inputs['k']\n",
" c = inputs['c']\n",
" m = inputs['m']\n",
"\n",
" f_spring = -k * x\n",
" f_damper = -c * v\n",
"\n",
" outputs['v_dot'] = (f_spring + f_damper) / m"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{admonition} Things to note about the ODE system\n",
"- In this case, the ODE is a function of both states, but this isn't always the case. If the dynamics aren't functions of some states, those states aren't needed as inputs.\n",
"- This ODE only computes the rate of change of velocity. Since the rate of change of displacement can directly be obtained from another state variable, it doesn't need to be computed by the ODE. This would also be true if the state's rate was a control, design parameter, or input parameter value.\n",
"- It's possible that we might want to use parameters `c`, `k`, and `m` as design variables at some point, so they're also included as inputs here. Alternatively, if we had no interest in ever treating them as design variables, we could add their values as options to the ODE system in the `initialize` method.\n",
"```\n",
"\n",
"## Hello World: Propagating the dynamics\n",
"\n",
"One of the first things one might be interested in regarding an ODE is propagating it from some given initial conditions.\n",
"This is known as solving the initial value problem (IVP), and there are many software packages that can do this.\n",
"The following is a minimal script that starts the system at some set of initial conditions and propagates them for some fixed duration.\n",
"Some elements of this code will be explained later, but we'll hit the highlights now."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"active-ipynb",
"remove-input",
"remove-output"
]
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import openmdao.api as om\n",
"import dymos as dm\n",
"import matplotlib.pyplot as plt\n",
"# plt.switch_backend('Agg') # disable plotting to the screen\n",
"\n",
"from dymos.examples.oscillator.oscillator_ode import OscillatorODE\n",
"\n",
"# Instantiate an OpenMDAO Problem instance.\n",
"prob = om.Problem()\n",
"\n",
"# Instantiate a Dymos Trajectory and add it to the Problem model.\n",
"traj = dm.Trajectory()\n",
"prob.model.add_subsystem('traj', traj)\n",
"\n",
"# Instantiate a Phase and add it to the Trajectory.\n",
"# Here the transcription is necessary but not particularly relevant.\n",
"phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4))\n",
"traj.add_phase('phase0', phase)\n",
"\n",
"# Tell Dymos the states to be propagated using the given ODE.\n",
"phase.add_state('v', rate_source='v_dot', targets=['v'], units='m/s')\n",
"phase.add_state('x', rate_source='v', targets=['x'], units='m')\n",
"\n",
"# The spring constant, damping coefficient, and mass are inputs to the system\n",
"# that are constant throughout the phase.\n",
"phase.add_parameter('k', units='N/m', targets=['k'])\n",
"phase.add_parameter('c', units='N*s/m', targets=['c'])\n",
"phase.add_parameter('m', units='kg', targets=['m'])\n",
"\n",
"# Setup the OpenMDAO problem\n",
"prob.setup()\n",
"\n",
"# Assign values to the times and states\n",
"prob.set_val('traj.phase0.t_initial', 0.0)\n",
"prob.set_val('traj.phase0.t_duration', 15.0)\n",
"\n",
"prob.set_val('traj.phase0.states:x', 10.0)\n",
"prob.set_val('traj.phase0.states:v', 0.0)\n",
"\n",
"prob.set_val('traj.phase0.parameters:k', 1.0)\n",
"prob.set_val('traj.phase0.parameters:c', 0.5)\n",
"prob.set_val('traj.phase0.parameters:m', 1.0)\n",
"\n",
"# Perform a single execution of the model (executing the model is required before simulation).\n",
"prob.run_model()\n",
"\n",
"# Perform an explicit simulation of our ODE from the initial conditions.\n",
"sim_out = traj.simulate(times_per_seg=50)\n",
"\n",
"# Plot the state values obtained from the phase timeseries objects in the simulation output.\n",
"t_sol = prob.get_val('traj.phase0.timeseries.time')\n",
"t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n",
"\n",
"states = ['x', 'v']\n",
"fig, axes = plt.subplots(len(states), 1)\n",
"for i, state in enumerate(states):\n",
" sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.{state}'), 'o')\n",
" sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.{state}'), '-')\n",
" axes[i].set_ylabel(state)\n",
"axes[-1].set_xlabel('time (s)')\n",
"fig.legend((sol[0], sim[0]), ('solution', 'simulation'), loc='lower right', ncol=2)\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## What happened?\n",
"\n",
"This script consists of the following general steps:\n",
"\n",
"1. After importing relevant packages, an OpenMDAO Problem is instantiated\n",
"2. A Dymos Trajectory object is instantiated, and a single Phase named `'phase0'` is added to it.\n",
" 1. That Phase takes the ODE _class_ as one of its arguments. It will instantiate instances of it as needed.\n",
" 2. The transcription determines how the implicit integration and optimization are performed. It's necessary but not particularly relevant in this example.\n",
"3. The states to be integrated are added to the phase.\n",
" 1. Each state needs a rate source - an ODE-relative path of the output which provides the time derivative of the state variable.\n",
" For the rate_source of `x`, we provide `v`. Dymos understands this is the name of one of the other states (or time, or controls, or parameters).\n",
" 2. Those states which are inputs to the ODE need to provide their targets in the ODE (again, with an ODE-relative path).\n",
"4. The problem is setup (this prepares the model for execution in OpenMDAO).\n",
"5. Default values are assigned to the states and time.\n",
" 1. Variables `t_initial` and `t_duration` (the initial time and duration of the Phase) are scalars.\n",
" 2. State variables are vectors whose values are provided throughout the Phase. Here they're all being filled with a single value (10.0 for displacement, 0.0 for the velocity)\n",
"6. `Problem.run_model` is called. This executes the Problem's `model` one time. This is a necessary step before using the `Trajectory.simulate` method.\n",
"7. The trajectory is simulated using the `simulate()` method and the results returned as an OpenMDAO Problem instance called `sim_out`.\n",
"8. The states are plotted using values obtained from the _timeseries_. Phases contain _`timeseries`_ data that provides contiguous values regardless of the transcription used.\n",
"\n",
"Method `simulate` exists on both Trajectory and Phase objects.\n",
"It uses the [scipy.integrate.solve_ivp](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html) function to propagate the states defined in each phase of the trajectory from their initial values at the initial time to some final value at `time = t_initial + t_duration`.\n",
"\n",
"In Dymos, the `simulate` method is useful for testing the functionality of an ODE (making sure it behaves as expected) and for checking the validity of answers after optimization.\n",
"However, it cannot solve boundary value problems.\n",
"\n",
"## Why is the solution different from the simulation results?\n",
"\n",
"The plots above display both the solution from the implicit transcription (blue dots) and the results of the simulation (orange line).\n",
"Here they do not match because we only performed a single execution of the model.\n",
"**The purpose of a model execution in Dymos is to calculate the objective and constraints for the optimizer.**\n",
"These constraints include the collocation _defect_ constraints, which (when driven to zero) indicate that the current polynomial representation of the state-time history matches the physically correct trajectory.\n",
"In this case, no iteration was performed, and thus the solution is not physically valid.\n",
"\n",
"To be clear, the output of Dymos in this case is not a physically valid trajectory.\n",
"The `simulate()` call after executing the model is the expected result using the variable step integrator from Scipy.\n",
"\n",
"There are two ways to converge this solution using the implicit transcription techniques in Dymos.\n",
"1. We can run an optimization driver with some \"dummy\" objective to converge the collocation defect constraints.\n",
"2. We can have Dymos use a nonlinear solver to vary the state time-history until the collocation defect constraints are satisfied.\n",
"\n",
"Traditionally, many collocation optimal control techniques have used an optimizer-based approach because it is extremely efficient.\n",
"OpenMDAO provides a lot of versatility in adding nonlinear solvers within the optimization problem.\n",
"In our case, using a solver to converge state-time history means that the optimizer \"sees\" a physical trajectory at every iteration.\n",
"In an optimization context, we can use the solver-based convergence of defects to obtain a shooting method with analytic derivatives.\n",
"\n",
"## Using a solver to converge the physical trajectory\n",
"\n",
"We let Dymos know that one or more states should be converged using the `solve_segments=forward` argument.\n",
"If passed to the transcription, it applies to all states.\n",
"Otherwise, we can pass it only to certain states as an argument to `add_state` or `set_state_options`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import openmdao.api as om\n",
"import dymos as dm\n",
"import matplotlib.pyplot as plt\n",
"# plt.switch_backend('Agg') # disable plotting to the screen\n",
"\n",
"from dymos.examples.oscillator.oscillator_ode import OscillatorODE\n",
"\n",
"# Instantiate an OpenMDAO Problem instance.\n",
"prob = om.Problem()\n",
"\n",
"# Instantiate a Dymos Trajectory and add it to the Problem model.\n",
"traj = dm.Trajectory()\n",
"prob.model.add_subsystem('traj', traj)\n",
"\n",
"# Instantiate a Phase and add it to the Trajectory.\n",
"phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4, solve_segments='forward'))\n",
"traj.add_phase('phase0', phase)\n",
"\n",
"# Tell Dymos the states to be propagated using the given ODE.\n",
"phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n",
"phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n",
"\n",
"# The spring constant, damping coefficient, and mass are inputs to the system that are\n",
"# constant throughout the phase.\n",
"phase.add_parameter('k', units='N/m', targets=['k'])\n",
"phase.add_parameter('c', units='N*s/m', targets=['c'])\n",
"phase.add_parameter('m', units='kg', targets=['m'])\n",
"\n",
"# Setup the OpenMDAO problem\n",
"prob.setup()\n",
"\n",
"# Assign values to the times and states\n",
"prob.set_val('traj.phase0.t_initial', 0.0)\n",
"prob.set_val('traj.phase0.t_duration', 15.0)\n",
"\n",
"prob.set_val('traj.phase0.states:x', 10.0)\n",
"prob.set_val('traj.phase0.states:v', 0.0)\n",
"\n",
"prob.set_val('traj.phase0.parameters:k', 1.0)\n",
"prob.set_val('traj.phase0.parameters:c', 0.5)\n",
"prob.set_val('traj.phase0.parameters:m', 1.0)\n",
"\n",
"# Now we're using the optimization driver to iteratively run the model and vary the\n",
"# phase duration until the final y value is 0.\n",
"prob.run_model()\n",
"\n",
"# Perform an explicit simulation of our ODE from the initial conditions.\n",
"sim_out = traj.simulate(times_per_seg=50)\n",
"\n",
"# Plot the state values obtained from the phase timeseries objects in the simulation output.\n",
"t_sol = prob.get_val('traj.phase0.timeseries.time')\n",
"t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n",
"\n",
"states = ['x', 'v']\n",
"fig, axes = plt.subplots(len(states), 1)\n",
"for i, state in enumerate(states):\n",
" sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.{state}'), 'o')\n",
" sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.{state}'), '-')\n",
" axes[i].set_ylabel(state)\n",
"axes[-1].set_xlabel('time (s)')\n",
"fig.legend((sol[0], sim[0]), ('solution', 'simulation'), loc='lower right', ncol=2)\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using an optimization driver to converge the physical trajectory\n",
"\n",
"Alternatively, we can use an optimization driver to converge the state time histories."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the case of an initial value problem (fixed time duration, fixed initial states, and no controls or parameters as design variables) there are no\n",
"degrees of freedom to optimize the problem, just single possible trajectory which satisfies the collocation constraints.\n",
"\n",
"In OpenMDAO (and thus Dymos) optimizers require an objective.\n",
"Even though the initial time and duration of the phase are fixed, we provide the final time as a \"dummy\" objective here."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import openmdao.api as om\n",
"import dymos as dm\n",
"import matplotlib.pyplot as plt\n",
"# plt.switch_backend('Agg') # disable plotting to the screen\n",
"\n",
"from dymos.examples.oscillator.oscillator_ode import OscillatorODE\n",
"\n",
"# Instantiate an OpenMDAO Problem instance.\n",
"prob = om.Problem()\n",
"\n",
"# We need an optimization driver. To solve this simple problem ScipyOptimizerDriver will work.\n",
"prob.driver = om.ScipyOptimizeDriver()\n",
"\n",
"# Instantiate a Dymos Trajectory and add it to the Problem model.\n",
"traj = dm.Trajectory()\n",
"prob.model.add_subsystem('traj', traj)\n",
"\n",
"# Instantiate a Phase and add it to the Trajectory.\n",
"phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4))\n",
"traj.add_phase('phase0', phase)\n",
"\n",
"# Tell Dymos that the duration of the phase is bounded.\n",
"phase.set_time_options(fix_initial=True, fix_duration=True)\n",
"\n",
"# Tell Dymos the states to be propagated using the given ODE.\n",
"phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n",
"phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n",
"\n",
"# The spring constant, damping coefficient, and mass are inputs to the system that are\n",
"# constant throughout the phase.\n",
"phase.add_parameter('k', units='N/m', targets=['k'])\n",
"phase.add_parameter('c', units='N*s/m', targets=['c'])\n",
"phase.add_parameter('m', units='kg', targets=['m'])\n",
"\n",
"# Since we're using an optimization driver, an objective is required. We'll minimize\n",
"# the final time in this case.\n",
"phase.add_objective('time', loc='final')\n",
"\n",
"# Setup the OpenMDAO problem\n",
"prob.setup()\n",
"\n",
"# Assign values to the times and states\n",
"prob.set_val('traj.phase0.t_initial', 0.0)\n",
"prob.set_val('traj.phase0.t_duration', 15.0)\n",
"\n",
"prob.set_val('traj.phase0.states:x', 10.0)\n",
"prob.set_val('traj.phase0.states:v', 0.0)\n",
"\n",
"prob.set_val('traj.phase0.parameters:k', 1.0)\n",
"prob.set_val('traj.phase0.parameters:c', 0.5)\n",
"prob.set_val('traj.phase0.parameters:m', 1.0)\n",
"\n",
"# Now we're using the optimization driver to iteratively run the model and vary the\n",
"# phase duration until the final y value is 0.\n",
"prob.run_driver()\n",
"\n",
"# Perform an explicit simulation of our ODE from the initial conditions.\n",
"sim_out = traj.simulate(times_per_seg=50)\n",
"\n",
"# Plot the state values obtained from the phase timeseries objects in the simulation output.\n",
"t_sol = prob.get_val('traj.phase0.timeseries.time')\n",
"t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n",
"\n",
"states = ['x', 'v']\n",
"fig, axes = plt.subplots(len(states), 1)\n",
"for i, state in enumerate(states):\n",
" sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.{state}'), 'o')\n",
" sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.{state}'), '-')\n",
" axes[i].set_ylabel(state)\n",
"axes[-1].set_xlabel('time (s)')\n",
"fig.legend((sol[0], sim[0]), ('solution', 'simulation'), loc='lower right', ncol=2)\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## But the solution still doesn't match the simulation\n",
"\n",
"If you look at the plots from the last two examples, you'll notice that the state time-history from the solution has some pretty significant deviations from the simulation results.\n",
"This is an important lesson in using implicit collocation techniques.\n",
"\n",
"```{Note} \n",
"A converged trajectory isn't necessarily correct\n",
"```\n",
"\n",
"As we mentioned before, the `simulate()` method exists to provide a check on a converged trajectory.\n",
"In this case, the trajectory found using `simulate()` doesn't really interpolate the solution from the collocation technique.\n",
"In the next section, we'll explain how to deal with this."
]
}
],
"metadata": {
"celltoolbar": "Tags",
"jupytext": {
"cell_metadata_filter": "-all",
"notebook_metadata_filter": "-all",
"text_representation": {
"extension": ".md",
"format_name": "markdown"
}
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}