{
"cells": [
{
"cell_type": "markdown",
"id": "44fccf57",
"metadata": {},
"source": [
"# First-order differential equations\n",
"\n",
"- KEYWORDS: integration, quad, zeros, shape, enumerate, solve_ivp\n"
]
},
{
"cell_type": "markdown",
"id": "4f68e1c5",
"metadata": {},
"source": [
"## Solutions to first-order differential equations by integration\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "21892f0b",
"metadata": {},
"source": [
"Adapted from Ch. 2 in Advanced Engineering Mathematics, 2^{nd} Ed. by Michael Greenberg.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "059509f3",
"metadata": {},
"source": [
"### Homogeneous, first-order linear differential equations\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "03741cd5",
"metadata": {},
"source": [
"We first consider a homogeneous, first-order, linear differential equation of the form:\n",
"\n",
"$y' + p(x) y = 0$, with $y(a) = b$ as an initial value.\n",
"\n",
"You can derive a solution to this ODE as:\n",
"\n",
"$y(x) = b e^{-\\int_a^x p(\\xi) d\\xi}$\n",
"\n",
"For concreteness, consider $(x+2) y' - xy = 0, y(0) = 3$\n",
"\n",
"what is the value of $y(1)$?\n",
"\n",
"We need to cast this in the form required to identify $p(x)$. That form is:\n",
"\n",
"$y' + \\frac{-x}{x+2}y = 0$.\n",
"\n",
"Now, we simply evaluate the required integral and use it to compute the value of the solution at the desired new $x$ value.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad14f590",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"a = 0 # y(a)=b\n",
"b = 3\n",
"x1 = 1 # where we want y(1)\n",
"\n",
"def p(x):\n",
" return -x / (x + 2)\n",
"\n",
"import numpy as np\n",
"from scipy.integrate import quad\n",
"\n",
"I, err = quad(p, a, x1)\n",
"\n",
"y_x1 = b * np.exp(-I)\n",
"\n",
"print(f'y(1) = {y_x1:1.3f}')"
]
},
{
"cell_type": "markdown",
"id": "e0958fc0",
"metadata": {},
"source": [
"It is a little trickier to evaluate the solution at several x-values, e.g. to make a plot. The `quad` function is not \"vectorized\", meaning it only performs one integral for one range at a time. You cannot pass it a list of ranges to evaluate it several times. Instead, we have to use a loop for this. In the loop, we will solve the integral, and accumulate the result in a solution array. Before we do that, here are a few useful commands we will need to use.\n",
"\n",
"First, it is useful to make an array to store the results in. There are a few ways to do this, the one we use today is the `np.zeros` function. You specify the size of the array as an argument. For example, to make an array with three zeros, do this:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c27bd1bf",
"metadata": {},
"outputs": [],
"source": [
"np.zeros((4, )), np.ones(4), np.empty(4)"
]
},
{
"cell_type": "markdown",
"id": "352ecfe0",
"metadata": {},
"source": [
"Second, it is helpful to get the shape of an array. You use dot notation and the shape attribute of an array for this. This allows you to create an array, and later make an array of zeros with the same shape and size.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "90db04a0",
"metadata": {
"lines_to_next_cell": 2
},
"outputs": [],
"source": [
"x = np.linspace(0, 3.5)\n",
"np.zeros(x.shape)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "85da527f",
"metadata": {},
"outputs": [],
"source": [
"for i, value in enumerate(['a','b','c']):\n",
" print(i, value)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7fd01395",
"metadata": {},
"outputs": [],
"source": [
"# old-fashioned way to do this\n",
"L = ['a','b','c']\n",
"for i in range(len(L)):\n",
" print(i, L[i])"
]
},
{
"cell_type": "markdown",
"id": "a83592d8",
"metadata": {},
"source": [
"Finally we will iterate over the elements of the x array, and in each step we need to know the index of the element *and* the value of the element. `enumerate` provides this in a pretty straightforward syntax. This function iterates over an array and returns at each step the index and element, which you can assign to variables that you use inside the loop. There are other ways to achieve this, but we only consider this method today. Here, we create an array, and an array of zeros that is the same shape. Then, we iterate over the first array, and set the corresponding index in the second array equal to a computation using the index and element value.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b34f6a19",
"metadata": {},
"outputs": [],
"source": [
"np.zeros_like(np.linspace(0, 1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a16704a8",
"metadata": {},
"outputs": [],
"source": [
"arr = np.linspace(0, 1, 5)\n",
"new_arr = np.zeros(arr.shape)\n",
"print(f'Before the loop new_arr = {new_arr}')\n",
"\n",
"for i, val in enumerate(arr):\n",
" new_arr[i] = i * val\n",
" print(f'The element at index {i} is {val}')\n",
"\n",
"print(f'After the loop new_arr = {new_arr}')"
]
},
{
"cell_type": "markdown",
"id": "df709345",
"metadata": {},
"source": [
"Back to the solution to our integration problem. Our goal is to compute the value of the solution for an array of x-values. We will iterate over an array of x-values, and for each one compute the value of the solution at that x, and save the solution in a new array.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "99ed95b7",
"metadata": {},
"outputs": [],
"source": [
"x = np.linspace(0, 3.5) # xs we want y(x) for\n",
"y = np.zeros(x.shape)\n",
"\n",
"for i, x1 in enumerate(x):\n",
" I, err = quad(p, a, x1)\n",
" y[i] = b * np.exp(-I)\n",
"\n",
"import matplotlib.pyplot as plt\n",
"plt.plot(x, y)\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.xlim([x.min(), x.max()]);"
]
},
{
"cell_type": "markdown",
"id": "ce290585",
"metadata": {},
"source": [
"We should ask, how can we tell this is correct? We can confirm the initial values, which we know are correct.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9506f7d2",
"metadata": {},
"outputs": [],
"source": [
"x[0], y[0]"
]
},
{
"cell_type": "markdown",
"id": "b8ecc5e4",
"metadata": {},
"source": [
"We can express the ODE as: $y' = \\frac{x}{x+2}y$. By inspection, we can see that the derivative will always be positive, so the solution should increase from the initial value, which it does.\n",
"\n",
"We can also examine the derivatives of our solution. We have to rely on numerical derivatives of our solution because x and y are arrays. `np.gradient` will compute the derivative using a reasonable approximation. We know the derivative analytically from the ODE.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ca4367e1",
"metadata": {},
"outputs": [],
"source": [
"dydx = np.gradient(y, x, edge_order=2) # edge_order=2 is a more accurate estimate\n",
"\n",
"plt.plot(x, dydx, label='numerical')\n",
"plt.plot(x, x / (x + 2) * y, 'r--', label='analytical')\n",
"plt.xlabel('x')\n",
"plt.ylabel('dy/dx')\n",
"plt.legend()"
]
},
{
"cell_type": "markdown",
"id": "904e5a6b",
"metadata": {},
"source": [
"Here you see good agreement over most of the range. The end-points are always less accurate because the derivatives there are approximated by a less accurate formula. We interpret the sum of this evidence to mean our solution to the ODE is good over this range of x values.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "1804230b",
"metadata": {},
"source": [
"### Non-homogeneous linear first-order ODEs\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "455f4771",
"metadata": {},
"source": [
"A non-homogenous first order, linear differential equation has this form:\n",
"\n",
"$y' + p(x) y = q(x), y(a)=b$\n",
"\n",
"Equations of this form are typically solved with a method called variation of parameters. In the most general form, this leads to solutions of the form:\n",
"\n",
"$y(x) = e^{-\\int_a^x p(\\xi)d\\xi}\\left(\\int_a^x e^{\\int_a^{\\xi} p(\\zeta)d\\zeta} q(\\xi)d\\xi + b\\right)$\n",
"\n",
"It is a little tricky to implement this. It is helpful to break this down into several pieces. Note that it is not necessary to do this, it just makes it easier to read, debug, and see that you have done it correctly. Here are the easiest parts.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0f55c47b",
"metadata": {},
"outputs": [],
"source": [
"def p(xi):\n",
" return -2 * xi\n",
"\n",
"def q(xi):\n",
" return np.sin(xi)\n",
"\n",
"a = 0\n",
"b = 3"
]
},
{
"cell_type": "markdown",
"id": "b9394ea5",
"metadata": {},
"source": [
"Next, we will break the equation into two parts:\n",
"\n",
"$y(x) = term1 * term2$ where\n",
"\n",
"$term1 = e^{-\\int_a^x p(\\xi)d\\xi}$\n",
"\n",
"and\n",
"\n",
"$term2 = \\left(\\int_a^x e^{\\int_a^{\\xi} p(\\zeta)d\\zeta} q(\\xi)d\\xi + b\\right)$\n",
"\n",
"We can immediately define a function for term1 as:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ddee1161",
"metadata": {},
"outputs": [],
"source": [
"def term1(x):\n",
" I1, _ = quad(p, a, x)\n",
" return np.exp(-I1)"
]
},
{
"cell_type": "markdown",
"id": "bdfb16eb",
"metadata": {},
"source": [
"term2 is a little trickier, as it has a partial integral inside an integral. We can define a function for this term also, but we have to define an internal function to use for the integral. The internal function will have an integral inside of it.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7bfee3e0",
"metadata": {},
"outputs": [],
"source": [
"def integrand(xi):\n",
" internal_term1, _ = quad(p, a, xi)\n",
" return np.exp(internal_term1) * q(xi)\n",
" \n",
"def term2(x):\n",
" I2, _ = quad(integrand, a, x)\n",
" return I2 + b"
]
},
{
"cell_type": "markdown",
"id": "b94c7320",
"metadata": {},
"source": [
"Now, to use it, we form the product of the two terms:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0eef5622",
"metadata": {},
"outputs": [],
"source": [
"x1 = 0.5\n",
"print(term1(x1) * term2(x1))"
]
},
{
"cell_type": "markdown",
"id": "198821a4",
"metadata": {},
"source": [
"With some algebra and calculus on your part, you might arrive at the following non-elementary integral solution:\n",
"\n",
"$y(x) = e^{x^2} \\left(\\int_0^x e^{-\\xi^2} \\sin{\\xi} d\\xi + 3\\right)$\n",
"\n",
"The solution is called non-elementary because you cannot evaluate the integral in closed form using elementary functions, e.g. powers of x, trigonometric functions, exponentials or logarithms. You can, however, use numerical methods to integrate it.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fffd377e",
"metadata": {},
"outputs": [],
"source": [
"def integrand(x):\n",
" return np.exp(-x**2) * np.sin(x)\n",
"\n",
"I, _ = quad(integrand, 0, x1)\n",
"\n",
"sol = np.exp(x1**2) * (I + b)\n",
"sol"
]
},
{
"cell_type": "markdown",
"id": "ff7833ca",
"metadata": {},
"source": [
"Note there is some conservation of effort here. If you can derive the solution above correctly (and you have all learned how to do this if you had a differential equations course), the code below is quite short to get the solution at some value of x. If you are unable to derive that solution, you can use the general solution we gave, but then it is a trickier solution to implement in code.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "9c52ad35",
"metadata": {},
"source": [
"### Limitations of solutions by integration\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "615ffe0e",
"metadata": {},
"source": [
"Solution by integration has some advantages. You get an estimate of the error in the solution from the `quad` function, which is helpful to know how good the solution is. However, the methods described above are limited to *linear* differential equations of the form described. If you have a nonlinear differential equation, or if you are unable to separate the equations into integrable form, the methods simply don't work. Next, we consider how to approach equations where we cannot use integration to solve the problems.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "f8a53259",
"metadata": {},
"source": [
"## Numerical solutions to differential equations\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "d8f77d51",
"metadata": {},
"source": [
"We begin with a brief review of first order differential equations. The equations we are concerned with here all have the form:\n",
"\n",
"$\\frac{dy}{dx} = f(x, y)$\n",
"\n",
"And the value of the solution is known at some point, e.g. $y(x0) = y0$. $f(x, y)$ can be linear or nonlinear. Our goal in this section is to motivate how numerical solutions are obtained.\n",
"\n",
"These notes were adapted from Chapter 6 in Advanced Engineering Mathematics 2^{nd} ed. by Michael D. Greenberg.\n",
"\n",
"The basic idea behind these methods is that we know the initial value of the solution *and* the derivative of the solution (it is defined by the ODE definition above), and so we can estimate the solution a small distance away from the initial value. If you repeat this process with the newly estimated point, you can estimate the next point, and so on. There are many algorithms for performing the estimation, and we will consider a two of them. These algorithms differ in efficiency, ease of implementation, and accuracy.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "5119ede7",
"metadata": {},
"source": [
"### Euler's method\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "c782b39f",
"metadata": {
"lines_to_next_cell": 2
},
"source": [
"The main idea of Euler's method is that if you know the value of the solution at some point, and you know the derivative at that point, you can estimate the solution nearby at $x0 + h$, where $h$ is a small number:\n",
"\n",
"$y_{n+1} = y_n + f(x_n, y_n) h$\n",
"\n",
"Now, you just repeat this until you get to the x-value that you want. For concreteness, consider:\n",
"\n",
"$y' = y + 2x - x^2; y(0) = 1$.\n",
"\n",
"This ODE has a known analytical solution: $y(x) = x^2 + e^x$. We will use this for comparison.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7fd0c14c",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"def f(x, y):\n",
" return y + 2 * x - x**2\n",
"\n",
"x0 = 0\n",
"y0 = 1\n",
"\n",
"x, h = np.linspace(x0, 1.5, 1500, retstep=True) # Note the optional argument to get the stepsize.\n",
"print(f'h = {h}')\n",
"\n",
"y = np.zeros(x.shape)\n",
"y[0] = y0 # initial condition corresponding to x[0]\n",
"\n",
"# Implementation of Euler's method\n",
"for n in range(0, len(x) - 1):\n",
" y[n + 1] = y[n] + f(x[n], y[n]) * h"
]
},
{
"cell_type": "markdown",
"id": "b101ab45",
"metadata": {},
"source": [
"We can check out the solution graphically:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e00ad6ed",
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"plt.plot(x, y, label='Euler')\n",
"plt.plot(x, x**2 + np.exp(x), 'r--', label='Analytical')\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"id": "3c1155a7",
"metadata": {},
"source": [
"This solution does not look that good until you increase the number of points (i.e. decrease the value of $h$, significantly). It is known the error decreases only linearly with $h$.\n",
"\n",
"**Exercise** Increase the number of points in the x array and see how it affects the solution.\n",
"\n",
"This method is not used in practice; it is not very accurate, and you need quite small $h$ to get a good solution. It is used here to illustrate the idea of how one integrates a differential equation. We will consider one more advanced method, the fourth-order Runge-Kutta method.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "d28c2255",
"metadata": {},
"source": [
"### Fourth-order Runge-Kutta method\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "08b08457",
"metadata": {},
"source": [
"The general idea of the more advanced methods is to use a weighted average of slopes at various points around a point to best estimate the next function value. Here we consider the fourth-order Runge-Kutta algorithm. The terms are tedious to derive, and we will not do it here as they can be looked up in several places (e.g. [https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#The_Runge%E2%80%93Kutta_method](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods#The_Runge%E2%80%93Kutta_method)).\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7b76315b",
"metadata": {},
"outputs": [],
"source": [
"x0 = 0\n",
"y0 = 1\n",
"\n",
"x, h = np.linspace(x0, 1.5, 5, retstep=True)\n",
"print(f'h = {h}')\n",
"y = np.zeros(x.shape)\n",
"y[0] = y0\n",
"\n",
"# Implementation of fourth order Runge Kutta method\n",
"for i in range(0, len(x) - 1):\n",
" k1 = h * f(x[i], y[i]) # Note this is like Euler's method\n",
" k2 = h * f(x[i] + h / 2, y[i] + k1 / 2) # This is the increment at the midpoint using y, k1\n",
" k3 = h * f(x[i] + h / 2, y[i] + k2 / 2) # This is the increment at the midpoint using y, k2\n",
" k4 = h * f(x[i] + h, y[i] + k3) # This is the increment at the end of the interval\n",
" # This is a weighted average of the four increments computed above. There is a heavier weight on the midpoints\n",
" y[i + 1] = y[i] + (k1 + (2 * k2) + (2 * k3) + k4) / 6"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d800c586",
"metadata": {},
"outputs": [],
"source": [
"plt.plot(x, y, label='RK-4')\n",
"plt.plot(x, x**2 + np.exp(x), 'r--', label='Analytical')\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"id": "7d9f95e1",
"metadata": {},
"source": [
"Note you can get a much more accurate solution with a larger $h$ with this method.\n",
"\n",
"*If* our differential equation is just $\\frac{dy}{dt} = f(x)$, i.e. $f$ is independent of $y$, then this method is equivalent to Simpson't rule of integration.\n",
"\n",
"Both of these methods leave some things to be desired:\n",
"\n",
"1. We had to code them, and there are many places to make mistakes.\n",
"2. You have to choose $h$, or equivalently the number of points to use, and then make sure the solution has converged (does not depend on your choice).\n",
"3. $h$ is fixed in these examples, and you might prefer to use an adaptive value.\n",
"4. It is not easy to solve the inverse problem, e.g. for what value of $x$ does $y=4$?\n",
"\n",
"In practice, there are well-written ODE integrators to solve this kind of problem that address all the short-comings listed above. To use them, we just need to learn the syntax. We do that next.\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "ba677ec0",
"metadata": {},
"source": [
"## scipy.integrate.solve_ivp\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "30ee4d7a",
"metadata": {},
"source": [
"The `scipy.integrate` library provides `solve_ivp` to solve first order differential equations. It is not the only one available, but this function is recommended. You import the function like this:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3f6900d8",
"metadata": {},
"outputs": [],
"source": [
"from scipy.integrate import solve_ivp"
]
},
{
"cell_type": "markdown",
"id": "3e7dad68",
"metadata": {
"lines_to_next_cell": 2
},
"source": [
"Here is a minimal use of the function, with keyword arguments.\n",
"\n",
"`y0` is an array containing the initial values. `fun` is a function with a signature of f(t, y). Here, $t$ is considered the independent variable. You can call it whatever you want, so f(x, y) is also fine. Since `solve_ivp` had $t$ in mind, the second argument is the `t_span`, which is a tuple of two numbers for where the integration starts (t0, or x0) and where it ends. `solve_ivp` returns an object.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b5e6eed5",
"metadata": {},
"outputs": [],
"source": [
"y0 = 1\n",
"y0 = np.array([y0]) # It is a good idea to make y0 an array. It will be important later.\n",
"sol = solve_ivp(fun=f, t_span=(x0, 1.5), y0=y0)"
]
},
{
"cell_type": "markdown",
"id": "b3c3f329",
"metadata": {},
"source": [
"The output of `solve_ivp` is an object containing results in attributes on the object.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5bb4c0a9",
"metadata": {},
"outputs": [],
"source": [
"sol"
]
},
{
"cell_type": "markdown",
"id": "d4c7e2a8",
"metadata": {},
"source": [
"You should look for a few things here. One is that the message indicates success. Second, we access the solution using dot notation. Here are the independent variable values the solution was evaluated at.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b51a4e47",
"metadata": {},
"outputs": [],
"source": [
"sol.t.shape"
]
},
{
"cell_type": "markdown",
"id": "dcf4d7a3",
"metadata": {},
"source": [
"Third, the solution is in a 2D array. We only have one equation here, so we use indexing to get the first row as an array.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "98f60959",
"metadata": {},
"outputs": [],
"source": [
"sol.y"
]
},
{
"cell_type": "markdown",
"id": "f0cfe5d0",
"metadata": {},
"source": [
"Now, we can plot the solution.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "487ae410",
"metadata": {},
"outputs": [],
"source": [
"plt.plot(sol.t, sol.y.T, 'bo', label='solve_ivp')\n",
"plt.plot(sol.t, sol.t**2 + np.exp(sol.t), 'r--', label='Analytical')\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"id": "d33c35eb",
"metadata": {},
"source": [
"That doesn't looks so great since there are only four data points. By default, the algorithm only uses as many points as it needs to achieve a specified tolerance. We can specify that we want the solution evaluated at other points using the optional `t_eval` keyword arg.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "44a6cc9a",
"metadata": {},
"outputs": [],
"source": [
"X = np.linspace(x0, 1.5)\n",
"sol = solve_ivp(fun=f, t_span=(x0, 1.5), y0=y0, t_eval=X)\n",
"sol"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "70c240e9",
"metadata": {},
"outputs": [],
"source": [
"plt.plot(sol.t, sol.y[0], 'b.', label='solve_ivp')\n",
"plt.plot(X, X**2 + np.exp(X), 'r--', label='Analytical')\n",
"plt.xlabel('x')\n",
"plt.ylabel('y')\n",
"plt.legend()"
]
},
{
"cell_type": "markdown",
"id": "02cc7318",
"metadata": {},
"source": [
"So far, `solve_ivp` solves the issues with item 1 (we did not have to code the algorithm), and items 2 and 3 (it uses an adaptive step and converges to a tolerance for us). It will also help us solve for the inverse problem, i.e. for what value of $x$ is $y=4$?\n",
"\n",
"To do this, we need a new concept of an \"event function\". During each step of the integration, you can run a function that can detect an \"event\". When an event is detected, the location of the event is stored, and if desired integration can be terminated. `solve_ivp` can take a list of event functions. We consider only one for now.\n",
"\n",
"An event occurs when an event function is equal to zero. During integration, if the event function changes sign, then it is clear an event has occurred, and the algorithm determines where it occurred. Since we want to know when $y=4$, we will define a function that returns $y - 4$, because that will equal zero at that condition. We want the integration to terminate when that happens, so we set the \"terminal\" attribute on our function to True.\n",
"\n",
"An event function has a signature of f(x, y). Remember that $y$ is going to be an array,\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c0e08f92",
"metadata": {},
"outputs": [],
"source": [
"def event1(x, y):\n",
" return y[0] - 4\n",
"\n",
"event1.terminal = True\n",
"\n",
"sol = solve_ivp(fun=f, t_span=(x0, 1.5), y0=y0, events=event1)\n",
"sol"
]
},
{
"cell_type": "markdown",
"id": "c98a0738",
"metadata": {},
"source": [
"Now, there are a couple of new things to note. First, we got a message that a termination event occurred. Second, the sol.y array ends at 4.0, because we made the event function *terminal*. Next, sol.t\\_events is not empty, because an event occurred. It now contains the value where the event occurred, which is where $y=4$!\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "55f09091",
"metadata": {},
"outputs": [],
"source": [
"sol.t_events[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f15107f5",
"metadata": {},
"outputs": [],
"source": [
"sol.t"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6415e265",
"metadata": {},
"outputs": [],
"source": [
"print(f'y=4 at x={sol.t[-1]}. Confirming: y = {sol.t[-1]**2 + np.exp(sol.t[-1])}')"
]
},
{
"cell_type": "markdown",
"id": "9d0874bd",
"metadata": {},
"source": [
"That is pretty close. You have to decide if it is close enough for the purpose you want. You can control the tolerance with optional `atol` and `rtol` keywords. You should read the documentation before changing this.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c40f6316",
"metadata": {},
"outputs": [],
"source": [
"def event1(x, y):\n",
" return y[0] - 4\n",
"\n",
"event1.terminal = True\n",
"\n",
"sol = solve_ivp(fun=f, t_span=(x0, 1.5), y0=y0, events=event1, rtol=1e-9)\n",
"sol\n",
"sol.t[-1]**2 + np.exp(sol.t[-1])"
]
},
{
"cell_type": "markdown",
"id": "00c90575",
"metadata": {},
"source": [
"## Summary\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "9731f2af",
"metadata": {
"lines_to_next_cell": 2
},
"source": [
"We learned how to solve different types of first-order differential equations. Linear equations can be solved by integration, which has the benefit of providing an estimate of error if the `scipy.integrate.quad` function is used.\n",
"\n",
"Most first-order differential equations can be solved numerically with `scipy.integrate.solve_ivp`. This solver allows you to specify the points the solution is evaluated on, and to define event functions that can terminate the integration, or record where events occur.\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}