2

I am using SymPy for symbolic manipulation of expression, which is evaluated on huge amounts of data using NumPy. To speed up things, I use sympy.lambdify, but I cannot get abs to work.

import sympy
import numpy as np

x = sympy.symbols('x',real=True)

def f(x):
    return 1-sympy.Abs(x)

def g(x):
    return 1-sympy.sqrt(x)


fl = sympy.lambdify(x,f(x),'numpy')
gl = sympy.lambdify(x,g(x),'numpy')
gl(1) # success
gl(np.array([1,2,3]))
fl(2) # NameError: global name 'Abs' is not defined
fl(np.array([1,2,3])) # Same error

An option would be to use the 'sympy' argument for the lambdify call, but then I cannot use arrays. I have tried using sympy.abs and numpy.abs, but without success.

I use it in a program for solving cumbersome integrals using inverse-substitution and some tabulated integrals, but it would be so convenient with the option using an abs function instead of explicitly handling different regions.

sympy.Abs is indeed defined

Thanks in advance

Jens Munk
  • 4,627
  • 1
  • 25
  • 40
  • 1
    The error is telling you that the `abs` function isn't defined. Is it defined by `sympy`? Then in the definition of `f` you'll need to write `sympy.abs(x)`, rather than simply `abs(x)`. – jme Dec 22 '14 at 21:44
  • This works for me (apart from the missing parenthesis in the line `gl(np.array([1,2,3])`. Which Python are you using? – xnx Dec 22 '14 at 21:46
  • @jme: I get the same error if I use sympy.abs. – Jens Munk Dec 22 '14 at 21:47
  • @xnx: I use Python 2.7.3: If it is working for you, I would like to know what version you are using – Jens Munk Dec 22 '14 at 21:48

2 Answers2

2

This looks like a bug that has been fixed in recent versions of SymPy: https://code.google.com/p/sympy/issues/detail?id=2654 It works on Python 2.7.9, SymPy 0.7.3 and Python 3.3.5, SymPy 0.7.5.

xnx
  • 24,509
  • 11
  • 70
  • 109
  • Thanks, I will update my Python and SymPy. I am an old Debian fart and usually stick to stable. Thanks again – Jens Munk Dec 22 '14 at 21:52
  • OK - if you don't fancy upgrading, try using `sympy.Abs` directly as @Marius suggests. – xnx Dec 22 '14 at 21:53
  • This gives me the same error, I working quite some time on this. It doesn't make sense that I continue get the same error. – Jens Munk Dec 22 '14 at 21:54
1

You can workaround this by mapping Abs to abs, like lambdify(x, f(x), ["numpy", {'Abs': numpy.abs}]). Of course, upgrading SymPy is a much better solution if it's possible for you.

asmeurer
  • 86,894
  • 26
  • 169
  • 240