Search code examples
pythonscipydifferential-equations

using scipy solve_ivp for a function with extra arguments


I am trying to solve an initial value problem with solve_ivp. The problem is that my function f(x,y)=dy/dx contain extra arguments. I tried to use this:

Pass args for solve_ivp (new SciPy ODE API)

but it keeps giving me errors. Here is the code:

from numpy import arange
import math
import numpy as np
from scipy.integrate import solve_ivp
from numpy import pi

sigmav = 1.0e-9
Mpl = 1.22e19
ms=100.0
gg=100.0
gs=106.75

def Yeq(x):
    return 0.145*(gg/gs)*(x)**(3/2)*np.exp(-x)

def ss(x,m_dm):
    return (2/45)*((pi)**2)*gs*(m_dm**3/x**3)

def hubb(x,m_dm):
    return 1.66*(gg**(1/2))*(m_dm**2/Mpl)*(1/x**2)

def derivada(x,yl,m_dm,σv):
    return -(σv*ss(x,m_dm)*((yl**2)-(Yeq(x)**2)))/(x*hubb(x,m_dm))


xx=np.logspace(np.log10(3),3,100)
y00 = Yeq(xx[0])
x00 = xx[0] 
sigmav = 1.7475e-9
ms=100.0

solucion1 = solve_ivp(fun=lambda x, y: derivada(x, y, args=(ms,sigmav),[np.min(xx),np.max(xx)],[y00],method='BDF',rtol=1e-10,atol=1e-10))

When I try to run the cell for solucion1, it returns the following:

File "<ipython-input-17-afcf6c3782a9>", line 6
solucion1 = solve_ivp(fun=lambda x, y: derivada(x, y, args=(ms,sigmav),[np.min(xx),np.max(xx)],[y00],method='BDF',rtol=1e-10,atol=1e-10))
                                                                      ^
SyntaxError: positional argument follows keyword argument

It must be something very easy but I am just starting to work with python, so please help me with this.


Solution

  • You simply mis-placed a closing parenthesis. As derivada has no named args, remove the args statement there, the lambda expression already binds these additional parameters. Also, the passed function is not a named argument

    solucion1 = solve_ivp(lambda x, y: derivada(x, y, ms, sigmav),[np.min(xx),np.max(xx)], [y00], method='BDF', rtol=1e-10, atol=1e-10)
    

    or in the form that you cite from the github discussion, where the parameter list is constructed elsewhere

    args = ( ms, sigmav )
    
    solucion1 = solve_ivp(lambda x, y: derivada(x, y, *args),[np.min(xx),np.max(xx)], [y00], method='BDF', rtol=1e-10, atol=1e-10)