Skip to content

Commit

Permalink
maint: various fixes related to warnings in the test suite
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarbenjamin committed Jul 10, 2022
1 parent a524bfe commit 73b317a
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 36 deletions.
12 changes: 12 additions & 0 deletions sympy/printing/lambdarepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,20 @@ def _print_Piecewise(self, expr):
ans.append('where(%s, %s, ' % (cond, expr))
parenthesis_count += 1
if not is_last_cond_True:
# See https://github.com/pydata/numexpr/issues/298
#
# simplest way to put a nan but raises
# 'RuntimeWarning: invalid value encountered in log'
#
# There are other ways to do this such as
#
# >>> import numexpr as ne
# >>> nan = float('nan')
# >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan})
# array([-1., nan, nan])
#
# That needs to be handled in the lambdified function though rather
# than here in the printer.
ans.append('log(-1)')
return ''.join(ans) + ')' * parenthesis_count

Expand Down
4 changes: 1 addition & 3 deletions sympy/printing/tests/test_lambdarepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,12 @@ def test_numexpr():

from sympy.codegen.ast import Return, FunctionDefinition, Variable, Assignment
func_def = FunctionDefinition(None, 'foo', [Variable(x)], [Assignment(y,x), Return(y**2)])
print("")
print(NumExprPrinter().doprint(func_def))
expected = "def foo(x):\n"\
" y = numexpr.evaluate('x', truediv=True)\n"\
" return numexpr.evaluate('y**2', truediv=True)"
print(expected)
assert NumExprPrinter().doprint(func_def) == expected


class CustomPrintedObject(Expr):
def _lambdacode(self, printer):
return 'lambda'
Expand Down
2 changes: 1 addition & 1 deletion sympy/testing/runtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2030,7 +2030,7 @@ def findout_terminal_width():
process = subprocess.Popen(['stty', '-a'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout = process.stdout.read()
stdout, stderr = process.communicate()
stdout = stdout.decode("utf-8")
except OSError:
pass
Expand Down
6 changes: 4 additions & 2 deletions sympy/utilities/_compilation/compilation.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,15 +535,17 @@ def _write_sources_to_build_dir(sources, build_dir):
sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest()
if os.path.exists(dest):
if os.path.exists(dest + '.sha256'):
sha256_on_disk = open(dest + '.sha256').read()
with open(dest + '.sha256') as fh:
sha256_on_disk = fh.read()
else:
sha256_on_disk = sha256_of_file(dest).hexdigest()

differs = sha256_on_disk != sha256_in_mem
if differs:
with open(dest, 'wt') as fh:
fh.write(src)
open(dest + '.sha256', 'wt').write(sha256_in_mem)
with open(dest + '.sha256', 'wt') as fh:
fh.write(sha256_in_mem)
source_files.append(dest)
return source_files, build_dir

Expand Down
19 changes: 10 additions & 9 deletions sympy/utilities/_compilation/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,15 +192,16 @@ def pyx_is_cplus(path):
Returns True if such a file is present in the file, else False.
"""
for line in open(path):
if line.startswith('#') and '=' in line:
splitted = line.split('=')
if len(splitted) != 2:
continue
lhs, rhs = splitted
if lhs.strip().split()[-1].lower() == 'language' and \
rhs.strip().split()[0].lower() == 'c++':
return True
with open(path) as fh:
for line in fh:
if line.startswith('#') and '=' in line:
splitted = line.split('=')
if len(splitted) != 2:
continue
lhs, rhs = splitted
if lhs.strip().split()[-1].lower() == 'language' and \
rhs.strip().split()[0].lower() == 'c++':
return True
return False

def import_module_from_file(filename, only_if_newer_than=None):
Expand Down
16 changes: 1 addition & 15 deletions sympy/utilities/lambdify.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,25 +470,11 @@ def lambdify(args, expr, modules=None, printer=None, use_imps=True,
of numexpr functions can be found at:
https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions
- In previous versions of SymPy, ``lambdify`` replaced ``Matrix`` with
``numpy.matrix`` by default. As of SymPy 1.0 ``numpy.array`` is the
default. To get the old default behavior you must pass in
``[{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']`` to the
``modules`` kwarg.
>>> from sympy import lambdify, Matrix
>>> from sympy.abc import x, y
>>> import numpy
>>> array2mat = [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']
>>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat)
>>> f(1, 2)
[[1]
[2]]
- In the above examples, the generated functions can accept scalar
values or numpy arrays as arguments. However, in some cases
the generated function relies on the input being a numpy array:
>>> import numpy
>>> from sympy import Piecewise
>>> from sympy.testing.pytest import ignore_warnings
>>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy")
Expand Down
13 changes: 7 additions & 6 deletions sympy/utilities/tests/test_lambdify.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from sympy.utilities.lambdify import implemented_function, lambdastr
from sympy.testing.pytest import skip
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.utilities.exceptions import ignore_warnings
from sympy.external import import_module
from sympy.functions.special.gamma_functions import uppergamma, lowergamma

Expand Down Expand Up @@ -283,14 +284,13 @@ def test_issue_9334():
foo, bar = numpy.random.random((2, 4))
func_numexpr(foo, bar)


def test_issue_12984():
import warnings
if not numexpr:
skip("numexpr not installed.")
func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
assert func_numexpr(1, 24, 42) == 24
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
with ignore_warnings(RuntimeWarning):
assert func_numexpr(1, 24, 42) == 24
assert str(func_numexpr(-1, 24, 42)) == 'nan'


Expand Down Expand Up @@ -491,8 +491,9 @@ def test_numpy_old_matrix():
A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'])
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)
with ignore_warnings(PendingDeprecationWarning):
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)


def test_scipy_sparse_matrix():
Expand Down

0 comments on commit 73b317a

Please sign in to comment.