-1

I want to solve the equation in python over the time Interval I = [0,10] with initial condition (x_0, y_0) = (1,0) and the parameter values μ ∈ {-2, -1, 0, 1, 2} using the function

scipy.integrate.odeint

Then I want to plot the solutions (x(t;x_0,y_0), y(t;x_0,y_0)) in the xy-plane.

The originally given linear system is

dx/dt = y, x(0) = x_0

dy/dt = - x - μy, y(0) = y_0

Please see my code below:

import numpy as np

from scipy.integrate import odeint

sol = odeint(myode, y0, t , args=(mu,1)) #mu and 1 are the coefficients when set equation to 0

y0 = 0

myode(y, t, mu) = -x-mu*y

def t = np.linspace(0,10, 101) #time interval

dydt = [y[1], -y[0] - mu*y[1]]

return dydt

Could anyone check if I defined the callable function myode correctly? This function evaluates the right hand side of the ODE.

Also an syntax error message showed up for this line of code

def t = np.linspace(0,10, 101) #time interval

saying there is invalid syntax. Should I somehow use

for * in ** 

to get rid of the error message? If yes, how exactly?

I am very new to Python and ODE. Could anyone help me with this question? Thank you very much!

TZ2359
  • 1
  • 2

2 Answers2

0

Try using the solve_ivp method.

from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import numpy as np

i = 0
u = [-2,-1,0,1,2]
for x in u:
    def rhs2(t,y):
       return [y[1], -1*y[0] - u[x]*y[1]]
    value = u[i]
    res2 = solve_ivp(rhs2, [0,10],  [1,0] , t_eval=[0,1,2,3,4,5,6,7,8,9,10],  method = 'RK45') 

    t = np.array(res2.t[1:-1])
    x = np.array(res2.y[0][1:-1])
    y = np.array(res2.y[1][1:-1])
    fig = plt.figure()
    plt.plot(t, x, 'b-', label='X(t)')
    plt.plot(t, y, 'g-', label='Y(t)')
    plt.title("u = {}".format(value))
    plt.legend(loc='lower right')
    plt.show() 
    i = i + 1

Here is the solve_ivp method Documentation

Here is a very similar problem with a better explanation.

0

myode should be a function definition, thus

def myode(u, t, mu): x,y = u; return [ y, -x-mu*y]

The time array is a simple variable declaration/assignment, there should be no def there. As the system is two-dimensional, the initial value also needs to have dimension two

sol = odeint(myode, [x0,y0], t, args=(mu,) )

Thus a minimal modification of your script is

def myode(u, t, mu): x,y = u; return [ y, -x-mu*y]
t = np.linspace(0,10, 101) #time interval
x0,y0 = 1,0  # initial conditions
for mu in [-2,-1,0,1,2]:
    sol = odeint(myode, [x0,y0], t, args=(mu,) )
    x,y = sol.T
    plt.plot(x,y)
a=5; plt.xlim(-a,a); plt.ylim(-a,a)
plt.grid(); plt.show()

giving the plot

plot of solutions as per code

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51