May 10, 2024

Use Python and SymPy Function Lambdify() to Transform Symbolic Expressions and Symbolic Matrices to Python (Lambda) Functions


In this Python scientific computing tutorial, we will learn how to transform symbolic scalar and matrix expressions into Python (lambda) functions which can be used to quickly calculate numerical values of expressions. This is a very powerful technique for automatically generating Python functions from symbolic expressions. For example, we can use Python’s symbolic computation library called SymPy to automatically perform symbolic computations, such as integration, differentiation, addition, and inversion. Furthermore, we can also use this library to symbolically invert matrices and compute matrix expressions. After we compute the symbolic expressions, we can automatically generate Python functions from these expressions, and use the generated functions in algorithms and Python classes. We can automatically generate Python functions from symbolic expressions by using SymPy’s “lambdify()” function.

The YouTube video accompanying this tutorial is given below.

Create Python (Lambda) Functions from Scalar Symbolic Expressions

Let us start with the first example. Consider the following function

(1)   \begin{align*}y=e^{\tan(x)}\sin(x)+\cos(3x^{2})+\frac{x+2}{2x^{2}+1}\end{align*}

Let us assume that we want to create a Python function that for the given value of x will return us the value of

(2)   \begin{align*}\frac{dy}{dx}\end{align*}

We can solve this problem by analytically (by hand) calculating the derivative, and then by typing the resulting expression in Python by using the NumPy library. However, we will most likely make an error, either during the analytical computation or during the implementation of the derivative in Python. This is just one example, and we can imagine more complex and realistic examples where it is necessary to have a procedure for

  1. Automatically computing derivatives, integrals, and other operations on complex mathematical expressions
  2. Automatically generating Python functions out of the computed mathematical expression

One of the most elegant approaches to solve these problems is to use the SymPy Python library. We can use this library to define symbolic expressions and perform mathematical operations on symbolic expressions. In addition to this, the SymPy library has one very powerful function that can be used to automatically generate Python (lambda) functions from the symbolic expressions. The name of this function is “lambdify()”.

The following Python script explains how to solve the above problem by using SymPy and lambdify().

#import the necessary libraries
import numpy as np
#import the complete SymPy library
from sympy import *
# call this function for nice printing of symbolic 
# expressions
init_printing()

# create the symbolic x variable
x=Symbol('x')

# create the symbolic expression
y=sin(x)*E**(tan(x))+cos(3*x**2)+(x+2)/(2*x**2+1)

# compute the derivative with respect to x
dydt=diff(y,x)

# create a function out of the symbolic expression
diffFunction=lambdify(x,dydt)

# evaluate the derivative at the specified input point
result=diffFunction(3.1)

First, we create the symbolic variable “x” by using

x=Symbol('x')

Then, we define the function “y”

# create the symbolic expression
y=sin(x)*E**(tan(x))+cos(3*x**2)+(x+2)/(2*x**2+1)

Here, it should be kept in mind that SymPy is using “E” instead of “e” to denote the exponential function. Then, we compute the derivative of the symbolic expression “y”

# compute the derivative with respect to x
dydt=diff(y,x)

Finally, we use the function “lambdify()” to create a function from the symbolic expression “dydt”

# create a function out of the symbolic expression
diffFunction=lambdify(x,dydt)

# evaluate the derivative at the specified input point
result=diffFunction(3.1)

The first input argument of “lambdify()” is the name of the symbolic variable, and the second input argument is the name of the symbolic expression. The function “lambdify()” returns the Python (lambda) function that accepts the numerical value of “x” as the input argument and returns the numerical value of “dydt” as the output. Finally, we call the function “diffFunction()” by passing the numerical value of “x” as the input argument. The output is the numerical value of “dydt” at the point x=3.1.

Create Python (Lambda) Functions from Multivariable Symbolic Expressions

Here, we will explain how to create Python (Lambda) functions from multivariable symbolic expressions involving several symbolic variables.

For example, let us consider the following function of three input arguments x, y, and z:

(3)   \begin{align*}f(x,y,z)=(x-1)^{2}+(y+2)^{2}+xyz\end{align*}

The Python script given below first creates the symbolic description of this multivariable function, and then it creates a Python function for evaluating this multivariable function at the prescribed input point (x,y,z):

#import the necessary libraries
import numpy as np
#import the complete SymPy library
from sympy import *
# call this function for nice printing of symbolic 
# expressions
init_printing()

# create the symbolic x,y, and z variables
x,y,z=symbols('x y z')

# define the function f
f=(x-1)**2+(y+2)**2+x*y*z

# create the function out of the symbolic expression
functionExpression=lambdify([x, y, z],f)

# compute the function value by specifying the 
# x, y, and z values
functionValue=functionExpression(1,2,3)

This Python script uses the same implementation principle as the previous one. We define three symbolic variables “x”, “y”, and “z”

# create the symbolic x,y, and z variables
x,y,z=symbols('x y z')

We create the function out of the symbolic expression as follows

# create the function out of the symbolic expression
functionExpression=lambdify([x, y, z],f)

We compute the value of the function by using

# compute the function value by specifying the 
# x, y, and z values
functionValue=functionExpression(1,2,3)

Create Python (Lambda) Functions from Symbolic Matrix Expressions

In the sequel, we explain how to create symbolic matrix expressions and how to create Python (lambda) functions from the symbolic expressions. We consider the following matrix expression

(4)   \begin{align*}Y=A^{-1}+A\cdot B\end{align*}

where A and B are two square matrices, and Y is the resulting matrix

The following Python script creates the symbolic expression corresponding to (4), creates the Python function out of the symbolic expression, and finally, computes the value of this expression.


# import the necessary libraries
import numpy as np
# sympy library - we import everything
from sympy import *
# this function is used to generate nice 
# prints of symbolic expressions
init_printing()

# define the symbolic matrices A and B
A=MatrixSymbol('A',3,3)
B=MatrixSymbol('B',3,3)

# define the matrix expression
Y=A.inv()+A*B

# define the function 
functionExpression=lambdify([A,B],Y)

# create two NumPy matrices
A1=np.random.randn(3,3)
B1=np.random.randn(3,3)

# compute the expression
Y1=functionExpression(A1,B1)

We create the symbolic matrix expressions as follows

# define the symbolic matrices A and B
A=MatrixSymbol('A',3,3)
B=MatrixSymbol('B',3,3)

We define the matrix expressions

# define the matrix expression
Y=A.inv()+A*B

Next, we create the Python function from the symbolic expression, create two test NumPy matrices, and evaluate the function value for two created test matrices:

# define the function 
functionExpression=lambdify([A,B],Y)

# create two NumPy matrices
A1=np.random.randn(3,3)
B1=np.random.randn(3,3)

# compute the expression
Y1=functionExpression(A1,B1)