def eval(self, args, assumptions=True): # Support for deprecated design # When old design is removed, this will always return None sympy_deprecation_warning( """ The AskHandler system is deprecated. Evaluating UndefinedPredicate objects should be replaced with the multipledispatch handler of Predicate. """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', stacklevel=5, ) expr, = args res, _res = None, None mro = inspect.getmro(type(expr)) for handler in self.handlers: cls = get_class(handler) for subclass in mro: eval_ = getattr(cls, subclass.__name__, None) if eval_ is None: continue res = eval_(expr, assumptions) # Do not stop if value returned is None # Try to check for higher classes if res is None: continue if _res is None: _res = res else: # only check consistency if both resolutors have concluded if _res != res: raise ValueError('incompatible resolutors') break return res
def _warn_sympy_deprecation(stacklevel=3): sympy_deprecation_warning( "feature", active_deprecations_target="active-deprecations", deprecated_since_version="0.0.0", stacklevel=stacklevel, )
def __new__(cls, name, abbrev=None, dimension=None, scale_factor=None, latex_repr=None, pretty_unicode_repr=None, pretty_ascii_repr=None, mathml_presentation_repr=None, **assumptions): if not isinstance(name, Symbol): name = Symbol(name) # For Quantity(name, dim, scale, abbrev) to work like in the # old version of SymPy: if not isinstance(abbrev, str) and not \ isinstance(abbrev, Symbol): dimension, scale_factor, abbrev = abbrev, dimension, scale_factor if dimension is not None: sympy_deprecation_warning( """ The 'dimension' argument to to Quantity() is deprecated. Instead use the unit_system.set_quantity_dimension() method. """, deprecated_since_version="1.3", active_deprecations_target="deprecated-quantity-dimension-scale-factor" ) if scale_factor is not None: sympy_deprecation_warning( """ The 'scale_factor' argument to to Quantity() is deprecated. Instead use the unit_system.set_quantity_scale_factors() method. """, deprecated_since_version="1.3", active_deprecations_target="deprecated-quantity-dimension-scale-factor" ) if abbrev is None: abbrev = name elif isinstance(abbrev, str): abbrev = Symbol(abbrev) obj = AtomicExpr.__new__(cls, name, abbrev) obj._name = name obj._abbrev = abbrev obj._latex_repr = latex_repr obj._unicode_repr = pretty_unicode_repr obj._ascii_repr = pretty_ascii_repr obj._mathml_repr = mathml_presentation_repr if dimension is not None: # TODO: remove after deprecation: with ignore_warnings(SymPyDeprecationWarning): obj.set_dimension(dimension) if scale_factor is not None: # TODO: remove after deprecation: with ignore_warnings(SymPyDeprecationWarning): obj.set_scale_factor(scale_factor) return obj
def unicode(self): sympy_deprecation_warning( """ The prettyForm.unicode attribute is deprecated. Use the prettyForm.s attribute instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-pretty-printing-functions") return self._unicode
def max_degrees(self): sympy_deprecation_warning( """ The max_degrees property of DixonResultant is deprecated. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-dixonresultant-properties", ) return self._max_degrees
def xstr(*args): sympy_deprecation_warning( """ The sympy.printing.pretty.pretty_symbology.xstr() function is deprecated. Use str() instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-pretty-printing-functions") return str(*args)
def _mat(self): sympy_deprecation_warning( """ The private _mat attribute of Matrix is deprecated. Use the .flat() method instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-private-matrix-attributes") return self.flat()
def remove_handler(self, handler): sympy_deprecation_warning( """ The AskHandler system is deprecated. Predicate.remove_handler() should be replaced with the multipledispatch handler of Predicate. """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) self.handlers.remove(handler)
def __new__(cls, *args, **kwargs): sympy_deprecation_warning( """ The AskHandler system is deprecated. The AskHandler class should be replaced with the multipledispatch handler of Predicate """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) return super().__new__(cls, *args, **kwargs)
def __new__(cls, *args, evaluate=None, _sympify=True): # Allow faster processing by passing ``_sympify=False``, if all arguments # are already sympified. if _sympify: args = list(map(_sympify_, args)) # Disallow non-Expr args in Add/Mul typ = cls._args_type if typ is not None: from .relational import Relational if any(isinstance(arg, Relational) for arg in args): raise TypeError("Relational cannot be used in %s" % cls.__name__) # This should raise TypeError once deprecation period is over: for arg in args: if not isinstance(arg, typ): sympy_deprecation_warning( f""" Using non-Expr arguments in {cls.__name__} is deprecated (in this case, one of the arguments has type {type(arg).__name__!r}). If you really did intend to use a multiplication or addition operation with this object, use the * or + operator instead. """, deprecated_since_version="1.7", active_deprecations_target="non-expr-args-deprecated", stacklevel=4, ) if evaluate is None: evaluate = global_parameters.evaluate if not evaluate: obj = cls._from_args(args) obj = cls._exec_constructor_postprocessors(obj) return obj args = [a for a in args if a is not cls.identity] if len(args) == 0: return cls.identity if len(args) == 1: return args[0] c_part, nc_part, order_symbols = cls.flatten(args) is_commutative = not nc_part obj = cls._from_args(c_part + nc_part, is_commutative) obj = cls._exec_constructor_postprocessors(obj) if order_symbols is not None: from sympy.series.order import Order return Order(obj, *order_symbols) return obj
def expr_free_symbols(self): from sympy.utilities.exceptions import sympy_deprecation_warning sympy_deprecation_warning( """ The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return {self}
def mathematica(s, additional_translations=None): sympy_deprecation_warning( """The ``mathematica`` function for the Mathematica parser is now deprecated. Use ``parse_mathematica`` instead. The parameter ``additional_translation`` can be replaced by SymPy's .replace( ) or .subs( ) methods on the output expression instead.""", deprecated_since_version="1.11", active_deprecations_target="mathematica-parser-new", ) parser = MathematicaParser(additional_translations) return sympify(parser._parse_old(s))
def set_potential_energy(self, scalar): sympy_deprecation_warning( """ The sympy.physics.mechanics.Particle.set_potential_energy() method is deprecated. Instead use P.potential_energy = scalar """, deprecated_since_version="1.5", active_deprecations_target="deprecated-set-potential-energy", ) self.potential_energy = scalar
def test_sympy_deprecation_warning(): raises( TypeError, lambda: sympy_deprecation_warning( 'test', deprecated_since_version=1.10, active_deprecations_target='active-deprecations')) raises( ValueError, lambda: sympy_deprecation_warning( 'test', deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)='))
def __init__(self, s, baseline=0, binding=0, unicode=None): """Initialize from stringPict and binding power.""" stringPict.__init__(self, s, baseline) self.binding = binding if unicode is not None: sympy_deprecation_warning(""" The unicode argument to prettyForm is deprecated. Only the s argument (the first positional argument) should be passed. """, deprecated_since_version="1.7", active_deprecations_target= "deprecated-pretty-printing-functions") self._unicode = unicode or s
def set_dimension(self, dimension, unit_system="SI"): sympy_deprecation_warning( f""" Quantity.set_dimension() is deprecated. Use either unit_system.set_quantity_dimension() or {self}.set_global_dimension() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) unit_system.set_quantity_dimension(self, dimension)
def get_dimensional_expr(expr, unit_system="SI"): sympy_deprecation_warning( """ Quantity.get_dimensional_expr() is deprecated. It is now associated with UnitSystem objects. The dimensional relations depend on the unit system used. Use unit_system.get_dimensional_expr() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) return unit_system.get_dimensional_expr(expr)
def _collect_factor_and_dimension(expr, unit_system="SI"): """Return tuple with scale factor expression and dimension expression.""" sympy_deprecation_warning( """ Quantity._collect_factor_and_dimension() is deprecated. This method has been moved to the UnitSystem class. Use unit_system._collect_factor_and_dimension(expr) instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) return unit_system._collect_factor_and_dimension(expr)
def get_upper_degree(self): sympy_deprecation_warning( """ The get_upper_degree() method of DixonResultant is deprecated. Use get_max_degrees() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-dixonresultant-properties" ) list_of_products = [self.variables[i] ** self._max_degrees[i] for i in range(self.n)] product = prod(list_of_products) product = Poly(product).monoms() return monomial_deg(*product)
def theano_code(expr, cache=None, **kwargs): """ Convert a SymPy expression into a Theano graph variable. .. deprecated:: 1.8 ``sympy.printing.theanocode`` is deprecated. Theano has been renamed to Aesara. Use ``sympy.printing.aesaracode`` instead. See :ref:`theanocode-deprecated` for more information. Parameters ========== expr : sympy.core.expr.Expr SymPy expression object to convert. cache : dict Cached Theano variables (see :class:`TheanoPrinter.cache <TheanoPrinter>`). Defaults to the module-level global cache. dtypes : dict Passed to :meth:`.TheanoPrinter.doprint`. broadcastables : dict Passed to :meth:`.TheanoPrinter.doprint`. Returns ======= theano.gof.graph.Variable A variable corresponding to the expression's value in a Theano symbolic expression graph. """ sympy_deprecation_warning( """ sympy.printing.theanocode is deprecated. Theano has been renamed to Aesara. Use sympy.printing.aesaracode instead.""", deprecated_since_version="1.8", active_deprecations_target='theanocode-deprecated') if not theano: raise ImportError("theano is required for theano_code") if cache is None: cache = global_cache return TheanoPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle from sympy.utilities.exceptions import sympy_deprecation_warning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: sympy_deprecation_warning( f""" Setting Permutation.print_cyclic is deprecated. Instead use init_printing(perm_cyclic={perm_cyclic}). """, deprecated_since_version="1.6", active_deprecations_target= "deprecated-permutation-print_cyclic", stacklevel=7, ) else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: if not expr.size: return '()' # before taking Cycle notation, see if the last element is # a singleton and move it to the head of the string s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] last = s.rfind('(') if not last == 0 and ',' not in s[last:]: s = s[last:] + s[:last] s = s.replace(',', '') return s else: s = expr.support() if not s: if expr.size < 5: return 'Permutation(%s)' % self._print(expr.array_form) return 'Permutation([], size=%s)' % self._print(expr.size) trim = self._print( expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) use = full = self._print(expr.array_form) if len(trim) < len(full): use = trim return 'Permutation(%s)' % use
def remove_handler(key, handler): """ Removes a handler from the ask system. Same syntax as register_handler .. deprecated:: 1.8. Use multipledispatch handler instead. See :obj:`~.Predicate`. """ sympy_deprecation_warning( """ The AskHandler system is deprecated. The remove_handler() function should be replaced with the multipledispatch handler of Predicate. """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) if isinstance(key, Predicate): key = key.name.name # Don't show the same warning again recursively with ignore_warnings(SymPyDeprecationWarning): getattr(Q, key).remove_handler(handler)
def _unify_element_sympy(cls, rep, element): domain = rep.domain element = _sympify(element) if domain != EXRAW: # The domain can only be ZZ, QQ or EXRAW if element.is_Integer: new_domain = domain elif element.is_Rational: new_domain = QQ else: new_domain = EXRAW # XXX: This converts the domain for all elements in the matrix # which can be slow. This happens e.g. if __setitem__ changes one # element to something that does not fit in the domain if new_domain != domain: rep = rep.convert_to(new_domain) domain = new_domain if domain != EXRAW: element = new_domain.from_sympy(element) if domain == EXRAW and not isinstance(element, Expr): sympy_deprecation_warning( """ non-Expr objects in a Matrix is deprecated. Matrix represents a mathematical matrix. To represent a container of non-numeric entities, Use a list of lists, TableForm, NumPy array, or some other data structure instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-non-expr-in-matrix", stacklevel=4, ) return rep, element
def __init__(self, *args, **kwargs): sympy_deprecation_warning( """ The RawMatrix class is deprecated. Use either DomainMatrix or Matrix instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-rawmatrix", ) domain = ZZ for i in range(self.rows): for j in range(self.cols): val = self[i,j] if getattr(val, 'is_Poly', False): K = val.domain[val.gens] val_sympy = val.as_expr() elif hasattr(val, 'parent'): K = val.parent() val_sympy = K.to_sympy(val) elif isinstance(val, (int, Integer)): K = ZZ val_sympy = sympify(val) elif isinstance(val, Rational): K = QQ val_sympy = val else: for K in ZZ, QQ: if K.of_type(val): val_sympy = K.to_sympy(val) break else: raise TypeError domain = domain.unify(K) self[i,j] = val_sympy self.ring = domain
def register_handler(key, handler): """ Register a handler in the ask system. key must be a string and handler a class inheriting from AskHandler. .. deprecated:: 1.8. Use multipledispatch handler instead. See :obj:`~.Predicate`. """ sympy_deprecation_warning( """ The AskHandler system is deprecated. The register_handler() function should be replaced with the multipledispatch handler of Predicate. """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) if isinstance(key, Predicate): key = key.name.name Qkey = getattr(Q, key, None) if Qkey is not None: Qkey.add_handler(handler) else: setattr(Q, key, Predicate(key, handlers=[handler]))
def _dod_to_DomainMatrix(cls, rows, cols, dod, types): if not all(issubclass(typ, Expr) for typ in types): sympy_deprecation_warning( """ non-Expr objects in a Matrix is deprecated. Matrix represents a mathematical matrix. To represent a container of non-numeric entities, Use a list of lists, TableForm, NumPy array, or some other data structure instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-non-expr-in-matrix", stacklevel=6, ) rep = DomainMatrix(dod, (rows, cols), EXRAW) if all(issubclass(typ, Rational) for typ in types): if all(issubclass(typ, Integer) for typ in types): rep = rep.convert_to(ZZ) else: rep = rep.convert_to(QQ) return rep
def __new__(cls, sym, condition, base_set=S.UniversalSet): sym = _sympify(sym) flat = flatten([sym]) if has_dups(flat): raise BadSignatureError("Duplicate symbols detected") base_set = _sympify(base_set) if not isinstance(base_set, Set): raise TypeError('base set should be a Set object, not %s' % base_set) condition = _sympify(condition) if isinstance(condition, FiniteSet): condition_orig = condition temp = (Eq(lhs, 0) for lhs in condition) condition = And(*temp) sympy_deprecation_warning( f""" Using a set for the condition in ConditionSet is deprecated. Use a boolean instead. In this case, replace {condition_orig} with {condition} """, deprecated_since_version='1.5', active_deprecations_target="deprecated-conditionset-set", ) condition = as_Boolean(condition) if condition is S.true: return base_set if condition is S.false: return S.EmptySet if base_set is S.EmptySet: return S.EmptySet # no simple answers, so now check syms for i in flat: if not getattr(i, '_diff_wrt', False): raise ValueError('`%s` is not symbol-like' % i) if base_set.contains(sym) is S.false: raise TypeError('sym `%s` is not in base_set `%s`' % (sym, base_set)) know = None if isinstance(base_set, FiniteSet): sifted = sift(base_set, lambda _: fuzzy_bool(condition.subs(sym, _))) if sifted[None]: know = FiniteSet(*sifted[True]) base_set = FiniteSet(*sifted[None]) else: return FiniteSet(*sifted[True]) if isinstance(base_set, cls): s, c, b = base_set.args def sig(s): return cls(s, Eq(adummy, 0)).as_dummy().sym sa, sb = map(sig, (sym, s)) if sa != sb: raise BadSignatureError('sym does not match sym of base set') reps = dict(zip(flatten([sym]), flatten([s]))) if s == sym: condition = And(condition, c) base_set = b elif not c.free_symbols & sym.free_symbols: reps = {v: k for k, v in reps.items()} condition = And(condition, c.xreplace(reps)) base_set = b elif not condition.free_symbols & s.free_symbols: sym = sym.xreplace(reps) condition = And(condition.xreplace(reps), c) base_set = b # flatten ConditionSet(Contains(ConditionSet())) expressions if isinstance(condition, Contains) and (sym == condition.args[0]): if isinstance(condition.args[1], Set): return condition.args[1].intersect(base_set) rv = Basic.__new__(cls, sym, condition, base_set) return rv if know is None else Union(know, rv)
def _is_diagonalizable(M, reals_only=False, **kwargs): """Returns ``True`` if a matrix is diagonalizable. Parameters ========== reals_only : bool, optional If ``True``, it tests whether the matrix can be diagonalized to contain only real numbers on the diagonal. If ``False``, it tests whether the matrix can be diagonalized at all, even with numbers that may not be real. Examples ======== Example of a diagonalizable matrix: >>> from sympy import Matrix >>> M = Matrix([[1, 2, 0], [0, 3, 0], [2, -4, 2]]) >>> M.is_diagonalizable() True Example of a non-diagonalizable matrix: >>> M = Matrix([[0, 1], [0, 0]]) >>> M.is_diagonalizable() False Example of a matrix that is diagonalized in terms of non-real entries: >>> M = Matrix([[0, 1], [-1, 0]]) >>> M.is_diagonalizable(reals_only=False) True >>> M.is_diagonalizable(reals_only=True) False See Also ======== is_diagonal diagonalize """ if 'clear_cache' in kwargs: sympy_deprecation_warning( """ The 'clear_cache' keyword to Matrix.is_diagonalizable is deprecated. It does nothing and should be omitted. """, deprecated_since_version="1.4", active_deprecations_target= "deprecated-matrix-is_diagonalizable-cache", stacklevel=4, ) if 'clear_subproducts' in kwargs: sympy_deprecation_warning( """ The 'clear_subproducts' keyword to Matrix.is_diagonalizable is deprecated. It does nothing and should be omitted. """, deprecated_since_version="1.4", active_deprecations_target= "deprecated-matrix-is_diagonalizable-cache", stacklevel=4, ) if not M.is_square: return False if all(e.is_real for e in M) and M.is_symmetric(): return True if all(e.is_complex for e in M) and M.is_hermitian: return True return _is_diagonalizable_with_eigen(M, reals_only=reals_only)[0]
def lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=False, cse=False): """Convert a SymPy expression into a function that allows for fast numeric evaluation. .. warning:: This function uses ``exec``, and thus should not be used on unsanitized input. .. deprecated:: 1.7 Passing a set for the *args* parameter is deprecated as sets are unordered. Use an ordered iterable such as a list or tuple. Explanation =========== For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an equivalent NumPy function that numerically evaluates it: >>> from sympy import sin, cos, symbols, lambdify >>> import numpy as np >>> x = symbols('x') >>> expr = sin(x) + cos(x) >>> expr sin(x) + cos(x) >>> f = lambdify(x, expr, 'numpy') >>> a = np.array([1, 2]) >>> f(a) [1.38177329 0.49315059] The primary purpose of this function is to provide a bridge from SymPy expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath, and tensorflow. In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions. ``lambdify`` bridges the two by converting a SymPy expression to an equivalent numeric function. The basic workflow with ``lambdify`` is to first create a SymPy expression representing whatever mathematical function you wish to evaluate. This should be done using only SymPy functions and expressions. Then, use ``lambdify`` to convert this to an equivalent function for numerical evaluation. For instance, above we created ``expr`` using the SymPy symbol ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an equivalent NumPy function ``f``, and called it on a NumPy array ``a``. Parameters ========== args : List[Symbol] A variable or a list of variables whose nesting represents the nesting of the arguments that will be passed to the function. Variables can be symbols, undefined functions, or matrix symbols. >>> from sympy import Eq >>> from sympy.abc import x, y, z The list of variables should match the structure of how the arguments will be passed to the function. Simply enclose the parameters as they will be passed in a list. To call a function like ``f(x)`` then ``[x]`` should be the first argument to ``lambdify``; for this case a single ``x`` can also be used: >>> f = lambdify(x, x + 1) >>> f(1) 2 >>> f = lambdify([x], x + 1) >>> f(1) 2 To call a function like ``f(x, y)`` then ``[x, y]`` will be the first argument of the ``lambdify``: >>> f = lambdify([x, y], x + y) >>> f(1, 1) 2 To call a function with a single 3-element tuple like ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first argument of the ``lambdify``: >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2)) >>> f((3, 4, 5)) True If two args will be passed and the first is a scalar but the second is a tuple with two arguments then the items in the list should match that structure: >>> f = lambdify([x, (y, z)], x + y + z) >>> f(1, (2, 3)) 6 expr : Expr An expression, list of expressions, or matrix to be evaluated. Lists may be nested. If the expression is a list, the output will also be a list. >>> f = lambdify(x, [x, [x + 1, x + 2]]) >>> f(1) [1, [2, 3]] If it is a matrix, an array will be returned (for the NumPy module). >>> from sympy import Matrix >>> f = lambdify(x, Matrix([x, x + 1])) >>> f(1) [[1] [2]] Note that the argument order here (variables then expression) is used to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works (roughly) like ``lambda x: expr`` (see :ref:`lambdify-how-it-works` below). modules : str, optional Specifies the numeric library to use. If not specified, *modules* defaults to: - ``["scipy", "numpy"]`` if SciPy is installed - ``["numpy"]`` if only NumPy is installed - ``["math", "mpmath", "sympy"]`` if neither is installed. That is, SymPy functions are replaced as far as possible by either ``scipy`` or ``numpy`` functions if available, and Python's standard library ``math``, or ``mpmath`` functions otherwise. *modules* can be one of the following types: - The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``, ``"scipy"``, ``"sympy"``, or ``"tensorflow"``. This uses the corresponding printer and namespace mapping for that module. - A module (e.g., ``math``). This uses the global namespace of the module. If the module is one of the above known modules, it will also use the corresponding printer and namespace mapping (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``). - A dictionary that maps names of SymPy functions to arbitrary functions (e.g., ``{'sin': custom_sin}``). - A list that contains a mix of the arguments above, with higher priority given to entries appearing first (e.g., to use the NumPy module but override the ``sin`` function with a custom version, you can use ``[{'sin': custom_sin}, 'numpy']``). dummify : bool, optional Whether or not the variables in the provided expression that are not valid Python identifiers are substituted with dummy symbols. This allows for undefined functions like ``Function('f')(t)`` to be supplied as arguments. By default, the variables are only dummified if they are not valid Python identifiers. Set ``dummify=True`` to replace all arguments with dummy symbols (if ``args`` is not a string) - for example, to ensure that the arguments do not redefine any built-in names. cse : bool, or callable, optional Large expressions can be computed more efficiently when common subexpressions are identified and precomputed before being used multiple time. Finding the subexpressions will make creation of the 'lambdify' function slower, however. When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default) the user may pass a function matching the ``cse`` signature. Examples ======== >>> from sympy.utilities.lambdify import implemented_function >>> from sympy import sqrt, sin, Matrix >>> from sympy import Function >>> from sympy.abc import w, x, y, z >>> f = lambdify(x, x**2) >>> f(2) 4 >>> f = lambdify((x, y, z), [z, y, x]) >>> f(1,2,3) [3, 2, 1] >>> f = lambdify(x, sqrt(x)) >>> f(4) 2.0 >>> f = lambdify((x, y), sin(x*y)**2) >>> f(0, 5) 0.0 >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy') >>> row(1, 2) Matrix([[1, 3]]) ``lambdify`` can be used to translate SymPy expressions into mpmath functions. This may be preferable to using ``evalf`` (which uses mpmath on the backend) in some cases. >>> f = lambdify(x, sin(x), 'mpmath') >>> f(1) 0.8414709848078965 Tuple arguments are handled and the lambdified function should be called with the same type of arguments as were used to create the function: >>> f = lambdify((x, (y, z)), x + y) >>> f(1, (2, 4)) 3 The ``flatten`` function can be used to always work with flattened arguments: >>> from sympy.utilities.iterables import flatten >>> args = w, (x, (y, z)) >>> vals = 1, (2, (3, 4)) >>> f = lambdify(flatten(args), w + x + y + z) >>> f(*flatten(vals)) 10 Functions present in ``expr`` can also carry their own numerical implementations, in a callable attached to the ``_imp_`` attribute. This can be used with undefined functions using the ``implemented_function`` factory: >>> f = implemented_function(Function('f'), lambda x: x+1) >>> func = lambdify(x, f(x)) >>> func(4) 5 ``lambdify`` always prefers ``_imp_`` implementations to implementations in other namespaces, unless the ``use_imps`` input parameter is False. Usage with Tensorflow: >>> import tensorflow as tf >>> from sympy import Max, sin, lambdify >>> from sympy.abc import x >>> f = Max(x, sin(x)) >>> func = lambdify(x, f, 'tensorflow') After tensorflow v2, eager execution is enabled by default. If you want to get the compatible result across tensorflow v1 and v2 as same as this tutorial, run this line. >>> tf.compat.v1.enable_eager_execution() If you have eager execution enabled, you can get the result out immediately as you can use numpy. If you pass tensorflow objects, you may get an ``EagerTensor`` object instead of value. >>> result = func(tf.constant(1.0)) >>> print(result) tf.Tensor(1.0, shape=(), dtype=float32) >>> print(result.__class__) <class 'tensorflow.python.framework.ops.EagerTensor'> You can use ``.numpy()`` to get the numpy value of the tensor. >>> result.numpy() 1.0 >>> var = tf.Variable(2.0) >>> result = func(var) # also works for tf.Variable and tf.Placeholder >>> result.numpy() 2.0 And it works with any shape array. >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) >>> result = func(tensor) >>> result.numpy() [[1. 2.] [3. 4.]] Notes ===== - For functions involving large array calculations, numexpr can provide a significant speedup over numpy. Please note that the available functions for numexpr are more limited than numpy but can be expanded with ``implemented_function`` and user defined subclasses of Function. If specified, numexpr may be the only option in modules. The official list 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: >>> from sympy import Piecewise >>> from sympy.testing.pytest import ignore_warnings >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy") >>> with ignore_warnings(RuntimeWarning): ... f(numpy.array([-1, 0, 1, 2])) [-1. 0. 1. 0.5] >>> f(0) Traceback (most recent call last): ... ZeroDivisionError: division by zero In such cases, the input should be wrapped in a numpy array: >>> with ignore_warnings(RuntimeWarning): ... float(f(numpy.array([0]))) 0.0 Or if numpy functionality is not required another module can be used: >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math") >>> f(0) 0 .. _lambdify-how-it-works: How it works ============ When using this function, it helps a great deal to have an idea of what it is doing. At its core, lambdify is nothing more than a namespace translation, on top of a special printer that makes some corner cases work properly. To understand lambdify, first we must properly understand how Python namespaces work. Say we had two files. One called ``sin_cos_sympy.py``, with .. code:: python # sin_cos_sympy.py from sympy.functions.elementary.trigonometric import (cos, sin) def sin_cos(x): return sin(x) + cos(x) and one called ``sin_cos_numpy.py`` with .. code:: python # sin_cos_numpy.py from numpy import sin, cos def sin_cos(x): return sin(x) + cos(x) The two files define an identical function ``sin_cos``. However, in the first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and ``cos``. In the second, they are defined as the NumPy versions. If we were to import the first file and use the ``sin_cos`` function, we would get something like >>> from sin_cos_sympy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP cos(1) + sin(1) On the other hand, if we imported ``sin_cos`` from the second file, we would get >>> from sin_cos_numpy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP 1.38177329068 In the first case we got a symbolic output, because it used the symbolic ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions from NumPy. But notice that the versions of ``sin`` and ``cos`` that were used was not inherent to the ``sin_cos`` function definition. Both ``sin_cos`` definitions are exactly the same. Rather, it was based on the names defined at the module where the ``sin_cos`` function was defined. The key point here is that when function in Python references a name that is not defined in the function, that name is looked up in the "global" namespace of the module where that function is defined. Now, in Python, we can emulate this behavior without actually writing a file to disk using the ``exec`` function. ``exec`` takes a string containing a block of Python code, and a dictionary that should contain the global variables of the module. It then executes the code "in" that dictionary, as if it were the module globals. The following is equivalent to the ``sin_cos`` defined in ``sin_cos_sympy.py``: >>> import sympy >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) cos(1) + sin(1) and similarly with ``sin_cos_numpy``: >>> import numpy >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) 1.38177329068 So now we can get an idea of how ``lambdify`` works. The name "lambdify" comes from the fact that we can think of something like ``lambdify(x, sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why the symbols argument is first in ``lambdify``, as opposed to most SymPy functions where it comes after the expression: to better mimic the ``lambda`` keyword. ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and 1. Converts it to a string 2. Creates a module globals dictionary based on the modules that are passed in (by default, it uses the NumPy module) 3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the list of variables separated by commas, and ``{expr}`` is the string created in step 1., then ``exec``s that string with the module globals namespace and returns ``func``. In fact, functions returned by ``lambdify`` support inspection. So you can see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you are using IPython or the Jupyter notebook. >>> f = lambdify(x, sin(x) + cos(x)) >>> import inspect >>> print(inspect.getsource(f)) def _lambdifygenerated(x): return sin(x) + cos(x) This shows us the source code of the function, but not the namespace it was defined in. We can inspect that by looking at the ``__globals__`` attribute of ``f``: >>> f.__globals__['sin'] <ufunc 'sin'> >>> f.__globals__['cos'] <ufunc 'cos'> >>> f.__globals__['sin'] is numpy.sin True This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be ``numpy.sin`` and ``numpy.cos``. Note that there are some convenience layers in each of these steps, but at the core, this is how ``lambdify`` works. Step 1 is done using the ``LambdaPrinter`` printers defined in the printing module (see :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions to define how they should be converted to a string for different modules. You can change which printer ``lambdify`` uses by passing a custom printer in to the ``printer`` argument. Step 2 is augmented by certain translations. There are default translations for each module, but you can provide your own by passing a list to the ``modules`` argument. For instance, >>> def mysin(x): ... print('taking the sin of', x) ... return numpy.sin(x) ... >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy']) >>> f(1) taking the sin of 1 0.8414709848078965 The globals dictionary is generated from the list by merging the dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The merging is done so that earlier items take precedence, which is why ``mysin`` is used above instead of ``numpy.sin``. If you want to modify the way ``lambdify`` works for a given function, it is usually easiest to do so by modifying the globals dictionary as such. In more complicated cases, it may be necessary to create and pass in a custom printer. Finally, step 3 is augmented with certain convenience operations, such as the addition of a docstring. Understanding how ``lambdify`` works can make it easier to avoid certain gotchas when using it. For instance, a common mistake is to create a lambdified function for one module (say, NumPy), and pass it objects from another (say, a SymPy expression). For instance, say we create >>> from sympy.abc import x >>> f = lambdify(x, x + 1, 'numpy') Now if we pass in a NumPy array, we get that array plus 1 >>> import numpy >>> a = numpy.array([1, 2]) >>> f(a) [2 3] But what happens if you make the mistake of passing in a SymPy expression instead of a NumPy array: >>> f(x + 1) x + 2 This worked, but it was only by accident. Now take a different lambdified function: >>> from sympy import sin >>> g = lambdify(x, x + sin(x), 'numpy') This works as expected on NumPy arrays: >>> g(a) [1.84147098 2.90929743] But if we try to pass in a SymPy expression, it fails >>> try: ... g(x + 1) ... # NumPy release after 1.17 raises TypeError instead of ... # AttributeError ... except (AttributeError, TypeError): ... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... AttributeError: Now, let's look at what happened. The reason this fails is that ``g`` calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not know how to operate on a SymPy object. **As a general rule, NumPy functions do not know how to operate on SymPy expressions, and SymPy functions do not know how to operate on NumPy arrays. This is why lambdify exists: to provide a bridge between SymPy and NumPy.** However, why is it that ``f`` did work? That's because ``f`` does not call any functions, it only adds 1. So the resulting function that is created, ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals namespace it is defined in. Thus it works, but only by accident. A future version of ``lambdify`` may remove this behavior. Be aware that certain implementation details described here may change in future versions of SymPy. The API of passing in custom modules and printers will not change, but the details of how a lambda function is created may change. However, the basic idea will remain the same, and understanding it will be helpful to understanding the behavior of lambdify. **In general: you should create lambdified functions for one module (say, NumPy), and only pass it input types that are compatible with that module (say, NumPy arrays).** Remember that by default, if the ``module`` argument is not provided, ``lambdify`` creates functions using the NumPy and SciPy namespaces. """ from sympy.core.symbol import Symbol from sympy.core.expr import Expr # If the user hasn't specified any modules, use what is available. if modules is None: try: _import("scipy") except ImportError: try: _import("numpy") except ImportError: # Use either numpy (if available) or python.math where possible. # XXX: This leads to different behaviour on different systems and # might be the reason for irreproducible errors. modules = ["math", "mpmath", "sympy"] else: modules = ["numpy"] else: modules = ["numpy", "scipy"] # Get the needed namespaces. namespaces = [] # First find any function implementations if use_imps: namespaces.append(_imp_namespace(expr)) # Check for dict before iterating if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'): namespaces.append(modules) else: # consistency check if _module_present('numexpr', modules) and len(modules) > 1: raise TypeError("numexpr must be the only item in 'modules'") namespaces += list(modules) # fill namespace with first having highest priority namespace = {} # type: tDict[str, Any] for m in namespaces[::-1]: buf = _get_namespace(m) namespace.update(buf) if hasattr(expr, "atoms"): #Try if you can extract symbols from the expression. #Move on if expr.atoms in not implemented. syms = expr.atoms(Symbol) for term in syms: namespace.update({str(term): term}) if printer is None: if _module_present('mpmath', namespaces): from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore elif _module_present('scipy', namespaces): from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore elif _module_present('numpy', namespaces): from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore elif _module_present('cupy', namespaces): from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore elif _module_present('numexpr', namespaces): from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore elif _module_present('tensorflow', namespaces): from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore elif _module_present('sympy', namespaces): from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore else: from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore user_functions = {} for m in namespaces[::-1]: if isinstance(m, dict): for k in m: user_functions[k] = k printer = Printer({'fully_qualified_modules': False, 'inline': True, 'allow_unknown_functions': True, 'user_functions': user_functions}) if isinstance(args, set): sympy_deprecation_warning( """ Passing the function arguments to lambdify() as a set is deprecated. This leads to unpredictable results since sets are unordered. Instead, use a list or tuple for the function arguments. """, deprecated_since_version="1.6.3", active_deprecations_target="deprecated-lambdify-arguments-set", ) # Get the names of the args, for creating a docstring iterable_args = (args,) if isinstance(args, Expr) else args names = [] # Grab the callers frame, for getting the names by inspection (if needed) callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore for n, var in enumerate(iterable_args): if hasattr(var, 'name'): names.append(var.name) else: # It's an iterable. Try to get name by inspection of calling frame. name_list = [var_name for var_name, var_val in callers_local_vars if var_val is var] if len(name_list) == 1: names.append(name_list[0]) else: # Cannot infer name with certainty. arg_# will have to do. names.append('arg_' + str(n)) # Create the function definition code and execute it funcname = '_lambdifygenerated' if _module_present('tensorflow', namespaces): funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter else: funcprinter = _EvaluatorPrinter(printer, dummify) if cse == True: from sympy.simplify.cse_main import cse as _cse cses, _expr = _cse(expr, list=False) elif callable(cse): cses, _expr = cse(expr) else: cses, _expr = (), expr funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses) # Collect the module imports from the code printers. imp_mod_lines = [] for mod, keys in (getattr(printer, 'module_imports', None) or {}).items(): for k in keys: if k not in namespace: ln = "from %s import %s" % (mod, k) try: exec(ln, {}, namespace) except ImportError: # Tensorflow 2.0 has issues with importing a specific # function from its submodule. # https://github.com/tensorflow/tensorflow/issues/33022 ln = "%s = %s.%s" % (k, mod, k) exec(ln, {}, namespace) imp_mod_lines.append(ln) # Provide lambda expression with builtins, and compatible implementation of range namespace.update({'builtins':builtins, 'range':range}) funclocals = {} # type: tDict[str, Any] global _lambdify_generated_counter filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter _lambdify_generated_counter += 1 c = compile(funcstr, filename, 'exec') exec(c, namespace, funclocals) # mtime has to be None or else linecache.checkcache will remove it linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore func = funclocals[funcname] # Apply the docstring sig = "func({})".format(", ".join(str(i) for i in names)) sig = textwrap.fill(sig, subsequent_indent=' '*8) expr_str = str(expr) if len(expr_str) > 78: expr_str = textwrap.wrap(expr_str, 75)[0] + '...' func.__doc__ = ( "Created with lambdify. Signature:\n\n" "{sig}\n\n" "Expression:\n\n" "{expr}\n\n" "Source code:\n\n" "{src}\n\n" "Imported modules:\n\n" "{imp_mods}" ).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines)) return func
from sympy.utilities.exceptions import sympy_deprecation_warning sympy_deprecation_warning( """ sympy.core.trace is deprecated. Use sympy.physics.quantum.trace instead. """, deprecated_since_version="1.10", active_deprecations_target="sympy-core-trace-deprecated", ) from sympy.physics.quantum.trace import Tr # noqa:F401