Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using numba.autojit on a lambdify'd sympy expression

I've used numpy in the past and am fairly comfortable with it, but sometimes when I've wanted a little extra speed, I've been able to use the numba.autojit decorator. Easy. The problem now is I'm currently working on a chain of sympy expressions and numba (jit OR autojit) isn't sure what to make of the function out of lambdify. It looks like sympy doesn't maintain a specific argument list.

I suppose I could look at how sympy.lamdify works and make my own version that encorporates numba, but I figured I'd ask around first.

like image 800
Jacob Avatar asked Jan 27 '26 14:01

Jacob


2 Answers

To answer your second question, the way lambdify works is that it creates a string form of the expression as a lambda, and evals it in a namespace with the numerical functions.

For instance, for lambdify(x, sin(x), 'numpy'), sin(x) is converted to 'sin(x)' (the string form here is the same as the regular string form, but they can differ, e.g., because of function name differences between SymPy and NumPy. The function that does this is sympy.printing.lambdarepr.lambdarepr. Note that the function you want to use though is sympy.utilities.lambdify.lambdastr, which also does the next step.

This is then added to lambda, giving 'lambda x: sin(x)'.

Then, it roughly does

g = {}
exec 'from numpy import *' in g # or exec('from numpy import *', g) in Python 3
l = eval('lambda x: sin(x)', g)

and l will be the lambdifies function.

In other words, it evaluates 'lambda x: sin(x)' in a namespace where sin is numpy.sin.

As far as I know, numba.jit and numba.autojit just translate bytecode, so they should work fine on a lambda.

like image 68
asmeurer Avatar answered Jan 29 '26 04:01

asmeurer


I have not used numba myself, but I am familiar with lambdify and can tell you that it won't work out of the box. So if you are comfortable implementing this yourself a 'numba' module to lambdify would most probably be much appreciated as a "Pull Request" over at https://github.com/sympy/sympy

I myself, implemented something similar to lambdify for one of my projects where the default sympy one was too slow, if it is of any help you may look at the source code here: https://github.com/bjodah/symvarsub/

like image 45
Bjoern Dahlgren Avatar answered Jan 29 '26 02:01

Bjoern Dahlgren