Ask Your Question

fast_callable x numpy

asked 2022-01-09 22:18:27 +0200

cav_rt gravatar image

fast_callable is very handy for evaluating symbolic expressions with numpy arrays. Like

my_expr = integral(sin(x),x)
f = fast_callable(my_expr, vars=[x])

import numpy as np
z = np.linspace(0,10,5)

However, it does't work when the expression involves a special function.

my_expr2 = integral(sin(x^2),x)
g = fast_callable(my_expr2, vars=[x])

Throws The Function erf does not support numpy arrays as arguments.

Is there any way of turn symbolic expressions containing special functions into numpy-callable? Thus avoiding to rewrite them using scipy special functions?

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted

answered 2022-01-10 00:09:17 +0200

Emmanuel Charpentier gravatar image

updated 2022-01-10 00:26:46 +0200

What about :

sage: import numpy
sage: my_exp=integral(sin(x),x)
sage: f=fast_callable(my_exp.substitute_function({sin:numpy.sin, cos:numpy.cos}), vars=[x])
sage: z=numpy.linspace(0,10,5)
sage: %time f(z)
CPU times: user 47 µs, sys: 0 ns, total: 47 µs
Wall time: 51.5 µs
array([-1.        ,  0.80114362, -0.28366219, -0.34663532,  0.83907153])
sage: lz=list(map(SR, z))
sage: time list(map(sin, lz))
CPU times: user 154 µs, sys: 0 ns, total: 154 µs
Wall time: 159 µs

A "general sage-numpy dictionary" could be prepared and used at will (could even be packaged or Sage patched to include it).

Alternativelty, fast_callable could be adapted to accept sage's equivalent of standard numpy functions, for example by buildind a Sage->numpy [ExpressionTreeWalker]( (a reveres numpy->Sage converter might be harder to build...)...


edit flag offensive delete link more


For expressions with only elementary functions, there is no need of substitute_function. A callable function (or fast_callable) does the job.

array([-1.        ,  0.80114362, -0.28366219, -0.34663532,  0.83907153])

The problem are the special functions. erf in my minimal example. But the sage-numpy dictionary and substitute_function simplify the hard work. Thanks!!

I had a look at the documentation for expression conversion, but it not clear for me how to implement a general Sage->numpy conversion.

cav_rt gravatar imagecav_rt ( 2022-01-10 02:52:47 +0200 )edit

That amounts to completing sympy with your definitions of "misssing" function. Not a small undertaking...

Numerical analysis is a bitch, and DLMF (née Abramowitz and Stegun) is your friend...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2022-01-10 10:17:31 +0200 )edit

I see, thanks!

cav_rt gravatar imagecav_rt ( 2022-01-10 15:58:44 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2022-01-09 22:18:27 +0200

Seen: 220 times

Last updated: Jan 10 '22