Vadim Gubaidulin
Vadim Gubaidulin

Reputation: 23

Passing keyword argument to quad integration functions in scipy

I want to pass keyword arguments to integrand function in the dblquad or nquad. Is it possible at all to have a keyword argument here or should I just opt in for having positional arguments only?

Basically, I tried to pass dictionary as a normal argument. Below is my attempt at doing that:

def foo(A, B, **kwargs):
    alpha = kwargs.get('alpha', 1.0)
    beta = kwargs.get('beta', 1.0)
    return A*alpha+B*beta
def integrator(**kwargs):
    alpha = kwargs.get('alpha', 1.0)
    beta = kwargs.get('beta', 1.0)
    a = dblquad(foo, 0, 2*pi, lambda x: 0, lambda x: 2*pi, args=(kwargs))
integrator(alpha = 1.0, beta = 2.0)

Python complains about having an improper number of positional arguments. It treats keywords dictionary as a number of positional arguments.

Upvotes: 2

Views: 817

Answers (2)

Translunar
Translunar

Reputation: 3816

I was able to solve this problem just now by passing a function object to the integrate method (my example uses RK45 instead of quadrature).

Basically, you create a class like this one:

class MyFunction(object):
  def __init__(self, constant1, constant2, **kwargs):
    self.constant1 = constant1
    # ... and so on ...

  def __call__(self, t, y):
    # This is your 'fun' that gets passed.

When you setup the integrator, you do it like so:

my_fun = MyFunction(c1, c2, other_arg = 'foo', bar = 10.0)
integ = RK45(my_fun, t0, y0, tf)
while integ.t < tf and integ.status != 'failed':
  integ.step()

This does not, of course, allow you to change the parameters to my_fun in the middle of an integration. But it does allow you to pass a more customizable function to the integration method.

Upvotes: 0

ev-br
ev-br

Reputation: 26030

Short answer: kwargs are not supported.

Possible workarounds include passing keyword args as positionals, passing a single dict as a positional argument, or attaching relevant keywords as attributes to the function you're integrating.

Upvotes: 2

Related Questions