Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert symbolic expressions to Python functions using SymPy

I have a rather large symbolic function that is evaluated for different values of a parameter in a loop. In each iteration, after finding the expression of the function, partial derivatives are derived. Something like this:

from sympy import diff, symbols,exp

def lagrange_eqs(a):
    x,y,z= symbols('x y z')
    FUNC=x**2-2*x*y**2+z+a*exp(z)
    d_lgrng_1=diff(FUNC,x)
    d_lgrng_2=diff(FUNC,y)
    d_lgrng_3=diff(FUNC,z)
    return [d_lgrng_1,d_lgrng_2,d_lgrng_3]

Next, I need to convert the output of this function to a Python function so that I can use fsolve to find x, y, z values for which derivatives are zero. The function must take x,y,z as a list.

Now here is my problem: how do I convert the output of the above function to a Python function which could be passed on to a solver. Such a function should look like this (for a=3):

def lagrange_eqs_solve(X): 
    x,y,z=X
    return [2*x - 2*y**2, -4*x*y, 3*exp(z) + 1]

I simply copied the output of the first function to build the second one. Is there a way I could code it? (Matlab has a built-in function for this, called matlabFunction)

like image 253
AGandom Avatar asked Dec 10 '15 06:12

AGandom


People also ask

How do you evaluate a symbolic expression in Python?

evalf() function and subs() function from sympy is used to evaluate algebraic expressions. Example 1: In this example, we import symbols from sympy package. An expression is created and evalf() function is used to evaluate the expression.

How do you create a function in SymPy?

Defining a mathematical function in SymPy You can do so by simply assigning the expression to a variable f which will be your function. The sympy. symbols() method is used to declare variables for the mathematical function. The f(symbol(x)) will give a symbolic 2x.

How do you simplify expressions in SymPy?

With the help of sympy. simplify() method, we can simplify any mathematical expression. Parameters: expression – It is the mathematical expression which needs to be simplified.

Does SymPy work with NumPy?

In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions.


1 Answers

You want lambdify.

f = lambdify(((x, y, z),), lagrange_eqs(a))

will give you a Python function f that you can evaluate like f((1, 2, 3)) (for x=1, y=2, z=3). I have made the arguments in a tuple so that it will work with scipy's fsolve.

You can set the modules flag to lambdify to determine where the exp function will come from. For instance, to use numpy, use lambdify((x, y, z), lagrange_eqs(a), modules="numpy"). To use the standard library math library, use modules="math". By default, numpy is used if it is installed, otherwise math is used.

like image 72
asmeurer Avatar answered Oct 03 '22 15:10

asmeurer