# fast_callable x numpy

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)
f(z)


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])
g(z)


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 close merge delete

Sort by » oldest newest most voted

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
[0,
0.5984721441039564,
-0.9589242746631385,
0.9379999767747389,
-0.5440211108893698]


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](https://doc.sagemath.org/html/en/reference/calculus/sage/symbolic/expression_conversions.html. (a reveres numpy->Sage converter might be harder to build...)...

HTH,

more

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

-cos(z)
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.

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...