Search code examples
pythonsympysymbolic-math

Substitute placeholder function in integral using sympy


I am using sympy to evaluate a rather complex eigenvalue problem that relies on several state functions. I would like to be able to use placeholder functions that I can generate the integral and evaluate the dependence of the integral on the input function later.

import sympy as s
x, L = s.symbols('x L')
Q = s.Function('Q')(x)

# do some sort of integration
e = s.integrate(Q, (x, -L, L))
print(e)
# Integral(Q(x), (x, -L, L))

# evaluate a simple linear function
print(e.subs(Q, x))
# Integral(Q(x), (x, -L, L))
# Expected: Integral(x, (x, -L, L))
#       Or: 0 (evaluation)

# intermediate work around
interm = Q
e = s.integrate(interm.subs(Q, x), (x, -L, L))
print(e)
# 0 (expected)

As you can see, the evaluation of the integral does not allow for function substitution. Of course, I can perform the substitution at any point before the x integration of Q, but it would be convenient to perform substitution later. Is there a way around this? Or, is there a reason why this is avoided by sympy by design?


Solution

  • The behavior of subs on Integral has been changed in the development version of SymPy (see https://github.com/sympy/sympy/wiki/release-notes-for-0.7.4#unification-of-sum-product-and-integral-classes). We plan to do a release within the next few weeks. Your example works in the development version:

    >>> # This is in the development version
    >>> print(e.subs(Q, x))
    Integral(x, (x, -L, L))
    

    As a workaround, you can use replace instead of subs:

    >>> # This is in 0.7.3
    >>> print(e.replace(Q, x))
    Integral(x, (x, -L, L))