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.

634 lines
20 KiB

6 months ago
  1. """sympify -- convert objects SymPy internal format"""
  2. import typing
  3. if typing.TYPE_CHECKING:
  4. from typing import Any, Callable, Dict as tDict, Type
  5. from inspect import getmro
  6. import string
  7. from sympy.core.random import choice
  8. from .parameters import global_parameters
  9. from sympy.utilities.exceptions import sympy_deprecation_warning
  10. from sympy.utilities.iterables import iterable
  11. class SympifyError(ValueError):
  12. def __init__(self, expr, base_exc=None):
  13. self.expr = expr
  14. self.base_exc = base_exc
  15. def __str__(self):
  16. if self.base_exc is None:
  17. return "SympifyError: %r" % (self.expr,)
  18. return ("Sympify of expression '%s' failed, because of exception being "
  19. "raised:\n%s: %s" % (self.expr, self.base_exc.__class__.__name__,
  20. str(self.base_exc)))
  21. converter = {} # type: tDict[Type[Any], Callable[[Any], Basic]]
  22. #holds the conversions defined in SymPy itself, i.e. non-user defined conversions
  23. _sympy_converter = {} # type: tDict[Type[Any], Callable[[Any], Basic]]
  24. #alias for clearer use in the library
  25. _external_converter = converter
  26. class CantSympify:
  27. """
  28. Mix in this trait to a class to disallow sympification of its instances.
  29. Examples
  30. ========
  31. >>> from sympy import sympify
  32. >>> from sympy.core.sympify import CantSympify
  33. >>> class Something(dict):
  34. ... pass
  35. ...
  36. >>> sympify(Something())
  37. {}
  38. >>> class Something(dict, CantSympify):
  39. ... pass
  40. ...
  41. >>> sympify(Something())
  42. Traceback (most recent call last):
  43. ...
  44. SympifyError: SympifyError: {}
  45. """
  46. pass
  47. def _is_numpy_instance(a):
  48. """
  49. Checks if an object is an instance of a type from the numpy module.
  50. """
  51. # This check avoids unnecessarily importing NumPy. We check the whole
  52. # __mro__ in case any base type is a numpy type.
  53. return any(type_.__module__ == 'numpy'
  54. for type_ in type(a).__mro__)
  55. def _convert_numpy_types(a, **sympify_args):
  56. """
  57. Converts a numpy datatype input to an appropriate SymPy type.
  58. """
  59. import numpy as np
  60. if not isinstance(a, np.floating):
  61. if np.iscomplex(a):
  62. return _sympy_converter[complex](a.item())
  63. else:
  64. return sympify(a.item(), **sympify_args)
  65. else:
  66. try:
  67. from .numbers import Float
  68. prec = np.finfo(a).nmant + 1
  69. # E.g. double precision means prec=53 but nmant=52
  70. # Leading bit of mantissa is always 1, so is not stored
  71. a = str(list(np.reshape(np.asarray(a),
  72. (1, np.size(a)))[0]))[1:-1]
  73. return Float(a, precision=prec)
  74. except NotImplementedError:
  75. raise SympifyError('Translation for numpy float : %s '
  76. 'is not implemented' % a)
  77. def sympify(a, locals=None, convert_xor=True, strict=False, rational=False,
  78. evaluate=None):
  79. """
  80. Converts an arbitrary expression to a type that can be used inside SymPy.
  81. Explanation
  82. ===========
  83. It will convert Python ints into instances of :class:`~.Integer`, floats
  84. into instances of :class:`~.Float`, etc. It is also able to coerce
  85. symbolic expressions which inherit from :class:`~.Basic`. This can be
  86. useful in cooperation with SAGE.
  87. .. warning::
  88. Note that this function uses ``eval``, and thus shouldn't be used on
  89. unsanitized input.
  90. If the argument is already a type that SymPy understands, it will do
  91. nothing but return that value. This can be used at the beginning of a
  92. function to ensure you are working with the correct type.
  93. Examples
  94. ========
  95. >>> from sympy import sympify
  96. >>> sympify(2).is_integer
  97. True
  98. >>> sympify(2).is_real
  99. True
  100. >>> sympify(2.0).is_real
  101. True
  102. >>> sympify("2.0").is_real
  103. True
  104. >>> sympify("2e-45").is_real
  105. True
  106. If the expression could not be converted, a SympifyError is raised.
  107. >>> sympify("x***2")
  108. Traceback (most recent call last):
  109. ...
  110. SympifyError: SympifyError: "could not parse 'x***2'"
  111. Locals
  112. ------
  113. The sympification happens with access to everything that is loaded
  114. by ``from sympy import *``; anything used in a string that is not
  115. defined by that import will be converted to a symbol. In the following,
  116. the ``bitcount`` function is treated as a symbol and the ``O`` is
  117. interpreted as the :class:`~.Order` object (used with series) and it raises
  118. an error when used improperly:
  119. >>> s = 'bitcount(42)'
  120. >>> sympify(s)
  121. bitcount(42)
  122. >>> sympify("O(x)")
  123. O(x)
  124. >>> sympify("O + 1")
  125. Traceback (most recent call last):
  126. ...
  127. TypeError: unbound method...
  128. In order to have ``bitcount`` be recognized it can be imported into a
  129. namespace dictionary and passed as locals:
  130. >>> ns = {}
  131. >>> exec('from sympy.core.evalf import bitcount', ns)
  132. >>> sympify(s, locals=ns)
  133. 6
  134. In order to have the ``O`` interpreted as a Symbol, identify it as such
  135. in the namespace dictionary. This can be done in a variety of ways; all
  136. three of the following are possibilities:
  137. >>> from sympy import Symbol
  138. >>> ns["O"] = Symbol("O") # method 1
  139. >>> exec('from sympy.abc import O', ns) # method 2
  140. >>> ns.update(dict(O=Symbol("O"))) # method 3
  141. >>> sympify("O + 1", locals=ns)
  142. O + 1
  143. If you want *all* single-letter and Greek-letter variables to be symbols
  144. then you can use the clashing-symbols dictionaries that have been defined
  145. there as private variables: ``_clash1`` (single-letter variables),
  146. ``_clash2`` (the multi-letter Greek names) or ``_clash`` (both single and
  147. multi-letter names that are defined in ``abc``).
  148. >>> from sympy.abc import _clash1
  149. >>> set(_clash1)
  150. {'E', 'I', 'N', 'O', 'Q', 'S'}
  151. >>> sympify('I & Q', _clash1)
  152. I & Q
  153. Strict
  154. ------
  155. If the option ``strict`` is set to ``True``, only the types for which an
  156. explicit conversion has been defined are converted. In the other
  157. cases, a SympifyError is raised.
  158. >>> print(sympify(None))
  159. None
  160. >>> sympify(None, strict=True)
  161. Traceback (most recent call last):
  162. ...
  163. SympifyError: SympifyError: None
  164. .. deprecated:: 1.6
  165. ``sympify(obj)`` automatically falls back to ``str(obj)`` when all
  166. other conversion methods fail, but this is deprecated. ``strict=True``
  167. will disable this deprecated behavior. See
  168. :ref:`deprecated-sympify-string-fallback`.
  169. Evaluation
  170. ----------
  171. If the option ``evaluate`` is set to ``False``, then arithmetic and
  172. operators will be converted into their SymPy equivalents and the
  173. ``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will
  174. be denested first. This is done via an AST transformation that replaces
  175. operators with their SymPy equivalents, so if an operand redefines any
  176. of those operations, the redefined operators will not be used. If
  177. argument a is not a string, the mathematical expression is evaluated
  178. before being passed to sympify, so adding ``evaluate=False`` will still
  179. return the evaluated result of expression.
  180. >>> sympify('2**2 / 3 + 5')
  181. 19/3
  182. >>> sympify('2**2 / 3 + 5', evaluate=False)
  183. 2**2/3 + 5
  184. >>> sympify('4/2+7', evaluate=True)
  185. 9
  186. >>> sympify('4/2+7', evaluate=False)
  187. 4/2 + 7
  188. >>> sympify(4/2+7, evaluate=False)
  189. 9.00000000000000
  190. Extending
  191. ---------
  192. To extend ``sympify`` to convert custom objects (not derived from ``Basic``),
  193. just define a ``_sympy_`` method to your class. You can do that even to
  194. classes that you do not own by subclassing or adding the method at runtime.
  195. >>> from sympy import Matrix
  196. >>> class MyList1(object):
  197. ... def __iter__(self):
  198. ... yield 1
  199. ... yield 2
  200. ... return
  201. ... def __getitem__(self, i): return list(self)[i]
  202. ... def _sympy_(self): return Matrix(self)
  203. >>> sympify(MyList1())
  204. Matrix([
  205. [1],
  206. [2]])
  207. If you do not have control over the class definition you could also use the
  208. ``converter`` global dictionary. The key is the class and the value is a
  209. function that takes a single argument and returns the desired SymPy
  210. object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.
  211. >>> class MyList2(object): # XXX Do not do this if you control the class!
  212. ... def __iter__(self): # Use _sympy_!
  213. ... yield 1
  214. ... yield 2
  215. ... return
  216. ... def __getitem__(self, i): return list(self)[i]
  217. >>> from sympy.core.sympify import converter
  218. >>> converter[MyList2] = lambda x: Matrix(x)
  219. >>> sympify(MyList2())
  220. Matrix([
  221. [1],
  222. [2]])
  223. Notes
  224. =====
  225. The keywords ``rational`` and ``convert_xor`` are only used
  226. when the input is a string.
  227. convert_xor
  228. -----------
  229. >>> sympify('x^y',convert_xor=True)
  230. x**y
  231. >>> sympify('x^y',convert_xor=False)
  232. x ^ y
  233. rational
  234. --------
  235. >>> sympify('0.1',rational=False)
  236. 0.1
  237. >>> sympify('0.1',rational=True)
  238. 1/10
  239. Sometimes autosimplification during sympification results in expressions
  240. that are very different in structure than what was entered. Until such
  241. autosimplification is no longer done, the ``kernS`` function might be of
  242. some use. In the example below you can see how an expression reduces to
  243. $-1$ by autosimplification, but does not do so when ``kernS`` is used.
  244. >>> from sympy.core.sympify import kernS
  245. >>> from sympy.abc import x
  246. >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
  247. -1
  248. >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
  249. >>> sympify(s)
  250. -1
  251. >>> kernS(s)
  252. -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
  253. Parameters
  254. ==========
  255. a :
  256. - any object defined in SymPy
  257. - standard numeric Python types: ``int``, ``long``, ``float``, ``Decimal``
  258. - strings (like ``"0.09"``, ``"2e-19"`` or ``'sin(x)'``)
  259. - booleans, including ``None`` (will leave ``None`` unchanged)
  260. - dicts, lists, sets or tuples containing any of the above
  261. convert_xor : bool, optional
  262. If true, treats ``^`` as exponentiation.
  263. If False, treats ``^`` as XOR itself.
  264. Used only when input is a string.
  265. locals : any object defined in SymPy, optional
  266. In order to have strings be recognized it can be imported
  267. into a namespace dictionary and passed as locals.
  268. strict : bool, optional
  269. If the option strict is set to ``True``, only the types for which
  270. an explicit conversion has been defined are converted. In the
  271. other cases, a SympifyError is raised.
  272. rational : bool, optional
  273. If ``True``, converts floats into :class:`~.Rational`.
  274. If ``False``, it lets floats remain as it is.
  275. Used only when input is a string.
  276. evaluate : bool, optional
  277. If False, then arithmetic and operators will be converted into
  278. their SymPy equivalents. If True the expression will be evaluated
  279. and the result will be returned.
  280. """
  281. # XXX: If a is a Basic subclass rather than instance (e.g. sin rather than
  282. # sin(x)) then a.__sympy__ will be the property. Only on the instance will
  283. # a.__sympy__ give the *value* of the property (True). Since sympify(sin)
  284. # was used for a long time we allow it to pass. However if strict=True as
  285. # is the case in internal calls to _sympify then we only allow
  286. # is_sympy=True.
  287. #
  288. # https://github.com/sympy/sympy/issues/20124
  289. is_sympy = getattr(a, '__sympy__', None)
  290. if is_sympy is True:
  291. return a
  292. elif is_sympy is not None:
  293. if not strict:
  294. return a
  295. else:
  296. raise SympifyError(a)
  297. if isinstance(a, CantSympify):
  298. raise SympifyError(a)
  299. cls = getattr(a, "__class__", None)
  300. #Check if there exists a converter for any of the types in the mro
  301. for superclass in getmro(cls):
  302. #First check for user defined converters
  303. conv = _external_converter.get(superclass)
  304. if conv is None:
  305. #if none exists, check for SymPy defined converters
  306. conv = _sympy_converter.get(superclass)
  307. if conv is not None:
  308. return conv(a)
  309. if cls is type(None):
  310. if strict:
  311. raise SympifyError(a)
  312. else:
  313. return a
  314. if evaluate is None:
  315. evaluate = global_parameters.evaluate
  316. # Support for basic numpy datatypes
  317. if _is_numpy_instance(a):
  318. import numpy as np
  319. if np.isscalar(a):
  320. return _convert_numpy_types(a, locals=locals,
  321. convert_xor=convert_xor, strict=strict, rational=rational,
  322. evaluate=evaluate)
  323. _sympy_ = getattr(a, "_sympy_", None)
  324. if _sympy_ is not None:
  325. try:
  326. return a._sympy_()
  327. # XXX: Catches AttributeError: 'SymPyConverter' object has no
  328. # attribute 'tuple'
  329. # This is probably a bug somewhere but for now we catch it here.
  330. except AttributeError:
  331. pass
  332. if not strict:
  333. # Put numpy array conversion _before_ float/int, see
  334. # <https://github.com/sympy/sympy/issues/13924>.
  335. flat = getattr(a, "flat", None)
  336. if flat is not None:
  337. shape = getattr(a, "shape", None)
  338. if shape is not None:
  339. from sympy.tensor.array import Array
  340. return Array(a.flat, a.shape) # works with e.g. NumPy arrays
  341. if not isinstance(a, str):
  342. if _is_numpy_instance(a):
  343. import numpy as np
  344. assert not isinstance(a, np.number)
  345. if isinstance(a, np.ndarray):
  346. # Scalar arrays (those with zero dimensions) have sympify
  347. # called on the scalar element.
  348. if a.ndim == 0:
  349. try:
  350. return sympify(a.item(),
  351. locals=locals,
  352. convert_xor=convert_xor,
  353. strict=strict,
  354. rational=rational,
  355. evaluate=evaluate)
  356. except SympifyError:
  357. pass
  358. else:
  359. # float and int can coerce size-one numpy arrays to their lone
  360. # element. See issue https://github.com/numpy/numpy/issues/10404.
  361. for coerce in (float, int):
  362. try:
  363. return sympify(coerce(a))
  364. except (TypeError, ValueError, AttributeError, SympifyError):
  365. continue
  366. if strict:
  367. raise SympifyError(a)
  368. if iterable(a):
  369. try:
  370. return type(a)([sympify(x, locals=locals, convert_xor=convert_xor,
  371. rational=rational, evaluate=evaluate) for x in a])
  372. except TypeError:
  373. # Not all iterables are rebuildable with their type.
  374. pass
  375. if not isinstance(a, str):
  376. try:
  377. a = str(a)
  378. except Exception as exc:
  379. raise SympifyError(a, exc)
  380. sympy_deprecation_warning(
  381. f"""
  382. The string fallback in sympify() is deprecated.
  383. To explicitly convert the string form of an object, use
  384. sympify(str(obj)). To add define sympify behavior on custom
  385. objects, use sympy.core.sympify.converter or define obj._sympy_
  386. (see the sympify() docstring).
  387. sympify() performed the string fallback resulting in the following string:
  388. {a!r}
  389. """,
  390. deprecated_since_version='1.6',
  391. active_deprecations_target="deprecated-sympify-string-fallback",
  392. )
  393. from sympy.parsing.sympy_parser import (parse_expr, TokenError,
  394. standard_transformations)
  395. from sympy.parsing.sympy_parser import convert_xor as t_convert_xor
  396. from sympy.parsing.sympy_parser import rationalize as t_rationalize
  397. transformations = standard_transformations
  398. if rational:
  399. transformations += (t_rationalize,)
  400. if convert_xor:
  401. transformations += (t_convert_xor,)
  402. try:
  403. a = a.replace('\n', '')
  404. expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  405. except (TokenError, SyntaxError) as exc:
  406. raise SympifyError('could not parse %r' % a, exc)
  407. return expr
  408. def _sympify(a):
  409. """
  410. Short version of :func:`~.sympify` for internal usage for ``__add__`` and
  411. ``__eq__`` methods where it is ok to allow some things (like Python
  412. integers and floats) in the expression. This excludes things (like strings)
  413. that are unwise to allow into such an expression.
  414. >>> from sympy import Integer
  415. >>> Integer(1) == 1
  416. True
  417. >>> Integer(1) == '1'
  418. False
  419. >>> from sympy.abc import x
  420. >>> x + 1
  421. x + 1
  422. >>> x + '1'
  423. Traceback (most recent call last):
  424. ...
  425. TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
  426. see: sympify
  427. """
  428. return sympify(a, strict=True)
  429. def kernS(s):
  430. """Use a hack to try keep autosimplification from distributing a
  431. a number into an Add; this modification doesn't
  432. prevent the 2-arg Mul from becoming an Add, however.
  433. Examples
  434. ========
  435. >>> from sympy.core.sympify import kernS
  436. >>> from sympy.abc import x, y
  437. The 2-arg Mul distributes a number (or minus sign) across the terms
  438. of an expression, but kernS will prevent that:
  439. >>> 2*(x + y), -(x + 1)
  440. (2*x + 2*y, -x - 1)
  441. >>> kernS('2*(x + y)')
  442. 2*(x + y)
  443. >>> kernS('-(x + 1)')
  444. -(x + 1)
  445. If use of the hack fails, the un-hacked string will be passed to sympify...
  446. and you get what you get.
  447. XXX This hack should not be necessary once issue 4596 has been resolved.
  448. """
  449. hit = False
  450. quoted = '"' in s or "'" in s
  451. if '(' in s and not quoted:
  452. if s.count('(') != s.count(")"):
  453. raise SympifyError('unmatched left parenthesis')
  454. # strip all space from s
  455. s = ''.join(s.split())
  456. olds = s
  457. # now use space to represent a symbol that
  458. # will
  459. # step 1. turn potential 2-arg Muls into 3-arg versions
  460. # 1a. *( -> * *(
  461. s = s.replace('*(', '* *(')
  462. # 1b. close up exponentials
  463. s = s.replace('** *', '**')
  464. # 2. handle the implied multiplication of a negated
  465. # parenthesized expression in two steps
  466. # 2a: -(...) --> -( *(...)
  467. target = '-( *('
  468. s = s.replace('-(', target)
  469. # 2b: double the matching closing parenthesis
  470. # -( *(...) --> -( *(...))
  471. i = nest = 0
  472. assert target.endswith('(') # assumption below
  473. while True:
  474. j = s.find(target, i)
  475. if j == -1:
  476. break
  477. j += len(target) - 1
  478. for j in range(j, len(s)):
  479. if s[j] == "(":
  480. nest += 1
  481. elif s[j] == ")":
  482. nest -= 1
  483. if nest == 0:
  484. break
  485. s = s[:j] + ")" + s[j:]
  486. i = j + 2 # the first char after 2nd )
  487. if ' ' in s:
  488. # get a unique kern
  489. kern = '_'
  490. while kern in s:
  491. kern += choice(string.ascii_letters + string.digits)
  492. s = s.replace(' ', kern)
  493. hit = kern in s
  494. else:
  495. hit = False
  496. for i in range(2):
  497. try:
  498. expr = sympify(s)
  499. break
  500. except TypeError: # the kern might cause unknown errors...
  501. if hit:
  502. s = olds # maybe it didn't like the kern; use un-kerned s
  503. hit = False
  504. continue
  505. expr = sympify(s) # let original error raise
  506. if not hit:
  507. return expr
  508. from .symbol import Symbol
  509. rep = {Symbol(kern): 1}
  510. def _clear(expr):
  511. if isinstance(expr, (list, tuple, set)):
  512. return type(expr)([_clear(e) for e in expr])
  513. if hasattr(expr, 'subs'):
  514. return expr.subs(rep, hack2=True)
  515. return expr
  516. expr = _clear(expr)
  517. # hope that kern is not there anymore
  518. return expr
  519. # Avoid circular import
  520. from .basic import Basic