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.

618 lines
19 KiB

6 months ago
  1. """
  2. This module contains the machinery handling assumptions.
  3. Do also consider the guide :ref:`assumptions`.
  4. All symbolic objects have assumption attributes that can be accessed via
  5. ``.is_<assumption name>`` attribute.
  6. Assumptions determine certain properties of symbolic objects and can
  7. have 3 possible values: ``True``, ``False``, ``None``. ``True`` is returned if the
  8. object has the property and ``False`` is returned if it does not or cannot
  9. (i.e. does not make sense):
  10. >>> from sympy import I
  11. >>> I.is_algebraic
  12. True
  13. >>> I.is_real
  14. False
  15. >>> I.is_prime
  16. False
  17. When the property cannot be determined (or when a method is not
  18. implemented) ``None`` will be returned. For example, a generic symbol, ``x``,
  19. may or may not be positive so a value of ``None`` is returned for ``x.is_positive``.
  20. By default, all symbolic values are in the largest set in the given context
  21. without specifying the property. For example, a symbol that has a property
  22. being integer, is also real, complex, etc.
  23. Here follows a list of possible assumption names:
  24. .. glossary::
  25. commutative
  26. object commutes with any other object with
  27. respect to multiplication operation. See [12]_.
  28. complex
  29. object can have only values from the set
  30. of complex numbers. See [13]_.
  31. imaginary
  32. object value is a number that can be written as a real
  33. number multiplied by the imaginary unit ``I``. See
  34. [3]_. Please note that ``0`` is not considered to be an
  35. imaginary number, see
  36. `issue #7649 <https://github.com/sympy/sympy/issues/7649>`_.
  37. real
  38. object can have only values from the set
  39. of real numbers.
  40. extended_real
  41. object can have only values from the set
  42. of real numbers, ``oo`` and ``-oo``.
  43. integer
  44. object can have only values from the set
  45. of integers.
  46. odd
  47. even
  48. object can have only values from the set of
  49. odd (even) integers [2]_.
  50. prime
  51. object is a natural number greater than 1 that has
  52. no positive divisors other than 1 and itself. See [6]_.
  53. composite
  54. object is a positive integer that has at least one positive
  55. divisor other than 1 or the number itself. See [4]_.
  56. zero
  57. object has the value of 0.
  58. nonzero
  59. object is a real number that is not zero.
  60. rational
  61. object can have only values from the set
  62. of rationals.
  63. algebraic
  64. object can have only values from the set
  65. of algebraic numbers [11]_.
  66. transcendental
  67. object can have only values from the set
  68. of transcendental numbers [10]_.
  69. irrational
  70. object value cannot be represented exactly by :class:`~.Rational`, see [5]_.
  71. finite
  72. infinite
  73. object absolute value is bounded (arbitrarily large).
  74. See [7]_, [8]_, [9]_.
  75. negative
  76. nonnegative
  77. object can have only negative (nonnegative)
  78. values [1]_.
  79. positive
  80. nonpositive
  81. object can have only positive (nonpositive) values.
  82. extended_negative
  83. extended_nonnegative
  84. extended_positive
  85. extended_nonpositive
  86. extended_nonzero
  87. as without the extended part, but also including infinity with
  88. corresponding sign, e.g., extended_positive includes ``oo``
  89. hermitian
  90. antihermitian
  91. object belongs to the field of Hermitian
  92. (antihermitian) operators.
  93. Examples
  94. ========
  95. >>> from sympy import Symbol
  96. >>> x = Symbol('x', real=True); x
  97. x
  98. >>> x.is_real
  99. True
  100. >>> x.is_complex
  101. True
  102. See Also
  103. ========
  104. .. seealso::
  105. :py:class:`sympy.core.numbers.ImaginaryUnit`
  106. :py:class:`sympy.core.numbers.Zero`
  107. :py:class:`sympy.core.numbers.One`
  108. :py:class:`sympy.core.numbers.Infinity`
  109. :py:class:`sympy.core.numbers.NegativeInfinity`
  110. :py:class:`sympy.core.numbers.ComplexInfinity`
  111. Notes
  112. =====
  113. The fully-resolved assumptions for any SymPy expression
  114. can be obtained as follows:
  115. >>> from sympy.core.assumptions import assumptions
  116. >>> x = Symbol('x',positive=True)
  117. >>> assumptions(x + I)
  118. {'commutative': True, 'complex': True, 'composite': False, 'even':
  119. False, 'extended_negative': False, 'extended_nonnegative': False,
  120. 'extended_nonpositive': False, 'extended_nonzero': False,
  121. 'extended_positive': False, 'extended_real': False, 'finite': True,
  122. 'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
  123. False, 'negative': False, 'noninteger': False, 'nonnegative': False,
  124. 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
  125. False, 'prime': False, 'rational': False, 'real': False, 'zero':
  126. False}
  127. Developers Notes
  128. ================
  129. The current (and possibly incomplete) values are stored
  130. in the ``obj._assumptions dictionary``; queries to getter methods
  131. (with property decorators) or attributes of objects/classes
  132. will return values and update the dictionary.
  133. >>> eq = x**2 + I
  134. >>> eq._assumptions
  135. {}
  136. >>> eq.is_finite
  137. True
  138. >>> eq._assumptions
  139. {'finite': True, 'infinite': False}
  140. For a :class:`~.Symbol`, there are two locations for assumptions that may
  141. be of interest. The ``assumptions0`` attribute gives the full set of
  142. assumptions derived from a given set of initial assumptions. The
  143. latter assumptions are stored as ``Symbol._assumptions.generator``
  144. >>> Symbol('x', prime=True, even=True)._assumptions.generator
  145. {'even': True, 'prime': True}
  146. The ``generator`` is not necessarily canonical nor is it filtered
  147. in any way: it records the assumptions used to instantiate a Symbol
  148. and (for storage purposes) represents a more compact representation
  149. of the assumptions needed to recreate the full set in
  150. ``Symbol.assumptions0``.
  151. References
  152. ==========
  153. .. [1] https://en.wikipedia.org/wiki/Negative_number
  154. .. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29
  155. .. [3] https://en.wikipedia.org/wiki/Imaginary_number
  156. .. [4] https://en.wikipedia.org/wiki/Composite_number
  157. .. [5] https://en.wikipedia.org/wiki/Irrational_number
  158. .. [6] https://en.wikipedia.org/wiki/Prime_number
  159. .. [7] https://en.wikipedia.org/wiki/Finite
  160. .. [8] https://docs.python.org/3/library/math.html#math.isfinite
  161. .. [9] http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html
  162. .. [10] https://en.wikipedia.org/wiki/Transcendental_number
  163. .. [11] https://en.wikipedia.org/wiki/Algebraic_number
  164. .. [12] https://en.wikipedia.org/wiki/Commutative_property
  165. .. [13] https://en.wikipedia.org/wiki/Complex_number
  166. """
  167. from .facts import FactRules, FactKB, InconsistentAssumptions
  168. from .core import BasicMeta
  169. from .sympify import sympify
  170. from sympy.core.random import shuffle
  171. _assume_rules = FactRules([
  172. 'integer -> rational',
  173. 'rational -> real',
  174. 'rational -> algebraic',
  175. 'algebraic -> complex',
  176. 'transcendental == complex & !algebraic',
  177. 'real -> hermitian',
  178. 'imaginary -> complex',
  179. 'imaginary -> antihermitian',
  180. 'extended_real -> commutative',
  181. 'complex -> commutative',
  182. 'complex -> finite',
  183. 'odd == integer & !even',
  184. 'even == integer & !odd',
  185. 'real -> complex',
  186. 'extended_real -> real | infinite',
  187. 'real == extended_real & finite',
  188. 'extended_real == extended_negative | zero | extended_positive',
  189. 'extended_negative == extended_nonpositive & extended_nonzero',
  190. 'extended_positive == extended_nonnegative & extended_nonzero',
  191. 'extended_nonpositive == extended_real & !extended_positive',
  192. 'extended_nonnegative == extended_real & !extended_negative',
  193. 'real == negative | zero | positive',
  194. 'negative == nonpositive & nonzero',
  195. 'positive == nonnegative & nonzero',
  196. 'nonpositive == real & !positive',
  197. 'nonnegative == real & !negative',
  198. 'positive == extended_positive & finite',
  199. 'negative == extended_negative & finite',
  200. 'nonpositive == extended_nonpositive & finite',
  201. 'nonnegative == extended_nonnegative & finite',
  202. 'nonzero == extended_nonzero & finite',
  203. 'zero -> even & finite',
  204. 'zero == extended_nonnegative & extended_nonpositive',
  205. 'zero == nonnegative & nonpositive',
  206. 'nonzero -> real',
  207. 'prime -> integer & positive',
  208. 'composite -> integer & positive & !prime',
  209. '!composite -> !positive | !even | prime',
  210. 'irrational == real & !rational',
  211. 'imaginary -> !extended_real',
  212. 'infinite == !finite',
  213. 'noninteger == extended_real & !integer',
  214. 'extended_nonzero == extended_real & !zero',
  215. ])
  216. _assume_defined = _assume_rules.defined_facts.copy()
  217. _assume_defined.add('polar')
  218. _assume_defined = frozenset(_assume_defined)
  219. def assumptions(expr, _check=None):
  220. """return the T/F assumptions of ``expr``"""
  221. n = sympify(expr)
  222. if n.is_Symbol:
  223. rv = n.assumptions0 # are any important ones missing?
  224. if _check is not None:
  225. rv = {k: rv[k] for k in set(rv) & set(_check)}
  226. return rv
  227. rv = {}
  228. for k in _assume_defined if _check is None else _check:
  229. v = getattr(n, 'is_{}'.format(k))
  230. if v is not None:
  231. rv[k] = v
  232. return rv
  233. def common_assumptions(exprs, check=None):
  234. """return those assumptions which have the same True or False
  235. value for all the given expressions.
  236. Examples
  237. ========
  238. >>> from sympy.core import common_assumptions
  239. >>> from sympy import oo, pi, sqrt
  240. >>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo])
  241. {'commutative': True, 'composite': False,
  242. 'extended_real': True, 'imaginary': False, 'odd': False}
  243. By default, all assumptions are tested; pass an iterable of the
  244. assumptions to limit those that are reported:
  245. >>> common_assumptions([0, 1, 2], ['positive', 'integer'])
  246. {'integer': True}
  247. """
  248. check = _assume_defined if check is None else set(check)
  249. if not check or not exprs:
  250. return {}
  251. # get all assumptions for each
  252. assume = [assumptions(i, _check=check) for i in sympify(exprs)]
  253. # focus on those of interest that are True
  254. for i, e in enumerate(assume):
  255. assume[i] = {k: e[k] for k in set(e) & check}
  256. # what assumptions are in common?
  257. common = set.intersection(*[set(i) for i in assume])
  258. # which ones hold the same value
  259. a = assume[0]
  260. return {k: a[k] for k in common if all(a[k] == b[k]
  261. for b in assume)}
  262. def failing_assumptions(expr, **assumptions):
  263. """
  264. Return a dictionary containing assumptions with values not
  265. matching those of the passed assumptions.
  266. Examples
  267. ========
  268. >>> from sympy import failing_assumptions, Symbol
  269. >>> x = Symbol('x', positive=True)
  270. >>> y = Symbol('y')
  271. >>> failing_assumptions(6*x + y, positive=True)
  272. {'positive': None}
  273. >>> failing_assumptions(x**2 - 1, positive=True)
  274. {'positive': None}
  275. If *expr* satisfies all of the assumptions, an empty dictionary is returned.
  276. >>> failing_assumptions(x**2, positive=True)
  277. {}
  278. """
  279. expr = sympify(expr)
  280. failed = {}
  281. for k in assumptions:
  282. test = getattr(expr, 'is_%s' % k, None)
  283. if test is not assumptions[k]:
  284. failed[k] = test
  285. return failed # {} or {assumption: value != desired}
  286. def check_assumptions(expr, against=None, **assume):
  287. """
  288. Checks whether assumptions of ``expr`` match the T/F assumptions
  289. given (or possessed by ``against``). True is returned if all
  290. assumptions match; False is returned if there is a mismatch and
  291. the assumption in ``expr`` is not None; else None is returned.
  292. Explanation
  293. ===========
  294. *assume* is a dict of assumptions with True or False values
  295. Examples
  296. ========
  297. >>> from sympy import Symbol, pi, I, exp, check_assumptions
  298. >>> check_assumptions(-5, integer=True)
  299. True
  300. >>> check_assumptions(pi, real=True, integer=False)
  301. True
  302. >>> check_assumptions(pi, negative=True)
  303. False
  304. >>> check_assumptions(exp(I*pi/7), real=False)
  305. True
  306. >>> x = Symbol('x', positive=True)
  307. >>> check_assumptions(2*x + 1, positive=True)
  308. True
  309. >>> check_assumptions(-2*x - 5, positive=True)
  310. False
  311. To check assumptions of *expr* against another variable or expression,
  312. pass the expression or variable as ``against``.
  313. >>> check_assumptions(2*x + 1, x)
  314. True
  315. To see if a number matches the assumptions of an expression, pass
  316. the number as the first argument, else its specific assumptions
  317. may not have a non-None value in the expression:
  318. >>> check_assumptions(x, 3)
  319. >>> check_assumptions(3, x)
  320. True
  321. ``None`` is returned if ``check_assumptions()`` could not conclude.
  322. >>> check_assumptions(2*x - 1, x)
  323. >>> z = Symbol('z')
  324. >>> check_assumptions(z, real=True)
  325. See Also
  326. ========
  327. failing_assumptions
  328. """
  329. expr = sympify(expr)
  330. if against is not None:
  331. if assume:
  332. raise ValueError(
  333. 'Expecting `against` or `assume`, not both.')
  334. assume = assumptions(against)
  335. known = True
  336. for k, v in assume.items():
  337. if v is None:
  338. continue
  339. e = getattr(expr, 'is_' + k, None)
  340. if e is None:
  341. known = None
  342. elif v != e:
  343. return False
  344. return known
  345. class StdFactKB(FactKB):
  346. """A FactKB specialized for the built-in rules
  347. This is the only kind of FactKB that Basic objects should use.
  348. """
  349. def __init__(self, facts=None):
  350. super().__init__(_assume_rules)
  351. # save a copy of the facts dict
  352. if not facts:
  353. self._generator = {}
  354. elif not isinstance(facts, FactKB):
  355. self._generator = facts.copy()
  356. else:
  357. self._generator = facts.generator
  358. if facts:
  359. self.deduce_all_facts(facts)
  360. def copy(self):
  361. return self.__class__(self)
  362. @property
  363. def generator(self):
  364. return self._generator.copy()
  365. def as_property(fact):
  366. """Convert a fact name to the name of the corresponding property"""
  367. return 'is_%s' % fact
  368. def make_property(fact):
  369. """Create the automagic property corresponding to a fact."""
  370. def getit(self):
  371. try:
  372. return self._assumptions[fact]
  373. except KeyError:
  374. if self._assumptions is self.default_assumptions:
  375. self._assumptions = self.default_assumptions.copy()
  376. return _ask(fact, self)
  377. getit.func_name = as_property(fact)
  378. return property(getit)
  379. def _ask(fact, obj):
  380. """
  381. Find the truth value for a property of an object.
  382. This function is called when a request is made to see what a fact
  383. value is.
  384. For this we use several techniques:
  385. First, the fact-evaluation function is tried, if it exists (for
  386. example _eval_is_integer). Then we try related facts. For example
  387. rational --> integer
  388. another example is joined rule:
  389. integer & !odd --> even
  390. so in the latter case if we are looking at what 'even' value is,
  391. 'integer' and 'odd' facts will be asked.
  392. In all cases, when we settle on some fact value, its implications are
  393. deduced, and the result is cached in ._assumptions.
  394. """
  395. assumptions = obj._assumptions
  396. handler_map = obj._prop_handler
  397. # Store None into the assumptions so that recursive attempts at
  398. # evaluating the same fact don't trigger infinite recursion.
  399. #
  400. # Potentially in a multithreaded context it is possible that the
  401. # assumptions query for fact was already resolved in another thread. If
  402. # that happens and the query was resolved as True or False then
  403. # assumptions._tell will raise InconsistentAssumptions because of the
  404. # attempt to replace True/False with None. In that case it should be safe
  405. # to catch the exception and return the result that was computed in the
  406. # other thread.
  407. #
  408. # XXX: Ideally this call to assumptions._tell would be removed. Its purpose
  409. # is to guard against infinite recursion if a query for one fact attempts
  410. # to evaluate a related fact for the same object. However really this is
  411. # just masking bugs because a query for a fact about obj should only query
  412. # the properties of obj.args and not obj itself. This is not easy to change
  413. # though because it requires fixing all of the buggy _eval_is_* handlers.
  414. try:
  415. assumptions._tell(fact, None)
  416. except InconsistentAssumptions:
  417. return assumptions[fact]
  418. # First try the assumption evaluation function if it exists
  419. try:
  420. evaluate = handler_map[fact]
  421. except KeyError:
  422. pass
  423. else:
  424. a = evaluate(obj)
  425. if a is not None:
  426. assumptions.deduce_all_facts(((fact, a),))
  427. return a
  428. # Try assumption's prerequisites
  429. prereq = list(_assume_rules.prereq[fact])
  430. shuffle(prereq)
  431. for pk in prereq:
  432. if pk in assumptions:
  433. continue
  434. if pk in handler_map:
  435. _ask(pk, obj)
  436. # we might have found the value of fact
  437. ret_val = assumptions.get(fact)
  438. if ret_val is not None:
  439. return ret_val
  440. # Note: the result has already been cached
  441. return None
  442. class ManagedProperties(BasicMeta):
  443. """Metaclass for classes with old-style assumptions"""
  444. def __init__(cls, *args, **kws):
  445. BasicMeta.__init__(cls, *args, **kws)
  446. local_defs = {}
  447. for k in _assume_defined:
  448. attrname = as_property(k)
  449. v = cls.__dict__.get(attrname, '')
  450. if isinstance(v, (bool, int, type(None))):
  451. if v is not None:
  452. v = bool(v)
  453. local_defs[k] = v
  454. defs = {}
  455. for base in reversed(cls.__bases__):
  456. assumptions = getattr(base, '_explicit_class_assumptions', None)
  457. if assumptions is not None:
  458. defs.update(assumptions)
  459. defs.update(local_defs)
  460. cls._explicit_class_assumptions = defs
  461. cls.default_assumptions = StdFactKB(defs)
  462. cls._prop_handler = {}
  463. for k in _assume_defined:
  464. eval_is_meth = getattr(cls, '_eval_is_%s' % k, None)
  465. if eval_is_meth is not None:
  466. cls._prop_handler[k] = eval_is_meth
  467. # Put definite results directly into the class dict, for speed
  468. for k, v in cls.default_assumptions.items():
  469. setattr(cls, as_property(k), v)
  470. # protection e.g. for Integer.is_even=F <- (Rational.is_integer=F)
  471. derived_from_bases = set()
  472. for base in cls.__bases__:
  473. default_assumptions = getattr(base, 'default_assumptions', None)
  474. # is an assumption-aware class
  475. if default_assumptions is not None:
  476. derived_from_bases.update(default_assumptions)
  477. for fact in derived_from_bases - set(cls.default_assumptions):
  478. pname = as_property(fact)
  479. if pname not in cls.__dict__:
  480. setattr(cls, pname, make_property(fact))
  481. # Finally, add any missing automagic property (e.g. for Basic)
  482. for fact in _assume_defined:
  483. pname = as_property(fact)
  484. if not hasattr(cls, pname):
  485. setattr(cls, pname, make_property(fact))