m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2136 lines
68 KiB

6 months ago
  1. """Base class for all the objects in SymPy"""
  2. from collections import defaultdict
  3. from collections.abc import Mapping
  4. from itertools import chain, zip_longest
  5. from typing import Set, Tuple, Any
  6. from .assumptions import ManagedProperties
  7. from .cache import cacheit
  8. from .core import BasicMeta
  9. from .sympify import _sympify, sympify, SympifyError, _external_converter
  10. from .sorting import ordered
  11. from .kind import Kind, UndefinedKind
  12. from ._print_helpers import Printable
  13. from sympy.utilities.decorator import deprecated
  14. from sympy.utilities.exceptions import sympy_deprecation_warning
  15. from sympy.utilities.iterables import iterable, numbered_symbols
  16. from sympy.utilities.misc import filldedent, func_name
  17. from inspect import getmro
  18. def as_Basic(expr):
  19. """Return expr as a Basic instance using strict sympify
  20. or raise a TypeError; this is just a wrapper to _sympify,
  21. raising a TypeError instead of a SympifyError."""
  22. try:
  23. return _sympify(expr)
  24. except SympifyError:
  25. raise TypeError(
  26. 'Argument must be a Basic object, not `%s`' % func_name(
  27. expr))
  28. class Basic(Printable, metaclass=ManagedProperties):
  29. """
  30. Base class for all SymPy objects.
  31. Notes and conventions
  32. =====================
  33. 1) Always use ``.args``, when accessing parameters of some instance:
  34. >>> from sympy import cot
  35. >>> from sympy.abc import x, y
  36. >>> cot(x).args
  37. (x,)
  38. >>> cot(x).args[0]
  39. x
  40. >>> (x*y).args
  41. (x, y)
  42. >>> (x*y).args[1]
  43. y
  44. 2) Never use internal methods or variables (the ones prefixed with ``_``):
  45. >>> cot(x)._args # do not use this, use cot(x).args instead
  46. (x,)
  47. 3) By "SymPy object" we mean something that can be returned by
  48. ``sympify``. But not all objects one encounters using SymPy are
  49. subclasses of Basic. For example, mutable objects are not:
  50. >>> from sympy import Basic, Matrix, sympify
  51. >>> A = Matrix([[1, 2], [3, 4]]).as_mutable()
  52. >>> isinstance(A, Basic)
  53. False
  54. >>> B = sympify(A)
  55. >>> isinstance(B, Basic)
  56. True
  57. """
  58. __slots__ = ('_mhash', # hash value
  59. '_args', # arguments
  60. '_assumptions'
  61. )
  62. _args: 'Tuple[Basic, ...]'
  63. _mhash: 'Any'
  64. # To be overridden with True in the appropriate subclasses
  65. is_number = False
  66. is_Atom = False
  67. is_Symbol = False
  68. is_symbol = False
  69. is_Indexed = False
  70. is_Dummy = False
  71. is_Wild = False
  72. is_Function = False
  73. is_Add = False
  74. is_Mul = False
  75. is_Pow = False
  76. is_Number = False
  77. is_Float = False
  78. is_Rational = False
  79. is_Integer = False
  80. is_NumberSymbol = False
  81. is_Order = False
  82. is_Derivative = False
  83. is_Piecewise = False
  84. is_Poly = False
  85. is_AlgebraicNumber = False
  86. is_Relational = False
  87. is_Equality = False
  88. is_Boolean = False
  89. is_Not = False
  90. is_Matrix = False
  91. is_Vector = False
  92. is_Point = False
  93. is_MatAdd = False
  94. is_MatMul = False
  95. kind: Kind = UndefinedKind
  96. def __new__(cls, *args):
  97. obj = object.__new__(cls)
  98. obj._assumptions = cls.default_assumptions
  99. obj._mhash = None # will be set by __hash__ method.
  100. obj._args = args # all items in args must be Basic objects
  101. return obj
  102. def copy(self):
  103. return self.func(*self.args)
  104. def __getnewargs__(self):
  105. return self.args
  106. def __getstate__(self):
  107. return None
  108. def __setstate__(self, state):
  109. for name, value in state.items():
  110. setattr(self, name, value)
  111. def __reduce_ex__(self, protocol):
  112. if protocol < 2:
  113. msg = "Only pickle protocol 2 or higher is supported by SymPy"
  114. raise NotImplementedError(msg)
  115. return super().__reduce_ex__(protocol)
  116. def __hash__(self) -> int:
  117. # hash cannot be cached using cache_it because infinite recurrence
  118. # occurs as hash is needed for setting cache dictionary keys
  119. h = self._mhash
  120. if h is None:
  121. h = hash((type(self).__name__,) + self._hashable_content())
  122. self._mhash = h
  123. return h
  124. def _hashable_content(self):
  125. """Return a tuple of information about self that can be used to
  126. compute the hash. If a class defines additional attributes,
  127. like ``name`` in Symbol, then this method should be updated
  128. accordingly to return such relevant attributes.
  129. Defining more than _hashable_content is necessary if __eq__ has
  130. been defined by a class. See note about this in Basic.__eq__."""
  131. return self._args
  132. @property
  133. def assumptions0(self):
  134. """
  135. Return object `type` assumptions.
  136. For example:
  137. Symbol('x', real=True)
  138. Symbol('x', integer=True)
  139. are different objects. In other words, besides Python type (Symbol in
  140. this case), the initial assumptions are also forming their typeinfo.
  141. Examples
  142. ========
  143. >>> from sympy import Symbol
  144. >>> from sympy.abc import x
  145. >>> x.assumptions0
  146. {'commutative': True}
  147. >>> x = Symbol("x", positive=True)
  148. >>> x.assumptions0
  149. {'commutative': True, 'complex': True, 'extended_negative': False,
  150. 'extended_nonnegative': True, 'extended_nonpositive': False,
  151. 'extended_nonzero': True, 'extended_positive': True, 'extended_real':
  152. True, 'finite': True, 'hermitian': True, 'imaginary': False,
  153. 'infinite': False, 'negative': False, 'nonnegative': True,
  154. 'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
  155. True, 'zero': False}
  156. """
  157. return {}
  158. def compare(self, other):
  159. """
  160. Return -1, 0, 1 if the object is smaller, equal, or greater than other.
  161. Not in the mathematical sense. If the object is of a different type
  162. from the "other" then their classes are ordered according to
  163. the sorted_classes list.
  164. Examples
  165. ========
  166. >>> from sympy.abc import x, y
  167. >>> x.compare(y)
  168. -1
  169. >>> x.compare(x)
  170. 0
  171. >>> y.compare(x)
  172. 1
  173. """
  174. # all redefinitions of __cmp__ method should start with the
  175. # following lines:
  176. if self is other:
  177. return 0
  178. n1 = self.__class__
  179. n2 = other.__class__
  180. c = (n1 > n2) - (n1 < n2)
  181. if c:
  182. return c
  183. #
  184. st = self._hashable_content()
  185. ot = other._hashable_content()
  186. c = (len(st) > len(ot)) - (len(st) < len(ot))
  187. if c:
  188. return c
  189. for l, r in zip(st, ot):
  190. l = Basic(*l) if isinstance(l, frozenset) else l
  191. r = Basic(*r) if isinstance(r, frozenset) else r
  192. if isinstance(l, Basic):
  193. c = l.compare(r)
  194. else:
  195. c = (l > r) - (l < r)
  196. if c:
  197. return c
  198. return 0
  199. @staticmethod
  200. def _compare_pretty(a, b):
  201. from sympy.series.order import Order
  202. if isinstance(a, Order) and not isinstance(b, Order):
  203. return 1
  204. if not isinstance(a, Order) and isinstance(b, Order):
  205. return -1
  206. if a.is_Rational and b.is_Rational:
  207. l = a.p * b.q
  208. r = b.p * a.q
  209. return (l > r) - (l < r)
  210. else:
  211. from .symbol import Wild
  212. p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3")
  213. r_a = a.match(p1 * p2**p3)
  214. if r_a and p3 in r_a:
  215. a3 = r_a[p3]
  216. r_b = b.match(p1 * p2**p3)
  217. if r_b and p3 in r_b:
  218. b3 = r_b[p3]
  219. c = Basic.compare(a3, b3)
  220. if c != 0:
  221. return c
  222. return Basic.compare(a, b)
  223. @classmethod
  224. def fromiter(cls, args, **assumptions):
  225. """
  226. Create a new object from an iterable.
  227. This is a convenience function that allows one to create objects from
  228. any iterable, without having to convert to a list or tuple first.
  229. Examples
  230. ========
  231. >>> from sympy import Tuple
  232. >>> Tuple.fromiter(i for i in range(5))
  233. (0, 1, 2, 3, 4)
  234. """
  235. return cls(*tuple(args), **assumptions)
  236. @classmethod
  237. def class_key(cls):
  238. """Nice order of classes. """
  239. return 5, 0, cls.__name__
  240. @cacheit
  241. def sort_key(self, order=None):
  242. """
  243. Return a sort key.
  244. Examples
  245. ========
  246. >>> from sympy import S, I
  247. >>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
  248. [1/2, -I, I]
  249. >>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
  250. [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
  251. >>> sorted(_, key=lambda x: x.sort_key())
  252. [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
  253. """
  254. # XXX: remove this when issue 5169 is fixed
  255. def inner_key(arg):
  256. if isinstance(arg, Basic):
  257. return arg.sort_key(order)
  258. else:
  259. return arg
  260. args = self._sorted_args
  261. args = len(args), tuple([inner_key(arg) for arg in args])
  262. return self.class_key(), args, S.One.sort_key(), S.One
  263. def _do_eq_sympify(self, other):
  264. """Returns a boolean indicating whether a == b when either a
  265. or b is not a Basic. This is only done for types that were either
  266. added to `converter` by a 3rd party or when the object has `_sympy_`
  267. defined. This essentially reuses the code in `_sympify` that is
  268. specific for this use case. Non-user defined types that are meant
  269. to work with SymPy should be handled directly in the __eq__ methods
  270. of the `Basic` classes it could equate to and not be converted. Note
  271. that after conversion, `==` is used again since it is not
  272. neccesarily clear whether `self` or `other`'s __eq__ method needs
  273. to be used."""
  274. for superclass in type(other).__mro__:
  275. conv = _external_converter.get(superclass)
  276. if conv is not None:
  277. return self == conv(other)
  278. if hasattr(other, '_sympy_'):
  279. return self == other._sympy_()
  280. return NotImplemented
  281. def __eq__(self, other):
  282. """Return a boolean indicating whether a == b on the basis of
  283. their symbolic trees.
  284. This is the same as a.compare(b) == 0 but faster.
  285. Notes
  286. =====
  287. If a class that overrides __eq__() needs to retain the
  288. implementation of __hash__() from a parent class, the
  289. interpreter must be told this explicitly by setting
  290. __hash__ : Callable[[object], int] = <ParentClass>.__hash__.
  291. Otherwise the inheritance of __hash__() will be blocked,
  292. just as if __hash__ had been explicitly set to None.
  293. References
  294. ==========
  295. from http://docs.python.org/dev/reference/datamodel.html#object.__hash__
  296. """
  297. if self is other:
  298. return True
  299. if not isinstance(other, Basic):
  300. return self._do_eq_sympify(other)
  301. # check for pure number expr
  302. if not (self.is_Number and other.is_Number) and (
  303. type(self) != type(other)):
  304. return False
  305. a, b = self._hashable_content(), other._hashable_content()
  306. if a != b:
  307. return False
  308. # check number *in* an expression
  309. for a, b in zip(a, b):
  310. if not isinstance(a, Basic):
  311. continue
  312. if a.is_Number and type(a) != type(b):
  313. return False
  314. return True
  315. def __ne__(self, other):
  316. """``a != b`` -> Compare two symbolic trees and see whether they are different
  317. this is the same as:
  318. ``a.compare(b) != 0``
  319. but faster
  320. """
  321. return not self == other
  322. def dummy_eq(self, other, symbol=None):
  323. """
  324. Compare two expressions and handle dummy symbols.
  325. Examples
  326. ========
  327. >>> from sympy import Dummy
  328. >>> from sympy.abc import x, y
  329. >>> u = Dummy('u')
  330. >>> (u**2 + 1).dummy_eq(x**2 + 1)
  331. True
  332. >>> (u**2 + 1) == (x**2 + 1)
  333. False
  334. >>> (u**2 + y).dummy_eq(x**2 + y, x)
  335. True
  336. >>> (u**2 + y).dummy_eq(x**2 + y, y)
  337. False
  338. """
  339. s = self.as_dummy()
  340. o = _sympify(other)
  341. o = o.as_dummy()
  342. dummy_symbols = [i for i in s.free_symbols if i.is_Dummy]
  343. if len(dummy_symbols) == 1:
  344. dummy = dummy_symbols.pop()
  345. else:
  346. return s == o
  347. if symbol is None:
  348. symbols = o.free_symbols
  349. if len(symbols) == 1:
  350. symbol = symbols.pop()
  351. else:
  352. return s == o
  353. tmp = dummy.__class__()
  354. return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp})
  355. def atoms(self, *types):
  356. """Returns the atoms that form the current object.
  357. By default, only objects that are truly atomic and cannot
  358. be divided into smaller pieces are returned: symbols, numbers,
  359. and number symbols like I and pi. It is possible to request
  360. atoms of any type, however, as demonstrated below.
  361. Examples
  362. ========
  363. >>> from sympy import I, pi, sin
  364. >>> from sympy.abc import x, y
  365. >>> (1 + x + 2*sin(y + I*pi)).atoms()
  366. {1, 2, I, pi, x, y}
  367. If one or more types are given, the results will contain only
  368. those types of atoms.
  369. >>> from sympy import Number, NumberSymbol, Symbol
  370. >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
  371. {x, y}
  372. >>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
  373. {1, 2}
  374. >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
  375. {1, 2, pi}
  376. >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
  377. {1, 2, I, pi}
  378. Note that I (imaginary unit) and zoo (complex infinity) are special
  379. types of number symbols and are not part of the NumberSymbol class.
  380. The type can be given implicitly, too:
  381. >>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
  382. {x, y}
  383. Be careful to check your assumptions when using the implicit option
  384. since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type
  385. of SymPy atom, while ``type(S(2))`` is type ``Integer`` and will find all
  386. integers in an expression:
  387. >>> from sympy import S
  388. >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
  389. {1}
  390. >>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
  391. {1, 2}
  392. Finally, arguments to atoms() can select more than atomic atoms: any
  393. SymPy type (loaded in core/__init__.py) can be listed as an argument
  394. and those types of "atoms" as found in scanning the arguments of the
  395. expression recursively:
  396. >>> from sympy import Function, Mul
  397. >>> from sympy.core.function import AppliedUndef
  398. >>> f = Function('f')
  399. >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
  400. {f(x), sin(y + I*pi)}
  401. >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
  402. {f(x)}
  403. >>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
  404. {I*pi, 2*sin(y + I*pi)}
  405. """
  406. if types:
  407. types = tuple(
  408. [t if isinstance(t, type) else type(t) for t in types])
  409. nodes = _preorder_traversal(self)
  410. if types:
  411. result = {node for node in nodes if isinstance(node, types)}
  412. else:
  413. result = {node for node in nodes if not node.args}
  414. return result
  415. @property
  416. def free_symbols(self) -> 'Set[Basic]':
  417. """Return from the atoms of self those which are free symbols.
  418. For most expressions, all symbols are free symbols. For some classes
  419. this is not true. e.g. Integrals use Symbols for the dummy variables
  420. which are bound variables, so Integral has a method to return all
  421. symbols except those. Derivative keeps track of symbols with respect
  422. to which it will perform a derivative; those are
  423. bound variables, too, so it has its own free_symbols method.
  424. Any other method that uses bound variables should implement a
  425. free_symbols method."""
  426. empty: 'Set[Basic]' = set()
  427. return empty.union(*(a.free_symbols for a in self.args))
  428. @property
  429. def expr_free_symbols(self):
  430. sympy_deprecation_warning("""
  431. The expr_free_symbols property is deprecated. Use free_symbols to get
  432. the free symbols of an expression.
  433. """,
  434. deprecated_since_version="1.9",
  435. active_deprecations_target="deprecated-expr-free-symbols")
  436. return set()
  437. def as_dummy(self):
  438. """Return the expression with any objects having structurally
  439. bound symbols replaced with unique, canonical symbols within
  440. the object in which they appear and having only the default
  441. assumption for commutativity being True. When applied to a
  442. symbol a new symbol having only the same commutativity will be
  443. returned.
  444. Examples
  445. ========
  446. >>> from sympy import Integral, Symbol
  447. >>> from sympy.abc import x
  448. >>> r = Symbol('r', real=True)
  449. >>> Integral(r, (r, x)).as_dummy()
  450. Integral(_0, (_0, x))
  451. >>> _.variables[0].is_real is None
  452. True
  453. >>> r.as_dummy()
  454. _r
  455. Notes
  456. =====
  457. Any object that has structurally bound variables should have
  458. a property, `bound_symbols` that returns those symbols
  459. appearing in the object.
  460. """
  461. from .symbol import Dummy, Symbol
  462. def can(x):
  463. # mask free that shadow bound
  464. free = x.free_symbols
  465. bound = set(x.bound_symbols)
  466. d = {i: Dummy() for i in bound & free}
  467. x = x.subs(d)
  468. # replace bound with canonical names
  469. x = x.xreplace(x.canonical_variables)
  470. # return after undoing masking
  471. return x.xreplace({v: k for k, v in d.items()})
  472. if not self.has(Symbol):
  473. return self
  474. return self.replace(
  475. lambda x: hasattr(x, 'bound_symbols'),
  476. can,
  477. simultaneous=False)
  478. @property
  479. def canonical_variables(self):
  480. """Return a dictionary mapping any variable defined in
  481. ``self.bound_symbols`` to Symbols that do not clash
  482. with any free symbols in the expression.
  483. Examples
  484. ========
  485. >>> from sympy import Lambda
  486. >>> from sympy.abc import x
  487. >>> Lambda(x, 2*x).canonical_variables
  488. {x: _0}
  489. """
  490. if not hasattr(self, 'bound_symbols'):
  491. return {}
  492. dums = numbered_symbols('_')
  493. reps = {}
  494. # watch out for free symbol that are not in bound symbols;
  495. # those that are in bound symbols are about to get changed
  496. bound = self.bound_symbols
  497. names = {i.name for i in self.free_symbols - set(bound)}
  498. for b in bound:
  499. d = next(dums)
  500. if b.is_Symbol:
  501. while d.name in names:
  502. d = next(dums)
  503. reps[b] = d
  504. return reps
  505. def rcall(self, *args):
  506. """Apply on the argument recursively through the expression tree.
  507. This method is used to simulate a common abuse of notation for
  508. operators. For instance, in SymPy the following will not work:
  509. ``(x+Lambda(y, 2*y))(z) == x+2*z``,
  510. however, you can use:
  511. >>> from sympy import Lambda
  512. >>> from sympy.abc import x, y, z
  513. >>> (x + Lambda(y, 2*y)).rcall(z)
  514. x + 2*z
  515. """
  516. return Basic._recursive_call(self, args)
  517. @staticmethod
  518. def _recursive_call(expr_to_call, on_args):
  519. """Helper for rcall method."""
  520. from .symbol import Symbol
  521. def the_call_method_is_overridden(expr):
  522. for cls in getmro(type(expr)):
  523. if '__call__' in cls.__dict__:
  524. return cls != Basic
  525. if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call):
  526. if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is
  527. return expr_to_call # transformed into an UndefFunction
  528. else:
  529. return expr_to_call(*on_args)
  530. elif expr_to_call.args:
  531. args = [Basic._recursive_call(
  532. sub, on_args) for sub in expr_to_call.args]
  533. return type(expr_to_call)(*args)
  534. else:
  535. return expr_to_call
  536. def is_hypergeometric(self, k):
  537. from sympy.simplify.simplify import hypersimp
  538. from sympy.functions.elementary.piecewise import Piecewise
  539. if self.has(Piecewise):
  540. return None
  541. return hypersimp(self, k) is not None
  542. @property
  543. def is_comparable(self):
  544. """Return True if self can be computed to a real number
  545. (or already is a real number) with precision, else False.
  546. Examples
  547. ========
  548. >>> from sympy import exp_polar, pi, I
  549. >>> (I*exp_polar(I*pi/2)).is_comparable
  550. True
  551. >>> (I*exp_polar(I*pi*2)).is_comparable
  552. False
  553. A False result does not mean that `self` cannot be rewritten
  554. into a form that would be comparable. For example, the
  555. difference computed below is zero but without simplification
  556. it does not evaluate to a zero with precision:
  557. >>> e = 2**pi*(1 + 2**pi)
  558. >>> dif = e - e.expand()
  559. >>> dif.is_comparable
  560. False
  561. >>> dif.n(2)._prec
  562. 1
  563. """
  564. is_extended_real = self.is_extended_real
  565. if is_extended_real is False:
  566. return False
  567. if not self.is_number:
  568. return False
  569. # don't re-eval numbers that are already evaluated since
  570. # this will create spurious precision
  571. n, i = [p.evalf(2) if not p.is_Number else p
  572. for p in self.as_real_imag()]
  573. if not (i.is_Number and n.is_Number):
  574. return False
  575. if i:
  576. # if _prec = 1 we can't decide and if not,
  577. # the answer is False because numbers with
  578. # imaginary parts can't be compared
  579. # so return False
  580. return False
  581. else:
  582. return n._prec != 1
  583. @property
  584. def func(self):
  585. """
  586. The top-level function in an expression.
  587. The following should hold for all objects::
  588. >> x == x.func(*x.args)
  589. Examples
  590. ========
  591. >>> from sympy.abc import x
  592. >>> a = 2*x
  593. >>> a.func
  594. <class 'sympy.core.mul.Mul'>
  595. >>> a.args
  596. (2, x)
  597. >>> a.func(*a.args)
  598. 2*x
  599. >>> a == a.func(*a.args)
  600. True
  601. """
  602. return self.__class__
  603. @property
  604. def args(self) -> 'Tuple[Basic, ...]':
  605. """Returns a tuple of arguments of 'self'.
  606. Examples
  607. ========
  608. >>> from sympy import cot
  609. >>> from sympy.abc import x, y
  610. >>> cot(x).args
  611. (x,)
  612. >>> cot(x).args[0]
  613. x
  614. >>> (x*y).args
  615. (x, y)
  616. >>> (x*y).args[1]
  617. y
  618. Notes
  619. =====
  620. Never use self._args, always use self.args.
  621. Only use _args in __new__ when creating a new function.
  622. Don't override .args() from Basic (so that it's easy to
  623. change the interface in the future if needed).
  624. """
  625. return self._args
  626. @property
  627. def _sorted_args(self):
  628. """
  629. The same as ``args``. Derived classes which do not fix an
  630. order on their arguments should override this method to
  631. produce the sorted representation.
  632. """
  633. return self.args
  634. def as_content_primitive(self, radical=False, clear=True):
  635. """A stub to allow Basic args (like Tuple) to be skipped when computing
  636. the content and primitive components of an expression.
  637. See Also
  638. ========
  639. sympy.core.expr.Expr.as_content_primitive
  640. """
  641. return S.One, self
  642. def subs(self, *args, **kwargs):
  643. """
  644. Substitutes old for new in an expression after sympifying args.
  645. `args` is either:
  646. - two arguments, e.g. foo.subs(old, new)
  647. - one iterable argument, e.g. foo.subs(iterable). The iterable may be
  648. o an iterable container with (old, new) pairs. In this case the
  649. replacements are processed in the order given with successive
  650. patterns possibly affecting replacements already made.
  651. o a dict or set whose key/value items correspond to old/new pairs.
  652. In this case the old/new pairs will be sorted by op count and in
  653. case of a tie, by number of args and the default_sort_key. The
  654. resulting sorted list is then processed as an iterable container
  655. (see previous).
  656. If the keyword ``simultaneous`` is True, the subexpressions will not be
  657. evaluated until all the substitutions have been made.
  658. Examples
  659. ========
  660. >>> from sympy import pi, exp, limit, oo
  661. >>> from sympy.abc import x, y
  662. >>> (1 + x*y).subs(x, pi)
  663. pi*y + 1
  664. >>> (1 + x*y).subs({x:pi, y:2})
  665. 1 + 2*pi
  666. >>> (1 + x*y).subs([(x, pi), (y, 2)])
  667. 1 + 2*pi
  668. >>> reps = [(y, x**2), (x, 2)]
  669. >>> (x + y).subs(reps)
  670. 6
  671. >>> (x + y).subs(reversed(reps))
  672. x**2 + 2
  673. >>> (x**2 + x**4).subs(x**2, y)
  674. y**2 + y
  675. To replace only the x**2 but not the x**4, use xreplace:
  676. >>> (x**2 + x**4).xreplace({x**2: y})
  677. x**4 + y
  678. To delay evaluation until all substitutions have been made,
  679. set the keyword ``simultaneous`` to True:
  680. >>> (x/y).subs([(x, 0), (y, 0)])
  681. 0
  682. >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
  683. nan
  684. This has the added feature of not allowing subsequent substitutions
  685. to affect those already made:
  686. >>> ((x + y)/y).subs({x + y: y, y: x + y})
  687. 1
  688. >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
  689. y/(x + y)
  690. In order to obtain a canonical result, unordered iterables are
  691. sorted by count_op length, number of arguments and by the
  692. default_sort_key to break any ties. All other iterables are left
  693. unsorted.
  694. >>> from sympy import sqrt, sin, cos
  695. >>> from sympy.abc import a, b, c, d, e
  696. >>> A = (sqrt(sin(2*x)), a)
  697. >>> B = (sin(2*x), b)
  698. >>> C = (cos(2*x), c)
  699. >>> D = (x, d)
  700. >>> E = (exp(x), e)
  701. >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
  702. >>> expr.subs(dict([A, B, C, D, E]))
  703. a*c*sin(d*e) + b
  704. The resulting expression represents a literal replacement of the
  705. old arguments with the new arguments. This may not reflect the
  706. limiting behavior of the expression:
  707. >>> (x**3 - 3*x).subs({x: oo})
  708. nan
  709. >>> limit(x**3 - 3*x, x, oo)
  710. oo
  711. If the substitution will be followed by numerical
  712. evaluation, it is better to pass the substitution to
  713. evalf as
  714. >>> (1/x).evalf(subs={x: 3.0}, n=21)
  715. 0.333333333333333333333
  716. rather than
  717. >>> (1/x).subs({x: 3.0}).evalf(21)
  718. 0.333333333333333314830
  719. as the former will ensure that the desired level of precision is
  720. obtained.
  721. See Also
  722. ========
  723. replace: replacement capable of doing wildcard-like matching,
  724. parsing of match, and conditional replacements
  725. xreplace: exact node replacement in expr tree; also capable of
  726. using matching rules
  727. sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision
  728. """
  729. from .containers import Dict
  730. from .symbol import Dummy, Symbol
  731. from sympy.polys.polyutils import illegal
  732. unordered = False
  733. if len(args) == 1:
  734. sequence = args[0]
  735. if isinstance(sequence, set):
  736. unordered = True
  737. elif isinstance(sequence, (Dict, Mapping)):
  738. unordered = True
  739. sequence = sequence.items()
  740. elif not iterable(sequence):
  741. raise ValueError(filldedent("""
  742. When a single argument is passed to subs
  743. it should be a dictionary of old: new pairs or an iterable
  744. of (old, new) tuples."""))
  745. elif len(args) == 2:
  746. sequence = [args]
  747. else:
  748. raise ValueError("subs accepts either 1 or 2 arguments")
  749. sequence = list(sequence)
  750. for i, s in enumerate(sequence):
  751. if isinstance(s[0], str):
  752. # when old is a string we prefer Symbol
  753. s = Symbol(s[0]), s[1]
  754. try:
  755. s = [sympify(_, strict=not isinstance(_, (str, type)))
  756. for _ in s]
  757. except SympifyError:
  758. # if it can't be sympified, skip it
  759. sequence[i] = None
  760. continue
  761. # skip if there is no change
  762. sequence[i] = None if _aresame(*s) else tuple(s)
  763. sequence = list(filter(None, sequence))
  764. simultaneous = kwargs.pop('simultaneous', False)
  765. if unordered:
  766. from .sorting import _nodes, default_sort_key
  767. sequence = dict(sequence)
  768. # order so more complex items are first and items
  769. # of identical complexity are ordered so
  770. # f(x) < f(y) < x < y
  771. # \___ 2 __/ \_1_/ <- number of nodes
  772. #
  773. # For more complex ordering use an unordered sequence.
  774. k = list(ordered(sequence, default=False, keys=(
  775. lambda x: -_nodes(x),
  776. default_sort_key,
  777. )))
  778. sequence = [(k, sequence[k]) for k in k]
  779. # do infinities first
  780. if not simultaneous:
  781. redo = []
  782. for i in range(len(sequence)):
  783. if sequence[i][1] in illegal: # nan, zoo and +/-oo
  784. redo.append(i)
  785. for i in reversed(redo):
  786. sequence.insert(0, sequence.pop(i))
  787. if simultaneous: # XXX should this be the default for dict subs?
  788. reps = {}
  789. rv = self
  790. kwargs['hack2'] = True
  791. m = Dummy('subs_m')
  792. for old, new in sequence:
  793. com = new.is_commutative
  794. if com is None:
  795. com = True
  796. d = Dummy('subs_d', commutative=com)
  797. # using d*m so Subs will be used on dummy variables
  798. # in things like Derivative(f(x, y), x) in which x
  799. # is both free and bound
  800. rv = rv._subs(old, d*m, **kwargs)
  801. if not isinstance(rv, Basic):
  802. break
  803. reps[d] = new
  804. reps[m] = S.One # get rid of m
  805. return rv.xreplace(reps)
  806. else:
  807. rv = self
  808. for old, new in sequence:
  809. rv = rv._subs(old, new, **kwargs)
  810. if not isinstance(rv, Basic):
  811. break
  812. return rv
  813. @cacheit
  814. def _subs(self, old, new, **hints):
  815. """Substitutes an expression old -> new.
  816. If self is not equal to old then _eval_subs is called.
  817. If _eval_subs doesn't want to make any special replacement
  818. then a None is received which indicates that the fallback
  819. should be applied wherein a search for replacements is made
  820. amongst the arguments of self.
  821. >>> from sympy import Add
  822. >>> from sympy.abc import x, y, z
  823. Examples
  824. ========
  825. Add's _eval_subs knows how to target x + y in the following
  826. so it makes the change:
  827. >>> (x + y + z).subs(x + y, 1)
  828. z + 1
  829. Add's _eval_subs doesn't need to know how to find x + y in
  830. the following:
  831. >>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None
  832. True
  833. The returned None will cause the fallback routine to traverse the args and
  834. pass the z*(x + y) arg to Mul where the change will take place and the
  835. substitution will succeed:
  836. >>> (z*(x + y) + 3).subs(x + y, 1)
  837. z + 3
  838. ** Developers Notes **
  839. An _eval_subs routine for a class should be written if:
  840. 1) any arguments are not instances of Basic (e.g. bool, tuple);
  841. 2) some arguments should not be targeted (as in integration
  842. variables);
  843. 3) if there is something other than a literal replacement
  844. that should be attempted (as in Piecewise where the condition
  845. may be updated without doing a replacement).
  846. If it is overridden, here are some special cases that might arise:
  847. 1) If it turns out that no special change was made and all
  848. the original sub-arguments should be checked for
  849. replacements then None should be returned.
  850. 2) If it is necessary to do substitutions on a portion of
  851. the expression then _subs should be called. _subs will
  852. handle the case of any sub-expression being equal to old
  853. (which usually would not be the case) while its fallback
  854. will handle the recursion into the sub-arguments. For
  855. example, after Add's _eval_subs removes some matching terms
  856. it must process the remaining terms so it calls _subs
  857. on each of the un-matched terms and then adds them
  858. onto the terms previously obtained.
  859. 3) If the initial expression should remain unchanged then
  860. the original expression should be returned. (Whenever an
  861. expression is returned, modified or not, no further
  862. substitution of old -> new is attempted.) Sum's _eval_subs
  863. routine uses this strategy when a substitution is attempted
  864. on any of its summation variables.
  865. """
  866. def fallback(self, old, new):
  867. """
  868. Try to replace old with new in any of self's arguments.
  869. """
  870. hit = False
  871. args = list(self.args)
  872. for i, arg in enumerate(args):
  873. if not hasattr(arg, '_eval_subs'):
  874. continue
  875. arg = arg._subs(old, new, **hints)
  876. if not _aresame(arg, args[i]):
  877. hit = True
  878. args[i] = arg
  879. if hit:
  880. rv = self.func(*args)
  881. hack2 = hints.get('hack2', False)
  882. if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack
  883. coeff = S.One
  884. nonnumber = []
  885. for i in args:
  886. if i.is_Number:
  887. coeff *= i
  888. else:
  889. nonnumber.append(i)
  890. nonnumber = self.func(*nonnumber)
  891. if coeff is S.One:
  892. return nonnumber
  893. else:
  894. return self.func(coeff, nonnumber, evaluate=False)
  895. return rv
  896. return self
  897. if _aresame(self, old):
  898. return new
  899. rv = self._eval_subs(old, new)
  900. if rv is None:
  901. rv = fallback(self, old, new)
  902. return rv
  903. def _eval_subs(self, old, new):
  904. """Override this stub if you want to do anything more than
  905. attempt a replacement of old with new in the arguments of self.
  906. See also
  907. ========
  908. _subs
  909. """
  910. return None
  911. def xreplace(self, rule):
  912. """
  913. Replace occurrences of objects within the expression.
  914. Parameters
  915. ==========
  916. rule : dict-like
  917. Expresses a replacement rule
  918. Returns
  919. =======
  920. xreplace : the result of the replacement
  921. Examples
  922. ========
  923. >>> from sympy import symbols, pi, exp
  924. >>> x, y, z = symbols('x y z')
  925. >>> (1 + x*y).xreplace({x: pi})
  926. pi*y + 1
  927. >>> (1 + x*y).xreplace({x: pi, y: 2})
  928. 1 + 2*pi
  929. Replacements occur only if an entire node in the expression tree is
  930. matched:
  931. >>> (x*y + z).xreplace({x*y: pi})
  932. z + pi
  933. >>> (x*y*z).xreplace({x*y: pi})
  934. x*y*z
  935. >>> (2*x).xreplace({2*x: y, x: z})
  936. y
  937. >>> (2*2*x).xreplace({2*x: y, x: z})
  938. 4*z
  939. >>> (x + y + 2).xreplace({x + y: 2})
  940. x + y + 2
  941. >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
  942. x + exp(y) + 2
  943. xreplace doesn't differentiate between free and bound symbols. In the
  944. following, subs(x, y) would not change x since it is a bound symbol,
  945. but xreplace does:
  946. >>> from sympy import Integral
  947. >>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
  948. Integral(y, (y, 1, 2*y))
  949. Trying to replace x with an expression raises an error:
  950. >>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP
  951. ValueError: Invalid limits given: ((2*y, 1, 4*y),)
  952. See Also
  953. ========
  954. replace: replacement capable of doing wildcard-like matching,
  955. parsing of match, and conditional replacements
  956. subs: substitution of subexpressions as defined by the objects
  957. themselves.
  958. """
  959. value, _ = self._xreplace(rule)
  960. return value
  961. def _xreplace(self, rule):
  962. """
  963. Helper for xreplace. Tracks whether a replacement actually occurred.
  964. """
  965. if self in rule:
  966. return rule[self], True
  967. elif rule:
  968. args = []
  969. changed = False
  970. for a in self.args:
  971. _xreplace = getattr(a, '_xreplace', None)
  972. if _xreplace is not None:
  973. a_xr = _xreplace(rule)
  974. args.append(a_xr[0])
  975. changed |= a_xr[1]
  976. else:
  977. args.append(a)
  978. args = tuple(args)
  979. if changed:
  980. return self.func(*args), True
  981. return self, False
  982. @cacheit
  983. def has(self, *patterns):
  984. """
  985. Test whether any subexpression matches any of the patterns.
  986. Examples
  987. ========
  988. >>> from sympy import sin
  989. >>> from sympy.abc import x, y, z
  990. >>> (x**2 + sin(x*y)).has(z)
  991. False
  992. >>> (x**2 + sin(x*y)).has(x, y, z)
  993. True
  994. >>> x.has(x)
  995. True
  996. Note ``has`` is a structural algorithm with no knowledge of
  997. mathematics. Consider the following half-open interval:
  998. >>> from sympy import Interval
  999. >>> i = Interval.Lopen(0, 5); i
  1000. Interval.Lopen(0, 5)
  1001. >>> i.args
  1002. (0, 5, True, False)
  1003. >>> i.has(4) # there is no "4" in the arguments
  1004. False
  1005. >>> i.has(0) # there *is* a "0" in the arguments
  1006. True
  1007. Instead, use ``contains`` to determine whether a number is in the
  1008. interval or not:
  1009. >>> i.contains(4)
  1010. True
  1011. >>> i.contains(0)
  1012. False
  1013. Note that ``expr.has(*patterns)`` is exactly equivalent to
  1014. ``any(expr.has(p) for p in patterns)``. In particular, ``False`` is
  1015. returned when the list of patterns is empty.
  1016. >>> x.has()
  1017. False
  1018. """
  1019. return self._has(iterargs, *patterns)
  1020. @cacheit
  1021. def has_free(self, *patterns):
  1022. """return True if self has object(s) ``x`` as a free expression
  1023. else False.
  1024. Examples
  1025. ========
  1026. >>> from sympy import Integral, Function
  1027. >>> from sympy.abc import x, y
  1028. >>> f = Function('f')
  1029. >>> g = Function('g')
  1030. >>> expr = Integral(f(x), (f(x), 1, g(y)))
  1031. >>> expr.free_symbols
  1032. {y}
  1033. >>> expr.has_free(g(y))
  1034. True
  1035. >>> expr.has_free(*(x, f(x)))
  1036. False
  1037. This works for subexpressions and types, too:
  1038. >>> expr.has_free(g)
  1039. True
  1040. >>> (x + y + 1).has_free(y + 1)
  1041. True
  1042. """
  1043. return self._has(iterfreeargs, *patterns)
  1044. def _has(self, iterargs, *patterns):
  1045. # separate out types and unhashable objects
  1046. type_set = set() # only types
  1047. p_set = set() # hashable non-types
  1048. for p in patterns:
  1049. if isinstance(p, BasicMeta):
  1050. type_set.add(p)
  1051. continue
  1052. if not isinstance(p, Basic):
  1053. try:
  1054. p = _sympify(p)
  1055. except SympifyError:
  1056. continue # Basic won't have this in it
  1057. p_set.add(p) # fails if object defines __eq__ but
  1058. # doesn't define __hash__
  1059. types = tuple(type_set) #
  1060. for i in iterargs(self): #
  1061. if i in p_set: # <--- here, too
  1062. return True
  1063. if isinstance(i, types):
  1064. return True
  1065. # use matcher if defined, e.g. operations defines
  1066. # matcher that checks for exact subset containment,
  1067. # (x + y + 1).has(x + 1) -> True
  1068. for i in p_set - type_set: # types don't have matchers
  1069. if not hasattr(i, '_has_matcher'):
  1070. continue
  1071. match = i._has_matcher()
  1072. if any(match(arg) for arg in iterargs(self)):
  1073. return True
  1074. # no success
  1075. return False
  1076. def replace(self, query, value, map=False, simultaneous=True, exact=None):
  1077. """
  1078. Replace matching subexpressions of ``self`` with ``value``.
  1079. If ``map = True`` then also return the mapping {old: new} where ``old``
  1080. was a sub-expression found with query and ``new`` is the replacement
  1081. value for it. If the expression itself doesn't match the query, then
  1082. the returned value will be ``self.xreplace(map)`` otherwise it should
  1083. be ``self.subs(ordered(map.items()))``.
  1084. Traverses an expression tree and performs replacement of matching
  1085. subexpressions from the bottom to the top of the tree. The default
  1086. approach is to do the replacement in a simultaneous fashion so
  1087. changes made are targeted only once. If this is not desired or causes
  1088. problems, ``simultaneous`` can be set to False.
  1089. In addition, if an expression containing more than one Wild symbol
  1090. is being used to match subexpressions and the ``exact`` flag is None
  1091. it will be set to True so the match will only succeed if all non-zero
  1092. values are received for each Wild that appears in the match pattern.
  1093. Setting this to False accepts a match of 0; while setting it True
  1094. accepts all matches that have a 0 in them. See example below for
  1095. cautions.
  1096. The list of possible combinations of queries and replacement values
  1097. is listed below:
  1098. Examples
  1099. ========
  1100. Initial setup
  1101. >>> from sympy import log, sin, cos, tan, Wild, Mul, Add
  1102. >>> from sympy.abc import x, y
  1103. >>> f = log(sin(x)) + tan(sin(x**2))
  1104. 1.1. type -> type
  1105. obj.replace(type, newtype)
  1106. When object of type ``type`` is found, replace it with the
  1107. result of passing its argument(s) to ``newtype``.
  1108. >>> f.replace(sin, cos)
  1109. log(cos(x)) + tan(cos(x**2))
  1110. >>> sin(x).replace(sin, cos, map=True)
  1111. (cos(x), {sin(x): cos(x)})
  1112. >>> (x*y).replace(Mul, Add)
  1113. x + y
  1114. 1.2. type -> func
  1115. obj.replace(type, func)
  1116. When object of type ``type`` is found, apply ``func`` to its
  1117. argument(s). ``func`` must be written to handle the number
  1118. of arguments of ``type``.
  1119. >>> f.replace(sin, lambda arg: sin(2*arg))
  1120. log(sin(2*x)) + tan(sin(2*x**2))
  1121. >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
  1122. sin(2*x*y)
  1123. 2.1. pattern -> expr
  1124. obj.replace(pattern(wild), expr(wild))
  1125. Replace subexpressions matching ``pattern`` with the expression
  1126. written in terms of the Wild symbols in ``pattern``.
  1127. >>> a, b = map(Wild, 'ab')
  1128. >>> f.replace(sin(a), tan(a))
  1129. log(tan(x)) + tan(tan(x**2))
  1130. >>> f.replace(sin(a), tan(a/2))
  1131. log(tan(x/2)) + tan(tan(x**2/2))
  1132. >>> f.replace(sin(a), a)
  1133. log(x) + tan(x**2)
  1134. >>> (x*y).replace(a*x, a)
  1135. y
  1136. Matching is exact by default when more than one Wild symbol
  1137. is used: matching fails unless the match gives non-zero
  1138. values for all Wild symbols:
  1139. >>> (2*x + y).replace(a*x + b, b - a)
  1140. y - 2
  1141. >>> (2*x).replace(a*x + b, b - a)
  1142. 2*x
  1143. When set to False, the results may be non-intuitive:
  1144. >>> (2*x).replace(a*x + b, b - a, exact=False)
  1145. 2/x
  1146. 2.2. pattern -> func
  1147. obj.replace(pattern(wild), lambda wild: expr(wild))
  1148. All behavior is the same as in 2.1 but now a function in terms of
  1149. pattern variables is used rather than an expression:
  1150. >>> f.replace(sin(a), lambda a: sin(2*a))
  1151. log(sin(2*x)) + tan(sin(2*x**2))
  1152. 3.1. func -> func
  1153. obj.replace(filter, func)
  1154. Replace subexpression ``e`` with ``func(e)`` if ``filter(e)``
  1155. is True.
  1156. >>> g = 2*sin(x**3)
  1157. >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
  1158. 4*sin(x**9)
  1159. The expression itself is also targeted by the query but is done in
  1160. such a fashion that changes are not made twice.
  1161. >>> e = x*(x*y + 1)
  1162. >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
  1163. 2*x*(2*x*y + 1)
  1164. When matching a single symbol, `exact` will default to True, but
  1165. this may or may not be the behavior that is desired:
  1166. Here, we want `exact=False`:
  1167. >>> from sympy import Function
  1168. >>> f = Function('f')
  1169. >>> e = f(1) + f(0)
  1170. >>> q = f(a), lambda a: f(a + 1)
  1171. >>> e.replace(*q, exact=False)
  1172. f(1) + f(2)
  1173. >>> e.replace(*q, exact=True)
  1174. f(0) + f(2)
  1175. But here, the nature of matching makes selecting
  1176. the right setting tricky:
  1177. >>> e = x**(1 + y)
  1178. >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False)
  1179. x
  1180. >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True)
  1181. x**(-x - y + 1)
  1182. >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False)
  1183. x
  1184. >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True)
  1185. x**(1 - y)
  1186. It is probably better to use a different form of the query
  1187. that describes the target expression more precisely:
  1188. >>> (1 + x**(1 + y)).replace(
  1189. ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1,
  1190. ... lambda x: x.base**(1 - (x.exp - 1)))
  1191. ...
  1192. x**(1 - y) + 1
  1193. See Also
  1194. ========
  1195. subs: substitution of subexpressions as defined by the objects
  1196. themselves.
  1197. xreplace: exact node replacement in expr tree; also capable of
  1198. using matching rules
  1199. """
  1200. try:
  1201. query = _sympify(query)
  1202. except SympifyError:
  1203. pass
  1204. try:
  1205. value = _sympify(value)
  1206. except SympifyError:
  1207. pass
  1208. if isinstance(query, type):
  1209. _query = lambda expr: isinstance(expr, query)
  1210. if isinstance(value, type):
  1211. _value = lambda expr, result: value(*expr.args)
  1212. elif callable(value):
  1213. _value = lambda expr, result: value(*expr.args)
  1214. else:
  1215. raise TypeError(
  1216. "given a type, replace() expects another "
  1217. "type or a callable")
  1218. elif isinstance(query, Basic):
  1219. _query = lambda expr: expr.match(query)
  1220. if exact is None:
  1221. from .symbol import Wild
  1222. exact = (len(query.atoms(Wild)) > 1)
  1223. if isinstance(value, Basic):
  1224. if exact:
  1225. _value = lambda expr, result: (value.subs(result)
  1226. if all(result.values()) else expr)
  1227. else:
  1228. _value = lambda expr, result: value.subs(result)
  1229. elif callable(value):
  1230. # match dictionary keys get the trailing underscore stripped
  1231. # from them and are then passed as keywords to the callable;
  1232. # if ``exact`` is True, only accept match if there are no null
  1233. # values amongst those matched.
  1234. if exact:
  1235. _value = lambda expr, result: (value(**
  1236. {str(k)[:-1]: v for k, v in result.items()})
  1237. if all(val for val in result.values()) else expr)
  1238. else:
  1239. _value = lambda expr, result: value(**
  1240. {str(k)[:-1]: v for k, v in result.items()})
  1241. else:
  1242. raise TypeError(
  1243. "given an expression, replace() expects "
  1244. "another expression or a callable")
  1245. elif callable(query):
  1246. _query = query
  1247. if callable(value):
  1248. _value = lambda expr, result: value(expr)
  1249. else:
  1250. raise TypeError(
  1251. "given a callable, replace() expects "
  1252. "another callable")
  1253. else:
  1254. raise TypeError(
  1255. "first argument to replace() must be a "
  1256. "type, an expression or a callable")
  1257. def walk(rv, F):
  1258. """Apply ``F`` to args and then to result.
  1259. """
  1260. args = getattr(rv, 'args', None)
  1261. if args is not None:
  1262. if args:
  1263. newargs = tuple([walk(a, F) for a in args])
  1264. if args != newargs:
  1265. rv = rv.func(*newargs)
  1266. if simultaneous:
  1267. # if rv is something that was already
  1268. # matched (that was changed) then skip
  1269. # applying F again
  1270. for i, e in enumerate(args):
  1271. if rv == e and e != newargs[i]:
  1272. return rv
  1273. rv = F(rv)
  1274. return rv
  1275. mapping = {} # changes that took place
  1276. def rec_replace(expr):
  1277. result = _query(expr)
  1278. if result or result == {}:
  1279. v = _value(expr, result)
  1280. if v is not None and v != expr:
  1281. if map:
  1282. mapping[expr] = v
  1283. expr = v
  1284. return expr
  1285. rv = walk(self, rec_replace)
  1286. return (rv, mapping) if map else rv
  1287. def find(self, query, group=False):
  1288. """Find all subexpressions matching a query. """
  1289. query = _make_find_query(query)
  1290. results = list(filter(query, _preorder_traversal(self)))
  1291. if not group:
  1292. return set(results)
  1293. else:
  1294. groups = {}
  1295. for result in results:
  1296. if result in groups:
  1297. groups[result] += 1
  1298. else:
  1299. groups[result] = 1
  1300. return groups
  1301. def count(self, query):
  1302. """Count the number of matching subexpressions. """
  1303. query = _make_find_query(query)
  1304. return sum(bool(query(sub)) for sub in _preorder_traversal(self))
  1305. def matches(self, expr, repl_dict=None, old=False):
  1306. """
  1307. Helper method for match() that looks for a match between Wild symbols
  1308. in self and expressions in expr.
  1309. Examples
  1310. ========
  1311. >>> from sympy import symbols, Wild, Basic
  1312. >>> a, b, c = symbols('a b c')
  1313. >>> x = Wild('x')
  1314. >>> Basic(a + x, x).matches(Basic(a + b, c)) is None
  1315. True
  1316. >>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
  1317. {x_: b + c}
  1318. """
  1319. expr = sympify(expr)
  1320. if not isinstance(expr, self.__class__):
  1321. return None
  1322. if repl_dict is None:
  1323. repl_dict = dict()
  1324. else:
  1325. repl_dict = repl_dict.copy()
  1326. if self == expr:
  1327. return repl_dict
  1328. if len(self.args) != len(expr.args):
  1329. return None
  1330. d = repl_dict # already a copy
  1331. for arg, other_arg in zip(self.args, expr.args):
  1332. if arg == other_arg:
  1333. continue
  1334. if arg.is_Relational:
  1335. try:
  1336. d = arg.xreplace(d).matches(other_arg, d, old=old)
  1337. except TypeError: # Should be InvalidComparisonError when introduced
  1338. d = None
  1339. else:
  1340. d = arg.xreplace(d).matches(other_arg, d, old=old)
  1341. if d is None:
  1342. return None
  1343. return d
  1344. def match(self, pattern, old=False):
  1345. """
  1346. Pattern matching.
  1347. Wild symbols match all.
  1348. Return ``None`` when expression (self) does not match
  1349. with pattern. Otherwise return a dictionary such that::
  1350. pattern.xreplace(self.match(pattern)) == self
  1351. Examples
  1352. ========
  1353. >>> from sympy import Wild, Sum
  1354. >>> from sympy.abc import x, y
  1355. >>> p = Wild("p")
  1356. >>> q = Wild("q")
  1357. >>> r = Wild("r")
  1358. >>> e = (x+y)**(x+y)
  1359. >>> e.match(p**p)
  1360. {p_: x + y}
  1361. >>> e.match(p**q)
  1362. {p_: x + y, q_: x + y}
  1363. >>> e = (2*x)**2
  1364. >>> e.match(p*q**r)
  1365. {p_: 4, q_: x, r_: 2}
  1366. >>> (p*q**r).xreplace(e.match(p*q**r))
  1367. 4*x**2
  1368. Structurally bound symbols are ignored during matching:
  1369. >>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))
  1370. {p_: 2}
  1371. But they can be identified if desired:
  1372. >>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p)))
  1373. {p_: 2, q_: x}
  1374. The ``old`` flag will give the old-style pattern matching where
  1375. expressions and patterns are essentially solved to give the
  1376. match. Both of the following give None unless ``old=True``:
  1377. >>> (x - 2).match(p - x, old=True)
  1378. {p_: 2*x - 2}
  1379. >>> (2/x).match(p*x, old=True)
  1380. {p_: 2/x**2}
  1381. """
  1382. pattern = sympify(pattern)
  1383. # match non-bound symbols
  1384. canonical = lambda x: x if x.is_Symbol else x.as_dummy()
  1385. m = canonical(pattern).matches(canonical(self), old=old)
  1386. if m is None:
  1387. return m
  1388. from .symbol import Wild
  1389. from .function import WildFunction
  1390. wild = pattern.atoms(Wild, WildFunction)
  1391. # sanity check
  1392. if set(m) - wild:
  1393. raise ValueError(filldedent('''
  1394. Some `matches` routine did not use a copy of repl_dict
  1395. and injected unexpected symbols. Report this as an
  1396. error at https://github.com/sympy/sympy/issues'''))
  1397. # now see if bound symbols were requested
  1398. bwild = wild - set(m)
  1399. if not bwild:
  1400. return m
  1401. # replace free-Wild symbols in pattern with match result
  1402. # so they will match but not be in the next match
  1403. wpat = pattern.xreplace(m)
  1404. # identify remaining bound wild
  1405. w = wpat.matches(self, old=old)
  1406. # add them to m
  1407. if w:
  1408. m.update(w)
  1409. # done
  1410. return m
  1411. def count_ops(self, visual=None):
  1412. """wrapper for count_ops that returns the operation count."""
  1413. from .function import count_ops
  1414. return count_ops(self, visual)
  1415. def doit(self, **hints):
  1416. """Evaluate objects that are not evaluated by default like limits,
  1417. integrals, sums and products. All objects of this kind will be
  1418. evaluated recursively, unless some species were excluded via 'hints'
  1419. or unless the 'deep' hint was set to 'False'.
  1420. >>> from sympy import Integral
  1421. >>> from sympy.abc import x
  1422. >>> 2*Integral(x, x)
  1423. 2*Integral(x, x)
  1424. >>> (2*Integral(x, x)).doit()
  1425. x**2
  1426. >>> (2*Integral(x, x)).doit(deep=False)
  1427. 2*Integral(x, x)
  1428. """
  1429. if hints.get('deep', True):
  1430. terms = [term.doit(**hints) if isinstance(term, Basic) else term
  1431. for term in self.args]
  1432. return self.func(*terms)
  1433. else:
  1434. return self
  1435. def simplify(self, **kwargs):
  1436. """See the simplify function in sympy.simplify"""
  1437. from sympy.simplify.simplify import simplify
  1438. return simplify(self, **kwargs)
  1439. def refine(self, assumption=True):
  1440. """See the refine function in sympy.assumptions"""
  1441. from sympy.assumptions.refine import refine
  1442. return refine(self, assumption)
  1443. def _eval_derivative_n_times(self, s, n):
  1444. # This is the default evaluator for derivatives (as called by `diff`
  1445. # and `Derivative`), it will attempt a loop to derive the expression
  1446. # `n` times by calling the corresponding `_eval_derivative` method,
  1447. # while leaving the derivative unevaluated if `n` is symbolic. This
  1448. # method should be overridden if the object has a closed form for its
  1449. # symbolic n-th derivative.
  1450. from .numbers import Integer
  1451. if isinstance(n, (int, Integer)):
  1452. obj = self
  1453. for i in range(n):
  1454. obj2 = obj._eval_derivative(s)
  1455. if obj == obj2 or obj2 is None:
  1456. break
  1457. obj = obj2
  1458. return obj2
  1459. else:
  1460. return None
  1461. def rewrite(self, *args, deep=True, **hints):
  1462. """
  1463. Rewrite *self* using a defined rule.
  1464. Rewriting transforms an expression to another, which is mathematically
  1465. equivalent but structurally different. For example you can rewrite
  1466. trigonometric functions as complex exponentials or combinatorial
  1467. functions as gamma function.
  1468. This method takes a *pattern* and a *rule* as positional arguments.
  1469. *pattern* is optional parameter which defines the types of expressions
  1470. that will be transformed. If it is not passed, all possible expressions
  1471. will be rewritten. *rule* defines how the expression will be rewritten.
  1472. Parameters
  1473. ==========
  1474. args : *rule*, or *pattern* and *rule*.
  1475. - *pattern* is a type or an iterable of types.
  1476. - *rule* can be any object.
  1477. deep : bool, optional.
  1478. If ``True``, subexpressions are recursively transformed. Default is
  1479. ``True``.
  1480. Examples
  1481. ========
  1482. If *pattern* is unspecified, all possible expressions are transformed.
  1483. >>> from sympy import cos, sin, exp, I
  1484. >>> from sympy.abc import x
  1485. >>> expr = cos(x) + I*sin(x)
  1486. >>> expr.rewrite(exp)
  1487. exp(I*x)
  1488. Pattern can be a type or an iterable of types.
  1489. >>> expr.rewrite(sin, exp)
  1490. exp(I*x)/2 + cos(x) - exp(-I*x)/2
  1491. >>> expr.rewrite([cos,], exp)
  1492. exp(I*x)/2 + I*sin(x) + exp(-I*x)/2
  1493. >>> expr.rewrite([cos, sin], exp)
  1494. exp(I*x)
  1495. Rewriting behavior can be implemented by defining ``_eval_rewrite()``
  1496. method.
  1497. >>> from sympy import Expr, sqrt, pi
  1498. >>> class MySin(Expr):
  1499. ... def _eval_rewrite(self, rule, args, **hints):
  1500. ... x, = args
  1501. ... if rule == cos:
  1502. ... return cos(pi/2 - x, evaluate=False)
  1503. ... if rule == sqrt:
  1504. ... return sqrt(1 - cos(x)**2)
  1505. >>> MySin(MySin(x)).rewrite(cos)
  1506. cos(-cos(-x + pi/2) + pi/2)
  1507. >>> MySin(x).rewrite(sqrt)
  1508. sqrt(1 - cos(x)**2)
  1509. Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards
  1510. compatibility reason. This may be removed in the future and using it is
  1511. discouraged.
  1512. >>> class MySin(Expr):
  1513. ... def _eval_rewrite_as_cos(self, *args, **hints):
  1514. ... x, = args
  1515. ... return cos(pi/2 - x, evaluate=False)
  1516. >>> MySin(x).rewrite(cos)
  1517. cos(-x + pi/2)
  1518. """
  1519. if not args:
  1520. return self
  1521. hints.update(deep=deep)
  1522. pattern = args[:-1]
  1523. rule = args[-1]
  1524. # support old design by _eval_rewrite_as_[...] method
  1525. if isinstance(rule, str):
  1526. method = "_eval_rewrite_as_%s" % rule
  1527. elif hasattr(rule, "__name__"):
  1528. # rule is class or function
  1529. clsname = rule.__name__
  1530. method = "_eval_rewrite_as_%s" % clsname
  1531. else:
  1532. # rule is instance
  1533. clsname = rule.__class__.__name__
  1534. method = "_eval_rewrite_as_%s" % clsname
  1535. if pattern:
  1536. if iterable(pattern[0]):
  1537. pattern = pattern[0]
  1538. pattern = tuple(p for p in pattern if self.has(p))
  1539. if not pattern:
  1540. return self
  1541. # hereafter, empty pattern is interpreted as all pattern.
  1542. return self._rewrite(pattern, rule, method, **hints)
  1543. def _rewrite(self, pattern, rule, method, **hints):
  1544. deep = hints.pop('deep', True)
  1545. if deep:
  1546. args = [a._rewrite(pattern, rule, method, **hints)
  1547. for a in self.args]
  1548. else:
  1549. args = self.args
  1550. if not pattern or any(isinstance(self, p) for p in pattern):
  1551. meth = getattr(self, method, None)
  1552. if meth is not None:
  1553. rewritten = meth(*args, **hints)
  1554. else:
  1555. rewritten = self._eval_rewrite(rule, args, **hints)
  1556. if rewritten is not None:
  1557. return rewritten
  1558. if not args:
  1559. return self
  1560. return self.func(*args)
  1561. def _eval_rewrite(self, rule, args, **hints):
  1562. return None
  1563. _constructor_postprocessor_mapping = {} # type: ignore
  1564. @classmethod
  1565. def _exec_constructor_postprocessors(cls, obj):
  1566. # WARNING: This API is experimental.
  1567. # This is an experimental API that introduces constructor
  1568. # postprosessors for SymPy Core elements. If an argument of a SymPy
  1569. # expression has a `_constructor_postprocessor_mapping` attribute, it will
  1570. # be interpreted as a dictionary containing lists of postprocessing
  1571. # functions for matching expression node names.
  1572. clsname = obj.__class__.__name__
  1573. postprocessors = defaultdict(list)
  1574. for i in obj.args:
  1575. try:
  1576. postprocessor_mappings = (
  1577. Basic._constructor_postprocessor_mapping[cls].items()
  1578. for cls in type(i).mro()
  1579. if cls in Basic._constructor_postprocessor_mapping
  1580. )
  1581. for k, v in chain.from_iterable(postprocessor_mappings):
  1582. postprocessors[k].extend([j for j in v if j not in postprocessors[k]])
  1583. except TypeError:
  1584. pass
  1585. for f in postprocessors.get(clsname, []):
  1586. obj = f(obj)
  1587. return obj
  1588. def _sage_(self):
  1589. """
  1590. Convert *self* to a symbolic expression of SageMath.
  1591. This version of the method is merely a placeholder.
  1592. """
  1593. old_method = self._sage_
  1594. from sage.interfaces.sympy import sympy_init
  1595. sympy_init() # may monkey-patch _sage_ method into self's class or superclasses
  1596. if old_method == self._sage_:
  1597. raise NotImplementedError('conversion to SageMath is not implemented')
  1598. else:
  1599. # call the freshly monkey-patched method
  1600. return self._sage_()
  1601. def could_extract_minus_sign(self):
  1602. return False # see Expr.could_extract_minus_sign
  1603. class Atom(Basic):
  1604. """
  1605. A parent class for atomic things. An atom is an expression with no subexpressions.
  1606. Examples
  1607. ========
  1608. Symbol, Number, Rational, Integer, ...
  1609. But not: Add, Mul, Pow, ...
  1610. """
  1611. is_Atom = True
  1612. __slots__ = ()
  1613. def matches(self, expr, repl_dict=None, old=False):
  1614. if self == expr:
  1615. if repl_dict is None:
  1616. return dict()
  1617. return repl_dict.copy()
  1618. def xreplace(self, rule, hack2=False):
  1619. return rule.get(self, self)
  1620. def doit(self, **hints):
  1621. return self
  1622. @classmethod
  1623. def class_key(cls):
  1624. return 2, 0, cls.__name__
  1625. @cacheit
  1626. def sort_key(self, order=None):
  1627. return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One
  1628. def _eval_simplify(self, **kwargs):
  1629. return self
  1630. @property
  1631. def _sorted_args(self):
  1632. # this is here as a safeguard against accidentally using _sorted_args
  1633. # on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args)
  1634. # since there are no args. So the calling routine should be checking
  1635. # to see that this property is not called for Atoms.
  1636. raise AttributeError('Atoms have no args. It might be necessary'
  1637. ' to make a check for Atoms in the calling code.')
  1638. def _aresame(a, b):
  1639. """Return True if a and b are structurally the same, else False.
  1640. Examples
  1641. ========
  1642. In SymPy (as in Python) two numbers compare the same if they
  1643. have the same underlying base-2 representation even though
  1644. they may not be the same type:
  1645. >>> from sympy import S
  1646. >>> 2.0 == S(2)
  1647. True
  1648. >>> 0.5 == S.Half
  1649. True
  1650. This routine was written to provide a query for such cases that
  1651. would give false when the types do not match:
  1652. >>> from sympy.core.basic import _aresame
  1653. >>> _aresame(S(2.0), S(2))
  1654. False
  1655. """
  1656. from .numbers import Number
  1657. from .function import AppliedUndef, UndefinedFunction as UndefFunc
  1658. if isinstance(a, Number) and isinstance(b, Number):
  1659. return a == b and a.__class__ == b.__class__
  1660. for i, j in zip_longest(_preorder_traversal(a), _preorder_traversal(b)):
  1661. if i != j or type(i) != type(j):
  1662. if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or
  1663. (isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))):
  1664. if i.class_key() != j.class_key():
  1665. return False
  1666. else:
  1667. return False
  1668. return True
  1669. def _ne(a, b):
  1670. # use this as a second test after `a != b` if you want to make
  1671. # sure that things are truly equal, e.g.
  1672. # a, b = 0.5, S.Half
  1673. # a !=b or _ne(a, b) -> True
  1674. from .numbers import Number
  1675. # 0.5 == S.Half
  1676. if isinstance(a, Number) and isinstance(b, Number):
  1677. return a.__class__ != b.__class__
  1678. def _atomic(e, recursive=False):
  1679. """Return atom-like quantities as far as substitution is
  1680. concerned: Derivatives, Functions and Symbols. Don't
  1681. return any 'atoms' that are inside such quantities unless
  1682. they also appear outside, too, unless `recursive` is True.
  1683. Examples
  1684. ========
  1685. >>> from sympy import Derivative, Function, cos
  1686. >>> from sympy.abc import x, y
  1687. >>> from sympy.core.basic import _atomic
  1688. >>> f = Function('f')
  1689. >>> _atomic(x + y)
  1690. {x, y}
  1691. >>> _atomic(x + f(y))
  1692. {x, f(y)}
  1693. >>> _atomic(Derivative(f(x), x) + cos(x) + y)
  1694. {y, cos(x), Derivative(f(x), x)}
  1695. """
  1696. pot = _preorder_traversal(e)
  1697. seen = set()
  1698. if isinstance(e, Basic):
  1699. free = getattr(e, "free_symbols", None)
  1700. if free is None:
  1701. return {e}
  1702. else:
  1703. return set()
  1704. from .symbol import Symbol
  1705. from .function import Derivative, Function
  1706. atoms = set()
  1707. for p in pot:
  1708. if p in seen:
  1709. pot.skip()
  1710. continue
  1711. seen.add(p)
  1712. if isinstance(p, Symbol) and p in free:
  1713. atoms.add(p)
  1714. elif isinstance(p, (Derivative, Function)):
  1715. if not recursive:
  1716. pot.skip()
  1717. atoms.add(p)
  1718. return atoms
  1719. def _make_find_query(query):
  1720. """Convert the argument of Basic.find() into a callable"""
  1721. try:
  1722. query = _sympify(query)
  1723. except SympifyError:
  1724. pass
  1725. if isinstance(query, type):
  1726. return lambda expr: isinstance(expr, query)
  1727. elif isinstance(query, Basic):
  1728. return lambda expr: expr.match(query) is not None
  1729. return query
  1730. # Delayed to avoid cyclic import
  1731. from .singleton import S
  1732. from .traversal import (preorder_traversal as _preorder_traversal,
  1733. iterargs, iterfreeargs)
  1734. preorder_traversal = deprecated(
  1735. """
  1736. Using preorder_traversal from the sympy.core.basic submodule is
  1737. deprecated.
  1738. Instead, use preorder_traversal from the top-level sympy namespace, like
  1739. sympy.preorder_traversal
  1740. """,
  1741. deprecated_since_version="1.10",
  1742. active_deprecations_target="deprecated-traversal-functions-moved",
  1743. )(_preorder_traversal)