{
"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 # noqa: F401\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 # noqa: F401\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 # noqa: F401\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": [
"# Analytic Phases in Dymos\n",
"\n",
"In certain situations analytic solutions are known for the ODE.\n",
"Typically such situations arise when higher fidelity isn't needed, but these include:\n",
"- analytic propagation of a two-body orbit\n",
"- the Breguet-range equations for an aircraft in steady flight.\n",
"\n",
"In these situations it can be advantageous to utilize the analytic solution and simplify the trajectory optimization problem.\n",
"Such phases are avaialble in dymos through the `AnalyticPhase` class.\n",
"Compared to implicit approaches this reduces the size of the optimization problem by removing some design variables and corresponding defect constraints.\n",
"Compared to explicit approaches it removes the need to numerically propagate the ODE, which is generally a performance bottleneck.\n",
"\n",
"For analytic phases, the OpenMDAO system we provide to the phase provides the _solution_ to the ODE, not the ODE itself.\n",
"\n",
"\n",
"\\begin{align} \n",
" \\textbf x = \\textbf f(t, \\textbf p)\n",
"\\end{align}\n",
"\n",
"where\n",
"$\\textbf x$ is the vector of *state variables* (the variable being integrated),\n",
"$t$ is *time* (or *time-like*),\n",
"$\\textbf p$ is the vector of *parameters* (an input to the ODE),\n",
"and\n",
"$\\textbf f$ is the *ODE solution function*."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Differences with other transcriptions\n",
"\n",
"Note that AnalyticPhase differ from other phases in dymos in a few key ways.\n",
"\n",
"First, the states themselves are purely outputs of the ODE solution function.\n",
"This means that the values of the states are never used as design variables, and therefore things like `lower` and `upper` bounds or `scalers` have no meaning.\n",
"It is an error to provide these options to a state in an analytic phase.\n",
"\n",
"There is generally no analytic solution to a system when a general time-varying control is provided as an input to the ODE, so they are not permitted to be used with AnalyticPhase.\n",
"All outputs of the ODE must be based on the values of static parameters and the independent variable (generally time).\n",
"\n",
"AnalyticPhase has the notion of _states_ but they are generally just \"special\" outputs of the ODE solution system. They are automatically added to the timeseries output with the name `{path.to.phase}.states:{state_name}`.\n",
"\n",
"Finally, AnalyticPhase doesn't have the notion of a multi-segment _grid_ on which the solution is calculated.\n",
"To keep things as simple as possible, the user provides the phase with a number of nodes at which the solution is requested (lets call it _N_ for now).\n",
"Dymos then provides the solution at _N_ Legendre-Gauss-Lobatto (LGL) nodes.\n",
"This design decision was made because phase types use the LGL nodes to define the input times of polynomial control variables.\n",
"This means that values of an output of an `AnalyticPhase` can be fed into another phase as a polynomial control."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{eval-rst}\n",
" .. automethod:: dymos.AnalyticPhase.add_state\n",
" :noindex:\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A basic example\n",
"\n",
"Suppose we want to use Dymos to solve the ODE\n",
"\n",
"\\begin{align}\n",
" \\frac{dx}{dt} = x - t^2 + 1\n",
"\\end{align}\n",
"\n",
"subject to:\n",
"\n",
"\\begin{align}\n",
" x(0) = 0.5\n",
"\\end{align}\n",
"\n",
"Here we want to find the value of _x_ at t=2.\n",
"\n",
"We can absolutely use a pseudospectral method or explicit shooting in Dymos to find the value of _x_ on a given interval using this information.\n",
"But in this case, the solution is known analytically.\n",
"\n",
"\\begin{align}\n",
" x(t) &= t^2 + 2t + 1 - c_1e^t\n",
"\\end{align}\n",
"\n",
"We need to find the value of constant $c_1$ to find our particular solution.\n",
"Applying the given initial condition gives c_1 as 0.\n",
"\n",
"\\begin{align}\n",
" x(0) &= 1 - c_1 = 0.5 \\\\\n",
" c_1 &\\equiv y_0 = 0.5\n",
"\\end{align}\n",
"\n",
"The component that provides the solution is then:"
]
},
{
"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 numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import openmdao.api as om\n",
"import dymos as dm\n",
"\n",
"\n",
"class SimpleIVPSolution(om.ExplicitComponent):\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",
" self.add_input('t', shape=(nn,), units='s')\n",
" self.add_input('x0', shape=(1,), units='unitless', tags=['dymos.static_target'])\n",
" self.add_output('x', shape=(nn,), units='unitless')\n",
"\n",
" ar = np.arange(nn, dtype=int)\n",
" self.declare_partials(of='x', wrt='t', rows=ar, cols=ar)\n",
" self.declare_partials(of='x', wrt='x0')\n",
"\n",
" def compute(self, inputs, outputs):\n",
" t = inputs['t']\n",
" x0 = inputs['x0']\n",
" outputs['x'] = t ** 2 + 2 * t + 1 - x0 * np.exp(t)\n",
"\n",
" def compute_partials(self, inputs, partials):\n",
" t = inputs['t']\n",
" x0 = inputs['x0']\n",
" partials['x', 't'] = 2 * t + 2 - x0 * np.exp(t)\n",
" partials['x', 'x0'] = -np.exp(t)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Solving the problem with Dymos looks like this"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"p = om.Problem()\n",
"traj = p.model.add_subsystem('traj', dm.Trajectory())\n",
"\n",
"phase = dm.AnalyticPhase(ode_class=SimpleIVPSolution, num_nodes=10)\n",
"\n",
"traj.add_phase('phase', phase)\n",
"\n",
"phase.set_time_options(units='s', targets=['t'], fix_initial=True, fix_duration=True)\n",
"phase.add_state('x')\n",
"phase.add_parameter('x0', opt=False)\n",
"\n",
"p.setup()\n",
"\n",
"p.set_val('traj.phase.t_initial', 0.0, units='s')\n",
"p.set_val('traj.phase.t_duration', 2.0, units='s')\n",
"p.set_val('traj.phase.parameters:x0', 0.5, units='unitless')\n",
"\n",
"p.run_model()\n",
"\n",
"t = p.get_val('traj.phase.timeseries.time', units='s')\n",
"x = p.get_val('traj.phase.timeseries.x', units='unitless')\n",
"\n",
"print(f'x({t[-1, 0]}) = {x[-1, 0]}')\n",
"\n",
"# A dense version of the analytic solution for plot comparison.\n",
"def expected(time):\n",
" return time ** 2 + 2 * time + 1 - 0.5 * np.exp(time)\n",
"\n",
"t_dense = np.linspace(t[0], t[-1], 100)\n",
"\n",
"plt.subplots(1, 1, figsize=(8, 6))\n",
"plt.plot(t, x, 'o')\n",
"plt.plot(t_dense, expected(t_dense), '-')\n",
"plt.xlabel('time (s)')\n",
"plt.ylabel('x (n.d.)')\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remove-input",
"remove-output"
]
},
"outputs": [],
"source": [
"from openmdao.utils.assert_utils import assert_near_equal\n",
"\n",
"def expected(time):\n",
" return time ** 2 + 2 * time + 1 - 0.5 * np.exp(time)\n",
"\n",
"assert_near_equal(x, expected(t))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Possible Questions\n",
"\n",
"You might be asking\n",
"\n",
"**Why use Dymos at all here? This is just as easy to do with a pure OpenMDAO component.**\n",
"\n",
"And you'd be absolutely right.\n",
"But what makes this useful in the context of Dymos is that it allows us to pose a trajectory as the continuous evolution of a system in time.\n",
"Often in real practice we have portions of a trajectory where an analytic solution is available, and by utilizing an analytic solution to obtain the output in those phases, we make the problem easier for the optimizer to solve.\n",
"\n",
"**Why not allow the initial state value to be an input to the phase?**\n",
"\n",
"We had considered having the initial state value be a variable in this case, but it was a construct that didn't mesh well with the other transcriptions.\n",
"It would require the addition of an `initial_state_targets` option that wouldn't apply to other transcriptions.\n",
"Also, the particular solution is often, but not _always_ found using the value of the state at the initial time.\n",
"In these cases, using a generic parameter felt like the more flexible way of doing things while minimizing changes to the existing code."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Additional differences\n",
"\n",
"Since AnalyticPhases only output state values, there is no notion of a target of state variable in an `AnalyticPhase`.\n",
"In an `AnalyticPhase`, states need a *source*.\n",
"Much like timeseries outputs, when we add a state to the `AnalyticPhase` we can specify the entire path, and the last bit of the path (after the last period) will be used for the name of the state.\n",
"And just as `add_timeseries_output` uses argument `output_name` to disambiguate the name of the timeseries output if necessary, `add_state` will accept `state_name` if the last portion of the path is ambiguous."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linking Analytic Phases\n",
"\n",
"`AnalyticPhase` provides timeseries output and so it can be linked to other phases using continuity constraints. However, since the initial value of the state is not an input variable in the phase it does not support linking with option `connected = True`.\n",
"\n",
"In the example below, we add an intermediate breakpoint to the solution above where $x = 1.5$.\n",
"Changing the `connected` argument of `link_phases` to `True` will raise an error."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"p = om.Problem()\n",
"traj = p.model.add_subsystem('traj', dm.Trajectory())\n",
"\n",
"first_phase = dm.AnalyticPhase(ode_class=SimpleIVPSolution, num_nodes=10)\n",
"first_phase.set_time_options(units='s', targets=['t'], fix_initial=True, duration_bounds=(0.5, 10.0))\n",
"first_phase.add_state('x')\n",
"first_phase.add_parameter('x0', opt=False)\n",
"\n",
"first_phase.add_boundary_constraint('x', loc='final', equals=1.5, units='unitless')\n",
"\n",
"second_phase = dm.AnalyticPhase(ode_class=SimpleIVPSolution, num_nodes=10)\n",
"second_phase.set_time_options(units='s', targets=['t'], duration_bounds=(0.1, 10.0))\n",
"second_phase.add_state('x')\n",
"second_phase.add_parameter('x0', opt=False)\n",
"\n",
"second_phase.add_boundary_constraint('time', loc='final', equals=2.0, units='s')\n",
"\n",
"# Since we're using constraints to enforce continuity between the two phases, we need a \n",
"# driver and a dummy objective. As usual, time works well for a dummy objective here.\n",
"first_phase.add_objective('time', loc='final')\n",
"p.driver = om.ScipyOptimizeDriver()\n",
"\n",
"traj.add_phase('first_phase', first_phase)\n",
"traj.add_phase('second_phase', second_phase)\n",
"\n",
"# We can link time with a connection, since initial time is an input to the second phase.\n",
"traj.link_phases(['first_phase', 'second_phase'], ['time'], connected=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Different ways to handle the phase linkage for state continuity\n",
"\n",
"At this point we need to choose how to enforce state continuity.\n",
"We cannot simply use `traj.link_phases(['first_phase', 'second_phase'], ['x'], connected=True)` because **the initial value of state `x` is not an input to the phase**.\n",
"\n",
"One might think to link state `x` from `first_phase` to parameter `x0` from second phase, but that is also not correct, because `x0` is not the initial value of `x` in the phase but the value of `x` at `t=0`.\n",
"We could redefine `x0` to be the value at the initial time, however.\n",
"\n",
"Valid options here would be to link the states together with unconnected phases, using a constraint:\n",
"\n",
"`traj.link_phases(['first_phase', 'second_phase'], ['x'], connected=False)`\n",
"\n",
"Alternatively, we could either link parameters `x0` together in both phases (a connection would be fine) or use a trajectory-level parameter to pass a single value of `x0` to both phases.\n",
"\n",
"In the example below, trajectory parameter `x0` is fed to the parameter of the same name in the phases.\n",
"You'll need to make sure that both of the target parameters are not designated as design variables (`opt = False`).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"traj.add_parameter('x0', val=0.5, opt=False)\n",
"\n",
"p.setup()\n",
"\n",
"p.set_val('traj.first_phase.t_initial', 0.0, units='s')\n",
"p.set_val('traj.first_phase.t_duration', 2.0, units='s')\n",
"p.set_val('traj.parameters:x0', 0.5, units='unitless')\n",
"\n",
"p.run_driver()\n",
"\n",
"t_1 = p.get_val('traj.first_phase.timeseries.time', units='s')[:, 0]\n",
"x_1 = p.get_val('traj.first_phase.timeseries.x', units='unitless')[:, 0]\n",
"x0_1 = p.get_val('traj.first_phase.parameter_vals:x0')[:, 0]\n",
"\n",
"t_2 = p.get_val('traj.second_phase.timeseries.time', units='s')[:, 0]\n",
"x_2 = p.get_val('traj.second_phase.timeseries.x', units='unitless')[:, 0]\n",
"x0_2 = p.get_val('traj.second_phase.parameter_vals:x0')[:, 0]\n",
"\n",
"print(f'x({t_1[-1]}) = {x_1[-1]}')\n",
"print(f'x({t_2[-1]}) = {x_2[-1]}')\n",
"\n",
"# A dense version of the analytic solution for plot comparison.\n",
"def expected(time):\n",
" return time ** 2 + 2 * time + 1 - x0_1 * np.exp(time)\n",
"\n",
"t_dense = np.linspace(t_1[0], t_2[-1], 100)\n",
"\n",
"plt.subplots(1, 1, figsize=(8, 6))\n",
"plt.plot(t_1, x_1, 'o', label='first_phase')\n",
"plt.plot(t_2, x_2, 'o', label='second_phase')\n",
"plt.plot(t_dense, expected(t_dense), '-', label='continuous solution')\n",
"plt.xlabel('time (s)')\n",
"plt.ylabel('x (n.d.)')\n",
"plt.grid()\n",
"plt.legend(ncol=3, loc='lower center')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"remove-input",
"remove-output"
]
},
"outputs": [],
"source": [
"assert_near_equal(1.500000, x_1[-1], tolerance=1.0E-6)\n",
"assert_near_equal(0.5338712554624387, t_1[-1], tolerance=1.0E-6)\n",
"assert_near_equal(2.0, t_2[-1], tolerance=1.0E-6)\n",
"assert_near_equal(5.305471950533106, x_2[-1], tolerance=1.0E-6)"
]
}
],
"metadata": {
"celltoolbar": "Tags",
"jupytext": {
"cell_metadata_filter": "-all",
"notebook_metadata_filter": "-all",
"text_representation": {
"extension": ".md",
"format_name": "markdown"
}
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.10.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}