Replacing derivatives by python functions

271 views
Skip to first unread message

Lucas Campos

unread,
Mar 27, 2018, 12:22:50 PM3/27/18
to sympy
Dear all,

I am trying to get SymPy 1.1.1 to replace derivatives of a Function (i.e., generated by sympy.Function) by a python function (created with def). I can replace the Functions itself, but not their derivatives.

Right now, I am using some "toy" functions, but eventually, they will be created as the interpolation of a data set.

I tried doing this in two ways: First, just adding a dictionary to sympy.lambidify. A function is returned by lambidify, but calling it fails with:

Traceback (most recent call last):
  File "./replace_direct.py", line 56, in <module>
    print(du_f(1, 1, 1))
  File "<string>", line 1, in <lambda>
NameError: name 'Derivative' is not defined


I tried a similar approach as suggested in https://groups.google.com/forum/#!topic/sympy/U3s0mSTszd4, namely, creating a temporary name and then replacing it. This also fails, but with

[1, 2, 3]
Traceback (most recent call last):
  File "./replace_indirect.py", line 67, in <module>
    print(du_f(1, 1, 1))
  File "<string>", line 1, in <lambda>
NameError: name 'x' is not defined


Does anyone know the best way to do such replacement?

Bests,
Lucas 
replace_direct.py
replace_indirect.py

Aaron Meurer

unread,
Mar 27, 2018, 4:36:34 PM3/27/18
to sy...@googlegroups.com
The keys in the lambdify modules dictionary should be strings, which
are the names that are looked up in the lambdified function. Setting
them as expressions as you are doing here does not work. The
documentation that I've written in this unmerged pull request explains
this better https://github.com/sympy/sympy/pull/13485.

Your indirect replacement doesn't work because SymPy converts the
string "dxx(x, y, z)" to a symbol named "dxx(x, y, z)", not a
function. If you instead define

dxx = Function('dxx')

and so on, and

subs({sympy.Derivative(ux, x): dxx(x, y, z), ...})

it works.

Of course, it's all much simpler if you just use SymPy objects, like
substituting Derivative(ux, x) for 1 directly, or substituting ux for
whatever it is, at let SymPy do the math.

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 https://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/d5a20080-6571-4473-b78d-23780ed993f3%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages