Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enumerate the undefined functions in a SymPy expression?

Tags:

sympy

I have a variety of SymPy expressions involving UndefinedFunction instances:

f = Function('f')
g = Function('g')
e = f(x) / g(x)

How can I obtain a list of the function invocations appearing in such expressions? In this example, I'd like to get [f(x), g(x)].

I'm aware of free_symbols but it kicks back set([x]) (as it should).

like image 837
Rhys Ulerich Avatar asked Oct 02 '22 15:10

Rhys Ulerich


1 Answers

You are right that you want to use atoms, but be aware that all functions in SymPy subclass from Function, not just undefined functions. So you'll also get

>>> (sin(x) + f(x)).atoms(Function)
set([f(x), sin(x)])

So you'll want to further reduce your list to only those functions that are UndefinedFunctions. Note that UndefinedFunction is the metaclass of f, so do to this, you need something like

>>> [i for i in expr.atoms(Function) if isinstance(i.__class__, UndefinedFunction)]
[f(x)]
like image 165
asmeurer Avatar answered Oct 05 '22 10:10

asmeurer