4

I am studying python for what concerns ode numerical integration, in particular I found the scipy.integrate function solve_ipv . I tried the example shown in the scipy.integrate.solve_ipv page but there could be a mistake in the code related to the Lotka Volterra example:

def lotkavolterra(t, z, a, b, c, d):
    x, y = z
    return [a*x - b*x*y, -c*y + d*x*y]

sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1))

t = np.linspace(0, 15, 300)
z = sol.sol(t)

import matplotlib.pyplot as plt
plt.plot(t, z.T)
plt.xlabel('t')
plt.legend(['x', 'y'], shadow=True)
plt.title('Lotka-Volterra System')
plt.show()
  1. sol.sol(t) has no meaning in this code. What should we write? Maybe a tuple z = sol.t, sol.y ?

  2. It is also clear that len(sol.y[0])=57 and len(sol.y[1])=57 while t has 300 elements. For this reason coupling their values for a plot can be a problem.

In the page there is also a plot of what we would obtain if the code run.

I don't think it's important but I am using python3.

EDIT: I did not insert dense_output=True in solv_ipv()

Siderius
  • 174
  • 2
  • 14

1 Answers1

6

In the solver call

sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
                dense_output=True)

the last option dense_output=True is responsible for adding the sol function to the solution "bunch" object. This function implements the method-specific piecewise polynomial interpolation that in the literature is called "dense output". Thus the next two lines make complete sense, as z = sol.sol(t) contains a sample for any point in t.

This option does not change the sequence of internal nodes and step sizes. sol.t and sol.y contain the same values with or without that option. There is even no additional computation involved, as the stepper computes this interpolation polynomial for every step. This is used even without the dense output option in the event mechanism. Only the memory use is increased when the individual interpolation polynomials are stored after each step and assembled in the dense output function.


To avoid the confusion of sol.sol, some have taken res for "result" or similar as the variable name for the solver return value, so that the interpolation function is accessed as res.sol(t).

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
  • Yes I forgot that call but in my code I didn't use `dense_output=True`. Briefly speaking does this command make the output array smoother in relation to the parameter `t`? Are we definitely changing the real vector output? – Siderius Jan 12 '21 at 10:59
  • 1
    Yes, a polynomial interpolation makes a smoother look than a piecewise linear function. Matlab's ode45 etc. does this better with the "Refine" option that adds internal points of the segment of each step to the output. So a plot looks more smooth but the density of the points is still adapted to the actual "curvature" of the solution. – Lutz Lehmann Jan 12 '21 at 11:10