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.

353 lines
9.7 KiB

6 months ago
  1. """Module for SymPy containers
  2. (SymPy objects that store other SymPy objects)
  3. The containers implemented in this module are subclassed to Basic.
  4. They are supposed to work seamlessly within the SymPy framework.
  5. """
  6. from collections import OrderedDict
  7. from collections.abc import MutableSet
  8. from typing import Any, Callable
  9. from .basic import Basic
  10. from .sorting import default_sort_key, ordered
  11. from .sympify import _sympify, sympify, _sympy_converter, SympifyError
  12. from sympy.utilities.iterables import iterable
  13. from sympy.utilities.misc import as_int
  14. class Tuple(Basic):
  15. """
  16. Wrapper around the builtin tuple object.
  17. Explanation
  18. ===========
  19. The Tuple is a subclass of Basic, so that it works well in the
  20. SymPy framework. The wrapped tuple is available as self.args, but
  21. you can also access elements or slices with [:] syntax.
  22. Parameters
  23. ==========
  24. sympify : bool
  25. If ``False``, ``sympify`` is not called on ``args``. This
  26. can be used for speedups for very large tuples where the
  27. elements are known to already be SymPy objects.
  28. Examples
  29. ========
  30. >>> from sympy import Tuple, symbols
  31. >>> a, b, c, d = symbols('a b c d')
  32. >>> Tuple(a, b, c)[1:]
  33. (b, c)
  34. >>> Tuple(a, b, c).subs(a, d)
  35. (d, b, c)
  36. """
  37. def __new__(cls, *args, **kwargs):
  38. if kwargs.get('sympify', True):
  39. args = (sympify(arg) for arg in args)
  40. obj = Basic.__new__(cls, *args)
  41. return obj
  42. def __getitem__(self, i):
  43. if isinstance(i, slice):
  44. indices = i.indices(len(self))
  45. return Tuple(*(self.args[j] for j in range(*indices)))
  46. return self.args[i]
  47. def __len__(self):
  48. return len(self.args)
  49. def __contains__(self, item):
  50. return item in self.args
  51. def __iter__(self):
  52. return iter(self.args)
  53. def __add__(self, other):
  54. if isinstance(other, Tuple):
  55. return Tuple(*(self.args + other.args))
  56. elif isinstance(other, tuple):
  57. return Tuple(*(self.args + other))
  58. else:
  59. return NotImplemented
  60. def __radd__(self, other):
  61. if isinstance(other, Tuple):
  62. return Tuple(*(other.args + self.args))
  63. elif isinstance(other, tuple):
  64. return Tuple(*(other + self.args))
  65. else:
  66. return NotImplemented
  67. def __mul__(self, other):
  68. try:
  69. n = as_int(other)
  70. except ValueError:
  71. raise TypeError("Can't multiply sequence by non-integer of type '%s'" % type(other))
  72. return self.func(*(self.args*n))
  73. __rmul__ = __mul__
  74. def __eq__(self, other):
  75. if isinstance(other, Basic):
  76. return super().__eq__(other)
  77. return self.args == other
  78. def __ne__(self, other):
  79. if isinstance(other, Basic):
  80. return super().__ne__(other)
  81. return self.args != other
  82. def __hash__(self):
  83. return hash(self.args)
  84. def _to_mpmath(self, prec):
  85. return tuple(a._to_mpmath(prec) for a in self.args)
  86. def __lt__(self, other):
  87. return _sympify(self.args < other.args)
  88. def __le__(self, other):
  89. return _sympify(self.args <= other.args)
  90. # XXX: Basic defines count() as something different, so we can't
  91. # redefine it here. Originally this lead to cse() test failure.
  92. def tuple_count(self, value):
  93. """T.count(value) -> integer -- return number of occurrences of value"""
  94. return self.args.count(value)
  95. def index(self, value, start=None, stop=None):
  96. """Searches and returns the first index of the value."""
  97. # XXX: One would expect:
  98. #
  99. # return self.args.index(value, start, stop)
  100. #
  101. # here. Any trouble with that? Yes:
  102. #
  103. # >>> (1,).index(1, None, None)
  104. # Traceback (most recent call last):
  105. # File "<stdin>", line 1, in <module>
  106. # TypeError: slice indices must be integers or None or have an __index__ method
  107. #
  108. # See: http://bugs.python.org/issue13340
  109. if start is None and stop is None:
  110. return self.args.index(value)
  111. elif stop is None:
  112. return self.args.index(value, start)
  113. else:
  114. return self.args.index(value, start, stop)
  115. _sympy_converter[tuple] = lambda tup: Tuple(*tup)
  116. def tuple_wrapper(method):
  117. """
  118. Decorator that converts any tuple in the function arguments into a Tuple.
  119. Explanation
  120. ===========
  121. The motivation for this is to provide simple user interfaces. The user can
  122. call a function with regular tuples in the argument, and the wrapper will
  123. convert them to Tuples before handing them to the function.
  124. Explanation
  125. ===========
  126. >>> from sympy.core.containers import tuple_wrapper
  127. >>> def f(*args):
  128. ... return args
  129. >>> g = tuple_wrapper(f)
  130. The decorated function g sees only the Tuple argument:
  131. >>> g(0, (1, 2), 3)
  132. (0, (1, 2), 3)
  133. """
  134. def wrap_tuples(*args, **kw_args):
  135. newargs = []
  136. for arg in args:
  137. if isinstance(arg, tuple):
  138. newargs.append(Tuple(*arg))
  139. else:
  140. newargs.append(arg)
  141. return method(*newargs, **kw_args)
  142. return wrap_tuples
  143. class Dict(Basic):
  144. """
  145. Wrapper around the builtin dict object
  146. Explanation
  147. ===========
  148. The Dict is a subclass of Basic, so that it works well in the
  149. SymPy framework. Because it is immutable, it may be included
  150. in sets, but its values must all be given at instantiation and
  151. cannot be changed afterwards. Otherwise it behaves identically
  152. to the Python dict.
  153. Examples
  154. ========
  155. >>> from sympy import Dict, Symbol
  156. >>> D = Dict({1: 'one', 2: 'two'})
  157. >>> for key in D:
  158. ... if key == 1:
  159. ... print('%s %s' % (key, D[key]))
  160. 1 one
  161. The args are sympified so the 1 and 2 are Integers and the values
  162. are Symbols. Queries automatically sympify args so the following work:
  163. >>> 1 in D
  164. True
  165. >>> D.has(Symbol('one')) # searches keys and values
  166. True
  167. >>> 'one' in D # not in the keys
  168. False
  169. >>> D[1]
  170. one
  171. """
  172. def __new__(cls, *args):
  173. if len(args) == 1 and isinstance(args[0], (dict, Dict)):
  174. items = [Tuple(k, v) for k, v in args[0].items()]
  175. elif iterable(args) and all(len(arg) == 2 for arg in args):
  176. items = [Tuple(k, v) for k, v in args]
  177. else:
  178. raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
  179. elements = frozenset(items)
  180. obj = Basic.__new__(cls, *ordered(items))
  181. obj.elements = elements
  182. obj._dict = dict(items) # In case Tuple decides it wants to sympify
  183. return obj
  184. def __getitem__(self, key):
  185. """x.__getitem__(y) <==> x[y]"""
  186. try:
  187. key = _sympify(key)
  188. except SympifyError:
  189. raise KeyError(key)
  190. return self._dict[key]
  191. def __setitem__(self, key, value):
  192. raise NotImplementedError("SymPy Dicts are Immutable")
  193. def items(self):
  194. '''Returns a set-like object providing a view on dict's items.
  195. '''
  196. return self._dict.items()
  197. def keys(self):
  198. '''Returns the list of the dict's keys.'''
  199. return self._dict.keys()
  200. def values(self):
  201. '''Returns the list of the dict's values.'''
  202. return self._dict.values()
  203. def __iter__(self):
  204. '''x.__iter__() <==> iter(x)'''
  205. return iter(self._dict)
  206. def __len__(self):
  207. '''x.__len__() <==> len(x)'''
  208. return self._dict.__len__()
  209. def get(self, key, default=None):
  210. '''Returns the value for key if the key is in the dictionary.'''
  211. try:
  212. key = _sympify(key)
  213. except SympifyError:
  214. return default
  215. return self._dict.get(key, default)
  216. def __contains__(self, key):
  217. '''D.__contains__(k) -> True if D has a key k, else False'''
  218. try:
  219. key = _sympify(key)
  220. except SympifyError:
  221. return False
  222. return key in self._dict
  223. def __lt__(self, other):
  224. return _sympify(self.args < other.args)
  225. @property
  226. def _sorted_args(self):
  227. return tuple(sorted(self.args, key=default_sort_key))
  228. def __eq__(self, other):
  229. if isinstance(other, dict):
  230. return self == Dict(other)
  231. return super().__eq__(other)
  232. __hash__ : Callable[[Basic], Any] = Basic.__hash__
  233. # this handles dict, defaultdict, OrderedDict
  234. _sympy_converter[dict] = lambda d: Dict(*d.items())
  235. class OrderedSet(MutableSet):
  236. def __init__(self, iterable=None):
  237. if iterable:
  238. self.map = OrderedDict((item, None) for item in iterable)
  239. else:
  240. self.map = OrderedDict()
  241. def __len__(self):
  242. return len(self.map)
  243. def __contains__(self, key):
  244. return key in self.map
  245. def add(self, key):
  246. self.map[key] = None
  247. def discard(self, key):
  248. self.map.pop(key)
  249. def pop(self, last=True):
  250. return self.map.popitem(last=last)[0]
  251. def __iter__(self):
  252. yield from self.map.keys()
  253. def __repr__(self):
  254. if not self.map:
  255. return '%s()' % (self.__class__.__name__,)
  256. return '%s(%r)' % (self.__class__.__name__, list(self.map.keys()))
  257. def intersection(self, other):
  258. result = []
  259. for val in self:
  260. if val in other:
  261. result.append(val)
  262. return self.__class__(result)
  263. def difference(self, other):
  264. result = []
  265. for val in self:
  266. if val not in other:
  267. result.append(val)
  268. return self.__class__(result)
  269. def update(self, iterable):
  270. for val in iterable:
  271. self.add(val)