assume.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. """A module which implements predicates and assumption context."""
  2. from contextlib import contextmanager
  3. import inspect
  4. from sympy.core.symbol import Str
  5. from sympy.core.sympify import _sympify
  6. from sympy.logic.boolalg import Boolean, false, true
  7. from sympy.multipledispatch.dispatcher import Dispatcher, str_signature
  8. from sympy.utilities.exceptions import sympy_deprecation_warning
  9. from sympy.utilities.iterables import is_sequence
  10. from sympy.utilities.source import get_class
  11. class AssumptionsContext(set):
  12. """
  13. Set containing default assumptions which are applied to the ``ask()``
  14. function.
  15. Explanation
  16. ===========
  17. This is used to represent global assumptions, but you can also use this
  18. class to create your own local assumptions contexts. It is basically a thin
  19. wrapper to Python's set, so see its documentation for advanced usage.
  20. Examples
  21. ========
  22. The default assumption context is ``global_assumptions``, which is initially empty:
  23. >>> from sympy import ask, Q
  24. >>> from sympy.assumptions import global_assumptions
  25. >>> global_assumptions
  26. AssumptionsContext()
  27. You can add default assumptions:
  28. >>> from sympy.abc import x
  29. >>> global_assumptions.add(Q.real(x))
  30. >>> global_assumptions
  31. AssumptionsContext({Q.real(x)})
  32. >>> ask(Q.real(x))
  33. True
  34. And remove them:
  35. >>> global_assumptions.remove(Q.real(x))
  36. >>> print(ask(Q.real(x)))
  37. None
  38. The ``clear()`` method removes every assumption:
  39. >>> global_assumptions.add(Q.positive(x))
  40. >>> global_assumptions
  41. AssumptionsContext({Q.positive(x)})
  42. >>> global_assumptions.clear()
  43. >>> global_assumptions
  44. AssumptionsContext()
  45. See Also
  46. ========
  47. assuming
  48. """
  49. def add(self, *assumptions):
  50. """Add assumptions."""
  51. for a in assumptions:
  52. super().add(a)
  53. def _sympystr(self, printer):
  54. if not self:
  55. return "%s()" % self.__class__.__name__
  56. return "{}({})".format(self.__class__.__name__, printer._print_set(self))
  57. global_assumptions = AssumptionsContext()
  58. class AppliedPredicate(Boolean):
  59. """
  60. The class of expressions resulting from applying ``Predicate`` to
  61. the arguments. ``AppliedPredicate`` merely wraps its argument and
  62. remain unevaluated. To evaluate it, use the ``ask()`` function.
  63. Examples
  64. ========
  65. >>> from sympy import Q, ask
  66. >>> Q.integer(1)
  67. Q.integer(1)
  68. The ``function`` attribute returns the predicate, and the ``arguments``
  69. attribute returns the tuple of arguments.
  70. >>> type(Q.integer(1))
  71. <class 'sympy.assumptions.assume.AppliedPredicate'>
  72. >>> Q.integer(1).function
  73. Q.integer
  74. >>> Q.integer(1).arguments
  75. (1,)
  76. Applied predicates can be evaluated to a boolean value with ``ask``:
  77. >>> ask(Q.integer(1))
  78. True
  79. """
  80. __slots__ = ()
  81. def __new__(cls, predicate, *args):
  82. if not isinstance(predicate, Predicate):
  83. raise TypeError("%s is not a Predicate." % predicate)
  84. args = map(_sympify, args)
  85. return super().__new__(cls, predicate, *args)
  86. @property
  87. def arg(self):
  88. """
  89. Return the expression used by this assumption.
  90. Examples
  91. ========
  92. >>> from sympy import Q, Symbol
  93. >>> x = Symbol('x')
  94. >>> a = Q.integer(x + 1)
  95. >>> a.arg
  96. x + 1
  97. """
  98. # Will be deprecated
  99. args = self._args
  100. if len(args) == 2:
  101. # backwards compatibility
  102. return args[1]
  103. raise TypeError("'arg' property is allowed only for unary predicates.")
  104. @property
  105. def function(self):
  106. """
  107. Return the predicate.
  108. """
  109. # Will be changed to self.args[0] after args overriding is removed
  110. return self._args[0]
  111. @property
  112. def arguments(self):
  113. """
  114. Return the arguments which are applied to the predicate.
  115. """
  116. # Will be changed to self.args[1:] after args overriding is removed
  117. return self._args[1:]
  118. def _eval_ask(self, assumptions):
  119. return self.function.eval(self.arguments, assumptions)
  120. @property
  121. def binary_symbols(self):
  122. from .ask import Q
  123. if self.function == Q.is_true:
  124. i = self.arguments[0]
  125. if i.is_Boolean or i.is_Symbol:
  126. return i.binary_symbols
  127. if self.function in (Q.eq, Q.ne):
  128. if true in self.arguments or false in self.arguments:
  129. if self.arguments[0].is_Symbol:
  130. return {self.arguments[0]}
  131. elif self.arguments[1].is_Symbol:
  132. return {self.arguments[1]}
  133. return set()
  134. class PredicateMeta(type):
  135. def __new__(cls, clsname, bases, dct):
  136. # If handler is not defined, assign empty dispatcher.
  137. if "handler" not in dct:
  138. name = f"Ask{clsname.capitalize()}Handler"
  139. handler = Dispatcher(name, doc="Handler for key %s" % name)
  140. dct["handler"] = handler
  141. dct["_orig_doc"] = dct.get("__doc__", "")
  142. return super().__new__(cls, clsname, bases, dct)
  143. @property
  144. def __doc__(cls):
  145. handler = cls.handler
  146. doc = cls._orig_doc
  147. if cls is not Predicate and handler is not None:
  148. doc += "Handler\n"
  149. doc += " =======\n\n"
  150. # Append the handler's doc without breaking sphinx documentation.
  151. docs = [" Multiply dispatched method: %s" % handler.name]
  152. if handler.doc:
  153. for line in handler.doc.splitlines():
  154. if not line:
  155. continue
  156. docs.append(" %s" % line)
  157. other = []
  158. for sig in handler.ordering[::-1]:
  159. func = handler.funcs[sig]
  160. if func.__doc__:
  161. s = ' Inputs: <%s>' % str_signature(sig)
  162. lines = []
  163. for line in func.__doc__.splitlines():
  164. lines.append(" %s" % line)
  165. s += "\n".join(lines)
  166. docs.append(s)
  167. else:
  168. other.append(str_signature(sig))
  169. if other:
  170. othersig = " Other signatures:"
  171. for line in other:
  172. othersig += "\n * %s" % line
  173. docs.append(othersig)
  174. doc += '\n\n'.join(docs)
  175. return doc
  176. class Predicate(Boolean, metaclass=PredicateMeta):
  177. """
  178. Base class for mathematical predicates. It also serves as a
  179. constructor for undefined predicate objects.
  180. Explanation
  181. ===========
  182. Predicate is a function that returns a boolean value [1].
  183. Predicate function is object, and it is instance of predicate class.
  184. When a predicate is applied to arguments, ``AppliedPredicate``
  185. instance is returned. This merely wraps the argument and remain
  186. unevaluated. To obtain the truth value of applied predicate, use the
  187. function ``ask``.
  188. Evaluation of predicate is done by multiple dispatching. You can
  189. register new handler to the predicate to support new types.
  190. Every predicate in SymPy can be accessed via the property of ``Q``.
  191. For example, ``Q.even`` returns the predicate which checks if the
  192. argument is even number.
  193. To define a predicate which can be evaluated, you must subclass this
  194. class, make an instance of it, and register it to ``Q``. After then,
  195. dispatch the handler by argument types.
  196. If you directly construct predicate using this class, you will get
  197. ``UndefinedPredicate`` which cannot be dispatched. This is useful
  198. when you are building boolean expressions which do not need to be
  199. evaluated.
  200. Examples
  201. ========
  202. Applying and evaluating to boolean value:
  203. >>> from sympy import Q, ask
  204. >>> ask(Q.prime(7))
  205. True
  206. You can define a new predicate by subclassing and dispatching. Here,
  207. we define a predicate for sexy primes [2] as an example.
  208. >>> from sympy import Predicate, Integer
  209. >>> class SexyPrimePredicate(Predicate):
  210. ... name = "sexyprime"
  211. >>> Q.sexyprime = SexyPrimePredicate()
  212. >>> @Q.sexyprime.register(Integer, Integer)
  213. ... def _(int1, int2, assumptions):
  214. ... args = sorted([int1, int2])
  215. ... if not all(ask(Q.prime(a), assumptions) for a in args):
  216. ... return False
  217. ... return args[1] - args[0] == 6
  218. >>> ask(Q.sexyprime(5, 11))
  219. True
  220. Direct constructing returns ``UndefinedPredicate``, which can be
  221. applied but cannot be dispatched.
  222. >>> from sympy import Predicate, Integer
  223. >>> Q.P = Predicate("P")
  224. >>> type(Q.P)
  225. <class 'sympy.assumptions.assume.UndefinedPredicate'>
  226. >>> Q.P(1)
  227. Q.P(1)
  228. >>> Q.P.register(Integer)(lambda expr, assump: True)
  229. Traceback (most recent call last):
  230. ...
  231. TypeError: <class 'sympy.assumptions.assume.UndefinedPredicate'> cannot be dispatched.
  232. References
  233. ==========
  234. .. [1] https://en.wikipedia.org/wiki/Predicate_%28mathematical_logic%29
  235. .. [2] https://en.wikipedia.org/wiki/Sexy_prime
  236. """
  237. is_Atom = True
  238. def __new__(cls, *args, **kwargs):
  239. if cls is Predicate:
  240. return UndefinedPredicate(*args, **kwargs)
  241. obj = super().__new__(cls, *args)
  242. return obj
  243. @property
  244. def name(self):
  245. # May be overridden
  246. return type(self).__name__
  247. @classmethod
  248. def register(cls, *types, **kwargs):
  249. """
  250. Register the signature to the handler.
  251. """
  252. if cls.handler is None:
  253. raise TypeError("%s cannot be dispatched." % type(cls))
  254. return cls.handler.register(*types, **kwargs)
  255. @classmethod
  256. def register_many(cls, *types, **kwargs):
  257. """
  258. Register multiple signatures to same handler.
  259. """
  260. def _(func):
  261. for t in types:
  262. if not is_sequence(t):
  263. t = (t,) # for convenience, allow passing `type` to mean `(type,)`
  264. cls.register(*t, **kwargs)(func)
  265. return _
  266. def __call__(self, *args):
  267. return AppliedPredicate(self, *args)
  268. def eval(self, args, assumptions=True):
  269. """
  270. Evaluate ``self(*args)`` under the given assumptions.
  271. This uses only direct resolution methods, not logical inference.
  272. """
  273. result = None
  274. try:
  275. result = self.handler(*args, assumptions=assumptions)
  276. except NotImplementedError:
  277. pass
  278. return result
  279. def _eval_refine(self, assumptions):
  280. # When Predicate is no longer Boolean, delete this method
  281. return self
  282. class UndefinedPredicate(Predicate):
  283. """
  284. Predicate without handler.
  285. Explanation
  286. ===========
  287. This predicate is generated by using ``Predicate`` directly for
  288. construction. It does not have a handler, and evaluating this with
  289. arguments is done by SAT solver.
  290. Examples
  291. ========
  292. >>> from sympy import Predicate, Q
  293. >>> Q.P = Predicate('P')
  294. >>> Q.P.func
  295. <class 'sympy.assumptions.assume.UndefinedPredicate'>
  296. >>> Q.P.name
  297. Str('P')
  298. """
  299. handler = None
  300. def __new__(cls, name, handlers=None):
  301. # "handlers" parameter supports old design
  302. if not isinstance(name, Str):
  303. name = Str(name)
  304. obj = super(Boolean, cls).__new__(cls, name)
  305. obj.handlers = handlers or []
  306. return obj
  307. @property
  308. def name(self):
  309. return self.args[0]
  310. def _hashable_content(self):
  311. return (self.name,)
  312. def __getnewargs__(self):
  313. return (self.name,)
  314. def __call__(self, expr):
  315. return AppliedPredicate(self, expr)
  316. def add_handler(self, handler):
  317. sympy_deprecation_warning(
  318. """
  319. The AskHandler system is deprecated. Predicate.add_handler()
  320. should be replaced with the multipledispatch handler of Predicate.
  321. """,
  322. deprecated_since_version="1.8",
  323. active_deprecations_target='deprecated-askhandler',
  324. )
  325. self.handlers.append(handler)
  326. def remove_handler(self, handler):
  327. sympy_deprecation_warning(
  328. """
  329. The AskHandler system is deprecated. Predicate.remove_handler()
  330. should be replaced with the multipledispatch handler of Predicate.
  331. """,
  332. deprecated_since_version="1.8",
  333. active_deprecations_target='deprecated-askhandler',
  334. )
  335. self.handlers.remove(handler)
  336. def eval(self, args, assumptions=True):
  337. # Support for deprecated design
  338. # When old design is removed, this will always return None
  339. sympy_deprecation_warning(
  340. """
  341. The AskHandler system is deprecated. Evaluating UndefinedPredicate
  342. objects should be replaced with the multipledispatch handler of
  343. Predicate.
  344. """,
  345. deprecated_since_version="1.8",
  346. active_deprecations_target='deprecated-askhandler',
  347. stacklevel=5,
  348. )
  349. expr, = args
  350. res, _res = None, None
  351. mro = inspect.getmro(type(expr))
  352. for handler in self.handlers:
  353. cls = get_class(handler)
  354. for subclass in mro:
  355. eval_ = getattr(cls, subclass.__name__, None)
  356. if eval_ is None:
  357. continue
  358. res = eval_(expr, assumptions)
  359. # Do not stop if value returned is None
  360. # Try to check for higher classes
  361. if res is None:
  362. continue
  363. if _res is None:
  364. _res = res
  365. else:
  366. # only check consistency if both resolutors have concluded
  367. if _res != res:
  368. raise ValueError('incompatible resolutors')
  369. break
  370. return res
  371. @contextmanager
  372. def assuming(*assumptions):
  373. """
  374. Context manager for assumptions.
  375. Examples
  376. ========
  377. >>> from sympy import assuming, Q, ask
  378. >>> from sympy.abc import x, y
  379. >>> print(ask(Q.integer(x + y)))
  380. None
  381. >>> with assuming(Q.integer(x), Q.integer(y)):
  382. ... print(ask(Q.integer(x + y)))
  383. True
  384. """
  385. old_global_assumptions = global_assumptions.copy()
  386. global_assumptions.update(assumptions)
  387. try:
  388. yield
  389. finally:
  390. global_assumptions.clear()
  391. global_assumptions.update(old_global_assumptions)