def fbenchmark(f, var=[Symbol('x')]): """ Do some benchmarks with f using clambdify, lambdify and psyco. """ global cf, pf, psyf start = time() cf = clambdify(var, f) print('compile time (including sympy overhead): %f s' % ( time() - start)) pf = lambdify(var, f, 'math') psyf = None psyco = import_module('psyco') if psyco: psyf = lambdify(var, f, 'math') psyco.bind(psyf) code = '''for x in (i/1000. for i in range(1000)): f(%s)''' % ('x,'*len(var)).rstrip(',') t1 = Timer(code, 'from __main__ import cf as f') t2 = Timer(code, 'from __main__ import pf as f') if psyf: t3 = Timer(code, 'from __main__ import psyf as f') else: t3 = None print('for x = (0, 1, 2, ..., 999)/1000') print('20 times in 3 runs') print('compiled: %.4f %.4f %.4f' % tuple(t1.repeat(3, 20))) print('Python lambda: %.4f %.4f %.4f' % tuple(t2.repeat(3, 20))) if t3: print('Psyco lambda: %.4f %.4f %.4f' % tuple(t3.repeat(3, 20)))
def mplot3d(f, var1, var2, show=True): """ Plot a 3d function using matplotlib/Tk. """ import warnings warnings.filterwarnings("ignore", "Could not match \S") p = import_module('pylab') # Try newer version first p3 = import_module('mpl_toolkits.mplot3d', __import__kwargs={'fromlist':['something']}) or import_module('matplotlib.axes3d') if not p or not p3: sys.exit("Matplotlib is required to use mplot3d.") x, y, z = sample(f, var1, var2) fig = p.figure() ax = p3.Axes3D(fig) #ax.plot_surface(x,y,z) #seems to be a bug in matplotlib ax.plot_wireframe(x,y,z) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if show: p.show()
def test_entropy(): up = JzKet(S(1)/2, S(1)/2) down = JzKet(S(1)/2, -S(1)/2) d = Density((up, 0.5), (down, 0.5)) # test for density object ent = entropy(d) assert entropy(d) == 0.5*log(2) assert d.entropy() == 0.5*log(2) np = import_module('numpy', min_module_version='1.4.0') if np: #do this test only if 'numpy' is available on test machine np_mat = represent(d, format='numpy') ent = entropy(np_mat) assert isinstance(np_mat, np.matrixlib.defmatrix.matrix) assert ent.real == 0.69314718055994529 assert ent.imag == 0 scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) if scipy and np: #do this test only if numpy and scipy are available mat = represent(d, format="scipy.sparse") assert isinstance(mat, scipy_sparse_matrix) assert ent.real == 0.69314718055994529 assert ent.imag == 0
def test_is_scalar_sparse_matrix(): np = import_module('numpy') if not np: skip("numpy not installed.") scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) if not scipy: skip("scipy not installed.") numqubits = 2 id_only = False id_gate = (IdentityGate(1),) assert is_scalar_sparse_matrix(id_gate, numqubits, id_only) is True x0 = X(0) xx_circuit = (x0, x0) assert is_scalar_sparse_matrix(xx_circuit, numqubits, id_only) is True x1 = X(1) y1 = Y(1) xy_circuit = (x1, y1) assert is_scalar_sparse_matrix(xy_circuit, numqubits, id_only) is False z1 = Z(1) xyz_circuit = (x1, y1, z1) assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is True cnot = CNOT(1, 0) cnot_circuit = (cnot, cnot) assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True h = H(0) hh_circuit = (h, h) assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True # NOTE: # The elements of the sparse matrix for the following circuit # is actually 1.0000000000000002+0.0j. h1 = H(1) xhzh_circuit = (x1, h1, z1, h1) assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True id_only = True assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is False assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
def test_valued_tensor_self_contraction(): numpy = import_module("numpy") if numpy is None: skip("numpy not installed.") assert AB(i0, -i0) == 4 assert BA(i0, -i0) == 2
def parse_latex(s): r"""Converts the string ``s`` to a SymPy ``Expr`` Parameters ========== s : str The LaTeX string to parse. In Python source containing LaTeX, *raw strings* (denoted with ``r"``, like this one) are preferred, as LaTeX makes liberal use of the ``\`` character, which would trigger escaping in normal Python strings. Examples ======== >>> from sympy.parsing.latex import parse_latex # doctest: +SKIP >>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}") # doctest: +SKIP >>> expr # doctest: +SKIP (sqrt(a) + 1)/b >>> expr.evalf(4, subs=dict(a=5, b=2)) # doctest: +SKIP 1.618 """ _latex = import_module( 'sympy.parsing.latex._parse_latex_antlr', __import__kwargs={'fromlist': ['X']}) if _latex is not None: return _latex.parse_latex(s)
def test_valued_non_diagonal_metric(): numpy = import_module("numpy") if numpy is None: skip("numpy not installed.") mmatrix = Matrix(ndm_matrix) assert NA(n0)*NA(-n0) == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0]
def test_valued_tensor_applyfunc(): numpy = import_module("numpy") if numpy is None: skip("numpy not installed.") aA = A(i0).applyfunc(lambda x: x**2) aB = B(i0).applyfunc(lambda x: x**3) aB2 = B(-i0).applyfunc(lambda x: x**3) for i in range(4): assert aA[i] == A(i0)[i]**2 assert aB[i] == B(i1)[i]**3 assert aB*aB2 == -794 tA = A.applyfunc(lambda x: x + 33) tB = B.applyfunc(lambda x: x + 33) tAB = AB.applyfunc(lambda x: x + 33) assert (tA(i0)*tA(-i0)).expand() == ((E + 33)**2 - (px + 33)**2 - (py + 33)**2 - (pz + 33)**2).expand() assert tB(i0).get_matrix() == Matrix([33, 34, 35, 36]) assert tAB(i0, i1).get_matrix() == Matrix([ [34, 33, 33, 33], [33, 32, 33, 33], [33, 33, 32, 33], [33, 33, 33, 32], ])
def _get_meshes_grid(self): """Generates the mesh for generating a contour. In the case of equality, ``contour`` function of matplotlib can be used. In other cases, matplotlib's ``contourf`` is used. """ equal = False if isinstance(self.expr, Equality): expr = self.expr.lhs - self.expr.rhs equal = True elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)): expr = self.expr.lhs - self.expr.rhs elif isinstance(self.expr, (LessThan, StrictLessThan)): expr = self.expr.rhs - self.expr.lhs else: raise NotImplementedError("The expression is not supported for " "plotting in uniform meshed plot.") np = import_module("numpy") xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points) yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points) x_grid, y_grid = np.meshgrid(xarray, yarray) func = vectorized_lambdify((self.var_x, self.var_y), expr) z_grid = func(x_grid, y_grid) z_grid[np.ma.where(z_grid < 0)] = -1 z_grid[np.ma.where(z_grid > 0)] = 1 if equal: return xarray, yarray, z_grid, "contour" else: return xarray, yarray, z_grid, "contourf"
def init_ipython_session(argv=[], auto_symbols=False, auto_int_to_Integer=False): """Construct new IPython session. """ import IPython if IPython.__version__ >= '0.11': # use an app to parse the command line, and init config # IPython 1.0 deprecates the frontend module, so we import directly # from the terminal module to prevent a deprecation message from being # shown. if IPython.__version__ >= '1.0': from IPython.terminal import ipapp else: from IPython.frontend.terminal import ipapp app = ipapp.TerminalIPythonApp() # don't draw IPython banner during initialization: app.display_banner = False app.initialize(argv) if auto_symbols: readline = import_module("readline") if readline: enable_automatic_symbols(app) if auto_int_to_Integer: enable_automatic_int_sympification(app) return app.shell else: from IPython.Shell import make_IPython return make_IPython(argv)
def test_evalonarray_numpy(): numpy = import_module('numpy') a = numpy.arange(10, dtype=float) evalonarray('lambda x: x + 1', a) for i, j in enumerate(a): if float(i + 1) != j: raise ValueError("Values should be equal")
def parse_latex(sympy): antlr4 = import_module('antlr4', warn_not_installed=True) if None in [antlr4, MathErrorListener]: raise ImportError("LaTeX parsing requires the antlr4 python package," " provided by pip (antlr4-python2-runtime or" " antlr4-python3-runtime) or" " conda (antlr-python-runtime)") matherror = MathErrorListener(sympy) stream = antlr4.InputStream(sympy) lex = LaTeXLexer(stream) lex.removeErrorListeners() lex.addErrorListener(matherror) tokens = antlr4.CommonTokenStream(lex) parser = LaTeXParser(tokens) # remove default console error listener parser.removeErrorListeners() parser.addErrorListener(matherror) relation = parser.math().relation() expr = convert_relation(relation) return expr
def test_issue_15265(): from sympy.core.sympify import sympify from sympy.core.singleton import S matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') eqn = sin(x) p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14'))) p._backend.close() p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1)) p._backend.close() raises(ValueError, lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit))) raises(ValueError, lambda: plot(eqn, xlim=(-S.Infinity, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
def test_matplotlib(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: plot_implicit_tests('test') test_line_color() else: skip("Matplotlib not the default backend")
def mplot2d(f, var, show=True): """ Plot a 2d function using matplotlib/Tk. """ import warnings warnings.filterwarnings("ignore", "Could not match \S") p = import_module('pylab') if not p: sys.exit("Matplotlib is required to use mplot2d.") if not is_sequence(f): f = [f,] for f_i in f: x, y = sample2d(f_i, var) p.plot(x, y,'black') p.draw() p.ylabel("Transverse beam cordinate") p.xlabel("Propagation coordinate") p.grid(True) if show: p.show()
def cos(x): """Evaluates the cos of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.sin(x)) elif isinstance(x, interval): if not (np.isfinite(x.start) and np.isfinite(x.end)): return interval(-1, 1, is_valid=x.is_valid) na, __ = divmod(x.start, np.pi / 2.0) nb, __ = divmod(x.end, np.pi / 2.0) start = min(np.cos(x.start), np.cos(x.end)) end = max(np.cos(x.start), np.cos(x.end)) if nb - na > 4: #differ more than 2*pi return interval(-1, 1, is_valid=x.is_valid) elif na == nb: #in the same quadarant return interval(start, end, is_valid=x.is_valid) else: if (na) // 4 != (nb) // 4: #cos has max end = 1 if (na - 2) // 4 != (nb - 2) // 4: #cos has min start = -1 return interval(start, end, is_valid=x.is_valid) else: raise NotImplementedError
def sin(x): """evaluates the sine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.sin(x)) elif isinstance(x, interval): if not x.is_valid: return interval(-1, 1, is_valid=x.is_valid) na, __ = divmod(x.start, np.pi / 2.0) nb, __ = divmod(x.end, np.pi / 2.0) start = min(np.sin(x.start), np.sin(x.end)) end = max(np.sin(x.start), np.sin(x.end)) if nb - na > 4: return interval(-1, 1, is_valid=x.is_valid) elif na == nb: return interval(start, end, is_valid=x.is_valid) else: if (na - 1) // 4 != (nb - 1) // 4: #sin has max end = 1 if (na - 3) // 4 != (nb - 3) // 4: #sin has min start = -1 return interval(start, end) else: raise NotImplementedError
def test_no_stdlib_collections3(): '''make sure we get the right collections with no catch''' import collections matplotlib = import_module('matplotlib', __import__kwargs={'fromlist': ['cm', 'collections']}, min_module_version='1.1.0') if matplotlib: assert collections != matplotlib.collections
def __call__(self, *args): np = import_module('numpy') np_old_err = np.seterr(invalid='raise') try: temp_args = (np.array(a, dtype=np.complex) for a in args) results = self.vector_func(*temp_args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False) except Exception as e: #DEBUG: print 'Error', type(e), e if ((isinstance(e, TypeError) and 'unhashable type: \'numpy.ndarray\'' in str(e)) or (isinstance(e, ValueError) and ('Invalid limits given:' in str(e) or 'negative dimensions are not allowed' in str(e) # XXX or 'sequence too large; must be smaller than 32' in str(e)))): # XXX # Almost all functions were translated to numpy, but some were # left as sympy functions. They received an ndarray as an # argument and failed. # sin(ndarray(...)) raises "unhashable type" # Integral(x, (x, 0, ndarray(...))) raises "Invalid limits" # other ugly exceptions that are not well understood (marked with XXX) # TODO: Cleanup the ugly special cases marked with xxx above. # Solution: use cmath and vectorize the final lambda. self.lambda_func = experimental_lambdify( self.args, self.expr, use_python_cmath=True) self.vector_func = np.vectorize( self.lambda_func, otypes=[np.complex]) results = self.vector_func(*args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False) else: # Complete failure. One last try with no translations, only # wrapping in complex((...).evalf()) and returning the real # part. if self.failure: raise e else: self.failure = True self.lambda_func = experimental_lambdify( self.args, self.expr, use_evalf=True, complex_wrap_evalf=True) self.vector_func = np.vectorize( self.lambda_func, otypes=[np.complex]) results = self.vector_func(*args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False) warnings.warn('The evaluation of the expression is' ' problematic. We are trying a failback method' ' that may still work. Please report this as a bug.') finally: np.seterr(**np_old_err) return results
def test_valued_tensor_pow(): numpy = import_module("numpy") if numpy is None: skip("numpy not installed.") assert C**2 == -E**2 + px**2 + py**2 + pz**2 assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2) assert C(mu0)**2 == C**2 assert C(mu0)**1 == C**1
def test_bfs_identity_search_xfail(): scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) if scipy: skip("scipy installed.") s = PhaseGate(0) t = TGate(0) gate_list = [Dagger(s), t] id_set = {GateIdentity(Dagger(s), t, t)} assert bfs_identity_search(gate_list, 1, max_depth=3) == id_set
def test_matrix_numpy(): from sympy.external import import_module numpy = import_module('numpy') if not numpy: return l = [[1, 2], [3, 4], [5, 6]] a = numpy.matrix(l) assert matrix(l) == matrix(a)
def exp(x): """evaluates the exponential of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.exp(x), np.exp(x)) elif isinstance(x, interval): return interval(np.exp(x.start), np.exp(x.end), is_valid=x.is_valid) else: raise NotImplementedError
def tanh(x): """Evaluates the hyperbolic tan of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.tanh(x), np.tanh(x)) elif isinstance(x, interval): return interval(np.tanh(x.start), np.tanh(x.end), is_valid=x.is_valid) else: raise NotImplementedError
def test_matplotlib(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: try: plot_and_save('test') finally: # clean up TmpFileManager.cleanup() else: skip("Matplotlib not the default backend")
def asinh(x): """Evaluates the inverse hyperbolic sine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.arcsinh(x)) elif isinstance(x, interval): start = np.arcsinh(x.start) end = np.arcsinh(x.end) return interval(start, end, is_valid=x.is_valid) else: return NotImplementedError
def atan(x): """evaluates the tan inverse of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.arctan(x)) elif isinstance(x, interval): start = np.arctan(x.start) end = np.arctan(x.end) return interval(start, end, is_valid=x.is_valid) else: raise NotImplementedError
def test_issue_11463(): numpy = import_module('numpy') if not numpy: skip("numpy not installed.") x = Symbol('x') f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy') # numpy.select evaluates all options before considering conditions, # so it raises a warning about root of negative number which does # not affect the outcome. This warning is suppressed here with ignore_warnings(RuntimeWarning): assert f(numpy.array(-1)) < -1
def test_no_stdlib_collections(): ''' make sure we get the right collections when it is not part of a larger list ''' import collections matplotlib = import_module('matplotlib', __import__kwargs={'fromlist': ['cm', 'collections']}, min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: assert collections != matplotlib.collections
def test_valued_tensor_covariant_contravariant_elements(): numpy = import_module("numpy") if numpy is None: skip("numpy not installed.") assert A(-i0)[0] == A(i0)[0] assert A(-i0)[1] == -A(i0)[1] assert AB(i0, i1)[1, 1] == -1 assert AB(i0, -i1)[1, 1] == 1 assert AB(-i0, -i1)[1, 1] == -1 assert AB(-i0, i1)[1, 1] == 1
from __future__ import print_function, division from sympy import Mul from sympy.core.compatibility import u from sympy.external import import_module from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS __all__ = [ 'CircuitPlot', 'circuit_plot', 'labeller', 'Mz', 'Mx', ] np = import_module('numpy') matplotlib = import_module( 'matplotlib', __import__kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError, )) # This is raised in environments that have no display. if not np or not matplotlib: class CircuitPlot(object): def __init__(*args, **kwargs): raise ImportError('numpy or matplotlib not available.') def circuit_plot(*args, **kwargs): raise ImportError('numpy or matplotlib not available.') else:
def init_session(ipython=None, pretty_print=True, order=None, use_unicode=None, use_latex=None, quiet=False, auto_symbols=False, auto_int_to_Integer=False, argv=[]): """ Initialize an embedded IPython or Python session. The IPython session is initiated with the --pylab option, without the numpy imports, so that matplotlib plotting can be interactive. Parameters ========== pretty_print: boolean If True, use pretty_print to stringify; if False, use sstrrepr to stringify. order: string or None There are a few different settings for this parameter: lex (default), which is lexographic order; grlex, which is graded lexographic order; grevlex, which is reversed graded lexographic order; old, which is used for compatibility reasons and for long expressions; None, which sets it to lex. use_unicode: boolean or None If True, use unicode characters; if False, do not use unicode characters. use_latex: boolean or None If True, use latex rendering if IPython GUI's; if False, do not use latex rendering. quiet: boolean If True, init_session will not print messages regarding its status; if False, init_session will print messages regarding its status. auto_symbols: boolean If True, IPython will automatically create symbols for you. If False, it will not. The default is False. auto_int_to_Integer: boolean If True, IPython will automatically wrap int literals with Integer, so that things like 1/2 give Rational(1, 2). If False, it will not. The default is False. ipython: boolean or None If True, printing will initialize for an IPython console; if False, printing will initialize for a normal console; The default is None, which automatically determines whether we are in an ipython instance or not. argv: list of arguments for IPython See sympy.bin.isympy for options that can be used to initialize IPython. See Also ======== sympy.interactive.printing.init_printing: for examples and the rest of the parameters. Examples ======== >>> from sympy import init_session, Symbol, sin, sqrt >>> sin(x) #doctest: +SKIP NameError: name 'x' is not defined >>> init_session() #doctest: +SKIP >>> sin(x) #doctest: +SKIP sin(x) >>> sqrt(5) #doctest: +SKIP ___ \/ 5 >>> init_session(pretty_print=False) #doctest: +SKIP >>> sqrt(5) #doctest: +SKIP sqrt(5) >>> y + x + y**2 + x**2 #doctest: +SKIP x**2 + x + y**2 + y >>> init_session(order='grlex') #doctest: +SKIP >>> y + x + y**2 + x**2 #doctest: +SKIP x**2 + y**2 + x + y >>> init_session(order='grevlex') #doctest: +SKIP >>> y * x**2 + x * y**2 #doctest: +SKIP x**2*y + x*y**2 >>> init_session(order='old') #doctest: +SKIP >>> x**2 + y**2 + x + y #doctest: +SKIP x + y + x**2 + y**2 >>> theta = Symbol('theta') #doctest: +SKIP >>> theta #doctest: +SKIP theta >>> init_session(use_unicode=True) #doctest: +SKIP >>> theta # doctest: +SKIP \u03b8 """ import sys in_ipython = False if ipython is not False: try: import IPython except ImportError: if ipython is True: raise RuntimeError("IPython is not available on this system") ip = None else: if IPython.__version__ >= '0.11': try: ip = get_ipython() except NameError: ip = None else: ip = IPython.ipapi.get() if ip: ip = ip.IP in_ipython = bool(ip) if ipython is None: ipython = in_ipython if ipython is False: ip = init_python_session() mainloop = ip.interact else: if ip is None: ip = init_ipython_session(argv=argv, auto_symbols=auto_symbols, auto_int_to_Integer=auto_int_to_Integer) if IPython.__version__ >= '0.11': # runsource is gone, use run_cell instead, which doesn't # take a symbol arg. The second arg is `store_history`, # and False means don't add the line to IPython's history. ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False) #Enable interactive plotting using pylab. try: ip.enable_pylab(import_all=False) except Exception: # Causes an import error if matplotlib is not installed. # Causes other errors (depending on the backend) if there # is no display, or if there is some problem in the # backend, so we have a bare "except Exception" here pass if not in_ipython: mainloop = ip.mainloop readline = import_module("readline") if auto_symbols and (not ipython or IPython.__version__ < '0.11' or not readline): raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above with readline support") if auto_int_to_Integer and (not ipython or IPython.__version__ < '0.11'): raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above") _preexec_source = preexec_source ip.runsource(_preexec_source, symbol='exec') init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode, use_latex=use_latex, ip=ip) message = _make_message(ipython, quiet, _preexec_source) if not in_ipython: mainloop(message) sys.exit('Exiting ...') else: ip.write(message) import atexit atexit.register(lambda ip: ip.write("Exiting ...\n"), ip)
from sympy.parsing.sym_expr import SymPyExpression from sympy.testing.pytest import raises from sympy.external import import_module cin = import_module("clang.cindex", import_kwargs={"fromlist": ["cindex"]}) if cin: from sympy.codegen.ast import ( Variable, IntBaseType, FloatBaseType, String, Return, FunctionDefinition, Integer, Float, Declaration, CodeBlock, FunctionPrototype, FunctionCall, NoneToken, ) from sympy import Symbol import os def test_variable(): c_src1 = "int a;" + "\n" + "int b;" + "\n" c_src2 = "float a;" + "\n" + "float b;" + "\n" c_src3 = "int a;" + "\n" + "float b;" + "\n" + "int c;" c_src4 = "int x = 1, y = 6.78;" + "\n" + "float p = 2, q = 9.67;"
besselk, S, beta, MatrixSymbol, chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, assoc_legendre, assoc_laguerre, jacobi, fresnelc, fresnels) from sympy.printing.lambdarepr import LambdaPrinter from sympy.printing.pycode import NumPyPrinter from sympy.utilities.lambdify import implemented_function, lambdastr from sympy.utilities.pytest import skip from sympy.utilities.decorator import conserve_mpmath_dps from sympy.external import import_module from sympy.functions.special.gamma_functions import uppergamma, lowergamma import sympy MutableDenseMatrix = Matrix numpy = import_module('numpy') scipy = import_module('scipy') numexpr = import_module('numexpr') tensorflow = import_module('tensorflow') if tensorflow: # Hide Tensorflow warnings import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' w, x, y, z = symbols('w,x,y,z') #================== Test different arguments ======================= def test_no_args():
from functools import singledispatch from sympy import Dummy, lambdify, exp from sympy.external import import_module from sympy.stats import DiscreteDistributionHandmade from sympy.stats.crv import SingleContinuousDistribution from sympy.stats.crv_types import ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \ LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, BetaDistribution, \ StudentTDistribution, CauchyDistribution from sympy.stats.drv_types import GeometricDistribution, LogarithmicDistribution, NegativeBinomialDistribution, \ PoissonDistribution, SkellamDistribution, YuleSimonDistribution, ZetaDistribution from sympy.stats.frv import SingleFiniteDistribution scipy = import_module("scipy") if scipy is not None: import scipy.stats @singledispatch def do_sample_scipy(dist, size, seed): return None # CRV @do_sample_scipy.register(SingleContinuousDistribution) def _(dist: SingleContinuousDistribution, size, seed): # if we don't need to make a handmade pdf, we won't import scipy.stats
from sympy.external import import_module matchpy = import_module("matchpy") from sympy.utilities.decorator import doctest_depends_on from sympy.core import Integer, Float import inspect, re if matchpy: from matchpy import (Operation, CommutativeOperation, AssociativeOperation, ManyToOneReplacer, OneIdentityOperation, CustomConstraint) from matchpy.expressions.functions import register_operation_iterator, register_operation_factory from sympy import Pow, Add, Integral, Basic, Mul, S from sympy.functions import (log, sin, cos, tan, cot, csc, sec, sqrt, erf, exp, log, gamma, acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch, atan, acsc, asin, acot, acos, asec, fresnels, fresnelc, erfc, erfi) Operation.register(Integral) register_operation_iterator(Integral, lambda a: (a._args[0],) + a._args[1], lambda a: len((a._args[0],) + a._args[1])) Operation.register(Pow) OneIdentityOperation.register(Pow) register_operation_iterator(Pow, lambda a: a._args, lambda a: len(a._args)) Operation.register(Add) OneIdentityOperation.register(Add) CommutativeOperation.register(Add) AssociativeOperation.register(Add) register_operation_iterator(Add, lambda a: a._args, lambda a: len(a._args)) Operation.register(Mul) OneIdentityOperation.register(Mul)
exp, floor, imax, imin, interval, log, log10, Or, sin, sinh, sqrt, tan, tanh, ) np = import_module("numpy") if not np: disabled = True # requires Numpy. Hence included in interval_functions def test_interval_pow(): a = 2**interval(1, 2) == interval(2, 4) assert a == (True, True) a = interval(1, 2)**interval(1, 2) == interval(1, 4) assert a == (True, True) a = interval(-1, 1)**interval(0.5, 2) assert a.is_valid is None a = interval(-2, -1)**interval(1, 2) assert a.is_valid is False
def benchmark(): """ Run some benchmarks for clambdify and frange. NumPy and Psyco are used as reference if available. """ from time import time from timeit import Timer def fbenchmark(f, var=[Symbol('x')]): """ Do some benchmarks with f using clambdify, lambdify and psyco. """ global cf, pf, psyf start = time() cf = clambdify(var, f) print 'compile time (including sympy overhead): %f s' % (time() - start) pf = lambdify(var, f, 'math') psyf = None psyco = import_module('psyco') if psyco: psyf = lambdify(var, f, 'math') psyco.bind(psyf) code = '''for x in (i/1000. for i in range(1000)): f(%s)''' % ('x,'*len(var)).rstrip(',') t1 = Timer(code, 'from __main__ import cf as f') t2 = Timer(code, 'from __main__ import pf as f') if psyf: t3 = Timer(code, 'from __main__ import psyf as f') else: t3 = None print 'for x = (0, 1, 2, ..., 999)/1000' print '20 times in 3 runs' print 'compiled: %.4f %.4f %.4f' % tuple(t1.repeat(3, 20)) print 'Python lambda: %.4f %.4f %.4f' % tuple(t2.repeat(3, 20)) if t3: print 'Psyco lambda: %.4f %.4f %.4f' % tuple(t3.repeat(3, 20)) print 'big function:' from sympy import diff, _exp, _sin, _cos, pi, lambdify x = Symbol('x') ## f1 = diff(_exp(x)**2 - _sin(x)**pi, x) \ ## * x**12-2*x**3+2*_exp(x**2)-3*x**7+4*_exp(123+x-x**5+2*x**4) \ ## * ((x + pi)**5).expand() f1 = 2*_exp(x**2) + x**12*(-pi*_sin(x)**((-1) + pi)*_cos(x) + 2*_exp(2*x)) \ + 4*(10*pi**3*x**2 + 10*pi**2*x**3 + 5*pi*x**4 + 5*x*pi**4 + pi**5 \ + x**5)*_exp(123 + x + 2*x**4 - x**5) - 2*x**3 - 3*x**7 fbenchmark(f1) print print 'simple function:' y = Symbol('y') f2 = sqrt(x*y)+x*5 fbenchmark(f2, [x,y]) times = 100000 fstr = '_exp(_sin(_exp(-x**2)) + sqrt(pi)*_cos(x**5/(x**3-x**2+pi*x)))' print print 'frange with f(x) =' print fstr print 'for x=1, ..., %i' % times print 'in 3 runs including full compile time' t4 = Timer("frange('lambda x: %s', 0, %i)" % (fstr, times), 'from __main__ import frange') numpy = import_module('numpy') print 'frange: %.4f %.4f %.4f' % tuple(t4.repeat(3, 1)) if numpy: t5 = Timer('x = arange(%i); result = %s' % (times, fstr), 'from numpy import arange, sqrt, exp, sin, cos, exp, pi') print 'numpy: %.4f %.4f %.4f' % tuple(t5.repeat(3, 1))
# Q: What about _imp_ functions? # A: Those are taken care for by evalf. A special case treatment will work # faster but it's not worth the code complexity. # Q: Will ast fix all possible problems? # A: No. You will always have to use some printer. Even srepr may not work in # some cases. But if the printer does not work, that should be considered a # bug. # Q: Is there same way to fix all possible problems? # A: Probably by constructing our strings ourself by traversing the (func, # args) tree and creating the namespace at the same time. That actually sounds # good. from sympy.external import import_module np = import_module('numpy') import warnings #TODO debuging output class vectorized_lambdify(object): """ Return a sufficiently smart, vectorized and lambdified function. Returns only reals. This function uses experimental_lambdify to created a lambdified expression ready to be used with numpy. Many of the functions in sympy are not implemented in numpy so in some cases we resort to python cmath or even to evalf.
CodegenArrayPermuteDims, CodegenArrayDiagonal) from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.external import import_module from sympy.functions import \ Abs, Max, Min, ceiling, exp, floor, sign, sin, asin, sqrt, cos, \ acos, tan, atan, atan2, cosh, acosh, sinh, asinh, tanh, atanh, \ re, im, arg, erf, loggamma, log from sympy.matrices import Matrix, MatrixBase, eye, randMatrix from sympy.matrices.expressions import \ Determinant, HadamardProduct, Inverse, MatrixSymbol, Trace from sympy.printing.tensorflow import TensorflowPrinter, tensorflow_code from sympy.utilities.lambdify import lambdify from sympy.utilities.pytest import skip tf = tensorflow = import_module("tensorflow") if tensorflow: # Hide Tensorflow warnings import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) P = MatrixSymbol("P", 3, 3) Q = MatrixSymbol("Q", 3, 3) x, y, z, t = symbols("x y z t") if tf is not None: llo = [[j for j in range(i, i + 3)] for i in range(0, 9, 3)]
ad = RaisingOp('a') a = LoweringOp('a') k = SHOKet('k') kz = SHOKet(0) kf = SHOKet(1) k3 = SHOKet(3) b = SHOBra('b') b3 = SHOBra(3) H = Hamiltonian('H') N = NumberOp('N') omega = Symbol('omega') m = Symbol('m') ndim = Integer(4) np = import_module('numpy') scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) ad_rep_sympy = represent(ad, basis=N, ndim=4, format='sympy') a_rep = represent(a, basis=N, ndim=4, format='sympy') N_rep = represent(N, basis=N, ndim=4, format='sympy') H_rep = represent(H, basis=N, ndim=4, format='sympy') k3_rep = represent(k3, basis=N, ndim=4, format='sympy') b3_rep = represent(b3, basis=N, ndim=4, format='sympy') def test_RaisingOp(): assert Dagger(ad) == a assert Commutator(ad, a).doit() == Integer(-1) assert Commutator(ad, N).doit() == Integer(-1) * ad assert qapply(ad * k) == (sqrt(k.n + 1) * SHOKet(k.n + 1)).expand()
# Ported from latex2sympy by @augustt198 # https://github.com/augustt198/latex2sympy # See license in LICENSE.txt import sympy from sympy.external import import_module from sympy.printing.str import StrPrinter from .errors import LaTeXParsingError LaTeXParser = LaTeXLexer = MathErrorListener = None try: LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser', __import__kwargs={ 'fromlist': ['LaTeXParser'] }).LaTeXParser LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer', __import__kwargs={ 'fromlist': ['LaTeXLexer'] }).LaTeXLexer except Exception: pass ErrorListener = import_module('antlr4.error.ErrorListener', warn_not_installed=True, __import__kwargs={'fromlist': ['ErrorListener']}) if ErrorListener: class MathErrorListener(ErrorListener.ErrorListener):
def sample_iter(expr, condition=None, size=(1, ), library='scipy', numsamples=S.Infinity, **kwargs): """ Returns an iterator of realizations from the expression given a condition Parameters ========== expr: Expr Random expression to be realized condition: Expr, optional A conditional expression size : int, tuple Represents size of each sample in numsamples numsamples: integer, optional Length of the iterator (defaults to infinity) Examples ======== >>> from sympy.stats import Normal, sample_iter >>> X = Normal('X', 0, 1) >>> expr = X*X + 3 >>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP >>> list(iterator) # doctest: +SKIP [12, 4, 7] Returns ======= sample_iter: iterator object iterator object containing the sample/samples of given expr See Also ======== sample sampling_P sampling_E """ if not import_module(library): raise ValueError("Failed to import %s" % library) if condition is not None: ps = pspace(Tuple(expr, condition)) else: ps = pspace(expr) rvs = list(ps.values) if library == 'pymc3': # Currently unable to lambdify in pymc3 # TODO : Remove 'pymc3' when lambdify accepts 'pymc3' as module fn = lambdify(rvs, expr, **kwargs) else: fn = lambdify(rvs, expr, modules=library, **kwargs) if condition is not None: given_fn = lambdify(rvs, condition, **kwargs) def return_generator(): count = 0 while count < numsamples: d = ps.sample( size=size, library=library) # a dictionary that maps RVs to values args = [d[rv] for rv in rvs] if condition is not None: # Check that these values satisfy the condition gd = given_fn(*args) if gd != True and gd != False: raise ValueError( "Conditions must not contain free symbols") if not gd: # If the values don't satisfy then try again continue yield fn(*args) count += 1 return return_generator()
import sympy import tempfile import os from sympy import symbols, Eq, Mod from sympy.external import import_module from sympy.tensor import IndexedBase, Idx from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError from sympy.utilities.pytest import skip numpy = import_module('numpy', min_module_version='1.6.1') Cython = import_module('Cython', min_module_version='0.15.1') f2py = import_module('numpy.f2py', __import__kwargs={'fromlist': ['f2py']}) f2pyworks = False if f2py: try: autowrap(symbols('x'), 'f95', 'f2py') except (CodeWrapError, ImportError, OSError): f2pyworks = False else: f2pyworks = True a, b, c = symbols('a b c') n, m, d = symbols('n m d', integer=True) A, B, C = symbols('A B C', cls=IndexedBase) i = Idx('i', m) j = Idx('j', n) k = Idx('k', d) def has_module(module):
def test_evalonarray_numpy(): numpy = import_module('numpy') a = numpy.arange(10, dtype=float) evalonarray('lambda x: x + 1', a) for i, j in enumerate(a): assert float(i + 1) == j
# Ported from latex2sympy by @augustt198 # https://github.com/augustt198/latex2sympy # See license in LICENSE.txt import sympy from sympy.external import import_module from sympy.printing.str import StrPrinter from .errors import LaTeXParsingError LaTeXParser = LaTeXLexer = MathErrorListener = None try: LaTeXParser = import_module( "sympy.parsing.latex._antlr.latexparser", import_kwargs={ "fromlist": ["LaTeXParser"] }, ).LaTeXParser LaTeXLexer = import_module( "sympy.parsing.latex._antlr.latexlexer", import_kwargs={ "fromlist": ["LaTeXLexer"] }, ).LaTeXLexer except Exception: pass ErrorListener = import_module( "antlr4.error.ErrorListener", warn_not_installed=True, import_kwargs={"fromlist": ["ErrorListener"]},
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
from sympy.utilities.pytest import XFAIL, raises from sympy import (symbols, lambdify, sqrt, sin, cos, pi, Rational, Float, Matrix, Lambda, exp, Integral, oo, I, Abs) from sympy.printing.lambdarepr import LambdaPrinter from sympy import mpmath from sympy.utilities.lambdify import implemented_function from sympy.utilities.pytest import skip from sympy.utilities.decorator import conserve_mpmath_dps from sympy.external import import_module import math import sympy MutableDenseMatrix = Matrix numpy = import_module('numpy', min_python_version=(2, 6)) x, y, z = symbols('x,y,z') #================== Test different arguments ============== def test_no_args(): f = lambdify([], 1) raises(TypeError, lambda: f(-1)) assert f() == 1 def test_single_arg(): f = lambdify(x, 2 * x) assert f(1) == 2
from sympy import symbols, Eq from sympy.external import import_module from sympy.tensor import IndexedBase, Idx from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError from sympy.utilities.pytest import XFAIL, skip numpy = import_module('numpy') Cython = import_module('Cython') f2py = import_module('numpy.f2py', __import__kwargs={'fromlist': ['f2py']}) f2pyworks = False if f2py: try: autowrap(symbols('x'), 'f95', 'f2py') except (CodeWrapError, ImportError, OSError): f2pyworks = False else: f2pyworks = True a, b, c = symbols('a b c') n, m, d = symbols('n m d', integer=True) A, B, C = symbols('A B C', cls=IndexedBase) i = Idx('i', m) j = Idx('j', n) k = Idx('k', d) def has_module(module): """ Return True if module exists, otherwise run skip().
from __future__ import unicode_literals, print_function from sympy.external import import_module import os cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) """ This module contains all the necessary Classes and Function used to Parse C and C++ code into SymPy expression The module serves as a backend for SymPyExpression to parse C code It is also dependent on Clang's AST and Sympy's Codegen AST. The module only supports the features currently supported by the Clang and codegen AST which will be updated as the development of codegen AST and this module progresses. You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker Features Supported ================== - Variable Declarations (integers and reals) - Assignment (using integer & floating literal and function calls) - Function Definitions nad Declaration - Function Calls - Compound statements, Return statements Notes ===== The module is dependent on an external dependency which needs to be installed to use the features of this module.
from sympy.external import import_module if import_module('llvmlite'): import sympy.printing.llvmjitcode as g else: disabled = True import sympy from sympy.abc import a, b # copied from numpy.isclose documentation def isclose(a, b): rtol = 1e-5 atol = 1e-8 return abs(a - b) <= atol + rtol * abs(b) def test_simple_expr(): e = a + 1.0 f = g.llvm_callable([a], e) res = float(e.subs({a: 4.0}).evalf()) jit_res = f(4.0) assert isclose(jit_res, res) def test_two_arg(): e = 4.0 * a + b + 3.0 f = g.llvm_callable([a, b], e) res = float(e.subs({a: 4.0, b: 3.0}).evalf())
import sys from sympy.external import import_module autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser', __import__kwargs={'fromlist': ['AutolevParser']}) autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer', __import__kwargs={'fromlist': ['AutolevLexer']}) autolevlistener = import_module( 'sympy.parsing.autolev._antlr.autolevlistener', __import__kwargs={'fromlist': ['AutolevListener']}) AutolevParser = getattr(autolevparser, 'AutolevParser', None) AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None) AutolevListener = getattr(autolevlistener, 'AutolevListener', None) def parse_autolev(autolev_code, include_numeric): antlr4 = import_module('antlr4', warn_not_installed=True) if not antlr4: raise ImportError("Autolev parsing requires the antlr4 python package," " provided by pip (antlr4-python2-runtime or" " antlr4-python3-runtime) or" " conda (antlr-python-runtime)") try: l = autolev_code.readlines() input_stream = antlr4.InputStream("".join(l)) except Exception: input_stream = antlr4.InputStream(autolev_code) if AutolevListener: from ._listener_autolev_antlr import MyListener
from sympy.testing.pytest import raises from sympy.parsing.sym_expr import SymPyExpression from sympy.external import import_module lfortran = import_module('lfortran') if lfortran: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Return, FunctionDefinition, Assignment, Declaration, CodeBlock) from sympy.core import Integer, Float, Add from sympy import Symbol expr1 = SymPyExpression() expr2 = SymPyExpression() src = """\ integer :: a, b, c, d real :: p, q, r, s """ def test_sym_expr(): src1 = (src + """\ d = a + b -c """) expr3 = SymPyExpression(src, 'f') expr4 = SymPyExpression(src1, 'f') ls1 = expr3.return_expr() ls2 = expr4.return_expr() for i in range(0, 7): assert isinstance(ls1[i], Declaration) assert isinstance(ls2[i], Declaration)
def _get_raster_interval(self, func): """ Uses interval math to adaptively mesh and obtain the plot""" k = self.depth interval_list = [] #Create initial 32 divisions np = import_module('numpy') xsample = np.linspace(self.start_x, self.end_x, 33) ysample = np.linspace(self.start_y, self.end_y, 33) #Add a small jitter so that there are no false positives for equality. # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2) #which will draw a rectangle. jitterx = (np.random.rand( len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20 jittery = (np.random.rand( len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20 xsample += jitterx ysample += jittery xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1], xsample[1:])] yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1], ysample[1:])] interval_list = [[x, y] for x in xinter for y in yinter] plot_list = [] #recursive call refinepixels which subdivides the intervals which are #neither True nor False according to the expression. def refine_pixels(interval_list): """ Evaluates the intervals and subdivides the interval if the expression is partially satisfied.""" temp_interval_list = [] plot_list = [] for intervals in interval_list: #Convert the array indices to x and y values intervalx = intervals[0] intervaly = intervals[1] func_eval = func(intervalx, intervaly) #The expression is valid in the interval. Change the contour #array values to 1. if func_eval[1] is False or func_eval[0] is False: pass elif func_eval == (True, True): plot_list.append([intervalx, intervaly]) elif func_eval[1] is None or func_eval[0] is None: #Subdivide avgx = intervalx.mid avgy = intervaly.mid a = interval(intervalx.start, avgx) b = interval(avgx, intervalx.end) c = interval(intervaly.start, avgy) d = interval(avgy, intervaly.end) temp_interval_list.append([a, c]) temp_interval_list.append([a, d]) temp_interval_list.append([b, c]) temp_interval_list.append([b, d]) return temp_interval_list, plot_list while k >= 0 and len(interval_list): interval_list, plot_list_temp = refine_pixels(interval_list) plot_list.extend(plot_list_temp) k = k - 1 #Check whether the expression represents an equality #If it represents an equality, then none of the intervals #would have satisfied the expression due to floating point #differences. Add all the undecided values to the plot. if self.has_equality: for intervals in interval_list: intervalx = intervals[0] intervaly = intervals[1] func_eval = func(intervalx, intervaly) if func_eval[1] and func_eval[0] is not False: plot_list.append([intervalx, intervaly]) return plot_list, 'fill'
from __future__ import print_function, division import inspect from sympy.external import import_module from sympy.printing.printer import Printer from sympy.core.compatibility import range import sympy from functools import partial theano = import_module('theano') if theano: ts = theano.scalar tt = theano.tensor from theano.sandbox import linalg as tlinalg mapping = { sympy.Add: tt.add, sympy.Mul: tt.mul, sympy.Abs: tt.abs_, sympy.sign: tt.sgn, sympy.ceiling: tt.ceil, sympy.floor: tt.floor, sympy.log: tt.log, sympy.exp: tt.exp, sympy.sqrt: tt.sqrt, sympy.cos: tt.cos, sympy.acos: tt.arccos, sympy.sin: tt.sin, sympy.asin: tt.arcsin, sympy.tan: tt.tan,
def test_empty_plot(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if not matplotlib: skip("Matplotlib not the default backend") # No exception showing an empty plot plot()
from sympy.printing.lambdarepr import LambdaPrinter from sympy import mpmath from sympy.utilities.lambdify import implemented_function from sympy.utilities.pytest import skip from sympy.utilities.decorator import conserve_mpmath_dps from sympy.external import import_module import math import sympy # TODO: This should be removed for the release of 0.7.7, see issue #7853 from functools import partial lambdify = partial(lambdify, default_array=True) MutableDenseMatrix = Matrix numpy = import_module('numpy') numexpr = import_module('numexpr') w, x, y, z = symbols('w,x,y,z') #================== Test different arguments ======================= def test_no_args(): f = lambdify([], 1) raises(TypeError, lambda: f(-1)) assert f() == 1 def test_single_arg(): f = lambdify(x, 2*x)
def test_sampling_gamma_inverse(): scipy = import_module('scipy') if not scipy: skip('Scipy not installed. Abort tests for sampling of gamma inverse.') X = GammaInverse("x", 1, 1) assert sample(X) in X.pspace.domain.set
import tempfile import sympy as sp from sympy.codegen.ast import Assignment from sympy.codegen.algorithms import newtons_method, newtons_method_function from sympy.codegen.fnodes import bind_C from sympy.codegen.futils import render_as_module as f_module from sympy.codegen.pyutils import render_as_module as py_module from sympy.external import import_module from sympy.printing import ccode from sympy.utilities._compilation import compile_link_import_strings, has_c, has_fortran from sympy.utilities._compilation.util import may_xfail from sympy.testing.pytest import skip, raises cython = import_module('cython') wurlitzer = import_module('wurlitzer') def test_newtons_method(): x, dx, atol = sp.symbols('x dx atol') expr = sp.cos(x) - x**3 algo = newtons_method(expr, x, atol, dx) assert algo.has(Assignment(dx, -expr / expr.diff(x))) @may_xfail def test_newtons_method_function__ccode(): x = sp.Symbol('x', real=True) expr = sp.cos(x) - x**3 func = newtons_method_function(expr, x) if not cython:
def __call__(self, *args): np = import_module("numpy") np_old_err = np.seterr(invalid="raise") try: temp_args = (np.array(a, dtype=np.complex) for a in args) results = self.vector_func(*temp_args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False) except Exception as e: # DEBUG: print 'Error', type(e), e if (isinstance(e, TypeError) and "unhashable type: 'numpy.ndarray'" in str(e)) or ( isinstance(e, ValueError) and ("Invalid limits given:" in str(e) or "negative dimensions are not allowed" in str(e) # XXX or "sequence too large; must be smaller than 32" in str(e))): # XXX # Almost all functions were translated to numpy, but some were # left as sympy functions. They received an ndarray as an # argument and failed. # sin(ndarray(...)) raises "unhashable type" # Integral(x, (x, 0, ndarray(...))) raises "Invalid limits" # other ugly exceptions that are not well understood (marked with XXX) # TODO: Cleanup the ugly special cases marked with xxx above. # Solution: use cmath and vectorize the final lambda. self.lambda_func = experimental_lambdify(self.args, self.expr, use_python_cmath=True) self.vector_func = np.vectorize(self.lambda_func, otypes=[np.complex]) results = self.vector_func(*args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False, ) else: # Complete failure. One last try with no translations, only # wrapping in complex((...).evalf()) and returning the real # part. if self.failure: raise e else: self.failure = True self.lambda_func = experimental_lambdify( self.args, self.expr, use_evalf=True, complex_wrap_evalf=True) self.vector_func = np.vectorize(self.lambda_func, otypes=[np.complex]) results = self.vector_func(*args) results = np.ma.masked_where( np.abs(results.imag) > 1e-7 * np.abs(results), results.real, copy=False, ) warnings.warn( "The evaluation of the expression is" " problematic. We are trying a failback method" " that may still work. Please report this as a bug.") finally: np.seterr(**np_old_err) return results