Substitute a SciPy spline function into a SymPy expression

167 views
Skip to first unread message

Maksim Surov

unread,
Apr 27, 2015, 6:56:43 PM4/27/15
to sy...@googlegroups.com
I would like to lambdify a sympy expression, and substitute an implementation of an abstract function into the expression (as usual the implementation is scipy.interpolate.spline function). The typical problem is the expression contains derivatives of the function. For example:
import sympy as sy
import numpy as np
import scipy.interpolate as interp

# the expression:
t
= sy.Symbol('t')
f
= sy.Function('f')(t)
expr
= (f + f**2 / 2).diff()

# implementation:
f_spline
= interp.splrep(np.linspace(0, 1, 100), np.sin(np.linspace(0, 1, 100)))

def df_impl(x):
 
print '[trace] f_der(' + str(x) + ')'
 
return interp.splev(x, f_spline, der=1)

def f_impl(x):
 
print '[trace] f(' + str(x) + ')'
 
return interp.splev(x, f_spline)

expr_impl
= sy.lambdify(t, expr, {'Derivative(f(t), t)': df_impl, 'f': f_impl})
print expr_impl(0.1)


This latest line throws the error:
File "<string>", line 1, in <lambda>
NameError: global name 'Derivative' is not defined

It's clear because lambdify can't substitute the the derivative string. There is a workaround, I can do 2 subs:

expr = expr.subs({'Derivative(f(t), t)': 'g(t)'})
expr_impl
= sy.lambdify(t, expr, {'g': df_impl, 'f': f_impl})
print expr_impl(0.1)

But the solution looks ugly. Any suggestions?

Aaron Meurer

unread,
Apr 27, 2015, 7:04:14 PM4/27/15
to sy...@googlegroups.com
I would use subs to replace the Derivative with a different Symbol
before using lambdify.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/1600fcbd-1201-40a6-b962-e271fe73f7e3%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages