passagemath-objects 10.8.1a3__cp314-cp314-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (283) hide show
  1. passagemath_objects/__init__.py +3 -0
  2. passagemath_objects-10.8.1a3.dist-info/DELVEWHEEL +2 -0
  3. passagemath_objects-10.8.1a3.dist-info/METADATA +114 -0
  4. passagemath_objects-10.8.1a3.dist-info/RECORD +283 -0
  5. passagemath_objects-10.8.1a3.dist-info/WHEEL +5 -0
  6. passagemath_objects-10.8.1a3.dist-info/top_level.txt +3 -0
  7. passagemath_objects.libs/libgmp-10-60021eeab4282b29024e43b2b1412b53.dll +0 -0
  8. sage/all__sagemath_objects.py +46 -0
  9. sage/arith/all__sagemath_objects.py +5 -0
  10. sage/arith/long.pxd +411 -0
  11. sage/arith/numerical_approx.cp314-win_amd64.pyd +0 -0
  12. sage/arith/numerical_approx.pxd +35 -0
  13. sage/arith/numerical_approx.pyx +75 -0
  14. sage/arith/power.cp314-win_amd64.pyd +0 -0
  15. sage/arith/power.pxd +31 -0
  16. sage/arith/power.pyx +127 -0
  17. sage/categories/action.cp314-win_amd64.pyd +0 -0
  18. sage/categories/action.pxd +29 -0
  19. sage/categories/action.pyx +641 -0
  20. sage/categories/algebra_functor.py +745 -0
  21. sage/categories/all__sagemath_objects.py +33 -0
  22. sage/categories/basic.py +71 -0
  23. sage/categories/cartesian_product.py +292 -0
  24. sage/categories/category.py +3379 -0
  25. sage/categories/category_cy_helper.cp314-win_amd64.pyd +0 -0
  26. sage/categories/category_cy_helper.pxd +8 -0
  27. sage/categories/category_cy_helper.pyx +322 -0
  28. sage/categories/category_singleton.cp314-win_amd64.pyd +0 -0
  29. sage/categories/category_singleton.pxd +3 -0
  30. sage/categories/category_singleton.pyx +343 -0
  31. sage/categories/category_types.py +637 -0
  32. sage/categories/category_with_axiom.py +2889 -0
  33. sage/categories/covariant_functorial_construction.py +700 -0
  34. sage/categories/facade_sets.py +228 -0
  35. sage/categories/functor.cp314-win_amd64.pyd +0 -0
  36. sage/categories/functor.pxd +7 -0
  37. sage/categories/functor.pyx +659 -0
  38. sage/categories/homset.py +1289 -0
  39. sage/categories/homsets.py +364 -0
  40. sage/categories/isomorphic_objects.py +73 -0
  41. sage/categories/map.cp314-win_amd64.pyd +0 -0
  42. sage/categories/map.pxd +34 -0
  43. sage/categories/map.pyx +2106 -0
  44. sage/categories/morphism.cp314-win_amd64.pyd +0 -0
  45. sage/categories/morphism.pxd +14 -0
  46. sage/categories/morphism.pyx +895 -0
  47. sage/categories/objects.py +167 -0
  48. sage/categories/primer.py +1695 -0
  49. sage/categories/pushout.py +4847 -0
  50. sage/categories/quotients.py +64 -0
  51. sage/categories/realizations.py +200 -0
  52. sage/categories/sets_cat.py +3305 -0
  53. sage/categories/sets_with_partial_maps.py +52 -0
  54. sage/categories/subobjects.py +64 -0
  55. sage/categories/subquotients.py +21 -0
  56. sage/categories/with_realizations.py +311 -0
  57. sage/cpython/__init__.py +22 -0
  58. sage/cpython/_py2_random.py +619 -0
  59. sage/cpython/all.py +3 -0
  60. sage/cpython/atexit.cp314-win_amd64.pyd +0 -0
  61. sage/cpython/atexit.pyx +269 -0
  62. sage/cpython/builtin_types.cp314-win_amd64.pyd +0 -0
  63. sage/cpython/builtin_types.pyx +7 -0
  64. sage/cpython/cython_metaclass.cp314-win_amd64.pyd +0 -0
  65. sage/cpython/cython_metaclass.h +117 -0
  66. sage/cpython/cython_metaclass.pxd +3 -0
  67. sage/cpython/cython_metaclass.pyx +130 -0
  68. sage/cpython/debug.cp314-win_amd64.pyd +0 -0
  69. sage/cpython/debug.pyx +302 -0
  70. sage/cpython/dict_del_by_value.cp314-win_amd64.pyd +0 -0
  71. sage/cpython/dict_del_by_value.pxd +9 -0
  72. sage/cpython/dict_del_by_value.pyx +191 -0
  73. sage/cpython/dict_internal.h +80 -0
  74. sage/cpython/getattr.cp314-win_amd64.pyd +0 -0
  75. sage/cpython/getattr.pxd +9 -0
  76. sage/cpython/getattr.pyx +439 -0
  77. sage/cpython/pycore_long.h +97 -0
  78. sage/cpython/pycore_long.pxd +10 -0
  79. sage/cpython/python_debug.h +44 -0
  80. sage/cpython/python_debug.pxd +47 -0
  81. sage/cpython/pyx_visit.h +13 -0
  82. sage/cpython/string.cp314-win_amd64.pyd +0 -0
  83. sage/cpython/string.pxd +76 -0
  84. sage/cpython/string.pyx +34 -0
  85. sage/cpython/string_impl.h +60 -0
  86. sage/cpython/type.cp314-win_amd64.pyd +0 -0
  87. sage/cpython/type.pxd +2 -0
  88. sage/cpython/type.pyx +40 -0
  89. sage/cpython/wrapperdescr.pxd +67 -0
  90. sage/ext/all__sagemath_objects.py +3 -0
  91. sage/ext/ccobject.h +64 -0
  92. sage/ext/cplusplus.pxd +17 -0
  93. sage/ext/mod_int.h +30 -0
  94. sage/ext/mod_int.pxd +24 -0
  95. sage/ext/stdsage.pxd +39 -0
  96. sage/groups/all__sagemath_objects.py +1 -0
  97. sage/groups/group.cp314-win_amd64.pyd +0 -0
  98. sage/groups/group.pxd +14 -0
  99. sage/groups/group.pyx +296 -0
  100. sage/groups/old.cp314-win_amd64.pyd +0 -0
  101. sage/groups/old.pxd +14 -0
  102. sage/groups/old.pyx +219 -0
  103. sage/libs/all__sagemath_objects.py +3 -0
  104. sage/libs/gmp/__init__.py +1 -0
  105. sage/libs/gmp/all.pxd +6 -0
  106. sage/libs/gmp/binop.pxd +23 -0
  107. sage/libs/gmp/misc.pxd +8 -0
  108. sage/libs/gmp/mpf.pxd +88 -0
  109. sage/libs/gmp/mpn.pxd +57 -0
  110. sage/libs/gmp/mpq.pxd +57 -0
  111. sage/libs/gmp/mpz.pxd +202 -0
  112. sage/libs/gmp/pylong.cp314-win_amd64.pyd +0 -0
  113. sage/libs/gmp/pylong.pxd +12 -0
  114. sage/libs/gmp/pylong.pyx +150 -0
  115. sage/libs/gmp/random.pxd +25 -0
  116. sage/libs/gmp/randomize.pxd +59 -0
  117. sage/libs/gmp/types.pxd +53 -0
  118. sage/libs/gmpxx.pxd +19 -0
  119. sage/misc/abstract_method.py +276 -0
  120. sage/misc/all__sagemath_objects.py +43 -0
  121. sage/misc/bindable_class.py +253 -0
  122. sage/misc/c3_controlled.cp314-win_amd64.pyd +0 -0
  123. sage/misc/c3_controlled.pxd +2 -0
  124. sage/misc/c3_controlled.pyx +1402 -0
  125. sage/misc/cachefunc.cp314-win_amd64.pyd +0 -0
  126. sage/misc/cachefunc.pxd +43 -0
  127. sage/misc/cachefunc.pyx +3801 -0
  128. sage/misc/call.py +188 -0
  129. sage/misc/classcall_metaclass.cp314-win_amd64.pyd +0 -0
  130. sage/misc/classcall_metaclass.pxd +14 -0
  131. sage/misc/classcall_metaclass.pyx +599 -0
  132. sage/misc/constant_function.cp314-win_amd64.pyd +0 -0
  133. sage/misc/constant_function.pyx +130 -0
  134. sage/misc/decorators.py +739 -0
  135. sage/misc/fast_methods.cp314-win_amd64.pyd +0 -0
  136. sage/misc/fast_methods.pxd +20 -0
  137. sage/misc/fast_methods.pyx +351 -0
  138. sage/misc/flatten.py +90 -0
  139. sage/misc/fpickle.cp314-win_amd64.pyd +0 -0
  140. sage/misc/fpickle.pyx +176 -0
  141. sage/misc/function_mangling.cp314-win_amd64.pyd +0 -0
  142. sage/misc/function_mangling.pxd +11 -0
  143. sage/misc/function_mangling.pyx +308 -0
  144. sage/misc/inherit_comparison.cp314-win_amd64.pyd +0 -0
  145. sage/misc/inherit_comparison.pxd +5 -0
  146. sage/misc/inherit_comparison.pyx +105 -0
  147. sage/misc/instancedoc.cp314-win_amd64.pyd +0 -0
  148. sage/misc/instancedoc.pyx +331 -0
  149. sage/misc/lazy_attribute.cp314-win_amd64.pyd +0 -0
  150. sage/misc/lazy_attribute.pyx +607 -0
  151. sage/misc/lazy_format.py +132 -0
  152. sage/misc/lazy_import.cp314-win_amd64.pyd +0 -0
  153. sage/misc/lazy_import.pxd +13 -0
  154. sage/misc/lazy_import.pyx +1307 -0
  155. sage/misc/lazy_import_cache.py +36 -0
  156. sage/misc/lazy_list.cp314-win_amd64.pyd +0 -0
  157. sage/misc/lazy_list.pxd +19 -0
  158. sage/misc/lazy_list.pyx +1187 -0
  159. sage/misc/lazy_string.cp314-win_amd64.pyd +0 -0
  160. sage/misc/lazy_string.pxd +7 -0
  161. sage/misc/lazy_string.pyx +546 -0
  162. sage/misc/misc.py +980 -0
  163. sage/misc/misc_c.cp314-win_amd64.pyd +0 -0
  164. sage/misc/misc_c.pxd +3 -0
  165. sage/misc/misc_c.pyx +765 -0
  166. sage/misc/namespace_package.py +37 -0
  167. sage/misc/nested_class.cp314-win_amd64.pyd +0 -0
  168. sage/misc/nested_class.pxd +3 -0
  169. sage/misc/nested_class.pyx +394 -0
  170. sage/misc/persist.cp314-win_amd64.pyd +0 -0
  171. sage/misc/persist.pyx +1279 -0
  172. sage/misc/prandom.py +418 -0
  173. sage/misc/randstate.cp314-win_amd64.pyd +0 -0
  174. sage/misc/randstate.pxd +31 -0
  175. sage/misc/randstate.pyx +1096 -0
  176. sage/misc/repr.py +203 -0
  177. sage/misc/reset.cp314-win_amd64.pyd +0 -0
  178. sage/misc/reset.pyx +196 -0
  179. sage/misc/sage_ostools.cp314-win_amd64.pyd +0 -0
  180. sage/misc/sage_ostools.pyx +323 -0
  181. sage/misc/sage_timeit.py +275 -0
  182. sage/misc/sage_timeit_class.cp314-win_amd64.pyd +0 -0
  183. sage/misc/sage_timeit_class.pyx +120 -0
  184. sage/misc/sage_unittest.py +639 -0
  185. sage/misc/sageinspect.py +2792 -0
  186. sage/misc/session.cp314-win_amd64.pyd +0 -0
  187. sage/misc/session.pyx +392 -0
  188. sage/misc/superseded.py +576 -0
  189. sage/misc/test_nested_class.py +228 -0
  190. sage/misc/timing.py +264 -0
  191. sage/misc/unknown.py +222 -0
  192. sage/misc/verbose.py +253 -0
  193. sage/misc/weak_dict.cp314-win_amd64.pyd +0 -0
  194. sage/misc/weak_dict.pxd +15 -0
  195. sage/misc/weak_dict.pyx +1197 -0
  196. sage/modules/all__sagemath_objects.py +1 -0
  197. sage/modules/module.cp314-win_amd64.pyd +0 -0
  198. sage/modules/module.pxd +5 -0
  199. sage/modules/module.pyx +329 -0
  200. sage/rings/all__sagemath_objects.py +3 -0
  201. sage/rings/integer_fake.h +22 -0
  202. sage/rings/integer_fake.pxd +55 -0
  203. sage/rings/integer_fake.pyi +8 -0
  204. sage/sets/all__sagemath_objects.py +3 -0
  205. sage/sets/pythonclass.cp314-win_amd64.pyd +0 -0
  206. sage/sets/pythonclass.pxd +9 -0
  207. sage/sets/pythonclass.pyx +247 -0
  208. sage/structure/__init__.py +13 -0
  209. sage/structure/all.py +30 -0
  210. sage/structure/category_object.cp314-win_amd64.pyd +0 -0
  211. sage/structure/category_object.pxd +28 -0
  212. sage/structure/category_object.pyx +1090 -0
  213. sage/structure/coerce.cp314-win_amd64.pyd +0 -0
  214. sage/structure/coerce.pxd +44 -0
  215. sage/structure/coerce.pyx +2113 -0
  216. sage/structure/coerce_actions.cp314-win_amd64.pyd +0 -0
  217. sage/structure/coerce_actions.pxd +27 -0
  218. sage/structure/coerce_actions.pyx +988 -0
  219. sage/structure/coerce_dict.cp314-win_amd64.pyd +0 -0
  220. sage/structure/coerce_dict.pxd +51 -0
  221. sage/structure/coerce_dict.pyx +1557 -0
  222. sage/structure/coerce_exceptions.py +23 -0
  223. sage/structure/coerce_maps.cp314-win_amd64.pyd +0 -0
  224. sage/structure/coerce_maps.pxd +24 -0
  225. sage/structure/coerce_maps.pyx +656 -0
  226. sage/structure/debug_options.cp314-win_amd64.pyd +0 -0
  227. sage/structure/debug_options.pxd +6 -0
  228. sage/structure/debug_options.pyx +54 -0
  229. sage/structure/dynamic_class.py +541 -0
  230. sage/structure/element.cp314-win_amd64.pyd +0 -0
  231. sage/structure/element.pxd +271 -0
  232. sage/structure/element.pyx +4584 -0
  233. sage/structure/element_wrapper.cp314-win_amd64.pyd +0 -0
  234. sage/structure/element_wrapper.pxd +12 -0
  235. sage/structure/element_wrapper.pyx +582 -0
  236. sage/structure/factorization.py +1457 -0
  237. sage/structure/factorization_integer.py +154 -0
  238. sage/structure/factory.cp314-win_amd64.pyd +0 -0
  239. sage/structure/factory.pyx +863 -0
  240. sage/structure/formal_sum.py +489 -0
  241. sage/structure/gens_py.py +73 -0
  242. sage/structure/global_options.py +1725 -0
  243. sage/structure/indexed_generators.py +863 -0
  244. sage/structure/list_clone.cp314-win_amd64.pyd +0 -0
  245. sage/structure/list_clone.pxd +65 -0
  246. sage/structure/list_clone.pyx +1867 -0
  247. sage/structure/list_clone_demo.cp314-win_amd64.pyd +0 -0
  248. sage/structure/list_clone_demo.pyx +248 -0
  249. sage/structure/list_clone_timings.py +179 -0
  250. sage/structure/list_clone_timings_cy.cp314-win_amd64.pyd +0 -0
  251. sage/structure/list_clone_timings_cy.pyx +86 -0
  252. sage/structure/mutability.cp314-win_amd64.pyd +0 -0
  253. sage/structure/mutability.pxd +21 -0
  254. sage/structure/mutability.pyx +346 -0
  255. sage/structure/nonexact.py +69 -0
  256. sage/structure/parent.cp314-win_amd64.pyd +0 -0
  257. sage/structure/parent.pxd +112 -0
  258. sage/structure/parent.pyx +3087 -0
  259. sage/structure/parent_base.cp314-win_amd64.pyd +0 -0
  260. sage/structure/parent_base.pxd +13 -0
  261. sage/structure/parent_base.pyx +35 -0
  262. sage/structure/parent_gens.cp314-win_amd64.pyd +0 -0
  263. sage/structure/parent_gens.pxd +22 -0
  264. sage/structure/parent_gens.pyx +374 -0
  265. sage/structure/parent_old.cp314-win_amd64.pyd +0 -0
  266. sage/structure/parent_old.pxd +24 -0
  267. sage/structure/parent_old.pyx +278 -0
  268. sage/structure/proof/__init__.py +1 -0
  269. sage/structure/proof/all.py +243 -0
  270. sage/structure/proof/proof.py +300 -0
  271. sage/structure/richcmp.cp314-win_amd64.pyd +0 -0
  272. sage/structure/richcmp.pxd +212 -0
  273. sage/structure/richcmp.pyx +494 -0
  274. sage/structure/sage_object.cp314-win_amd64.pyd +0 -0
  275. sage/structure/sage_object.pxd +3 -0
  276. sage/structure/sage_object.pyx +1088 -0
  277. sage/structure/sage_object_test.py +19 -0
  278. sage/structure/sequence.py +937 -0
  279. sage/structure/set_factories.py +1178 -0
  280. sage/structure/set_factories_example.py +527 -0
  281. sage/structure/support_view.py +164 -0
  282. sage/structure/test_factory.py +56 -0
  283. sage/structure/unique_representation.py +1443 -0
@@ -0,0 +1,4584 @@
1
+ # sage_setup: distribution = sagemath-objects
2
+ # Compile this with -Os because it works around a bug with
3
+ # GCC-4.7.3 + Cython 0.19 on Itanium, see Issue #14452. Moreover, it
4
+ # actually results in faster code than -O3.
5
+ #
6
+ # distutils: extra_compile_args = -Os
7
+
8
+ r"""
9
+ Elements
10
+
11
+ AUTHORS:
12
+
13
+ - David Harvey (2006-10-16): changed CommutativeAlgebraElement to
14
+ derive from CommutativeRingElement instead of AlgebraElement
15
+
16
+ - David Harvey (2006-10-29): implementation and documentation of new
17
+ arithmetic architecture
18
+
19
+ - William Stein (2006-11): arithmetic architecture -- pushing it
20
+ through to completion.
21
+
22
+ - Gonzalo Tornaria (2007-06): recursive base extend for coercion --
23
+ lots of tests
24
+
25
+ - Robert Bradshaw (2007-2010): arithmetic operators and coercion
26
+
27
+ - Maarten Derickx (2010-07): added architecture for is_square and sqrt
28
+
29
+ - Jeroen Demeyer (2016-08): moved all coercion to the base class
30
+ :class:`Element`, see :issue:`20767`
31
+
32
+ The Abstract Element Class Hierarchy
33
+ ====================================
34
+
35
+ This is the abstract class hierarchy, i.e., these are all
36
+ abstract base classes.
37
+
38
+ ::
39
+
40
+ SageObject
41
+ Element
42
+ ModuleElement
43
+ RingElement
44
+ CommutativeRingElement
45
+ IntegralDomainElement
46
+ DedekindDomainElement
47
+ PrincipalIdealDomainElement
48
+ EuclideanDomainElement
49
+ FieldElement
50
+ CommutativeAlgebraElement
51
+ Expression
52
+ AlgebraElement
53
+ Matrix
54
+ InfinityElement
55
+ AdditiveGroupElement
56
+ Vector
57
+
58
+ MonoidElement
59
+ MultiplicativeGroupElement
60
+ ElementWithCachedMethod
61
+
62
+
63
+ How to Define a New Element Class
64
+ =================================
65
+
66
+ Elements typically define a method ``_new_c``, e.g.,
67
+
68
+ .. code-block:: cython
69
+
70
+ cdef _new_c(self, defining data):
71
+ cdef FreeModuleElement_generic_dense x
72
+ x = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)
73
+ x._parent = self._parent
74
+ x._entries = v
75
+
76
+ that creates a new sibling very quickly from defining data
77
+ with assumed properties.
78
+
79
+ .. _element_arithmetic:
80
+
81
+ Arithmetic for Elements
82
+ -----------------------
83
+
84
+ Sage has a special system for handling arithmetic operations on Sage
85
+ elements (that is instances of :class:`Element`), in particular to
86
+ manage uniformly mixed arithmetic operations using the :mod:`coercion
87
+ model <sage.structure.coerce>`. We describe here the rules that must
88
+ be followed by both arithmetic implementers and callers.
89
+
90
+ A quick summary for the impatient
91
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
92
+
93
+ To implement addition for any :class:`Element` subclass, override the
94
+ ``def _add_(self, other)`` method instead of the usual Python
95
+ ``__add__`` :python:`special method <reference/datamodel.html#special-method-names>`.
96
+ Within ``_add_(self, other)``, you may assume that ``self`` and
97
+ ``other`` have the same parent.
98
+
99
+ If the implementation is generic across all elements in a given
100
+ category `C`, then this method can be put in ``C.ElementMethods``.
101
+
102
+ When writing *Cython* code, ``_add_`` should be a cpdef method:
103
+ ``cpdef _add_(self, other)``.
104
+
105
+ When doing arithmetic with two elements having different parents,
106
+ the :mod:`coercion model <sage.structure.coerce>` is responsible for
107
+ "coercing" them to a common parent and performing arithmetic on the
108
+ coerced elements.
109
+
110
+ Arithmetic in more detail
111
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
112
+
113
+ The aims of this system are to provide (1) an efficient calling protocol
114
+ from both Python and Cython, (2) uniform coercion semantics across Sage,
115
+ (3) ease of use, (4) readability of code.
116
+
117
+ We will take addition as an example; all other operators are similar.
118
+ There are two relevant functions, with differing names
119
+ (single vs. double underscores).
120
+
121
+ - **def Element.__add__(left, right)**
122
+
123
+ This function is called by Python or Cython when the binary "+"
124
+ operator is encountered. It assumes that at least one of its
125
+ arguments is an :class:`Element`.
126
+
127
+ It has a fast pathway to deal with the most common case where both
128
+ arguments have the same parent. Otherwise, it uses the coercion
129
+ model to work out how to make them have the same parent. The
130
+ coercion model then adds the coerced elements (technically, it calls
131
+ ``operator.add``). Note that the result of coercion is not required
132
+ to be a Sage :class:`Element`, it could be a plain Python type.
133
+
134
+ Note that, although this function is declared as ``def``, it doesn't
135
+ have the usual overheads associated with Python functions (either
136
+ for the caller or for ``__add__`` itself). This is because Python
137
+ has optimised calling protocols for such special functions.
138
+
139
+ - **def Element._add_(self, other)**
140
+
141
+ This is the function that you should override to implement addition
142
+ in a subclass of :class:`Element`.
143
+
144
+ The two arguments to this function are guaranteed to have the **same
145
+ parent**, but not necessarily the same Python type.
146
+
147
+ When implementing ``_add_`` in a Cython extension type, use
148
+ ``cpdef _add_`` instead of ``def _add_``.
149
+
150
+ In Cython code, if you want to add two elements and you know that
151
+ their parents are identical, you are encouraged to call this
152
+ function directly, instead of using ``x + y``. This only works if
153
+ Cython knows that the left argument is an ``Element``. You can
154
+ always cast explicitly: ``(<Element>x)._add_(y)`` to force this.
155
+ In plain Python, ``x + y`` is always the fastest way to add two
156
+ elements because the special method ``__add__`` is optimized
157
+ unlike the normal method ``_add_``.
158
+
159
+ The difference in the names of the arguments (``left, right``
160
+ versus ``self, other``) is intentional: ``self`` is guaranteed to be an
161
+ instance of the class in which the method is defined. In Cython, we know
162
+ that at least one of ``left`` or ``right`` is an instance of the class
163
+ but we do not know a priori which one.
164
+
165
+ Powering is a special case: first of all, the 3-argument version of
166
+ ``pow()`` is not supported. Second, the coercion model checks whether
167
+ the exponent looks like an integer. If so, the function ``_pow_int``
168
+ is called. If the exponent is not an integer, the arguments are coerced
169
+ to a common parent and ``_pow_`` is called. So, if your type only
170
+ supports powering to an integer exponent, you should implement only
171
+ ``_pow_int``. If you want to support arbitrary powering, implement both
172
+ ``_pow_`` and ``_pow_int``.
173
+
174
+ For addition, multiplication and powering (not for other operators),
175
+ there is a fast path for operations with a C ``long``. For example,
176
+ implement ``cdef _add_long(self, long n)`` with optimized code for
177
+ ``self + n``. The addition and multiplication are assumed to be
178
+ commutative, so they are also called for ``n + self`` or ``n * self``.
179
+ From Cython code, you can also call ``_add_long`` or ``_mul_long``
180
+ directly. This is strictly an optimization: there is a default
181
+ implementation falling back to the generic arithmetic function.
182
+
183
+ Examples
184
+ ^^^^^^^^
185
+
186
+ We need some :class:`Parent` to work with::
187
+
188
+ sage: from sage.structure.parent import Parent
189
+ sage: class ExampleParent(Parent):
190
+ ....: def __init__(self, name, **kwds):
191
+ ....: Parent.__init__(self, **kwds)
192
+ ....: self.rename(name)
193
+
194
+ We start with a very basic example of a Python class implementing
195
+ ``_add_``::
196
+
197
+ sage: from sage.structure.element import Element
198
+ sage: class MyElement(Element):
199
+ ....: def _add_(self, other):
200
+ ....: return 42
201
+ sage: p = ExampleParent("Some parent")
202
+ sage: x = MyElement(p)
203
+ sage: x + x
204
+ 42
205
+
206
+ When two different parents are involved, this no longer works since
207
+ there is no coercion::
208
+
209
+ sage: q = ExampleParent("Other parent")
210
+ sage: y = MyElement(q)
211
+ sage: x + y
212
+ Traceback (most recent call last):
213
+ ...
214
+ TypeError: unsupported operand parent(s) for +: 'Some parent' and 'Other parent'
215
+
216
+ If ``_add_`` is not defined, an error message is raised, referring to
217
+ the parents::
218
+
219
+ sage: x = Element(p)
220
+ sage: x._add_(x)
221
+ Traceback (most recent call last):
222
+ ...
223
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_add_'...
224
+ sage: x + x
225
+ Traceback (most recent call last):
226
+ ...
227
+ TypeError: unsupported operand parent(s) for +: 'Some parent' and 'Some parent'
228
+ sage: y = Element(q)
229
+ sage: x + y
230
+ Traceback (most recent call last):
231
+ ...
232
+ TypeError: unsupported operand parent(s) for +: 'Some parent' and 'Other parent'
233
+
234
+ We can also implement arithmetic generically in categories::
235
+
236
+ sage: class MyCategory(Category):
237
+ ....: def super_categories(self):
238
+ ....: return [Sets()]
239
+ ....: class ElementMethods:
240
+ ....: def _add_(self, other):
241
+ ....: return 42
242
+ sage: p = ExampleParent("Parent in my category", category=MyCategory())
243
+ sage: x = Element(p)
244
+ sage: x + x
245
+ 42
246
+
247
+ Implementation details
248
+ ^^^^^^^^^^^^^^^^^^^^^^
249
+
250
+ Implementing the above features actually takes a bit of magic. Casual
251
+ callers and implementers can safely ignore it, but here are the
252
+ details for the curious.
253
+
254
+ To achieve fast arithmetic, it is critical to have a fast path in Cython
255
+ to call the ``_add_`` method of a Cython object. So we would like
256
+ to declare ``_add_`` as a ``cpdef`` method of class :class:`Element`.
257
+ Remember however that the abstract classes coming
258
+ from categories come after :class:`Element` in the method resolution
259
+ order (or fake method resolution order in case of a Cython
260
+ class). Hence any generic implementation of ``_add_`` in such an
261
+ abstract class would in principle be shadowed by ``Element._add_``.
262
+ This is worked around by defining ``Element._add_`` as a ``cdef``
263
+ instead of a ``cpdef`` method. Concrete implementations in subclasses
264
+ should be ``cpdef`` or ``def`` methods.
265
+
266
+ Let us now see what happens upon evaluating ``x + y`` when ``x`` and ``y``
267
+ are instances of a class that does not implement ``_add_`` but where
268
+ ``_add_`` is implemented in the category.
269
+ First, ``x.__add__(y)`` is called, where ``__add__`` is implemented
270
+ in :class:`Element`.
271
+ Assuming that ``x`` and ``y`` have the same parent, a Cython call to
272
+ ``x._add_(y)`` will be done.
273
+ The latter is implemented to trigger a Python level call to ``x._add_(y)``
274
+ which will succeed as desired.
275
+
276
+ In case that Python code calls ``x._add_(y)`` directly,
277
+ ``Element._add_`` will be invisible, and the method lookup will
278
+ continue down the MRO and find the ``_add_`` method in the category.
279
+ """
280
+
281
+ # ****************************************************************************
282
+ # Copyright (C) 2006-2016 ...
283
+ # Copyright (C) 2016 Jeroen Demeyer <jdemeyer@cage.ugent.be>
284
+ #
285
+ # This program is free software: you can redistribute it and/or modify
286
+ # it under the terms of the GNU General Public License as published by
287
+ # the Free Software Foundation, either version 2 of the License, or
288
+ # (at your option) any later version.
289
+ # https://www.gnu.org/licenses/
290
+ # ****************************************************************************
291
+
292
+ cimport cython
293
+ from cpython cimport *
294
+
295
+ from sage.ext.stdsage cimport *
296
+
297
+ cdef add, sub, mul, truediv, floordiv, mod, matmul, pow
298
+ from operator import (add, sub, mul, truediv, floordiv, mod, matmul, pow)
299
+
300
+ cdef dict _coerce_op_symbols = dict(
301
+ add='+', sub='-', mul='*', truediv='/', floordiv='//', mod='%', matmul='@', pow='^',
302
+ iadd='+', isub='-', imul='*', itruediv='/', ifloordiv='//', imod='%', imatmul='@', ipow='^')
303
+
304
+ from sage.structure.richcmp cimport rich_to_bool
305
+ from sage.structure.coerce cimport py_scalar_to_element, coercion_model
306
+ from sage.structure.parent cimport Parent
307
+ from sage.cpython.type cimport can_assign_class
308
+ from sage.cpython.getattr cimport getattr_from_other_class
309
+ from sage.misc.lazy_format import LazyFormat
310
+ from sage.arith.long cimport integer_check_long_py
311
+ from sage.arith.power cimport generic_power as arith_generic_power
312
+ from sage.arith.numerical_approx cimport digits_to_bits
313
+ from sage.misc.decorators import sage_wraps
314
+ from sage.misc.superseded import deprecation
315
+
316
+
317
+ def make_element(_class, _dict, parent):
318
+ """
319
+ This function is only here to support old pickles.
320
+
321
+ Pickling functionality is moved to Element.{__getstate__,__setstate__}
322
+ functions.
323
+ """
324
+ from sage.misc.pickle_old import make_element_old
325
+ return make_element_old(_class, _dict, parent)
326
+
327
+
328
+ cdef unary_op_exception(op, x):
329
+ try:
330
+ op = op.__name__
331
+ op = _coerce_op_symbols[op]
332
+ except (AttributeError, KeyError):
333
+ pass
334
+ px = parent(x)
335
+ return TypeError(f"unsupported operand parent for {op}: '{px}'")
336
+
337
+
338
+ cdef bin_op_exception(op, x, y):
339
+ try:
340
+ op = op.__name__
341
+ op = _coerce_op_symbols[op]
342
+ except (AttributeError, KeyError):
343
+ pass
344
+ px = parent(x)
345
+ py = parent(y)
346
+ return TypeError(f"unsupported operand parent(s) for {op}: '{px}' and '{py}'")
347
+
348
+
349
+ def is_Element(x):
350
+ """
351
+ Return ``True`` if x is of type Element.
352
+
353
+ EXAMPLES::
354
+
355
+ sage: from sage.structure.element import is_Element
356
+ sage: is_Element(2/3)
357
+ doctest:warning...
358
+ DeprecationWarning: The function is_Element is deprecated; use 'isinstance(..., Element)' instead.
359
+ See https://github.com/sagemath/sage/issues/38077 for details.
360
+ True
361
+ sage: is_Element(QQ^3) # needs sage.modules
362
+ False
363
+ """
364
+ from sage.misc.superseded import deprecation_cython
365
+ deprecation_cython(38077, "The function is_Element is deprecated; use 'isinstance(..., Element)' instead.")
366
+ return isinstance(x, Element)
367
+
368
+
369
+ cdef class Element(SageObject):
370
+ """
371
+ Generic element of a structure. All other types of elements
372
+ (:class:`RingElement`, :class:`ModuleElement`, etc)
373
+ derive from this type.
374
+
375
+ Subtypes must either call ``__init__()`` to set ``_parent``, or may
376
+ set ``_parent`` themselves if that would be more efficient.
377
+
378
+ .. automethod:: _richcmp_
379
+ .. automethod:: __add__
380
+ .. automethod:: __sub__
381
+ .. automethod:: __neg__
382
+ .. automethod:: __mul__
383
+ .. automethod:: __truediv__
384
+ .. automethod:: __floordiv__
385
+ .. automethod:: __mod__
386
+ """
387
+ @cython.binding(False)
388
+ @cython.always_allow_keywords(False)
389
+ def __getmetaclass__(_):
390
+ from sage.misc.inherit_comparison import InheritComparisonMetaclass
391
+ return InheritComparisonMetaclass
392
+
393
+ def __init__(self, parent):
394
+ r"""
395
+ INPUT:
396
+
397
+ - ``parent`` -- a SageObject
398
+ """
399
+ self._parent = parent
400
+
401
+ def _set_parent(self, parent):
402
+ r"""
403
+ Set the parent of ``self`` to ``parent``.
404
+
405
+ INPUT:
406
+
407
+ - ``parent`` -- a :class:`Parent`
408
+
409
+ .. WARNING::
410
+
411
+ Changing the parent of an object is not something you
412
+ should normally need. It is mainly meant for constructing a
413
+ new element from scratch, when ``__new__`` or ``__init__``
414
+ did not set the right parent. Using this method incorrectly
415
+ can break things badly.
416
+
417
+ EXAMPLES::
418
+
419
+ sage: q = 3/5
420
+ sage: parent(q)
421
+ Rational Field
422
+ sage: q._set_parent(CC) # needs sage.rings.real_mpfr
423
+ sage: parent(q) # needs sage.rings.real_mpfr
424
+ Complex Field with 53 bits of precision
425
+ sage: q._set_parent(float) # needs sage.rings.real_mpfr
426
+ Traceback (most recent call last):
427
+ ...
428
+ TypeError: Cannot convert type to sage.structure.parent.Parent
429
+ """
430
+ self._parent = <Parent?>parent
431
+
432
+ def __getattr__(self, name):
433
+ """
434
+ Lookup a method or attribute from the category abstract classes.
435
+
436
+ Let ``P`` be a parent in a category ``C``. Usually the methods
437
+ of ``C.element_class`` are made directly available to elements
438
+ of ``P`` via standard class inheritance. This is not the case
439
+ any more if the elements of ``P`` are instances of an
440
+ extension type. See :class:`Category` for details.
441
+
442
+ The purpose of this method is to emulate this inheritance: for
443
+ ``e`` and element of ``P``, if an attribute or method
444
+ ``e.foo`` is not found in the super classes of ``e``, it's
445
+ looked up manually in ``C.element_class`` and bound to ``e``.
446
+
447
+ .. NOTE::
448
+
449
+ - The attribute or method is actually looked up in
450
+ ``P._abstract_element_class``. In most cases this is
451
+ just an alias for ``C.element_class``, but some parents,
452
+ notably homsets, customizes this to let elements also
453
+ inherit from other abstract classes. See
454
+ :meth:`Parent._abstract_element_class` and
455
+ :meth:`Homset._abstract_element_class` for details.
456
+
457
+ - This mechanism may also enter into action when the
458
+ category of `P` is refined on the fly, leaving
459
+ previously constructed elements in an outdated element
460
+ class.
461
+
462
+ See :class:`~sage.rings.polynomial.polynomial_quotient_ring.PolynomialQuotientRing_generic`
463
+ for an example.
464
+
465
+ EXAMPLES:
466
+
467
+ We test that ``1`` (an instance of the extension type
468
+ ``Integer``) inherits the methods from the categories of
469
+ ``ZZ``, that is from ``CommutativeRings().element_class``::
470
+
471
+ sage: 1.is_idempotent(), 2.is_idempotent()
472
+ (True, False)
473
+
474
+ This method is actually provided by the ``Magmas()`` super
475
+ category of ``CommutativeRings()``::
476
+
477
+ sage: 1.is_idempotent
478
+ <bound method Magmas.ElementMethods.is_idempotent of 1>
479
+ sage: 1.is_idempotent.__module__
480
+ 'sage.categories.magmas'
481
+
482
+ TESTS::
483
+
484
+ sage: 1.blah_blah
485
+ Traceback (most recent call last):
486
+ ...
487
+ AttributeError: 'sage.rings.integer.Integer' object has no attribute 'blah_blah'...
488
+ sage: Semigroups().example().an_element().is_idempotent
489
+ <bound method LeftZeroSemigroup.Element.is_idempotent of 42>
490
+ sage: Semigroups().example().an_element().blah_blah
491
+ Traceback (most recent call last):
492
+ ...
493
+ AttributeError: 'LeftZeroSemigroup_with_category.element_class' object has no attribute 'blah_blah'...
494
+ """
495
+ return self.getattr_from_category(name)
496
+
497
+ cdef getattr_from_category(self, name):
498
+ # Lookup a method or attribute from the category abstract classes.
499
+ # See __getattr__ above for documentation.
500
+ cdef Parent P = self._parent
501
+ if P is None:
502
+ # This is highly unlikely but we deal with it anyway...
503
+ # Usually, this will just raise AttributeError in
504
+ # getattr_from_other_class().
505
+ cls = type
506
+ else:
507
+ cls = P._abstract_element_class
508
+ return getattr_from_other_class(self, cls, name)
509
+
510
+ def __dir__(self):
511
+ """
512
+ Emulate ``__dir__`` for elements with dynamically attached methods.
513
+
514
+ Let cat be the category of the parent of ``self``. This method
515
+ emulates ``self`` being an instance of both ``Element`` and
516
+ ``cat.element_class`` (and the corresponding ``morphism_class`` in the
517
+ case of a morphism), in that order, for attribute directory.
518
+
519
+ EXAMPLES::
520
+
521
+ sage: dir(1/2)
522
+ [..., 'is_idempotent', 'is_integer', 'is_integral', ...]
523
+
524
+ Caveat: dir on Integer's and some other extension types seem to ignore __dir__::
525
+
526
+ sage: 1.__dir__()
527
+ [..., 'is_idempotent', 'is_integer', 'is_integral', ...]
528
+ sage: dir(1) # todo: not implemented
529
+ [..., 'is_idempotent', 'is_integer', 'is_integral', ...]
530
+
531
+ TESTS:
532
+
533
+ Check that morphism classes are handled correctly (:issue:`29776`)::
534
+
535
+ sage: R.<x,y> = QQ[]
536
+ sage: f = R.hom([x, y+1], R)
537
+ sage: 'cartesian_product' in dir(f)
538
+ True
539
+ sage: 'extend_to_fraction_field' in dir(f)
540
+ True
541
+ """
542
+ from sage.cpython.getattr import dir_with_other_class
543
+ ec = self.parent().category().element_class
544
+ try:
545
+ mc = self.category_for().morphism_class
546
+ except AttributeError:
547
+ return dir_with_other_class(self, ec)
548
+ else:
549
+ return dir_with_other_class(self, ec, mc)
550
+
551
+ def _repr_(self):
552
+ return "Generic element of a structure"
553
+
554
+ def __getstate__(self):
555
+ """
556
+ Return a tuple describing the state of your object.
557
+
558
+ This should return all information that will be required to unpickle
559
+ the object. The functionality for unpickling is implemented in
560
+ __setstate__().
561
+
562
+ TESTS::
563
+
564
+ sage: R.<x,y> = QQ[]
565
+ sage: i = ideal(x^2 - y^2 + 1)
566
+ sage: i.__getstate__()
567
+ (Monoid of ideals of Multivariate Polynomial Ring in x, y over Rational Field,
568
+ {'_Ideal_generic__gens': (x^2 - y^2 + 1,),
569
+ '_Ideal_generic__ring': Multivariate Polynomial Ring in x, y over Rational Field,
570
+ '_gb_by_ordering': {}})
571
+ """
572
+ return (self._parent, self.__dict__)
573
+
574
+ def __setstate__(self, state):
575
+ """
576
+ Initialize the state of the object from data saved in a pickle.
577
+
578
+ During unpickling ``__init__`` methods of classes are not called, the
579
+ saved data is passed to the class via this function instead.
580
+
581
+ TESTS::
582
+
583
+ sage: R.<x,y> = QQ[]
584
+ sage: i = ideal(x); i
585
+ Ideal (x) of Multivariate Polynomial Ring in x, y over Rational Field
586
+ sage: S.<x,y,z> = ZZ[]
587
+ sage: i.__setstate__((R,{'_Ideal_generic__ring':S,'_Ideal_generic__gens': (S(x^2 - y^2 + 1),)}))
588
+ sage: i
589
+ Ideal (x^2 - y^2 + 1) of Multivariate Polynomial Ring in x, y, z over Integer Ring
590
+ """
591
+ self._set_parent(state[0])
592
+ self.__dict__ = state[1]
593
+
594
+ def __copy__(self):
595
+ """
596
+ Return a copy of ``self``.
597
+
598
+ OUTPUT: a new object which is a copy of ``self``
599
+
600
+ This implementation ensures that ``self.__dict__`` is properly copied
601
+ when it exists (typically for instances of classes deriving from
602
+ :class:`Element`).
603
+
604
+ TESTS::
605
+
606
+ sage: from sage.structure.element import Element
607
+ sage: el = Element(parent = ZZ)
608
+ sage: el1 = copy(el)
609
+ sage: el1 is el
610
+ False
611
+
612
+ sage: class Demo(Element): pass
613
+ sage: el = Demo(parent = ZZ)
614
+ sage: el.x = [1,2,3]
615
+ sage: el1 = copy(el)
616
+ sage: el1 is el
617
+ False
618
+ sage: el1.__dict__ is el.__dict__
619
+ False
620
+ """
621
+ cls = self.__class__
622
+ cdef Element res = cls.__new__(cls)
623
+ res._parent = self._parent
624
+ try:
625
+ D = self.__dict__
626
+ except AttributeError:
627
+ return res
628
+ for k, v in D.items():
629
+ try:
630
+ setattr(res, k, v)
631
+ except AttributeError:
632
+ pass
633
+ return res
634
+
635
+ def _im_gens_(self, codomain, im_gens, base_map=None):
636
+ """
637
+ Return the image of ``self`` in codomain under the map that sends
638
+ the images of the generators of the parent of ``self`` to the
639
+ tuple of elements of im_gens.
640
+ """
641
+ raise NotImplementedError
642
+
643
+ cpdef base_extend(self, R):
644
+ cdef Parent V
645
+ V = self._parent.base_extend(R)
646
+ return V.coerce(self)
647
+
648
+ def base_ring(self):
649
+ """
650
+ Return the base ring of this element's parent (if that makes sense).
651
+
652
+ TESTS::
653
+
654
+ sage: QQ.base_ring()
655
+ Rational Field
656
+ sage: identity_matrix(3).base_ring() # needs sage.modules
657
+ Integer Ring
658
+ """
659
+ return self._parent.base_ring()
660
+
661
+ def category(self):
662
+ from sage.categories.category_types import Elements
663
+ return Elements(self._parent)
664
+
665
+ def _test_new(self, **options):
666
+ """
667
+ Check that ``cls.__new__(cls)`` and
668
+ ``cls.__new__(cls, parent)`` do not crash Python,
669
+ where ``cls = type(self)`` and ``parent = parent(self)``.
670
+
671
+ It is perfectly legal for ``__new__`` to raise ordinary
672
+ exceptions.
673
+
674
+ EXAMPLES::
675
+
676
+ sage: from sage.structure.element import Element
677
+ sage: p = Parent()
678
+ sage: e = Element(p)
679
+ sage: e._test_new()
680
+ """
681
+ cdef type cls = type(self)
682
+ try:
683
+ cls.__new__(cls)
684
+ except Exception:
685
+ pass
686
+ try:
687
+ cls.__new__(cls, self._parent)
688
+ except Exception:
689
+ pass
690
+
691
+ def _test_category(self, **options):
692
+ """
693
+ Run generic tests on the method :meth:`.category`.
694
+
695
+ See also: :class:`TestSuite`.
696
+
697
+ EXAMPLES::
698
+
699
+ sage: 3._test_category()
700
+
701
+ Let us now write a broken :meth:`.category` method::
702
+
703
+ sage: from sage.categories.examples.sets_cat import PrimeNumbers
704
+ sage: class CCls(PrimeNumbers):
705
+ ....: def an_element(self):
706
+ ....: return 18
707
+ sage: CC = CCls()
708
+ sage: CC._test_an_element()
709
+ Traceback (most recent call last):
710
+ ...
711
+ AssertionError: self.an_element() is not in self
712
+ """
713
+ tester = self._tester(**options)
714
+ SageObject._test_category(self, tester=tester)
715
+ # Tests that self inherits methods from the categories
716
+ if can_assign_class(self):
717
+ # For usual Python classes, that should be done with
718
+ # standard inheritance
719
+ tester.assertTrue(isinstance(self, self.parent().category().element_class))
720
+ else:
721
+ # For extension types we just check that inheritance
722
+ # occurs on a dummy attribute of Sets().ElementMethods
723
+ tester.assertTrue(hasattr(self, "_dummy_attribute"))
724
+
725
+ def _test_eq(self, **options):
726
+ """
727
+ Test that ``self`` is equal to ``self`` and different to ``None``.
728
+
729
+ See also: :class:`TestSuite`.
730
+
731
+ TESTS::
732
+
733
+ sage: from sage.structure.element import Element
734
+ sage: O = Element(Parent())
735
+ sage: O._test_eq()
736
+
737
+ Let us now write a broken class method::
738
+
739
+ sage: class CCls(Element):
740
+ ....: def __eq__(self, other):
741
+ ....: return True
742
+ sage: CCls(Parent())._test_eq()
743
+ Traceback (most recent call last):
744
+ ...
745
+ AssertionError: broken equality: Generic element of a structure == None
746
+
747
+ Let us now break inequality::
748
+
749
+ sage: class CCls(Element):
750
+ ....: def __ne__(self, other):
751
+ ....: return True
752
+ sage: CCls(Parent())._test_eq()
753
+ Traceback (most recent call last):
754
+ ...
755
+ AssertionError: broken non-equality: Generic element of a structure != itself
756
+ """
757
+ tester = self._tester(**options)
758
+ # We don't use assertEqual / assertNonEqual in order to be
759
+ # 100% sure we indeed call the operators == and !=, whatever
760
+ # the version of Python is (see #11236)
761
+ tester.assertTrue(self == self,
762
+ LazyFormat("broken equality: %s == itself is False") % self)
763
+ tester.assertFalse(self == None,
764
+ LazyFormat("broken equality: %s == None") % self)
765
+ tester.assertFalse(self != self,
766
+ LazyFormat("broken non-equality: %s != itself") % self)
767
+ tester.assertTrue(self != None,
768
+ LazyFormat("broken non-equality: %s is not != None") % self)
769
+
770
+ def parent(self, x=None):
771
+ """
772
+ Return the parent of this element; or, if the optional argument x is
773
+ supplied, the result of coercing x into the parent of this element.
774
+ """
775
+ if x is None:
776
+ return self._parent
777
+ else:
778
+ return self._parent(x)
779
+
780
+ def subs(self, in_dict=None, **kwds):
781
+ """
782
+ Substitutes given generators with given values while not touching
783
+ other generators.
784
+
785
+ This is a generic wrapper around ``__call__``. The syntax is
786
+ meant to be compatible with the corresponding method for
787
+ symbolic expressions.
788
+
789
+ INPUT:
790
+
791
+ - ``in_dict`` -- (optional) dictionary of inputs
792
+
793
+ - ``**kwds`` -- named parameters
794
+
795
+ OUTPUT: new object if substitution is possible, otherwise ``self``
796
+
797
+ EXAMPLES::
798
+
799
+ sage: x, y = PolynomialRing(ZZ,2,'xy').gens()
800
+ sage: f = x^2 + y + x^2*y^2 + 5
801
+ sage: f((5,y))
802
+ 25*y^2 + y + 30
803
+ sage: f.subs({x:5})
804
+ 25*y^2 + y + 30
805
+ sage: f.subs(x=5)
806
+ 25*y^2 + y + 30
807
+ sage: (1/f).subs(x=5) # needs sage.libs.singular
808
+ 1/(25*y^2 + y + 30)
809
+ sage: Integer(5).subs(x=4)
810
+ 5
811
+ """
812
+ if not callable(self):
813
+ return self
814
+ parent = self._parent
815
+ try:
816
+ ngens = parent.ngens()
817
+ except (AttributeError, NotImplementedError, TypeError):
818
+ return self
819
+ variables = []
820
+
821
+ # using gen instead of gens
822
+ for i in range(ngens):
823
+ gen = parent.gen(i)
824
+ if str(gen) in kwds:
825
+ variables.append(kwds[str(gen)])
826
+ elif in_dict and gen in in_dict:
827
+ variables.append(in_dict[gen])
828
+ else:
829
+ variables.append(gen)
830
+ return self(*variables)
831
+
832
+ def substitute(self, *args, **kwds):
833
+ """
834
+ This calls :meth:`self.subs`.
835
+
836
+ EXAMPLES::
837
+
838
+ sage: x, y = PolynomialRing(ZZ, 2, 'xy').gens()
839
+ sage: f = x^2 + y + x^2*y^2 + 5
840
+ sage: f((5,y))
841
+ 25*y^2 + y + 30
842
+ sage: f.substitute({x: 5})
843
+ 25*y^2 + y + 30
844
+ sage: f.substitute(x=5)
845
+ 25*y^2 + y + 30
846
+ sage: (1/f).substitute(x=5) # needs sage.libs.singular
847
+ 1/(25*y^2 + y + 30)
848
+ sage: Integer(5).substitute(x=4)
849
+ 5
850
+ """
851
+ return self.subs(*args, **kwds)
852
+
853
+ def numerical_approx(self, prec=None, digits=None, algorithm=None):
854
+ """
855
+ Return a numerical approximation of ``self`` with ``prec`` bits
856
+ (or decimal ``digits``) of precision.
857
+
858
+ No guarantee is made about the accuracy of the result.
859
+
860
+ INPUT:
861
+
862
+ - ``prec`` -- precision in bits
863
+
864
+ - ``digits`` -- precision in decimal digits (only used if
865
+ ``prec`` is not given)
866
+
867
+ - ``algorithm`` -- which algorithm to use to compute this
868
+ approximation (the accepted algorithms depend on the object)
869
+
870
+ If neither ``prec`` nor ``digits`` is given, the default
871
+ precision is 53 bits (roughly 16 digits).
872
+
873
+ EXAMPLES::
874
+
875
+ sage: (2/3).numerical_approx() # needs sage.rings.real_mpfr
876
+ 0.666666666666667
877
+ sage: pi.n(digits=10) # needs sage.symbolic
878
+ 3.141592654
879
+ sage: pi.n(prec=20) # needs sage.symbolic
880
+ 3.1416
881
+
882
+ TESTS:
883
+
884
+ Check that :issue:`14778` is fixed::
885
+
886
+ sage: (0).n(algorithm='foo') # needs sage.rings.real_mpfr
887
+ 0.000000000000000
888
+ """
889
+ from sage.arith.numerical_approx import numerical_approx_generic
890
+ if prec is None:
891
+ prec = digits_to_bits(digits)
892
+ return numerical_approx_generic(self, prec)
893
+
894
+ def n(self, prec=None, digits=None, algorithm=None):
895
+ """
896
+ Alias for :meth:`numerical_approx`.
897
+
898
+ EXAMPLES::
899
+
900
+ sage: (2/3).n() # needs sage.rings.real_mpfr
901
+ 0.666666666666667
902
+ """
903
+ return self.numerical_approx(prec, digits, algorithm)
904
+
905
+ def _mpmath_(self, prec=53, rounding=None):
906
+ """
907
+ Evaluates numerically and returns an mpmath number.
908
+ Used as fallback for conversion by mpmath.mpmathify().
909
+
910
+ .. NOTE::
911
+
912
+ Currently, the rounding mode is ignored.
913
+
914
+ EXAMPLES::
915
+
916
+ sage: # needs mpmath
917
+ sage: from sage.libs.mpmath.all import mp, mpmathify
918
+ sage: mp.dps = 30
919
+ sage: 25._mpmath_(53)
920
+ mpf('25.0')
921
+ sage: mpmathify(3 + 4*I) # needs sage.symbolic
922
+ mpc(real='3.0', imag='4.0')
923
+ sage: mpmathify(1 + pi) # needs sage.symbolic
924
+ mpf('4.14159265358979323846264338327933')
925
+ sage: (1 + pi)._mpmath_(10) # needs sage.symbolic
926
+ mpf('4.140625')
927
+ sage: (1 + pi)._mpmath_(mp.prec) # needs sage.symbolic
928
+ mpf('4.14159265358979323846264338327933')
929
+ """
930
+ t = self.n(prec)
931
+ from sage.rings.real_mpfr import RealNumber
932
+ from sage.rings.complex_mpfr import ComplexNumber
933
+ if not isinstance(t, (RealNumber, ComplexNumber)):
934
+ # avoid infinite recursion
935
+ raise NotImplementedError("mpmath conversion not implemented for %s" % type(self))
936
+ return t._mpmath_(prec=prec)
937
+
938
+ cpdef _act_on_(self, x, bint self_on_left):
939
+ """
940
+ Use this method to implement ``self`` acting on ``x``.
941
+
942
+ Return ``None`` or raise a ``CoercionException`` if no
943
+ such action is defined here.
944
+ """
945
+ return None
946
+
947
+ cpdef _acted_upon_(self, x, bint self_on_left):
948
+ """
949
+ Use this method to implement ``self`` acted on by x.
950
+
951
+ Return ``None`` or raise a ``CoercionException`` if no
952
+ such action is defined here.
953
+ """
954
+ return None
955
+
956
+ def __xor__(self, right):
957
+ raise RuntimeError("Use ** for exponentiation, not '^', which means xor\n"
958
+ "in Python, and has the wrong precedence.")
959
+
960
+ def __pos__(self):
961
+ return self
962
+
963
+ def _coeff_repr(self, no_space=True):
964
+ if self._is_atomic():
965
+ s = repr(self)
966
+ else:
967
+ s = "(%s)" % repr(self)
968
+ if no_space:
969
+ return s.replace(' ', '')
970
+ return s
971
+
972
+ def _latex_coeff_repr(self):
973
+ try:
974
+ s = self._latex_()
975
+ except AttributeError:
976
+ s = str(self)
977
+ if self._is_atomic():
978
+ return s
979
+ else:
980
+ return "\\left(%s\\right)" % s
981
+
982
+ def _is_atomic(self):
983
+ """
984
+ Return ``True`` if and only if parenthesis are not required when
985
+ *printing* out any of `x - s`, `x + s`, `x^s` and `x/s`.
986
+
987
+ EXAMPLES::
988
+
989
+ sage: n = 5; n._is_atomic()
990
+ True
991
+ sage: n = x + 1; n._is_atomic() # needs sage.symbolic
992
+ False
993
+ """
994
+ if self._parent._repr_option('element_is_atomic'):
995
+ return True
996
+ s = str(self)
997
+ return s.find("+") == -1 and s.find("-") == -1 and s.find(" ") == -1
998
+
999
+ def __bool__(self):
1000
+ r"""
1001
+ Return whether this element is equal to ``self.parent()(0)``.
1002
+
1003
+ Note that this is automatically called when converting to
1004
+ boolean, as in the conditional of an if or while statement.
1005
+
1006
+ EXAMPLES::
1007
+
1008
+ sage: bool(1) # indirect doctest
1009
+ True
1010
+
1011
+ If ``self.parent()(0)`` raises an exception (because there is no
1012
+ meaningful zero element,) then this method returns ``True``. Here,
1013
+ there is no zero morphism of rings that goes to a non-trivial ring::
1014
+
1015
+ sage: bool(Hom(ZZ, Zmod(2)).an_element())
1016
+ True
1017
+
1018
+ But there is a zero morphism to the trivial ring::
1019
+
1020
+ sage: bool(Hom(ZZ, Zmod(1)).an_element())
1021
+ False
1022
+
1023
+ TESTS:
1024
+
1025
+ Verify that :issue:`5185` is fixed::
1026
+
1027
+ sage: # needs sage.modules
1028
+ sage: v = vector({1: 1, 3: -1})
1029
+ sage: w = vector({1: -1, 3: 1})
1030
+ sage: v + w
1031
+ (0, 0, 0, 0)
1032
+ sage: (v + w).is_zero()
1033
+ True
1034
+ sage: bool(v + w)
1035
+ False
1036
+ """
1037
+ try:
1038
+ zero = self._parent.zero()
1039
+ except Exception:
1040
+ return True # by convention
1041
+
1042
+ return self != zero
1043
+
1044
+ def is_zero(self):
1045
+ """
1046
+ Return ``True`` if ``self`` equals ``self.parent()(0)``.
1047
+
1048
+ The default implementation is to fall back to ``not
1049
+ self.__bool__``.
1050
+
1051
+ .. WARNING::
1052
+
1053
+ Do not re-implement this method in your subclass but
1054
+ implement ``__bool__`` instead.
1055
+ """
1056
+ return not self
1057
+
1058
+ def _cache_key(self):
1059
+ """
1060
+ Provide a hashable key for an element if it is not hashable.
1061
+
1062
+ EXAMPLES::
1063
+
1064
+ sage: a = sage.structure.element.Element(ZZ)
1065
+ sage: a._cache_key()
1066
+ (Integer Ring, 'Generic element of a structure')
1067
+ """
1068
+ return self.parent(), str(self)
1069
+
1070
+ ####################################################################
1071
+ # In a Cython or a Python class, you must define _richcmp_
1072
+ #
1073
+ # Rich comparisons (like a < b) will use _richcmp_
1074
+ #
1075
+ # In the _richcmp_ method, you can assume that both arguments have
1076
+ # identical parents.
1077
+ ####################################################################
1078
+ def __richcmp__(self, other, int op):
1079
+ """
1080
+ Compare ``self`` and ``other`` using the coercion framework,
1081
+ comparing according to the comparison operator ``op``.
1082
+
1083
+ Normally, a class will not redefine ``__richcmp__`` but rely on
1084
+ this ``Element.__richcmp__`` method which uses coercion if
1085
+ needed to compare elements. After coercion (or if no coercion
1086
+ is needed), ``_richcmp_`` is called.
1087
+
1088
+ If a class wants to implement rich comparison without coercion,
1089
+ then ``__richcmp__`` should be defined.
1090
+ See :class:`sage.numerical.linear_functions.LinearConstraint`
1091
+ for such an example.
1092
+
1093
+ For efficiency reasons, a class can do certain "manual"
1094
+ coercions directly in ``__richcmp__``, using
1095
+ ``coercion_model.richcmp()`` for the remaining cases.
1096
+ This is done for example in :class:`Integer`.
1097
+ """
1098
+ if have_same_parent(self, other):
1099
+ # Same parents, in particular self and other must both be
1100
+ # an instance of Element. The explicit casts below make
1101
+ # Cython generate optimized code for this call.
1102
+ return (<Element>self)._richcmp_(other, op)
1103
+ else:
1104
+ return coercion_model.richcmp(self, other, op)
1105
+
1106
+ cpdef _richcmp_(left, right, int op):
1107
+ r"""
1108
+ Basic default implementation of rich comparisons for elements with
1109
+ equal parents.
1110
+
1111
+ It does a comparison by id for ``==`` and ``!=``. Calling this
1112
+ default method with ``<``, ``<=``, ``>`` or ``>=`` will return
1113
+ ``NotImplemented``.
1114
+
1115
+ EXAMPLES::
1116
+
1117
+ sage: from sage.structure.parent import Parent
1118
+ sage: from sage.structure.element import Element
1119
+ sage: P = Parent()
1120
+ sage: e1 = Element(P); e2 = Element(P)
1121
+ sage: e1 == e1 # indirect doctest
1122
+ True
1123
+ sage: e1 == e2 # indirect doctest
1124
+ False
1125
+ sage: e1 < e2 # indirect doctest
1126
+ Traceback (most recent call last):
1127
+ ...
1128
+ TypeError: '<' not supported between instances of 'sage.structure.element.Element' and 'sage.structure.element.Element'
1129
+
1130
+ We now create an ``Element`` class where we define ``_richcmp_``
1131
+ and check that comparison works::
1132
+
1133
+ sage: # needs sage.misc.cython
1134
+ sage: cython(
1135
+ ....: '''
1136
+ ....: from sage.structure.richcmp cimport rich_to_bool
1137
+ ....: from sage.structure.element cimport Element
1138
+ ....: cdef class FloatCmp(Element):
1139
+ ....: cdef float x
1140
+ ....: def __init__(self, float v):
1141
+ ....: self.x = v
1142
+ ....: cpdef _richcmp_(self, other, int op):
1143
+ ....: cdef float x1 = (<FloatCmp>self).x
1144
+ ....: cdef float x2 = (<FloatCmp>other).x
1145
+ ....: return rich_to_bool(op, (x1 > x2) - (x1 < x2))
1146
+ ....: ''')
1147
+ sage: a = FloatCmp(1)
1148
+ sage: b = FloatCmp(2)
1149
+ sage: a <= b, b <= a
1150
+ (True, False)
1151
+ """
1152
+ # Obvious case
1153
+ if left is right:
1154
+ return rich_to_bool(op, 0)
1155
+ # Check equality by id(), knowing that left is not right
1156
+ if op == Py_EQ:
1157
+ return False
1158
+ if op == Py_NE:
1159
+ return True
1160
+ return NotImplemented
1161
+
1162
+ ##################################################
1163
+ # Arithmetic using the coercion model
1164
+ ##################################################
1165
+
1166
+ def __add__(left, right):
1167
+ """
1168
+ Top-level addition operator for :class:`Element` invoking
1169
+ the coercion model.
1170
+
1171
+ See :ref:`element_arithmetic`.
1172
+
1173
+ EXAMPLES::
1174
+
1175
+ sage: from sage.structure.element import Element
1176
+ sage: class MyElement(Element):
1177
+ ....: def _add_(self, other):
1178
+ ....: return 42
1179
+ sage: e = MyElement(Parent())
1180
+ sage: e + e
1181
+ 42
1182
+
1183
+ TESTS::
1184
+
1185
+ sage: e = Element(Parent())
1186
+ sage: e + e
1187
+ Traceback (most recent call last):
1188
+ ...
1189
+ TypeError: unsupported operand parent(s) for +: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1190
+ sage: 1 + e
1191
+ Traceback (most recent call last):
1192
+ ...
1193
+ TypeError: unsupported operand parent(s) for +: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1194
+ sage: e + 1
1195
+ Traceback (most recent call last):
1196
+ ...
1197
+ TypeError: unsupported operand parent(s) for +: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1198
+ sage: int(1) + e
1199
+ Traceback (most recent call last):
1200
+ ...
1201
+ TypeError: unsupported operand type(s) for +: 'int' and 'sage.structure.element.Element'
1202
+ sage: e + int(1)
1203
+ Traceback (most recent call last):
1204
+ ...
1205
+ TypeError: unsupported operand type(s) for +: 'sage.structure.element.Element' and 'int'
1206
+ sage: None + e
1207
+ Traceback (most recent call last):
1208
+ ...
1209
+ TypeError: unsupported operand type(s) for +: 'NoneType' and 'sage.structure.element.Element'
1210
+ sage: e + None
1211
+ Traceback (most recent call last):
1212
+ ...
1213
+ TypeError: unsupported operand type(s) for +: 'sage.structure.element.Element' and 'NoneType'
1214
+ """
1215
+ cdef int cl = classify_elements(left, right)
1216
+ if HAVE_SAME_PARENT(cl):
1217
+ return (<Element>left)._add_(right)
1218
+ # Left and right are Sage elements => use coercion model
1219
+ if BOTH_ARE_ELEMENT(cl):
1220
+ return coercion_model.bin_op(left, right, add)
1221
+
1222
+ cdef long value
1223
+ cdef int err = -1
1224
+ try:
1225
+ # Special case addition with Python int
1226
+ integer_check_long_py(right, &value, &err)
1227
+ if not err:
1228
+ return (<Element>left)._add_long(value)
1229
+ integer_check_long_py(left, &value, &err)
1230
+ if not err:
1231
+ return (<Element>right)._add_long(value)
1232
+ return coercion_model.bin_op(left, right, add)
1233
+ except TypeError:
1234
+ # Either coercion failed or arithmetic is not defined.
1235
+ #
1236
+ # According to the Python convention, we should return
1237
+ # NotImplemented now. This will cause Python to try the
1238
+ # reversed addition (__radd__).
1239
+ return NotImplemented
1240
+
1241
+ cdef _add_(self, other):
1242
+ """
1243
+ Virtual addition method for elements with identical parents.
1244
+
1245
+ This default Cython implementation of ``_add_`` calls the
1246
+ Python method ``self._add_`` if it exists. This method may be
1247
+ defined in the ``ElementMethods`` of the category of the parent.
1248
+ If the method is not found, a :exc:`TypeError` is raised
1249
+ indicating that the operation is not supported.
1250
+
1251
+ See :ref:`element_arithmetic`.
1252
+
1253
+ EXAMPLES:
1254
+
1255
+ This method is not visible from Python::
1256
+
1257
+ sage: from sage.structure.element import Element
1258
+ sage: e = Element(Parent())
1259
+ sage: e._add_(e)
1260
+ Traceback (most recent call last):
1261
+ ...
1262
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_add_'...
1263
+ """
1264
+ try:
1265
+ python_op = (<object>self)._add_
1266
+ except AttributeError:
1267
+ raise bin_op_exception('+', self, other)
1268
+ else:
1269
+ return python_op(other)
1270
+
1271
+ cdef _add_long(self, long n):
1272
+ """
1273
+ Generic path for adding a C long, assumed to commute.
1274
+
1275
+ EXAMPLES::
1276
+
1277
+ sage: # needs sage.misc.cython
1278
+ sage: cython( # long time
1279
+ ....: '''
1280
+ ....: from sage.structure.element cimport Element
1281
+ ....: cdef class MyElement(Element):
1282
+ ....: cdef _add_long(self, long n):
1283
+ ....: return n
1284
+ ....: ''')
1285
+ sage: e = MyElement(Parent()) # long time
1286
+ sage: i = int(42)
1287
+ sage: i + e, e + i # long time
1288
+ (42, 42)
1289
+ """
1290
+ return coercion_model.bin_op(self, n, add)
1291
+
1292
+ def __sub__(left, right):
1293
+ """
1294
+ Top-level subtraction operator for :class:`Element` invoking
1295
+ the coercion model.
1296
+
1297
+ See :ref:`element_arithmetic`.
1298
+
1299
+ EXAMPLES::
1300
+
1301
+ sage: from sage.structure.element import Element
1302
+ sage: class MyElement(Element):
1303
+ ....: def _sub_(self, other):
1304
+ ....: return 42
1305
+ sage: e = MyElement(Parent())
1306
+ sage: e - e
1307
+ 42
1308
+
1309
+ TESTS::
1310
+
1311
+ sage: e = Element(Parent())
1312
+ sage: e - e
1313
+ Traceback (most recent call last):
1314
+ ...
1315
+ TypeError: unsupported operand parent(s) for -: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1316
+ sage: 1 - e
1317
+ Traceback (most recent call last):
1318
+ ...
1319
+ TypeError: unsupported operand parent(s) for -: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1320
+ sage: e - 1
1321
+ Traceback (most recent call last):
1322
+ ...
1323
+ TypeError: unsupported operand parent(s) for -: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1324
+ sage: int(1) - e
1325
+ Traceback (most recent call last):
1326
+ ...
1327
+ TypeError: unsupported operand type(s) for -: 'int' and 'sage.structure.element.Element'
1328
+ sage: e - int(1)
1329
+ Traceback (most recent call last):
1330
+ ...
1331
+ TypeError: unsupported operand type(s) for -: 'sage.structure.element.Element' and 'int'
1332
+ sage: None - e
1333
+ Traceback (most recent call last):
1334
+ ...
1335
+ TypeError: unsupported operand type(s) for -: 'NoneType' and 'sage.structure.element.Element'
1336
+ sage: e - None
1337
+ Traceback (most recent call last):
1338
+ ...
1339
+ TypeError: unsupported operand type(s) for -: 'sage.structure.element.Element' and 'NoneType'
1340
+ """
1341
+ # See __add__ for comments
1342
+ cdef int cl = classify_elements(left, right)
1343
+ if HAVE_SAME_PARENT(cl):
1344
+ return (<Element>left)._sub_(right)
1345
+ if BOTH_ARE_ELEMENT(cl):
1346
+ return coercion_model.bin_op(left, right, sub)
1347
+
1348
+ try:
1349
+ return coercion_model.bin_op(left, right, sub)
1350
+ except TypeError:
1351
+ return NotImplemented
1352
+
1353
+ cdef _sub_(self, other):
1354
+ """
1355
+ Virtual subtraction method for elements with identical parents.
1356
+
1357
+ This default Cython implementation of ``_sub_`` calls the
1358
+ Python method ``self._sub_`` if it exists. This method may be
1359
+ defined in the ``ElementMethods`` of the category of the parent.
1360
+ If the method is not found, a :exc:`TypeError` is raised
1361
+ indicating that the operation is not supported.
1362
+
1363
+ See :ref:`element_arithmetic`.
1364
+
1365
+ EXAMPLES:
1366
+
1367
+ This method is not visible from Python::
1368
+
1369
+ sage: from sage.structure.element import Element
1370
+ sage: e = Element(Parent())
1371
+ sage: e._sub_(e)
1372
+ Traceback (most recent call last):
1373
+ ...
1374
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_sub_'...
1375
+ """
1376
+ try:
1377
+ python_op = (<object>self)._sub_
1378
+ except AttributeError:
1379
+ raise bin_op_exception('-', self, other)
1380
+ else:
1381
+ return python_op(other)
1382
+
1383
+ def __neg__(self):
1384
+ """
1385
+ Top-level negation operator for :class:`Element`.
1386
+
1387
+ EXAMPLES::
1388
+
1389
+ sage: from sage.structure.element import Element
1390
+ sage: class MyElement(Element):
1391
+ ....: def _neg_(self):
1392
+ ....: return 42
1393
+ sage: e = MyElement(Parent())
1394
+ sage: -e
1395
+ 42
1396
+
1397
+ TESTS::
1398
+
1399
+ sage: e = Element(Parent())
1400
+ sage: -e
1401
+ Traceback (most recent call last):
1402
+ ...
1403
+ TypeError: unsupported operand parent for unary -: '<sage.structure.parent.Parent object at ...>'
1404
+ """
1405
+ return self._neg_()
1406
+
1407
+ cdef _neg_(self):
1408
+ """
1409
+ Virtual unary negation method for elements.
1410
+
1411
+ This default Cython implementation of ``_neg_`` calls the
1412
+ Python method ``self._neg_`` if it exists. This method may be
1413
+ defined in the ``ElementMethods`` of the category of the parent.
1414
+ If the method is not found, a :exc:`TypeError` is raised
1415
+ indicating that the operation is not supported.
1416
+
1417
+ See :ref:`element_arithmetic`.
1418
+
1419
+ EXAMPLES:
1420
+
1421
+ This method is not visible from Python::
1422
+
1423
+ sage: from sage.structure.element import Element
1424
+ sage: e = Element(Parent())
1425
+ sage: e._neg_()
1426
+ Traceback (most recent call last):
1427
+ ...
1428
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_neg_'...
1429
+ """
1430
+ try:
1431
+ python_op = (<object>self)._neg_
1432
+ except AttributeError:
1433
+ raise unary_op_exception('unary -', self)
1434
+ else:
1435
+ return python_op()
1436
+
1437
+ def __mul__(left, right):
1438
+ """
1439
+ Top-level multiplication operator for :class:`Element` invoking
1440
+ the coercion model.
1441
+
1442
+ See :ref:`element_arithmetic`.
1443
+
1444
+ EXAMPLES::
1445
+
1446
+ sage: from sage.structure.element import Element
1447
+ sage: class MyElement(Element):
1448
+ ....: def _mul_(self, other):
1449
+ ....: return 42
1450
+ sage: e = MyElement(Parent())
1451
+ sage: e * e
1452
+ 42
1453
+
1454
+ TESTS::
1455
+
1456
+ sage: e = Element(Parent())
1457
+ sage: e * e
1458
+ Traceback (most recent call last):
1459
+ ...
1460
+ TypeError: unsupported operand parent(s) for *: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1461
+ sage: 1 * e
1462
+ Traceback (most recent call last):
1463
+ ...
1464
+ TypeError: unsupported operand parent(s) for *: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1465
+ sage: e * 1
1466
+ Traceback (most recent call last):
1467
+ ...
1468
+ TypeError: unsupported operand parent(s) for *: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1469
+ sage: int(1) * e
1470
+ Traceback (most recent call last):
1471
+ ...
1472
+ TypeError: unsupported operand type(s) for *: 'int' and 'sage.structure.element.Element'
1473
+ sage: e * int(1)
1474
+ Traceback (most recent call last):
1475
+ ...
1476
+ TypeError: unsupported operand type(s) for *: 'sage.structure.element.Element' and 'int'
1477
+ sage: None * e
1478
+ Traceback (most recent call last):
1479
+ ...
1480
+ TypeError: unsupported operand type(s) for *: 'NoneType' and 'sage.structure.element.Element'
1481
+ sage: e * None
1482
+ Traceback (most recent call last):
1483
+ ...
1484
+ TypeError: unsupported operand type(s) for *: 'sage.structure.element.Element' and 'NoneType'
1485
+
1486
+ ::
1487
+
1488
+ sage: # needs sage.combinat sage.modules
1489
+ sage: A = AlgebrasWithBasis(QQ).example(); A
1490
+ An example of an algebra with basis: the free algebra
1491
+ on the generators ('a', 'b', 'c') over Rational Field
1492
+ sage: x = A.an_element()
1493
+ sage: x
1494
+ B[word: ] + 2*B[word: a] + 3*B[word: b] + B[word: bab]
1495
+ sage: x.__mul__(x)
1496
+ B[word: ] + 4*B[word: a] + 4*B[word: aa] + 6*B[word: ab]
1497
+ + 2*B[word: abab] + 6*B[word: b] + 6*B[word: ba]
1498
+ + 2*B[word: bab] + 2*B[word: baba] + 3*B[word: babb]
1499
+ + B[word: babbab] + 9*B[word: bb] + 3*B[word: bbab]
1500
+ """
1501
+ cdef int cl = classify_elements(left, right)
1502
+ if HAVE_SAME_PARENT(cl):
1503
+ return (<Element>left)._mul_(right)
1504
+ if BOTH_ARE_ELEMENT(cl):
1505
+ return coercion_model.bin_op(left, right, mul)
1506
+
1507
+ cdef long value
1508
+ cdef int err = -1
1509
+ try:
1510
+ # Special case multiplication with Python int
1511
+ integer_check_long_py(right, &value, &err)
1512
+ if not err:
1513
+ return (<Element>left)._mul_long(value)
1514
+ integer_check_long_py(left, &value, &err)
1515
+ if not err:
1516
+ return (<Element>right)._mul_long(value)
1517
+ return coercion_model.bin_op(left, right, mul)
1518
+ except TypeError:
1519
+ return NotImplemented
1520
+
1521
+ cdef _mul_(self, other):
1522
+ """
1523
+ Virtual multiplication method for elements with identical parents.
1524
+
1525
+ This default Cython implementation of ``_mul_`` calls the
1526
+ Python method ``self._mul_`` if it exists. This method may be
1527
+ defined in the ``ElementMethods`` of the category of the parent.
1528
+ If the method is not found, a :exc:`TypeError` is raised
1529
+ indicating that the operation is not supported.
1530
+
1531
+ See :ref:`element_arithmetic`.
1532
+
1533
+ EXAMPLES:
1534
+
1535
+ This method is not visible from Python::
1536
+
1537
+ sage: from sage.structure.element import Element
1538
+ sage: e = Element(Parent())
1539
+ sage: e._mul_(e)
1540
+ Traceback (most recent call last):
1541
+ ...
1542
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_mul_'...
1543
+ """
1544
+ try:
1545
+ python_op = (<object>self)._mul_
1546
+ except AttributeError:
1547
+ raise bin_op_exception('*', self, other)
1548
+ else:
1549
+ return python_op(other)
1550
+
1551
+ cdef _mul_long(self, long n):
1552
+ """
1553
+ Generic path for multiplying by a C long, assumed to commute.
1554
+
1555
+ EXAMPLES::
1556
+
1557
+ sage: # needs sage.misc.cython
1558
+ sage: cython( # long time
1559
+ ....: '''
1560
+ ....: from sage.structure.element cimport Element
1561
+ ....: cdef class MyElement(Element):
1562
+ ....: cdef _mul_long(self, long n):
1563
+ ....: return n
1564
+ ....: ''')
1565
+ sage: e = MyElement(Parent()) # long time
1566
+ sage: i = int(42)
1567
+ sage: i * e, e * i # long time
1568
+ (42, 42)
1569
+ """
1570
+ return coercion_model.bin_op(self, n, mul)
1571
+
1572
+ def __matmul__(left, right):
1573
+ """
1574
+ Top-level matrix multiplication operator for :class:`Element`
1575
+ invoking the coercion model.
1576
+
1577
+ See :ref:`element_arithmetic`.
1578
+
1579
+ EXAMPLES::
1580
+
1581
+ sage: from sage.structure.element import Element
1582
+ sage: class MyElement(Element):
1583
+ ....: def _matmul_(self, other):
1584
+ ....: return 42
1585
+ sage: e = MyElement(Parent())
1586
+ sage: from operator import matmul
1587
+ sage: matmul(e, e)
1588
+ 42
1589
+
1590
+ TESTS::
1591
+
1592
+ sage: e = Element(Parent())
1593
+ sage: matmul(e, e)
1594
+ Traceback (most recent call last):
1595
+ ...
1596
+ TypeError: unsupported operand parent(s) for @: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1597
+ sage: matmul(1, e)
1598
+ Traceback (most recent call last):
1599
+ ...
1600
+ TypeError: unsupported operand parent(s) for @: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1601
+ sage: matmul(e, 1)
1602
+ Traceback (most recent call last):
1603
+ ...
1604
+ TypeError: unsupported operand parent(s) for @: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1605
+ sage: matmul(int(1), e)
1606
+ Traceback (most recent call last):
1607
+ ...
1608
+ TypeError: unsupported operand type(s) for @: 'int' and 'sage.structure.element.Element'
1609
+ sage: matmul(e, int(1))
1610
+ Traceback (most recent call last):
1611
+ ...
1612
+ TypeError: unsupported operand type(s) for @: 'sage.structure.element.Element' and 'int'
1613
+ sage: matmul(None, e)
1614
+ Traceback (most recent call last):
1615
+ ...
1616
+ TypeError: unsupported operand type(s) for @: 'NoneType' and 'sage.structure.element.Element'
1617
+ sage: matmul(e, None)
1618
+ Traceback (most recent call last):
1619
+ ...
1620
+ TypeError: unsupported operand type(s) for @: 'sage.structure.element.Element' and 'NoneType'
1621
+ """
1622
+ cdef int cl = classify_elements(left, right)
1623
+ if HAVE_SAME_PARENT(cl):
1624
+ return (<Element>left)._matmul_(right)
1625
+ if BOTH_ARE_ELEMENT(cl):
1626
+ return coercion_model.bin_op(left, right, matmul)
1627
+
1628
+ try:
1629
+ return coercion_model.bin_op(left, right, matmul)
1630
+ except TypeError:
1631
+ return NotImplemented
1632
+
1633
+ cdef _matmul_(self, other):
1634
+ """
1635
+ Virtual matrix multiplication method for elements with
1636
+ identical parents.
1637
+
1638
+ This default Cython implementation of ``_matmul_`` calls the
1639
+ Python method ``self._matmul_`` if it exists. This method may
1640
+ be defined in the ``ElementMethods`` of the category of the
1641
+ parent. If the method is not found, a :exc:`TypeError` is raised
1642
+ indicating that the operation is not supported.
1643
+
1644
+ See :ref:`element_arithmetic`.
1645
+
1646
+ EXAMPLES:
1647
+
1648
+ This method is not visible from Python::
1649
+
1650
+ sage: from sage.structure.element import Element
1651
+ sage: e = Element(Parent())
1652
+ sage: e._matmul_(e)
1653
+ Traceback (most recent call last):
1654
+ ...
1655
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_matmul_'...
1656
+ """
1657
+ try:
1658
+ python_op = (<object>self)._matmul_
1659
+ except AttributeError:
1660
+ raise bin_op_exception('@', self, other)
1661
+ else:
1662
+ return python_op(other)
1663
+
1664
+ def __truediv__(left, right):
1665
+ """
1666
+ Top-level true division operator for :class:`Element` invoking
1667
+ the coercion model.
1668
+
1669
+ See :ref:`element_arithmetic`.
1670
+
1671
+ EXAMPLES::
1672
+
1673
+ sage: operator.truediv(2, 3)
1674
+ 2/3
1675
+ sage: operator.truediv(pi, 3) # needs sage.symbolic
1676
+ 1/3*pi
1677
+ sage: x = polygen(QQ, 'x')
1678
+ sage: K.<i> = NumberField(x^2 + 1) # needs sage.rings.number_field
1679
+ sage: operator.truediv(2, K.ideal(i + 1)) # needs sage.rings.number_field
1680
+ Fractional ideal (-i + 1)
1681
+
1682
+ ::
1683
+
1684
+ sage: from sage.structure.element import Element
1685
+ sage: class MyElement(Element):
1686
+ ....: def _div_(self, other):
1687
+ ....: return 42
1688
+ sage: e = MyElement(Parent())
1689
+ sage: operator.truediv(e, e)
1690
+ 42
1691
+
1692
+ TESTS::
1693
+
1694
+ sage: e = Element(Parent())
1695
+ sage: operator.truediv(e, e)
1696
+ Traceback (most recent call last):
1697
+ ...
1698
+ TypeError: unsupported operand parent(s) for /: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1699
+ sage: operator.truediv(1, e)
1700
+ Traceback (most recent call last):
1701
+ ...
1702
+ TypeError: unsupported operand parent(s) for /: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1703
+ sage: operator.truediv(e, 1)
1704
+ Traceback (most recent call last):
1705
+ ...
1706
+ TypeError: unsupported operand parent(s) for /: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1707
+ sage: operator.truediv(int(1), e)
1708
+ Traceback (most recent call last):
1709
+ ...
1710
+ TypeError: unsupported operand type(s) for /: 'int' and 'sage.structure.element.Element'
1711
+ sage: operator.truediv(e, int(1))
1712
+ Traceback (most recent call last):
1713
+ ...
1714
+ TypeError: unsupported operand type(s) for /: 'sage.structure.element.Element' and 'int'
1715
+ sage: operator.truediv(None, e)
1716
+ Traceback (most recent call last):
1717
+ ...
1718
+ TypeError: unsupported operand type(s) for /: 'NoneType' and 'sage.structure.element.Element'
1719
+ sage: operator.truediv(e, None)
1720
+ Traceback (most recent call last):
1721
+ ...
1722
+ TypeError: unsupported operand type(s) for /: 'sage.structure.element.Element' and 'NoneType'
1723
+ """
1724
+ # See __add__ for comments
1725
+ cdef int cl = classify_elements(left, right)
1726
+ if HAVE_SAME_PARENT(cl):
1727
+ return (<Element>left)._div_(right)
1728
+ if BOTH_ARE_ELEMENT(cl):
1729
+ return coercion_model.bin_op(left, right, truediv)
1730
+
1731
+ try:
1732
+ return coercion_model.bin_op(left, right, truediv)
1733
+ except TypeError:
1734
+ return NotImplemented
1735
+
1736
+ cdef _div_(self, other):
1737
+ """
1738
+ Virtual division method for elements with identical parents.
1739
+ This is called for Python 2 division as well as true division.
1740
+
1741
+ This default Cython implementation of ``_div_`` calls the
1742
+ Python method ``self._div_`` if it exists. This method may be
1743
+ defined in the ``ElementMethods`` of the category of the parent.
1744
+ If the method is not found, a :exc:`TypeError` is raised
1745
+ indicating that the operation is not supported.
1746
+
1747
+ See :ref:`element_arithmetic`.
1748
+
1749
+ EXAMPLES:
1750
+
1751
+ This method is not visible from Python::
1752
+
1753
+ sage: from sage.structure.element import Element
1754
+ sage: e = Element(Parent())
1755
+ sage: e._div_(e)
1756
+ Traceback (most recent call last):
1757
+ ...
1758
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_div_'...
1759
+ """
1760
+ try:
1761
+ python_op = (<object>self)._div_
1762
+ except AttributeError:
1763
+ raise bin_op_exception('/', self, other)
1764
+ else:
1765
+ return python_op(other)
1766
+
1767
+ def __floordiv__(left, right):
1768
+ """
1769
+ Top-level floor division operator for :class:`Element` invoking
1770
+ the coercion model.
1771
+
1772
+ See :ref:`element_arithmetic`.
1773
+
1774
+ EXAMPLES::
1775
+
1776
+ sage: 7 // 3
1777
+ 2
1778
+ sage: 7 // int(3)
1779
+ 2
1780
+ sage: int(7) // 3
1781
+ 2
1782
+
1783
+ ::
1784
+
1785
+ sage: from sage.structure.element import Element
1786
+ sage: class MyElement(Element):
1787
+ ....: def _floordiv_(self, other):
1788
+ ....: return 42
1789
+ sage: e = MyElement(Parent())
1790
+ sage: e // e
1791
+ 42
1792
+
1793
+ TESTS::
1794
+
1795
+ sage: e = Element(Parent())
1796
+ sage: e // e
1797
+ Traceback (most recent call last):
1798
+ ...
1799
+ TypeError: unsupported operand parent(s) for //: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1800
+ sage: 1 // e
1801
+ Traceback (most recent call last):
1802
+ ...
1803
+ TypeError: unsupported operand parent(s) for //: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1804
+ sage: e // 1
1805
+ Traceback (most recent call last):
1806
+ ...
1807
+ TypeError: unsupported operand parent(s) for //: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1808
+ sage: int(1) // e
1809
+ Traceback (most recent call last):
1810
+ ...
1811
+ TypeError: unsupported operand type(s) for //: 'int' and 'sage.structure.element.Element'
1812
+ sage: e // int(1)
1813
+ Traceback (most recent call last):
1814
+ ...
1815
+ TypeError: unsupported operand type(s) for //: 'sage.structure.element.Element' and 'int'
1816
+ sage: None // e
1817
+ Traceback (most recent call last):
1818
+ ...
1819
+ TypeError: unsupported operand type(s) for //: 'NoneType' and 'sage.structure.element.Element'
1820
+ sage: e // None
1821
+ Traceback (most recent call last):
1822
+ ...
1823
+ TypeError: unsupported operand type(s) for //: 'sage.structure.element.Element' and 'NoneType'
1824
+ """
1825
+ # See __add__ for comments
1826
+ cdef int cl = classify_elements(left, right)
1827
+ if HAVE_SAME_PARENT(cl):
1828
+ return (<Element>left)._floordiv_(right)
1829
+ if BOTH_ARE_ELEMENT(cl):
1830
+ return coercion_model.bin_op(left, right, floordiv)
1831
+
1832
+ try:
1833
+ return coercion_model.bin_op(left, right, floordiv)
1834
+ except TypeError:
1835
+ return NotImplemented
1836
+
1837
+ cdef _floordiv_(self, other):
1838
+ """
1839
+ Virtual floor division method for elements with identical parents.
1840
+
1841
+ This default Cython implementation of ``_floordiv_`` calls the
1842
+ Python method ``self._floordiv_`` if it exists. This method may be
1843
+ defined in the ``ElementMethods`` of the category of the parent.
1844
+ If the method is not found, a :exc:`TypeError` is raised
1845
+ indicating that the operation is not supported.
1846
+
1847
+ See :ref:`element_arithmetic`.
1848
+
1849
+ EXAMPLES:
1850
+
1851
+ This method is not visible from Python::
1852
+
1853
+ sage: from sage.structure.element import Element
1854
+ sage: e = Element(Parent())
1855
+ sage: e._floordiv_(e)
1856
+ Traceback (most recent call last):
1857
+ ...
1858
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_floordiv_'...
1859
+ """
1860
+ try:
1861
+ python_op = (<object>self)._floordiv_
1862
+ except AttributeError:
1863
+ raise bin_op_exception('//', self, other)
1864
+ else:
1865
+ return python_op(other)
1866
+
1867
+ def __mod__(left, right):
1868
+ """
1869
+ Top-level modulo operator for :class:`Element` invoking
1870
+ the coercion model.
1871
+
1872
+ See :ref:`element_arithmetic`.
1873
+
1874
+ EXAMPLES::
1875
+
1876
+ sage: 7 % 3
1877
+ 1
1878
+ sage: 7 % int(3)
1879
+ 1
1880
+ sage: int(7) % 3
1881
+ 1
1882
+
1883
+ ::
1884
+
1885
+ sage: from sage.structure.element import Element
1886
+ sage: class MyElement(Element):
1887
+ ....: def _mod_(self, other):
1888
+ ....: return 42
1889
+ sage: e = MyElement(Parent())
1890
+ sage: e % e
1891
+ 42
1892
+
1893
+ TESTS::
1894
+
1895
+ sage: e = Element(Parent())
1896
+ sage: e % e
1897
+ Traceback (most recent call last):
1898
+ ...
1899
+ TypeError: unsupported operand parent(s) for %: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
1900
+ sage: 1 % e
1901
+ Traceback (most recent call last):
1902
+ ...
1903
+ TypeError: unsupported operand parent(s) for %: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
1904
+ sage: e % 1
1905
+ Traceback (most recent call last):
1906
+ ...
1907
+ TypeError: unsupported operand parent(s) for %: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
1908
+ sage: int(1) % e
1909
+ Traceback (most recent call last):
1910
+ ...
1911
+ TypeError: unsupported operand type(s) for %: 'int' and 'sage.structure.element.Element'
1912
+ sage: e % int(1)
1913
+ Traceback (most recent call last):
1914
+ ...
1915
+ TypeError: unsupported operand type(s) for %: 'sage.structure.element.Element' and 'int'
1916
+ sage: None % e
1917
+ Traceback (most recent call last):
1918
+ ...
1919
+ TypeError: unsupported operand type(s) for %: 'NoneType' and 'sage.structure.element.Element'
1920
+ sage: e % None
1921
+ Traceback (most recent call last):
1922
+ ...
1923
+ TypeError: unsupported operand type(s) for %: 'sage.structure.element.Element' and 'NoneType'
1924
+ """
1925
+ # See __add__ for comments
1926
+ cdef int cl = classify_elements(left, right)
1927
+ if HAVE_SAME_PARENT(cl):
1928
+ return (<Element>left)._mod_(right)
1929
+ if BOTH_ARE_ELEMENT(cl):
1930
+ return coercion_model.bin_op(left, right, mod)
1931
+
1932
+ try:
1933
+ return coercion_model.bin_op(left, right, mod)
1934
+ except TypeError:
1935
+ return NotImplemented
1936
+
1937
+ cdef _mod_(self, other):
1938
+ """
1939
+ Virtual modulo method for elements with identical parents.
1940
+
1941
+ This default Cython implementation of ``_mod_`` calls the
1942
+ Python method ``self._mod_`` if it exists. This method may be
1943
+ defined in the ``ElementMethods`` of the category of the parent.
1944
+ If the method is not found, a :exc:`TypeError` is raised
1945
+ indicating that the operation is not supported.
1946
+
1947
+ See :ref:`element_arithmetic`.
1948
+
1949
+ EXAMPLES:
1950
+
1951
+ This method is not visible from Python::
1952
+
1953
+ sage: from sage.structure.element import Element
1954
+ sage: e = Element(Parent())
1955
+ sage: e._mod_(e)
1956
+ Traceback (most recent call last):
1957
+ ...
1958
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_mod_'...
1959
+ """
1960
+ try:
1961
+ python_op = (<object>self)._mod_
1962
+ except AttributeError:
1963
+ raise bin_op_exception('%', self, other)
1964
+ else:
1965
+ return python_op(other)
1966
+
1967
+ def __pow__(left, right, modulus):
1968
+ """
1969
+ Top-level power operator for :class:`Element` invoking
1970
+ the coercion model.
1971
+
1972
+ See :ref:`element_arithmetic`.
1973
+
1974
+ EXAMPLES::
1975
+
1976
+ sage: from sage.structure.element import Element
1977
+ sage: class MyElement(Element):
1978
+ ....: def _add_(self, other):
1979
+ ....: return 42
1980
+ sage: e = MyElement(Parent())
1981
+ sage: e + e
1982
+ 42
1983
+ sage: a = Integers(389)['x']['y'](37)
1984
+ sage: p = sage.structure.element.RingElement.__pow__
1985
+ sage: p(a, 2)
1986
+ 202
1987
+ sage: p(a, 2, 1)
1988
+ Traceback (most recent call last):
1989
+ ...
1990
+ TypeError: the 3-argument version of pow() is not supported
1991
+
1992
+ ::
1993
+
1994
+ sage: # needs sage.symbolic
1995
+ sage: (2/3)^I
1996
+ (2/3)^I
1997
+ sage: (2/3)^sqrt(2)
1998
+ (2/3)^sqrt(2)
1999
+ sage: var('x,y,z,n')
2000
+ (x, y, z, n)
2001
+ sage: (2/3)^(x^n + y^n + z^n)
2002
+ (2/3)^(x^n + y^n + z^n)
2003
+ sage: (-7/11)^(tan(x)+exp(x))
2004
+ (-7/11)^(e^x + tan(x))
2005
+
2006
+ sage: float(1.2)**(1/2)
2007
+ 1.0954451150103321
2008
+ sage: complex(1,2)**(1/2) # needs sage.rings.complex_double
2009
+ (1.272019649514069+0.786151377757423...j)
2010
+
2011
+ TESTS::
2012
+
2013
+ sage: e = Element(Parent())
2014
+ sage: e ^ e
2015
+ Traceback (most recent call last):
2016
+ ...
2017
+ TypeError: unsupported operand parent(s) for ^: '<sage.structure.parent.Parent object at ...>' and '<sage.structure.parent.Parent object at ...>'
2018
+ sage: 1 ^ e
2019
+ Traceback (most recent call last):
2020
+ ...
2021
+ TypeError: unsupported operand parent(s) for ^: 'Integer Ring' and '<sage.structure.parent.Parent object at ...>'
2022
+ sage: e ^ 1
2023
+ Traceback (most recent call last):
2024
+ ...
2025
+ TypeError: unsupported operand parent(s) for ^: '<sage.structure.parent.Parent object at ...>' and 'Integer Ring'
2026
+ sage: int(1) ^ e
2027
+ Traceback (most recent call last):
2028
+ ...
2029
+ TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'sage.structure.element.Element'
2030
+ sage: e ^ int(1)
2031
+ Traceback (most recent call last):
2032
+ ...
2033
+ TypeError: unsupported operand type(s) for ** or pow(): 'sage.structure.element.Element' and 'int'
2034
+ sage: None ^ e
2035
+ Traceback (most recent call last):
2036
+ ...
2037
+ TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'sage.structure.element.Element'
2038
+ sage: e ^ None
2039
+ Traceback (most recent call last):
2040
+ ...
2041
+ TypeError: unsupported operand type(s) for ** or pow(): 'sage.structure.element.Element' and 'NoneType'
2042
+ """
2043
+ # The coercion model does not support a modulus
2044
+ if modulus is not None:
2045
+ raise TypeError("the 3-argument version of pow() is not supported")
2046
+
2047
+ cdef int cl = classify_elements(left, right)
2048
+ if HAVE_SAME_PARENT(cl):
2049
+ return (<Element>left)._pow_(right)
2050
+ if BOTH_ARE_ELEMENT(cl):
2051
+ return coercion_model.bin_op(left, right, pow)
2052
+
2053
+ cdef long value
2054
+ cdef int err = -1
2055
+ try:
2056
+ # Special case powering with Python integers
2057
+ integer_check_long_py(right, &value, &err)
2058
+ if not err:
2059
+ return (<Element>left)._pow_long(value)
2060
+ return coercion_model.bin_op(left, right, pow)
2061
+ except TypeError:
2062
+ return NotImplemented
2063
+
2064
+ cdef _pow_(self, other):
2065
+ """
2066
+ Virtual powering method for elements with identical parents.
2067
+
2068
+ This default Cython implementation of ``_pow_`` calls the
2069
+ Python method ``self._pow_`` if it exists. This method may be
2070
+ defined in the ``ElementMethods`` of the category of the parent.
2071
+ If the method is not found, a :exc:`TypeError` is raised
2072
+ indicating that the operation is not supported.
2073
+
2074
+ See :ref:`element_arithmetic`.
2075
+
2076
+ EXAMPLES:
2077
+
2078
+ This method is not visible from Python::
2079
+
2080
+ sage: from sage.structure.element import Element
2081
+ sage: e = Element(Parent())
2082
+ sage: e._pow_(e)
2083
+ Traceback (most recent call last):
2084
+ ...
2085
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_pow_'...
2086
+ """
2087
+ try:
2088
+ python_op = (<object>self)._pow_
2089
+ except AttributeError:
2090
+ raise bin_op_exception('^', self, other)
2091
+ else:
2092
+ return python_op(other)
2093
+
2094
+ cdef _pow_int(self, other):
2095
+ """
2096
+ Virtual powering method for powering to an integer exponent.
2097
+
2098
+ This default Cython implementation of ``_pow_int`` calls the
2099
+ Python method ``self._pow_int`` if it exists. This method may be
2100
+ defined in the ``ElementMethods`` of the category of the parent.
2101
+ If the method is not found, a :exc:`TypeError` is raised
2102
+ indicating that the operation is not supported.
2103
+
2104
+ See :ref:`element_arithmetic`.
2105
+
2106
+ EXAMPLES:
2107
+
2108
+ This method is not visible from Python::
2109
+
2110
+ sage: from sage.structure.element import Element
2111
+ sage: e = Element(Parent())
2112
+ sage: e._pow_int(e)
2113
+ Traceback (most recent call last):
2114
+ ...
2115
+ AttributeError: 'sage.structure.element.Element' object has no attribute '_pow_int'...
2116
+ """
2117
+ try:
2118
+ python_op = (<object>self)._pow_int
2119
+ except AttributeError:
2120
+ raise bin_op_exception('^', self, other)
2121
+ else:
2122
+ return python_op(other)
2123
+
2124
+ cdef _pow_long(self, long n):
2125
+ """
2126
+ Generic path for powering with a C long.
2127
+ """
2128
+ return self._pow_int(n)
2129
+
2130
+
2131
+ def is_ModuleElement(x):
2132
+ """
2133
+ Return ``True`` if x is of type ModuleElement.
2134
+
2135
+ This is even faster than using isinstance inline.
2136
+
2137
+ EXAMPLES::
2138
+
2139
+ sage: from sage.structure.element import is_ModuleElement
2140
+ sage: is_ModuleElement(2/3)
2141
+ doctest:warning...
2142
+ DeprecationWarning: The function is_ModuleElement is deprecated; use 'isinstance(..., ModuleElement)' instead.
2143
+ See https://github.com/sagemath/sage/issues/38077 for details.
2144
+ True
2145
+ sage: is_ModuleElement((QQ^3).0) # needs sage.modules
2146
+ True
2147
+ sage: is_ModuleElement('a')
2148
+ False
2149
+ """
2150
+ from sage.misc.superseded import deprecation_cython
2151
+ deprecation_cython(38077, "The function is_ModuleElement is deprecated; use 'isinstance(..., ModuleElement)' instead.")
2152
+ return isinstance(x, ModuleElement)
2153
+
2154
+
2155
+ cdef class ElementWithCachedMethod(Element):
2156
+ r"""
2157
+ An element class that fully supports cached methods.
2158
+
2159
+ NOTE:
2160
+
2161
+ The :class:`~sage.misc.cachefunc.cached_method` decorator provides
2162
+ a convenient way to automatically cache the result of a computation.
2163
+ Since :issue:`11115`, the cached method decorator applied to a
2164
+ method without optional arguments is faster than a hand-written cache
2165
+ in Python, and a cached method without any arguments (except ``self``)
2166
+ is actually faster than a Python method that does nothing more but
2167
+ to return ``1``. A cached method can also be inherited from the parent
2168
+ or element class of a category.
2169
+
2170
+ However, this holds true only if attribute assignment is supported.
2171
+ If you write an extension class in Cython that does not accept attribute
2172
+ assignment then a cached method inherited from the category will be
2173
+ slower (for :class:`~sage.structure.parent.Parent`) or the cache would
2174
+ even break (for :class:`Element`).
2175
+
2176
+ This class should be used if you write an element class, cannot provide
2177
+ it with attribute assignment, but want that it inherits a cached method
2178
+ from the category. Under these conditions, your class should inherit
2179
+ from this class rather than :class:`Element`. Then, the cache will work,
2180
+ but certainly slower than with attribute assignment. Lazy attributes
2181
+ work as well.
2182
+
2183
+ EXAMPLES:
2184
+
2185
+ We define three element extension classes. The first inherits from
2186
+ :class:`Element`, the second from this class, and the third simply
2187
+ is a Python class. We also define a parent class and, in Python, a
2188
+ category whose element and parent classes define cached methods.
2189
+ ::
2190
+
2191
+ sage: # needs sage.misc.cython
2192
+ sage: cython_code = ["from sage.structure.element cimport Element, ElementWithCachedMethod",
2193
+ ....: "from sage.structure.richcmp cimport richcmp",
2194
+ ....: "cdef class MyBrokenElement(Element):",
2195
+ ....: " cdef public object x",
2196
+ ....: " def __init__(self, P, x):",
2197
+ ....: " self.x = x",
2198
+ ....: " Element.__init__(self, P)",
2199
+ ....: " def __neg__(self):",
2200
+ ....: " return MyBrokenElement(self.parent(), -self.x)",
2201
+ ....: " def _repr_(self):",
2202
+ ....: " return '<%s>' % self.x",
2203
+ ....: " def __hash__(self):",
2204
+ ....: " return hash(self.x)",
2205
+ ....: " cpdef _richcmp_(left, right, int op):",
2206
+ ....: " return richcmp(left.x, right.x, op)",
2207
+ ....: " def raw_test(self):",
2208
+ ....: " return -self",
2209
+ ....: "cdef class MyElement(ElementWithCachedMethod):",
2210
+ ....: " cdef public object x",
2211
+ ....: " def __init__(self, P, x):",
2212
+ ....: " self.x = x",
2213
+ ....: " Element.__init__(self, P)",
2214
+ ....: " def __neg__(self):",
2215
+ ....: " return MyElement(self.parent(), -self.x)",
2216
+ ....: " def _repr_(self):",
2217
+ ....: " return '<%s>' % self.x",
2218
+ ....: " def __hash__(self):",
2219
+ ....: " return hash(self.x)",
2220
+ ....: " cpdef _richcmp_(left, right, int op):",
2221
+ ....: " return richcmp(left.x, right.x, op)",
2222
+ ....: " def raw_test(self):",
2223
+ ....: " return -self",
2224
+ ....: "class MyPythonElement(MyBrokenElement): pass",
2225
+ ....: "from sage.structure.parent cimport Parent",
2226
+ ....: "cdef class MyParent(Parent):",
2227
+ ....: " Element = MyElement"]
2228
+ sage: cython('\n'.join(cython_code))
2229
+ sage: cython_code = ["from sage.misc.cachefunc import cached_method",
2230
+ ....: "from sage.misc.cachefunc import cached_in_parent_method",
2231
+ ....: "from sage.categories.category import Category",
2232
+ ....: "from sage.categories.objects import Objects",
2233
+ ....: "class MyCategory(Category):",
2234
+ ....: " @cached_method",
2235
+ ....: " def super_categories(self):",
2236
+ ....: " return [Objects()]",
2237
+ ....: " class ElementMethods:",
2238
+ ....: " @cached_method",
2239
+ ....: " def element_cache_test(self):",
2240
+ ....: " return -self",
2241
+ ....: " @cached_in_parent_method",
2242
+ ....: " def element_via_parent_test(self):",
2243
+ ....: " return -self",
2244
+ ....: " class ParentMethods:",
2245
+ ....: " @cached_method",
2246
+ ....: " def one(self):",
2247
+ ....: " return self.element_class(self,1)",
2248
+ ....: " @cached_method",
2249
+ ....: " def invert(self, x):",
2250
+ ....: " return -x"]
2251
+ sage: cython('\n'.join(cython_code))
2252
+ sage: C = MyCategory()
2253
+ sage: P = MyParent(category=C)
2254
+ sage: ebroken = MyBrokenElement(P, 5)
2255
+ sage: e = MyElement(P, 5)
2256
+
2257
+ The cached methods inherited by ``MyElement`` works::
2258
+
2259
+ sage: # needs sage.misc.cython
2260
+ sage: e.element_cache_test()
2261
+ <-5>
2262
+ sage: e.element_cache_test() is e.element_cache_test()
2263
+ True
2264
+ sage: e.element_via_parent_test()
2265
+ <-5>
2266
+ sage: e.element_via_parent_test() is e.element_via_parent_test()
2267
+ True
2268
+
2269
+ The other element class can only inherit a
2270
+ ``cached_in_parent_method``, since the cache is stored in the
2271
+ parent. In fact, equal elements share the cache, even if they are
2272
+ of different types::
2273
+
2274
+ sage: e == ebroken # needs sage.misc.cython
2275
+ True
2276
+ sage: type(e) == type(ebroken) # needs sage.misc.cython
2277
+ False
2278
+ sage: ebroken.element_via_parent_test() is e.element_via_parent_test() # needs sage.misc.cython
2279
+ True
2280
+
2281
+ However, the cache of the other inherited method breaks, although the method
2282
+ as such works::
2283
+
2284
+ sage: ebroken.element_cache_test() # needs sage.misc.cython
2285
+ <-5>
2286
+ sage: ebroken.element_cache_test() is ebroken.element_cache_test() # needs sage.misc.cython
2287
+ False
2288
+
2289
+ Since ``e`` and ``ebroken`` share the cache, when we empty it for one element
2290
+ it is empty for the other as well::
2291
+
2292
+ sage: b = ebroken.element_via_parent_test() # needs sage.misc.cython
2293
+ sage: e.element_via_parent_test.clear_cache() # needs sage.misc.cython
2294
+ sage: b is ebroken.element_via_parent_test() # needs sage.misc.cython
2295
+ False
2296
+
2297
+ Note that the cache only breaks for elements that do no allow attribute assignment.
2298
+ A Python version of ``MyBrokenElement`` therefore allows for cached methods::
2299
+
2300
+ sage: epython = MyPythonElement(P, 5) # needs sage.misc.cython
2301
+ sage: epython.element_cache_test() # needs sage.misc.cython
2302
+ <-5>
2303
+ sage: epython.element_cache_test() is epython.element_cache_test() # needs sage.misc.cython
2304
+ True
2305
+ """
2306
+ cdef getattr_from_category(self, name):
2307
+ """
2308
+ This getattr method ensures that cached methods and lazy attributes
2309
+ can be inherited from the element class of a category.
2310
+
2311
+ .. NOTE::
2312
+
2313
+ The use of cached methods is demonstrated in the main doc
2314
+ string of this class. Here, we demonstrate lazy
2315
+ attributes.
2316
+
2317
+ EXAMPLES::
2318
+
2319
+ sage: # needs sage.misc.cython
2320
+ sage: cython(
2321
+ ....: '''
2322
+ ....: from sage.structure.element cimport ElementWithCachedMethod
2323
+ ....: cdef class MyElement(ElementWithCachedMethod):
2324
+ ....: cdef public object x
2325
+ ....: def __init__(self, P, x):
2326
+ ....: self.x = x
2327
+ ....: ElementWithCachedMethod.__init__(self,P)
2328
+ ....: def _repr_(self):
2329
+ ....: return '<%s>'%self.x
2330
+ ....: from sage.structure.parent cimport Parent
2331
+ ....: cdef class MyParent(Parent):
2332
+ ....: Element = MyElement
2333
+ ....: from sage.misc.cachefunc import cached_method
2334
+ ....: from sage.misc.lazy_attribute import lazy_attribute
2335
+ ....: from sage.categories.category import Category
2336
+ ....: from sage.categories.objects import Objects
2337
+ ....: class MyCategory(Category):
2338
+ ....: @cached_method
2339
+ ....: def super_categories(self):
2340
+ ....: return [Objects()]
2341
+ ....: class ElementMethods:
2342
+ ....: @lazy_attribute
2343
+ ....: def my_lazy_attr(self):
2344
+ ....: return 'lazy attribute of <%s>'%self.x
2345
+ ....: ''')
2346
+ sage: C = MyCategory()
2347
+ sage: P = MyParent(category=C)
2348
+ sage: e = MyElement(P, 5)
2349
+ sage: e.my_lazy_attr
2350
+ 'lazy attribute of <5>'
2351
+ sage: e.my_lazy_attr is e.my_lazy_attr
2352
+ True
2353
+ """
2354
+ try:
2355
+ return self._cached_methods[name]
2356
+ except KeyError:
2357
+ attr = getattr_from_other_class(self,
2358
+ self._parent.category().element_class,
2359
+ name)
2360
+ self._cached_methods[name] = attr
2361
+ return attr
2362
+ except TypeError:
2363
+ attr = getattr_from_other_class(self,
2364
+ self._parent.category().element_class,
2365
+ name)
2366
+ self._cached_methods = {name: attr}
2367
+ return attr
2368
+
2369
+
2370
+ cdef class ModuleElement(Element):
2371
+ """
2372
+ Generic element of a module.
2373
+ """
2374
+ cpdef _add_(self, other):
2375
+ """
2376
+ Abstract addition method.
2377
+
2378
+ TESTS::
2379
+
2380
+ sage: from sage.structure.element import ModuleElement
2381
+ sage: e = ModuleElement(Parent())
2382
+ sage: e + e
2383
+ Traceback (most recent call last):
2384
+ ...
2385
+ NotImplementedError: addition not implemented for <sage.structure.parent.Parent object at ...>
2386
+ """
2387
+ raise NotImplementedError(f"addition not implemented for {self._parent}")
2388
+
2389
+ cdef _add_long(self, long n):
2390
+ """
2391
+ Generic path for adding a C long, assumed to commute.
2392
+ """
2393
+ if n == 0:
2394
+ return self
2395
+ return coercion_model.bin_op(self, n, add)
2396
+
2397
+ cpdef _sub_(self, other):
2398
+ """
2399
+ Default implementation of subtraction using addition and
2400
+ negation.
2401
+ """
2402
+ return self + (-other)
2403
+
2404
+ cpdef _neg_(self):
2405
+ """
2406
+ Default implementation of negation using multiplication
2407
+ with -1.
2408
+ """
2409
+ return self._mul_long(-1)
2410
+
2411
+ cdef _mul_long(self, long n):
2412
+ """
2413
+ Generic path for multiplying by a C long, assumed to commute.
2414
+ """
2415
+ if n == 1:
2416
+ return self
2417
+ return coercion_model.bin_op(self, n, mul)
2418
+
2419
+ # rmul -- left * self
2420
+ cpdef _rmul_(self, Element left):
2421
+ """
2422
+ Reversed scalar multiplication for module elements with the
2423
+ module element on the right and the scalar on the left.
2424
+
2425
+ By default, we assume commutativity and reverse the arguments.
2426
+ """
2427
+ return self._lmul_(left)
2428
+
2429
+ # lmul -- self * right
2430
+ cpdef _lmul_(self, Element right):
2431
+ """
2432
+ Scalar multiplication for module elements with the module
2433
+ element on the left and the scalar on the right.
2434
+
2435
+ Returning ``None`` indicates that this action is not implemented here.
2436
+ """
2437
+ return None
2438
+
2439
+ ##################################################
2440
+ # Other properties
2441
+ ##################################################
2442
+ def order(self):
2443
+ # DO NOT OVERRIDE THIS!!! Instead, override additive_order.
2444
+ """
2445
+ Return the additive order of ``self``.
2446
+ """
2447
+ return self.additive_order()
2448
+
2449
+ def additive_order(self):
2450
+ """
2451
+ Return the additive order of ``self``.
2452
+ """
2453
+ raise NotImplementedError
2454
+
2455
+ cdef class ModuleElementWithMutability(ModuleElement):
2456
+ """
2457
+ Generic element of a module with mutability.
2458
+ """
2459
+
2460
+ def __init__(self, parent, is_immutable=False):
2461
+ """
2462
+ EXAMPLES::
2463
+
2464
+ sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3) # needs sage.modules
2465
+ sage: type(v) # needs sage.modules
2466
+ <class 'sage.modules.free_module_element.FreeModuleElement'>
2467
+ """
2468
+ self._parent = parent
2469
+ self._is_immutable = is_immutable
2470
+
2471
+ def set_immutable(self):
2472
+ """
2473
+ Make this vector immutable. This operation can't be undone.
2474
+
2475
+ EXAMPLES::
2476
+
2477
+ sage: # needs sage.modules
2478
+ sage: v = vector([1..5]); v
2479
+ (1, 2, 3, 4, 5)
2480
+ sage: v[1] = 10
2481
+ sage: v.set_immutable()
2482
+ sage: v[1] = 10
2483
+ Traceback (most recent call last):
2484
+ ...
2485
+ ValueError: vector is immutable; please change a copy instead (use copy())
2486
+ """
2487
+ self._is_immutable = 1
2488
+
2489
+ cpdef bint is_mutable(self) noexcept:
2490
+ """
2491
+ Return ``True`` if this vector is mutable, i.e., the entries can be
2492
+ changed.
2493
+
2494
+ EXAMPLES::
2495
+
2496
+ sage: v = vector(QQ['x,y'], [1..5]); v.is_mutable() # needs sage.modules
2497
+ True
2498
+ sage: v.set_immutable() # needs sage.modules
2499
+ sage: v.is_mutable() # needs sage.modules
2500
+ False
2501
+ """
2502
+ return not self._is_immutable
2503
+
2504
+ cpdef bint is_immutable(self) noexcept:
2505
+ """
2506
+ Return ``True`` if this vector is immutable, i.e., the entries cannot
2507
+ be changed.
2508
+
2509
+ EXAMPLES::
2510
+
2511
+ sage: v = vector(QQ['x,y'], [1..5]); v.is_immutable() # needs sage.modules
2512
+ False
2513
+ sage: v.set_immutable() # needs sage.modules
2514
+ sage: v.is_immutable() # needs sage.modules
2515
+ True
2516
+ """
2517
+ return self._is_immutable
2518
+
2519
+
2520
+ ########################################################################
2521
+ # Monoid
2522
+ ########################################################################
2523
+
2524
+ def is_MonoidElement(x):
2525
+ """
2526
+ Return ``True`` if x is of type MonoidElement.
2527
+ """
2528
+ from sage.misc.superseded import deprecation_cython
2529
+ deprecation_cython(38077, "The function is_MonoidElement is deprecated; use 'isinstance(..., MonoidElement)' instead.")
2530
+ return isinstance(x, MonoidElement)
2531
+
2532
+
2533
+ cdef class MonoidElement(Element):
2534
+ """
2535
+ Generic element of a monoid.
2536
+ """
2537
+
2538
+ #############################################################
2539
+ # Other generic functions that should be available to
2540
+ # any monoid element.
2541
+ #############################################################
2542
+ def order(self):
2543
+ """
2544
+ Return the multiplicative order of ``self``.
2545
+ """
2546
+ return self.multiplicative_order()
2547
+
2548
+ def multiplicative_order(self):
2549
+ """
2550
+ Return the multiplicative order of ``self``.
2551
+ """
2552
+ raise NotImplementedError
2553
+
2554
+ cpdef _pow_int(self, n):
2555
+ """
2556
+ Return the (integral) power of ``self``.
2557
+ """
2558
+ return arith_generic_power(self, n)
2559
+
2560
+ def powers(self, n):
2561
+ r"""
2562
+ Return the list `[x^0, x^1, \ldots, x^{n-1}]`.
2563
+
2564
+ EXAMPLES::
2565
+
2566
+ sage: G = SymmetricGroup(4) # needs sage.groups
2567
+ sage: g = G([2, 3, 4, 1]) # needs sage.groups
2568
+ sage: g.powers(4) # needs sage.groups
2569
+ [(), (1,2,3,4), (1,3)(2,4), (1,4,3,2)]
2570
+ """
2571
+ if n < 0:
2572
+ raise ValueError("negative number of powers requested")
2573
+ elif n == 0:
2574
+ return []
2575
+ x = self._parent.one()
2576
+ l = [x]
2577
+ for i in range(n - 1):
2578
+ x = x * self
2579
+ l.append(x)
2580
+ return l
2581
+
2582
+ def __bool__(self):
2583
+ return True
2584
+
2585
+
2586
+ def is_AdditiveGroupElement(x):
2587
+ """
2588
+ Return ``True`` if x is of type AdditiveGroupElement.
2589
+ """
2590
+ from sage.misc.superseded import deprecation_cython
2591
+ deprecation_cython(38077, "The function is_AdditiveGroupElement is deprecated; use 'isinstance(..., AdditiveGroupElement)' instead.")
2592
+ return isinstance(x, AdditiveGroupElement)
2593
+
2594
+
2595
+ cdef class AdditiveGroupElement(ModuleElement):
2596
+ """
2597
+ Generic element of an additive group.
2598
+ """
2599
+ def order(self):
2600
+ """
2601
+ Return additive order of element
2602
+ """
2603
+ return self.additive_order()
2604
+
2605
+ def __invert__(self):
2606
+ raise NotImplementedError("multiplicative inverse not defined for additive group elements")
2607
+
2608
+
2609
+ def is_MultiplicativeGroupElement(x):
2610
+ """
2611
+ Return ``True`` if x is of type MultiplicativeGroupElement.
2612
+ """
2613
+ from sage.misc.superseded import deprecation_cython
2614
+ deprecation_cython(38077, "The function is_MultiplicativeGroupElement is deprecated; use 'isinstance(..., MultiplicativeGroupElement)' instead.")
2615
+ return isinstance(x, MultiplicativeGroupElement)
2616
+
2617
+
2618
+ cdef class MultiplicativeGroupElement(MonoidElement):
2619
+ """
2620
+ Generic element of a multiplicative group.
2621
+ """
2622
+ def order(self):
2623
+ """
2624
+ Return the multiplicative order of ``self``.
2625
+ """
2626
+ return self.multiplicative_order()
2627
+
2628
+ cpdef _div_(self, right):
2629
+ """
2630
+ Default implementation of division using multiplication by
2631
+ the inverse.
2632
+ """
2633
+ return self * ~right
2634
+
2635
+ def __invert__(self):
2636
+ r"""
2637
+ Return the multiplicative inverse of ``self``.
2638
+
2639
+ This may cause infinite recursion because of the default definition
2640
+ of division using inversion in ``_div_``.
2641
+ """
2642
+ return self._parent.one() / self
2643
+
2644
+
2645
+ def is_RingElement(x):
2646
+ """
2647
+ Return ``True`` if x is of type RingElement.
2648
+ """
2649
+ from sage.misc.superseded import deprecation_cython
2650
+ deprecation_cython(38077, "The function is_RingElement is deprecated; use 'isinstance(..., RingElement)' instead.")
2651
+ return isinstance(x, RingElement)
2652
+
2653
+
2654
+ cdef class RingElement(ModuleElement):
2655
+ cpdef _mul_(self, other):
2656
+ """
2657
+ Abstract multiplication method.
2658
+
2659
+ TESTS::
2660
+
2661
+ sage: from sage.structure.element import RingElement
2662
+ sage: e = RingElement(Parent())
2663
+ sage: e * e
2664
+ Traceback (most recent call last):
2665
+ ...
2666
+ NotImplementedError: multiplication not implemented for <sage.structure.parent.Parent object at ...>
2667
+ """
2668
+ raise NotImplementedError(f"multiplication not implemented for {self._parent}")
2669
+
2670
+ def is_one(self):
2671
+ return self == self._parent.one()
2672
+
2673
+ cpdef _pow_int(self, n):
2674
+ """
2675
+ Return the (integral) power of ``self``.
2676
+
2677
+ EXAMPLES::
2678
+
2679
+ sage: a = GF(389)['x']['y'](37)
2680
+ sage: p = sage.structure.element.RingElement.__pow__
2681
+ sage: p(a,2)
2682
+ 202
2683
+ sage: p(a,2,1)
2684
+ Traceback (most recent call last):
2685
+ ...
2686
+ TypeError: the 3-argument version of pow() is not supported
2687
+ sage: p(a,388)
2688
+ 1
2689
+ sage: p(a,2^120)
2690
+ 81
2691
+ sage: p(a,0)
2692
+ 1
2693
+ sage: p(a,1) == a
2694
+ True
2695
+ sage: p(a,2) * p(a,3) == p(a,5)
2696
+ True
2697
+ sage: p(a,3)^2 == p(a,6)
2698
+ True
2699
+ sage: p(a,57) * p(a,43) == p(a,100)
2700
+ True
2701
+ sage: p(a,-1) == 1/a
2702
+ True
2703
+ sage: p(a,200) * p(a,-64) == p(a,136)
2704
+ True
2705
+ sage: p(2, 1/2) # needs sage.symbolic
2706
+ sqrt(2)
2707
+
2708
+ TESTS:
2709
+
2710
+ These are not testing this code, but they are probably good to have around::
2711
+
2712
+ sage: 2r**(SR(2)-1-1r) # needs sage.symbolic
2713
+ 1
2714
+ sage: 2r^(1/2) # needs sage.symbolic
2715
+ sqrt(2)
2716
+
2717
+ Exponent overflow should throw an :exc:`OverflowError` (:issue:`2956`)::
2718
+
2719
+ sage: K.<x,y> = AA[] # needs sage.rings.number_field
2720
+ sage: x^(2^64 + 12345) # known bug: macos # needs sage.rings.number_field
2721
+ Traceback (most recent call last):
2722
+ ...
2723
+ OverflowError: exponent overflow (2147483648)
2724
+
2725
+ Another example from :issue:`2956` which always overflows
2726
+ with Singular 4::
2727
+
2728
+ sage: K.<x,y> = ZZ[]
2729
+ sage: (x^123456)^654321
2730
+ Traceback (most recent call last):
2731
+ ...
2732
+ OverflowError: exponent overflow (...)
2733
+ """
2734
+ return arith_generic_power(self, n)
2735
+
2736
+ def powers(self, n):
2737
+ r"""
2738
+ Return the list `[x^0, x^1, \ldots, x^{n-1}]`.
2739
+
2740
+ EXAMPLES::
2741
+
2742
+ sage: 5.powers(3)
2743
+ [1, 5, 25]
2744
+ """
2745
+ if n < 0:
2746
+ raise ValueError("negative number of powers requested")
2747
+ elif n == 0:
2748
+ return []
2749
+ x = self._parent.one()
2750
+ l = [x]
2751
+ for i in range(n - 1):
2752
+ x = x * self
2753
+ l.append(x)
2754
+ return l
2755
+
2756
+ cpdef _div_(self, other):
2757
+ """
2758
+ Default implementation of division using the fraction field.
2759
+ """
2760
+ try:
2761
+ frac = self._parent.fraction_field()
2762
+ except AttributeError:
2763
+ raise bin_op_exception('/', self, other)
2764
+ return frac(self, other)
2765
+
2766
+ def __divmod__(self, other):
2767
+ """
2768
+ Return the quotient and remainder of ``self`` divided by ``other``.
2769
+
2770
+ This operation may not be defined in all rings.
2771
+
2772
+ EXAMPLES::
2773
+
2774
+ sage: divmod(5,3)
2775
+ (1, 2)
2776
+ sage: divmod(25r,12)
2777
+ (2, 1)
2778
+ sage: divmod(25,12r)
2779
+ (2, 1)
2780
+
2781
+ ::
2782
+
2783
+ sage: R.<x> = QQ[]
2784
+ sage: f = -19/13*x^5 - x^4 - 2/3*x^3 + 6*x^2 - 2
2785
+ sage: g = 3*x^2 + 5
2786
+ sage: q,r = divmod(f,g)
2787
+ sage: q
2788
+ -19/39*x^3 - 1/3*x^2 + 23/39*x + 23/9
2789
+ sage: r
2790
+ -115/39*x - 133/9
2791
+ sage: f == q*g + r
2792
+ True
2793
+
2794
+ ::
2795
+
2796
+ sage: R.<x> = ZZ[]
2797
+ sage: f = -2*x^5 + x^4 - 9*x^3 - 5*x^2 + 7*x + 4
2798
+ sage: g = x^2 + 5
2799
+ sage: q,r = divmod(f,g)
2800
+ sage: q
2801
+ -2*x^3 + x^2 + x - 10
2802
+ sage: r
2803
+ 2*x + 54
2804
+ sage: f == q*g + r
2805
+ True
2806
+ sage: h = 3*x^2 + 5
2807
+ sage: q,r = divmod(f,h)
2808
+ sage: q
2809
+ -3*x - 2
2810
+ sage: r
2811
+ -2*x^5 + x^4 + x^2 + 22*x + 14
2812
+ sage: f == q*h + r
2813
+ True
2814
+
2815
+ ::
2816
+
2817
+ sage: R.<x> = GF(7)[]
2818
+ sage: divmod(x^2, x - 1)
2819
+ (x + 1, 1)
2820
+
2821
+ ::
2822
+
2823
+ sage: divmod(22./7, RR(pi)) # needs sage.symbolic
2824
+ (1.00040249943477, 0.000000000000000)
2825
+ """
2826
+ try:
2827
+ return self.quo_rem(other)
2828
+ except (AttributeError, NotImplementedError):
2829
+ pass
2830
+ return (self // other, self % other)
2831
+
2832
+ def __invert__(self):
2833
+ return self._parent.one() / self
2834
+
2835
+ def additive_order(self):
2836
+ """
2837
+ Return the additive order of ``self``.
2838
+ """
2839
+ raise NotImplementedError
2840
+
2841
+ def multiplicative_order(self):
2842
+ r"""
2843
+ Return the multiplicative order of ``self``, if ``self`` is a unit.
2844
+
2845
+ This raises an :class:`ArithmeticError` otherwise.
2846
+ """
2847
+ if not self.is_unit():
2848
+ raise ArithmeticError("self (=%s) must be a unit to have a multiplicative order.")
2849
+ raise NotImplementedError
2850
+
2851
+ def is_nilpotent(self):
2852
+ """
2853
+ Return ``True`` if ``self`` is nilpotent, i.e., some power of ``self``
2854
+ is 0.
2855
+
2856
+ TESTS::
2857
+
2858
+ sage: a = QQ(2)
2859
+ sage: a.is_nilpotent()
2860
+ False
2861
+ sage: a = QQ(0)
2862
+ sage: a.is_nilpotent()
2863
+ True
2864
+ sage: m = matrix(QQ, 3, [[3,2,3], [9,0,3], [-9,0,-3]]) # needs sage.modules
2865
+ sage: m.is_nilpotent() # needs sage.libs.pari sage.modules
2866
+ True
2867
+ """
2868
+ if self.is_unit():
2869
+ return False
2870
+ if self.is_zero():
2871
+ return True
2872
+ raise NotImplementedError
2873
+
2874
+ def abs(self):
2875
+ """
2876
+ Return the absolute value of ``self``. (This just calls the ``__abs__``
2877
+ method, so it is equivalent to the ``abs()`` built-in function.)
2878
+
2879
+ EXAMPLES::
2880
+
2881
+ sage: RR(-1).abs() # needs sage.rings.real_mpfr
2882
+ 1.00000000000000
2883
+ sage: ZZ(-1).abs()
2884
+ 1
2885
+ sage: CC(I).abs() # needs sage.rings.real_mpfr sage.symbolic
2886
+ 1.00000000000000
2887
+ sage: Mod(-15, 37).abs()
2888
+ Traceback (most recent call last):
2889
+ ...
2890
+ ArithmeticError: absolute value not defined on integers modulo n.
2891
+ """
2892
+ return abs(self)
2893
+
2894
+ def is_prime(self):
2895
+ """
2896
+ Check whether ``self`` is a prime element.
2897
+
2898
+ A *prime* element is a nonzero, non-unit element `p` such that,
2899
+ whenever `p` divides `ab` for some `a` and `b`, then `p`
2900
+ divides `a` or `p` divides `b`.
2901
+
2902
+ EXAMPLES:
2903
+
2904
+ For polynomial rings, prime is the same as irreducible::
2905
+
2906
+ sage: # needs sage.libs.singular
2907
+ sage: R.<x,y> = QQ[]
2908
+ sage: x.is_prime()
2909
+ True
2910
+ sage: (x^2 + y^3).is_prime()
2911
+ True
2912
+ sage: (x^2 - y^2).is_prime()
2913
+ False
2914
+ sage: R(0).is_prime()
2915
+ False
2916
+ sage: R(2).is_prime()
2917
+ False
2918
+
2919
+ For the Gaussian integers::
2920
+
2921
+ sage: # needs sage.rings.number_field
2922
+ sage: K.<i> = QuadraticField(-1)
2923
+ sage: ZI = K.ring_of_integers()
2924
+ sage: ZI(3).is_prime()
2925
+ True
2926
+ sage: ZI(5).is_prime()
2927
+ False
2928
+ sage: ZI(2 + i).is_prime()
2929
+ True
2930
+ sage: ZI(0).is_prime()
2931
+ False
2932
+ sage: ZI(1).is_prime()
2933
+ False
2934
+
2935
+ In fields, an element is never prime::
2936
+
2937
+ sage: RR(0).is_prime()
2938
+ False
2939
+ sage: RR(2).is_prime()
2940
+ False
2941
+
2942
+ For integers, :meth:`is_prime` redefines prime numbers to be
2943
+ positive::
2944
+
2945
+ sage: (-2).is_prime()
2946
+ False
2947
+ sage: RingElement.is_prime(-2) # needs sage.libs.pari
2948
+ True
2949
+
2950
+ Similarly,
2951
+ :class:`~sage.rings.number_field.number_field_base.NumberField`
2952
+ redefines :meth:`is_prime` to determine primality in the ring
2953
+ of integers::
2954
+
2955
+ sage: # needs sage.rings.number_field
2956
+ sage: (1 + i).is_prime()
2957
+ True
2958
+ sage: K(5).is_prime()
2959
+ False
2960
+ sage: K(7).is_prime()
2961
+ True
2962
+ sage: K(7/13).is_prime()
2963
+ False
2964
+
2965
+ However, for rationals, :meth:`is_prime` *does* follow the
2966
+ general definition of prime elements in a ring (i.e., always
2967
+ returns ``False``) since the rationals are not a
2968
+ :class:`~sage.rings.number_field.number_field_base.NumberField`
2969
+ in Sage::
2970
+
2971
+ sage: QQ(7).is_prime()
2972
+ False
2973
+ """
2974
+ if not self: # We exclude the 0 element
2975
+ return False
2976
+ return self._parent.ideal(self).is_prime()
2977
+
2978
+
2979
+ def is_CommutativeRingElement(x):
2980
+ """
2981
+ Return ``True`` if x is of type CommutativeRingElement.
2982
+
2983
+ TESTS::
2984
+
2985
+ sage: from sage.structure.element import is_CommutativeRingElement
2986
+ sage: is_CommutativeRingElement(oo)
2987
+ doctest:warning...
2988
+ DeprecationWarning: The function is_CommutativeRingElement is deprecated; use 'isinstance(..., CommutativeRingElement)' instead.
2989
+ See https://github.com/sagemath/sage/issues/38077 for details.
2990
+ False
2991
+
2992
+ sage: is_CommutativeRingElement(1)
2993
+ True
2994
+ """
2995
+ from sage.misc.superseded import deprecation_cython
2996
+ deprecation_cython(38077, "The function is_CommutativeRingElement is deprecated; use 'isinstance(..., CommutativeRingElement)' instead.")
2997
+ return isinstance(x, CommutativeRingElement)
2998
+
2999
+
3000
+ cdef class CommutativeRingElement(RingElement):
3001
+ """
3002
+ Base class for elements of commutative rings.
3003
+ """
3004
+
3005
+ def inverse_mod(self, I):
3006
+ r"""
3007
+ Return an inverse of ``self`` modulo the ideal `I`, if defined,
3008
+ i.e., if `I` and ``self`` together generate the unit ideal.
3009
+
3010
+ EXAMPLES::
3011
+
3012
+ sage: # needs sage.rings.finite_rings
3013
+ sage: F = GF(25)
3014
+ sage: x = F.gen()
3015
+ sage: z = F.zero()
3016
+ sage: x.inverse_mod(F.ideal(z))
3017
+ 2*z2 + 3
3018
+ sage: x.inverse_mod(F.ideal(1))
3019
+ 1
3020
+ sage: z.inverse_mod(F.ideal(1))
3021
+ 1
3022
+ sage: z.inverse_mod(F.ideal(z))
3023
+ Traceback (most recent call last):
3024
+ ...
3025
+ ValueError: an element of a proper ideal does not have an inverse modulo that ideal
3026
+ """
3027
+ if I.is_one():
3028
+ return self.parent().one()
3029
+ elif self in I:
3030
+ raise ValueError("an element of a proper ideal does not have an inverse modulo that ideal")
3031
+ elif hasattr(self, "is_unit") and self.is_unit():
3032
+ return self.inverse_of_unit()
3033
+ else:
3034
+ raise NotImplementedError
3035
+
3036
+ def divides(self, x):
3037
+ """
3038
+ Return ``True`` if ``self`` divides x.
3039
+
3040
+ EXAMPLES::
3041
+
3042
+ sage: P.<x> = PolynomialRing(QQ)
3043
+ sage: x.divides(x^2)
3044
+ True
3045
+ sage: x.divides(x^2 + 2)
3046
+ False
3047
+ sage: (x^2 + 2).divides(x)
3048
+ False
3049
+ sage: P.<x> = PolynomialRing(ZZ)
3050
+ sage: x.divides(x^2)
3051
+ True
3052
+ sage: x.divides(x^2 + 2)
3053
+ False
3054
+ sage: (x^2 + 2).divides(x)
3055
+ False
3056
+
3057
+ :issue:`5347` has been fixed::
3058
+
3059
+ sage: K = GF(7)
3060
+ sage: K(3).divides(1)
3061
+ True
3062
+ sage: K(3).divides(K(1))
3063
+ True
3064
+
3065
+ ::
3066
+
3067
+ sage: R = Integers(128)
3068
+ sage: R(0).divides(1)
3069
+ False
3070
+ sage: R(0).divides(0)
3071
+ True
3072
+ sage: R(0).divides(R(0))
3073
+ True
3074
+ sage: R(1).divides(0)
3075
+ True
3076
+ sage: R(121).divides(R(120))
3077
+ True
3078
+ sage: R(120).divides(R(121))
3079
+ False
3080
+
3081
+ If ``x`` has different parent than ``self``, they are first coerced to a
3082
+ common parent if possible. If this coercion fails, it returns a
3083
+ :exc:`TypeError`. This fixes :issue:`5759`. ::
3084
+
3085
+ sage: Zmod(2)(0).divides(Zmod(2)(0))
3086
+ True
3087
+ sage: Zmod(2)(0).divides(Zmod(2)(1))
3088
+ False
3089
+ sage: Zmod(5)(1).divides(Zmod(2)(1))
3090
+ Traceback (most recent call last):
3091
+ ...
3092
+ TypeError: no common canonical parent for objects with parents:
3093
+ 'Ring of integers modulo 5' and 'Ring of integers modulo 2'
3094
+ sage: Zmod(35)(4).divides(Zmod(7)(1))
3095
+ True
3096
+ sage: Zmod(35)(7).divides(Zmod(7)(1))
3097
+ False
3098
+ """
3099
+ if have_same_parent(self, x):
3100
+ # First we test some generic conditions:
3101
+ try:
3102
+ if x.is_zero():
3103
+ return True # everything divides 0
3104
+ except (AttributeError, NotImplementedError):
3105
+ pass
3106
+
3107
+ try:
3108
+ if self.is_zero():
3109
+ return False # 0 divides nothing else
3110
+ except (AttributeError, NotImplementedError):
3111
+ pass
3112
+
3113
+ try:
3114
+ if self.is_unit():
3115
+ return True # units divide everything
3116
+ except (AttributeError, NotImplementedError):
3117
+ pass
3118
+
3119
+ try:
3120
+ if self.is_one():
3121
+ return True
3122
+ # 1 divides everything
3123
+ # (is_unit() may not be implemented)
3124
+ except (AttributeError, NotImplementedError):
3125
+ pass
3126
+
3127
+ try:
3128
+ return (x % self).is_zero()
3129
+ except (TypeError, NotImplementedError):
3130
+ pass
3131
+
3132
+ raise NotImplementedError
3133
+
3134
+ else:
3135
+ # Different parents, use coercion
3136
+ a, b = coercion_model.canonical_coercion(self, x)
3137
+ return a.divides(b)
3138
+
3139
+ def mod(self, I):
3140
+ r"""
3141
+ Return a representative for ``self`` modulo the ideal I (or the ideal
3142
+ generated by the elements of I if I is not an ideal.)
3143
+
3144
+ EXAMPLES: Integers
3145
+ Reduction of 5 modulo an ideal::
3146
+
3147
+ sage: n = 5
3148
+ sage: n.mod(3*ZZ)
3149
+ 2
3150
+
3151
+ Reduction of 5 modulo the ideal generated by 3::
3152
+
3153
+ sage: n.mod(3)
3154
+ 2
3155
+
3156
+ Reduction of 5 modulo the ideal generated by 15 and 6, which is `(3)`.
3157
+
3158
+ ::
3159
+
3160
+ sage: n.mod([15,6])
3161
+ 2
3162
+
3163
+ EXAMPLES: Univariate polynomials
3164
+
3165
+ ::
3166
+
3167
+ sage: R.<x> = PolynomialRing(QQ)
3168
+ sage: f = x^3 + x + 1
3169
+ sage: f.mod(x + 1)
3170
+ -1
3171
+
3172
+ Reduction for `\ZZ[x]`::
3173
+
3174
+ sage: R.<x> = PolynomialRing(ZZ)
3175
+ sage: f = x^3 + x + 1
3176
+ sage: f.mod(x + 1)
3177
+ -1
3178
+
3179
+ When little is implemented about a given ring, then ``mod`` may
3180
+ simply return `f`.
3181
+
3182
+ EXAMPLES: Multivariate polynomials
3183
+ We reduce a polynomial in two variables modulo a polynomial
3184
+ and an ideal::
3185
+
3186
+ sage: R.<x,y,z> = PolynomialRing(QQ, 3)
3187
+ sage: (x^2 + y^2 + z^2).mod(x + y + z) # needs sage.libs.singular
3188
+ 2*y^2 + 2*y*z + 2*z^2
3189
+
3190
+ Notice above that `x` is eliminated. In the next example,
3191
+ both `y` and `z` are eliminated::
3192
+
3193
+ sage: (x^2 + y^2 + z^2).mod( (x - y, y - z) ) # needs sage.libs.singular
3194
+ 3*z^2
3195
+ sage: f = (x^2 + y^2 + z^2)^2; f
3196
+ x^4 + 2*x^2*y^2 + y^4 + 2*x^2*z^2 + 2*y^2*z^2 + z^4
3197
+ sage: f.mod( (x - y, y - z) ) # needs sage.libs.singular
3198
+ 9*z^4
3199
+
3200
+ In this example `y` is eliminated::
3201
+
3202
+ sage: (x^2 + y^2 + z^2).mod( (x^3, y - z) ) # needs sage.libs.singular
3203
+ x^2 + 2*z^2
3204
+ """
3205
+ from sage.rings.ideal import Ideal_generic
3206
+ if not isinstance(I, Ideal_generic) or not I.ring() is self._parent:
3207
+ I = self._parent.ideal(I)
3208
+ return I.reduce(self)
3209
+
3210
+
3211
+ ##############################################
3212
+
3213
+ cdef class Expression(CommutativeRingElement):
3214
+
3215
+ r"""
3216
+ Abstract base class for :class:`~sage.symbolic.expression.Expression`.
3217
+
3218
+ This class is defined for the purpose of :func:`isinstance` tests. It should not be
3219
+ instantiated.
3220
+
3221
+ EXAMPLES::
3222
+
3223
+ sage: isinstance(SR.var('y'), sage.structure.element.Expression) # needs sage.symbolic
3224
+ True
3225
+
3226
+ By design, there is a unique direct subclass::
3227
+
3228
+ sage: len(sage.structure.element.Expression.__subclasses__()) <= 1
3229
+ True
3230
+ """
3231
+
3232
+ pass
3233
+
3234
+ ##############################################
3235
+
3236
+ cdef class Vector(ModuleElementWithMutability):
3237
+ cdef bint is_sparse_c(self) noexcept:
3238
+ raise NotImplementedError
3239
+
3240
+ cdef bint is_dense_c(self) noexcept:
3241
+ raise NotImplementedError
3242
+
3243
+ def __mul__(left, right):
3244
+ """
3245
+ Multiplication of vector by vector, matrix, or scalar.
3246
+
3247
+ AUTHOR:
3248
+
3249
+ - Gonzalo Tornaria (2007-06-21) - write test cases and fix them
3250
+
3251
+ .. NOTE::
3252
+
3253
+ scalar * vector is implemented (and tested) in class RingElement
3254
+ matrix * vector is implemented (and tested) in class Matrix
3255
+
3256
+ TESTS:
3257
+
3258
+ Here we test (vector * vector) multiplication::
3259
+
3260
+ sage: # needs sage.modules
3261
+ sage: parent(vector(ZZ, [1,2]) * vector(ZZ, [1,2]))
3262
+ Integer Ring
3263
+ sage: parent(vector(ZZ, [1,2]) * vector(QQ, [1,2]))
3264
+ Rational Field
3265
+ sage: parent(vector(QQ, [1,2]) * vector(ZZ, [1,2]))
3266
+ Rational Field
3267
+ sage: parent(vector(QQ, [1,2]) * vector(QQ, [1,2]))
3268
+ Rational Field
3269
+
3270
+ sage: parent(vector(QQ, [1,2,3,4]) * vector(ZZ['x'], [1,2,3,4])) # needs sage.modules
3271
+ Univariate Polynomial Ring in x over Rational Field
3272
+ sage: parent(vector(ZZ['x'], [1,2,3,4]) * vector(QQ, [1,2,3,4])) # needs sage.modules
3273
+ Univariate Polynomial Ring in x over Rational Field
3274
+
3275
+ sage: parent(vector(QQ, [1,2,3,4]) * vector(ZZ['x']['y'], [1,2,3,4])) # needs sage.modules
3276
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3277
+ sage: parent(vector(ZZ['x']['y'], [1,2,3,4]) * vector(QQ, [1,2,3,4])) # needs sage.modules
3278
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3279
+
3280
+ sage: parent(vector(QQ['x'], [1,2,3,4]) * vector(ZZ['x']['y'], [1,2,3,4])) # needs sage.modules
3281
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3282
+ sage: parent(vector(ZZ['x']['y'], [1,2,3,4]) * vector(QQ['x'], [1,2,3,4])) # needs sage.modules
3283
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3284
+
3285
+ sage: parent(vector(QQ['y'], [1,2,3,4]) * vector(ZZ['x']['y'], [1,2,3,4])) # needs sage.modules
3286
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3287
+ sage: parent(vector(ZZ['x']['y'], [1,2,3,4]) * vector(QQ['y'], [1,2,3,4])) # needs sage.modules
3288
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3289
+
3290
+ sage: # needs sage.modules
3291
+ sage: parent(vector(ZZ['x'], [1,2,3,4]) * vector(ZZ['y'], [1,2,3,4]))
3292
+ Traceback (most recent call last):
3293
+ ...
3294
+ TypeError: unsupported operand parent(s) for *:
3295
+ 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and
3296
+ 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
3297
+ sage: parent(vector(ZZ['x'], [1,2,3,4]) * vector(QQ['y'], [1,2,3,4]))
3298
+ Traceback (most recent call last):
3299
+ ...
3300
+ TypeError: unsupported operand parent(s) for *:
3301
+ 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and
3302
+ 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
3303
+ sage: parent(vector(QQ['x'], [1,2,3,4]) * vector(ZZ['y'], [1,2,3,4]))
3304
+ Traceback (most recent call last):
3305
+ ...
3306
+ TypeError: unsupported operand parent(s) for *:
3307
+ 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and
3308
+ 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
3309
+ sage: parent(vector(QQ['x'], [1,2,3,4]) * vector(QQ['y'], [1,2,3,4]))
3310
+ Traceback (most recent call last):
3311
+ ...
3312
+ TypeError: unsupported operand parent(s) for *:
3313
+ 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and
3314
+ 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
3315
+
3316
+ Here we test (vector * matrix) multiplication::
3317
+
3318
+ sage: # needs sage.modules
3319
+ sage: parent(vector(ZZ, [1,2]) * matrix(ZZ, 2, 2, [1,2,3,4]))
3320
+ Ambient free module of rank 2 over the principal ideal domain Integer Ring
3321
+ sage: parent(vector(QQ, [1,2]) * matrix(ZZ, 2, 2, [1,2,3,4]))
3322
+ Vector space of dimension 2 over Rational Field
3323
+ sage: parent(vector(ZZ, [1,2]) * matrix(QQ, 2, 2, [1,2,3,4]))
3324
+ Vector space of dimension 2 over Rational Field
3325
+ sage: parent(vector(QQ, [1,2]) * matrix(QQ, 2, 2, [1,2,3,4]))
3326
+ Vector space of dimension 2 over Rational Field
3327
+
3328
+ sage: parent(vector(QQ, [1,2]) * matrix(ZZ['x'], 2, 2, [1,2,3,4])) # needs sage.modules
3329
+ Ambient free module of rank 2
3330
+ over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
3331
+ sage: parent(vector(ZZ['x'], [1,2]) * matrix(QQ, 2, 2, [1,2,3,4])) # needs sage.modules
3332
+ Ambient free module of rank 2
3333
+ over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
3334
+
3335
+ sage: parent(vector(QQ, [1,2]) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3336
+ Ambient free module of rank 2 over the integral domain
3337
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3338
+ sage: parent(vector(ZZ['x']['y'], [1,2]) * matrix(QQ, 2, 2, [1,2,3,4])) # needs sage.modules
3339
+ Ambient free module of rank 2 over the integral domain
3340
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3341
+
3342
+ sage: parent(vector(QQ['x'], [1,2]) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3343
+ Ambient free module of rank 2 over the integral domain
3344
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3345
+ sage: parent(vector(ZZ['x']['y'], [1,2]) * matrix(QQ['x'], 2, 2, [1,2,3,4])) # needs sage.modules
3346
+ Ambient free module of rank 2 over the integral domain
3347
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3348
+
3349
+ sage: parent(vector(QQ['y'], [1,2]) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3350
+ Ambient free module of rank 2 over the integral domain
3351
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3352
+ sage: parent(vector(ZZ['x']['y'], [1,2]) * matrix(QQ['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3353
+ Ambient free module of rank 2 over the integral domain
3354
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3355
+
3356
+ sage: # needs sage.modules
3357
+ sage: parent(vector(ZZ['x'], [1,2]) * matrix(ZZ['y'], 2, 2, [1,2,3,4]))
3358
+ Traceback (most recent call last):
3359
+ ...
3360
+ TypeError: unsupported operand parent(s) for *:
3361
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and
3362
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
3363
+ sage: parent(vector(ZZ['x'], [1,2]) * matrix(QQ['y'], 2, 2, [1,2,3,4]))
3364
+ Traceback (most recent call last):
3365
+ ...
3366
+ TypeError: unsupported operand parent(s) for *:
3367
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and
3368
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
3369
+ sage: parent(vector(QQ['x'], [1,2]) * matrix(ZZ['y'], 2, 2, [1,2,3,4]))
3370
+ Traceback (most recent call last):
3371
+ ...
3372
+ TypeError: unsupported operand parent(s) for *:
3373
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and
3374
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
3375
+ sage: parent(vector(QQ['x'], [1,2]) * matrix(QQ['y'], 2, 2, [1,2,3,4]))
3376
+ Traceback (most recent call last):
3377
+ ...
3378
+ TypeError: unsupported operand parent(s) for *:
3379
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and
3380
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
3381
+
3382
+ Here we test (vector * scalar) multiplication::
3383
+
3384
+ sage: # needs sage.modules
3385
+ sage: parent(vector(ZZ, [1,2]) * ZZ(1))
3386
+ Ambient free module of rank 2 over the principal ideal domain Integer Ring
3387
+ sage: parent(vector(QQ, [1,2]) * ZZ(1))
3388
+ Vector space of dimension 2 over Rational Field
3389
+ sage: parent(vector(ZZ, [1,2]) * QQ(1))
3390
+ Vector space of dimension 2 over Rational Field
3391
+ sage: parent(vector(QQ, [1,2]) * QQ(1))
3392
+ Vector space of dimension 2 over Rational Field
3393
+
3394
+ sage: parent(vector(QQ, [1,2]) * ZZ['x'](1)) # needs sage.modules
3395
+ Ambient free module of rank 2
3396
+ over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
3397
+ sage: parent(vector(ZZ['x'], [1,2]) * QQ(1)) # needs sage.modules
3398
+ Ambient free module of rank 2
3399
+ over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
3400
+
3401
+ sage: parent(vector(QQ, [1,2]) * ZZ['x']['y'](1)) # needs sage.modules
3402
+ Ambient free module of rank 2 over the integral domain
3403
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3404
+ sage: parent(vector(ZZ['x']['y'], [1,2]) * QQ(1)) # needs sage.modules
3405
+ Ambient free module of rank 2 over the integral domain
3406
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3407
+
3408
+ sage: parent(vector(QQ['x'], [1,2]) * ZZ['x']['y'](1)) # needs sage.modules
3409
+ Ambient free module of rank 2 over the integral domain
3410
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3411
+ sage: parent(vector(ZZ['x']['y'], [1,2]) * QQ['x'](1)) # needs sage.modules
3412
+ Ambient free module of rank 2 over the integral domain
3413
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3414
+
3415
+ sage: parent(vector(QQ['y'], [1,2]) * ZZ['x']['y'](1)) # needs sage.modules
3416
+ Ambient free module of rank 2 over the integral domain
3417
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3418
+ sage: parent(vector(ZZ['x']['y'], [1,2]) * QQ['y'](1)) # needs sage.modules
3419
+ Ambient free module of rank 2 over the integral domain
3420
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3421
+
3422
+ sage: # needs sage.modules
3423
+ sage: parent(vector(ZZ['x'], [1,2]) * ZZ['y'](1))
3424
+ Traceback (most recent call last):
3425
+ ...
3426
+ TypeError: unsupported operand parent(s) for *:
3427
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and
3428
+ 'Univariate Polynomial Ring in y over Integer Ring'
3429
+ sage: parent(vector(ZZ['x'], [1,2]) * QQ['y'](1))
3430
+ Traceback (most recent call last):
3431
+ ...
3432
+ TypeError: unsupported operand parent(s) for *:
3433
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and
3434
+ 'Univariate Polynomial Ring in y over Rational Field'
3435
+ sage: parent(vector(QQ['x'], [1,2]) * ZZ['y'](1))
3436
+ Traceback (most recent call last):
3437
+ ...
3438
+ TypeError: unsupported operand parent(s) for *:
3439
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and
3440
+ 'Univariate Polynomial Ring in y over Integer Ring'
3441
+ sage: parent(vector(QQ['x'], [1,2]) * QQ['y'](1))
3442
+ Traceback (most recent call last):
3443
+ ...
3444
+ TypeError: unsupported operand parent(s) for *:
3445
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and
3446
+ 'Univariate Polynomial Ring in y over Rational Field'
3447
+
3448
+ Here we test (scalar * vector) multiplication::
3449
+
3450
+ sage: # needs sage.modules
3451
+ sage: parent(ZZ(1) * vector(ZZ, [1,2]))
3452
+ Ambient free module of rank 2 over the principal ideal domain Integer Ring
3453
+ sage: parent(QQ(1) * vector(ZZ, [1,2]))
3454
+ Vector space of dimension 2 over Rational Field
3455
+ sage: parent(ZZ(1) * vector(QQ, [1,2]))
3456
+ Vector space of dimension 2 over Rational Field
3457
+ sage: parent(QQ(1) * vector(QQ, [1,2]))
3458
+ Vector space of dimension 2 over Rational Field
3459
+
3460
+ sage: parent(QQ(1) * vector(ZZ['x'], [1,2])) # needs sage.modules
3461
+ Ambient free module of rank 2
3462
+ over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
3463
+ sage: parent(ZZ['x'](1) * vector(QQ, [1,2])) # needs sage.modules
3464
+ Ambient free module of rank 2
3465
+ over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
3466
+
3467
+ sage: parent(QQ(1) * vector(ZZ['x']['y'], [1,2])) # needs sage.modules
3468
+ Ambient free module of rank 2 over the integral domain
3469
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3470
+ sage: parent(ZZ['x']['y'](1) * vector(QQ, [1,2])) # needs sage.modules
3471
+ Ambient free module of rank 2 over the integral domain
3472
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3473
+
3474
+ sage: parent(QQ['x'](1) * vector(ZZ['x']['y'], [1,2])) # needs sage.modules
3475
+ Ambient free module of rank 2 over the integral domain
3476
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3477
+ sage: parent(ZZ['x']['y'](1) * vector(QQ['x'], [1,2])) # needs sage.modules
3478
+ Ambient free module of rank 2 over the integral domain
3479
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3480
+
3481
+ sage: parent(QQ['y'](1) * vector(ZZ['x']['y'], [1,2])) # needs sage.modules
3482
+ Ambient free module of rank 2 over the integral domain
3483
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3484
+ sage: parent(ZZ['x']['y'](1) * vector(QQ['y'], [1,2])) # needs sage.modules
3485
+ Ambient free module of rank 2 over the integral domain
3486
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3487
+
3488
+ sage: # needs sage.modules
3489
+ sage: parent(ZZ['x'](1) * vector(ZZ['y'], [1,2]))
3490
+ Traceback (most recent call last):
3491
+ ...
3492
+ TypeError: unsupported operand parent(s) for *:
3493
+ 'Univariate Polynomial Ring in x over Integer Ring' and
3494
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
3495
+ sage: parent(ZZ['x'](1) * vector(QQ['y'], [1,2]))
3496
+ Traceback (most recent call last):
3497
+ ...
3498
+ TypeError: unsupported operand parent(s) for *:
3499
+ 'Univariate Polynomial Ring in x over Integer Ring' and
3500
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
3501
+ sage: parent(QQ['x'](1) * vector(ZZ['y'], [1,2]))
3502
+ Traceback (most recent call last):
3503
+ ...
3504
+ TypeError: unsupported operand parent(s) for *:
3505
+ 'Univariate Polynomial Ring in x over Rational Field' and
3506
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
3507
+ sage: parent(QQ['x'](1) * vector(QQ['y'], [1,2]))
3508
+ Traceback (most recent call last):
3509
+ ...
3510
+ TypeError: unsupported operand parent(s) for *:
3511
+ 'Univariate Polynomial Ring in x over Rational Field' and
3512
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
3513
+ """
3514
+ if have_same_parent(left, right):
3515
+ return (<Vector>left)._dot_product_(<Vector>right)
3516
+ return coercion_model.bin_op(left, right, mul)
3517
+
3518
+ cpdef _dot_product_(Vector left, Vector right):
3519
+ return left._dot_product_coerce_(right)
3520
+
3521
+ cpdef _dot_product_coerce_(Vector left, Vector right):
3522
+ raise bin_op_exception('*', left, right)
3523
+
3524
+ cpdef _pairwise_product_(Vector left, Vector right):
3525
+ raise TypeError("unsupported operation for '%s' and '%s'" % (parent(left), parent(right)))
3526
+
3527
+ def __truediv__(self, right):
3528
+ """
3529
+ Divide this vector by a scalar, vector or matrix.
3530
+
3531
+ TESTS::
3532
+
3533
+ sage: # needs sage.modules
3534
+ sage: A = matrix([[1, 2], [0, 3]])
3535
+ sage: b = vector([0, 1])
3536
+ sage: x = b / A; x
3537
+ (0, 1/3)
3538
+ sage: x == b * ~A
3539
+ True
3540
+ sage: A = matrix([[1, 2], [0, 3], [1, 5]])
3541
+ sage: (b / A) * A == b
3542
+ True
3543
+ """
3544
+ right = py_scalar_to_element(right)
3545
+ if isinstance(right, RingElement):
3546
+ # Let __mul__ do the job
3547
+ return self * ~right
3548
+ if isinstance(right, Vector):
3549
+ try:
3550
+ W = (<Vector>right)._parent.submodule([right])
3551
+ return W.coordinates(self)[0] / W.coordinates(right)[0]
3552
+ except ArithmeticError:
3553
+ if right.is_zero():
3554
+ raise ZeroDivisionError("division by zero vector")
3555
+ else:
3556
+ raise ArithmeticError("vector is not in free module")
3557
+ if isinstance(right, Matrix):
3558
+ return right.solve_left(self)
3559
+ raise bin_op_exception('/', self, right)
3560
+
3561
+ def _magma_init_(self, magma):
3562
+ """
3563
+ Return string that evaluates in Magma to something equivalent
3564
+ to this vector.
3565
+
3566
+ EXAMPLES::
3567
+
3568
+ sage: # optional - magma, needs sage.modules
3569
+ sage: v = vector([1,2,3])
3570
+ sage: v._magma_init_(magma)
3571
+ '_sage_[...]![1,2,3]'
3572
+ sage: mv = magma(v); mv
3573
+ (1 2 3)
3574
+ sage: mv.Type()
3575
+ ModTupRngElt
3576
+ sage: mv.Parent()
3577
+ Full RSpace of degree 3 over Integer Ring
3578
+
3579
+ sage: # optional - magma, needs sage.modules
3580
+ sage: v = vector(QQ, [1/2, 3/4, 5/6])
3581
+ sage: mv = magma(v); mv
3582
+ (1/2 3/4 5/6)
3583
+ sage: mv.Type()
3584
+ ModTupFldElt
3585
+ sage: mv.Parent()
3586
+ Full Vector space of degree 3 over Rational Field
3587
+
3588
+ A more demanding example::
3589
+
3590
+ sage: # optional - magma, needs sage.modules
3591
+ sage: R.<x,y,z> = QQ[]
3592
+ sage: v = vector([x^3, y, 2/3*z + x/y])
3593
+ sage: magma(v)
3594
+ ( x^3 y (2/3*y*z + x)/y)
3595
+ sage: magma(v).Parent()
3596
+ Full Vector space of degree 3
3597
+ over Multivariate rational function field of rank 3 over Rational Field
3598
+ """
3599
+ V = magma(self._parent)
3600
+ v = [x._magma_init_(magma) for x in self.list()]
3601
+ return '%s![%s]' % (V.name(), ','.join(v))
3602
+
3603
+
3604
+ def is_Vector(x):
3605
+ from sage.misc.superseded import deprecation_cython
3606
+ deprecation_cython(38077, "The function is_Vector is deprecated; use 'isinstance(..., Vector)' instead.")
3607
+ return isinstance(x, Vector)
3608
+
3609
+
3610
+ cdef class Matrix(ModuleElement):
3611
+
3612
+ cdef bint is_sparse_c(self) noexcept:
3613
+ raise NotImplementedError
3614
+
3615
+ cdef bint is_dense_c(self) noexcept:
3616
+ raise NotImplementedError
3617
+
3618
+ def __mul__(left, right):
3619
+ """
3620
+ Multiplication of matrix by matrix, vector, or scalar.
3621
+
3622
+ AUTHOR:
3623
+
3624
+ - Gonzalo Tornaria (2007-06-25) - write test cases and fix them
3625
+
3626
+ .. NOTE::
3627
+
3628
+ scalar * matrix is implemented (and tested) in class RingElement
3629
+ vector * matrix is implemented (and tested) in class Vector
3630
+
3631
+ TESTS:
3632
+
3633
+ Here we test (matrix * matrix) multiplication::
3634
+
3635
+ sage: # needs sage.modules
3636
+ sage: parent(matrix(ZZ, 2, 2, [1,2,3,4]) * matrix(ZZ, 2, 2, [1,2,3,4]))
3637
+ Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
3638
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * matrix(ZZ, 2, 2, [1,2,3,4]))
3639
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3640
+ sage: parent(matrix(ZZ, 2, 2, [1,2,3,4]) * matrix(QQ, 2, 2, [1,2,3,4]))
3641
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3642
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * matrix(QQ, 2, 2, [1,2,3,4]))
3643
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3644
+
3645
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * matrix(ZZ['x'], 2, 2, [1,2,3,4])) # needs sage.modules
3646
+ Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
3647
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * matrix(QQ, 2, 2, [1,2,3,4])) # needs sage.modules
3648
+ Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
3649
+
3650
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3651
+ Full MatrixSpace of 2 by 2 dense matrices over
3652
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3653
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * matrix(QQ, 2, 2, [1,2,3,4])) # needs sage.modules
3654
+ Full MatrixSpace of 2 by 2 dense matrices over
3655
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3656
+
3657
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3658
+ Full MatrixSpace of 2 by 2 dense matrices over
3659
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3660
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * matrix(QQ['x'], 2, 2, [1,2,3,4])) # needs sage.modules
3661
+ Full MatrixSpace of 2 by 2 dense matrices over
3662
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3663
+
3664
+ sage: parent(matrix(QQ['y'], 2, 2, [1,2,3,4]) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3665
+ Full MatrixSpace of 2 by 2 dense matrices over
3666
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3667
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * matrix(QQ['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3668
+ Full MatrixSpace of 2 by 2 dense matrices over
3669
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3670
+
3671
+ sage: # needs sage.modules
3672
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * matrix(ZZ['y'], 2, 2, [1,2,3,4]))
3673
+ Traceback (most recent call last):
3674
+ ...
3675
+ TypeError: unsupported operand parent(s) for *:
3676
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and
3677
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
3678
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * matrix(QQ['y'], 2, 2, [1,2,3,4]))
3679
+ Traceback (most recent call last):
3680
+ ...
3681
+ TypeError: unsupported operand parent(s) for *:
3682
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and
3683
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
3684
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * matrix(ZZ['y'], 2, 2, [1,2,3,4]))
3685
+ Traceback (most recent call last):
3686
+ ...
3687
+ TypeError: unsupported operand parent(s) for *:
3688
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and
3689
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
3690
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * matrix(QQ['y'], 2, 2, [1,2,3,4]))
3691
+ Traceback (most recent call last):
3692
+ ...
3693
+ TypeError: unsupported operand parent(s) for *:
3694
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and
3695
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
3696
+
3697
+ We test that the bug reported in :issue:`27352` has been fixed::
3698
+
3699
+ sage: A = matrix(QQ, [[1, 2], [-1, 0], [1, 1]]) # needs sage.modules
3700
+ sage: B = matrix(QQ, [[0, 4], [1, -1], [1, 2]]) # needs sage.modules
3701
+ sage: A * B # needs sage.modules
3702
+ Traceback (most recent call last):
3703
+ ...
3704
+ TypeError: unsupported operand parent(s) for *:
3705
+ 'Full MatrixSpace of 3 by 2 dense matrices over Rational Field' and 'Full MatrixSpace of 3 by 2 dense matrices over Rational Field'
3706
+
3707
+ Here we test (matrix * vector) multiplication::
3708
+
3709
+ sage: # needs sage.modules
3710
+ sage: parent(matrix(ZZ, 2, 2, [1,2,3,4]) * vector(ZZ, [1,2]))
3711
+ Ambient free module of rank 2 over the principal ideal domain Integer Ring
3712
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * vector(ZZ, [1,2]))
3713
+ Vector space of dimension 2 over Rational Field
3714
+ sage: parent(matrix(ZZ, 2, 2, [1,2,3,4]) * vector(QQ, [1,2]))
3715
+ Vector space of dimension 2 over Rational Field
3716
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * vector(QQ, [1,2]))
3717
+ Vector space of dimension 2 over Rational Field
3718
+
3719
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * vector(ZZ['x'], [1,2])) # needs sage.modules
3720
+ Ambient free module of rank 2 over the principal ideal domain
3721
+ Univariate Polynomial Ring in x over Rational Field
3722
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * vector(QQ, [1,2])) # needs sage.modules
3723
+ Ambient free module of rank 2 over the principal ideal domain
3724
+ Univariate Polynomial Ring in x over Rational Field
3725
+
3726
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * vector(ZZ['x']['y'], [1,2])) # needs sage.modules
3727
+ Ambient free module of rank 2 over the integral domain
3728
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3729
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * vector(QQ, [1,2])) # needs sage.modules
3730
+ Ambient free module of rank 2 over the integral domain
3731
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3732
+
3733
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * vector(ZZ['x']['y'], [1,2])) # needs sage.modules
3734
+ Ambient free module of rank 2 over the integral domain
3735
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3736
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * vector(QQ['x'], [1,2])) # needs sage.modules
3737
+ Ambient free module of rank 2 over the integral domain
3738
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3739
+
3740
+ sage: parent(matrix(QQ['y'], 2, 2, [1,2,3,4]) * vector(ZZ['x']['y'], [1,2])) # needs sage.modules
3741
+ Ambient free module of rank 2 over the integral domain
3742
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3743
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * vector(QQ['y'], [1,2])) # needs sage.modules
3744
+ Ambient free module of rank 2 over the integral domain
3745
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3746
+
3747
+ sage: # needs sage.modules
3748
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * vector(ZZ['y'], [1,2]))
3749
+ Traceback (most recent call last):
3750
+ ...
3751
+ TypeError: unsupported operand parent(s) for *:
3752
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and
3753
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
3754
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * vector(QQ['y'], [1,2]))
3755
+ Traceback (most recent call last):
3756
+ ...
3757
+ TypeError: unsupported operand parent(s) for *:
3758
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and
3759
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
3760
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * vector(ZZ['y'], [1,2]))
3761
+ Traceback (most recent call last):
3762
+ ...
3763
+ TypeError: unsupported operand parent(s) for *:
3764
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and
3765
+ 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
3766
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * vector(QQ['y'], [1,2]))
3767
+ Traceback (most recent call last):
3768
+ ...
3769
+ TypeError: unsupported operand parent(s) for *:
3770
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and
3771
+ 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
3772
+
3773
+ Here we test (matrix * scalar) multiplication::
3774
+
3775
+ sage: # needs sage.modules
3776
+ sage: parent(matrix(ZZ, 2, 2, [1,2,3,4]) * ZZ(1))
3777
+ Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
3778
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * ZZ(1))
3779
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3780
+ sage: parent(matrix(ZZ, 2, 2, [1,2,3,4]) * QQ(1))
3781
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3782
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * QQ(1))
3783
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3784
+
3785
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * ZZ['x'](1)) # needs sage.modules
3786
+ Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
3787
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * QQ(1)) # needs sage.modules
3788
+ Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
3789
+
3790
+ sage: parent(matrix(QQ, 2, 2, [1,2,3,4]) * ZZ['x']['y'](1)) # needs sage.modules
3791
+ Full MatrixSpace of 2 by 2 dense matrices over
3792
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3793
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * QQ(1)) # needs sage.modules
3794
+ Full MatrixSpace of 2 by 2 dense matrices over
3795
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3796
+
3797
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * ZZ['x']['y'](1)) # needs sage.modules
3798
+ Full MatrixSpace of 2 by 2 dense matrices over
3799
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3800
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * QQ['x'](1)) # needs sage.modules
3801
+ Full MatrixSpace of 2 by 2 dense matrices over
3802
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3803
+
3804
+ sage: parent(matrix(QQ['y'], 2, 2, [1,2,3,4]) * ZZ['x']['y'](1)) # needs sage.modules
3805
+ Full MatrixSpace of 2 by 2 dense matrices over
3806
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3807
+ sage: parent(matrix(ZZ['x']['y'], 2, 2, [1,2,3,4]) * QQ['y'](1)) # needs sage.modules
3808
+ Full MatrixSpace of 2 by 2 dense matrices over
3809
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3810
+
3811
+ sage: # needs sage.modules
3812
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * ZZ['y'](1))
3813
+ Traceback (most recent call last):
3814
+ ...
3815
+ TypeError: unsupported operand parent(s) for *:
3816
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and
3817
+ 'Univariate Polynomial Ring in y over Integer Ring'
3818
+ sage: parent(matrix(ZZ['x'], 2, 2, [1,2,3,4]) * QQ['y'](1))
3819
+ Traceback (most recent call last):
3820
+ ...
3821
+ TypeError: unsupported operand parent(s) for *:
3822
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and
3823
+ 'Univariate Polynomial Ring in y over Rational Field'
3824
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * ZZ['y'](1))
3825
+ Traceback (most recent call last):
3826
+ ...
3827
+ TypeError: unsupported operand parent(s) for *:
3828
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and
3829
+ 'Univariate Polynomial Ring in y over Integer Ring'
3830
+ sage: parent(matrix(QQ['x'], 2, 2, [1,2,3,4]) * QQ['y'](1))
3831
+ Traceback (most recent call last):
3832
+ ...
3833
+ TypeError: unsupported operand parent(s) for *:
3834
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and
3835
+ 'Univariate Polynomial Ring in y over Rational Field'
3836
+
3837
+ Here we test (scalar * matrix) multiplication::
3838
+
3839
+ sage: # needs sage.modules
3840
+ sage: parent(ZZ(1) * matrix(ZZ, 2, 2, [1,2,3,4]))
3841
+ Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
3842
+ sage: parent(QQ(1) * matrix(ZZ, 2, 2, [1,2,3,4]))
3843
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3844
+ sage: parent(ZZ(1) * matrix(QQ, 2, 2, [1,2,3,4]))
3845
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3846
+ sage: parent(QQ(1) * matrix(QQ, 2, 2, [1,2,3,4]))
3847
+ Full MatrixSpace of 2 by 2 dense matrices over Rational Field
3848
+
3849
+ sage: parent(QQ(1) * matrix(ZZ['x'], 2, 2, [1,2,3,4])) # needs sage.modules
3850
+ Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
3851
+ sage: parent(ZZ['x'](1) * matrix(QQ, 2, 2, [1,2,3,4])) # needs sage.modules
3852
+ Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
3853
+
3854
+ sage: parent(QQ(1) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3855
+ Full MatrixSpace of 2 by 2 dense matrices over
3856
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3857
+ sage: parent(ZZ['x']['y'](1) * matrix(QQ, 2, 2, [1,2,3,4])) # needs sage.modules
3858
+ Full MatrixSpace of 2 by 2 dense matrices over
3859
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3860
+
3861
+ sage: parent(QQ['x'](1) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3862
+ Full MatrixSpace of 2 by 2 dense matrices over
3863
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3864
+ sage: parent(ZZ['x']['y'](1) * matrix(QQ['x'], 2, 2, [1,2,3,4])) # needs sage.modules
3865
+ Full MatrixSpace of 2 by 2 dense matrices over
3866
+ Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3867
+
3868
+ sage: parent(QQ['y'](1) * matrix(ZZ['x']['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3869
+ Full MatrixSpace of 2 by 2 dense matrices
3870
+ over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3871
+ sage: parent(ZZ['x']['y'](1) * matrix(QQ['y'], 2, 2, [1,2,3,4])) # needs sage.modules
3872
+ Full MatrixSpace of 2 by 2 dense matrices
3873
+ over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
3874
+
3875
+ sage: # needs sage.modules
3876
+ sage: parent(ZZ['x'](1) * matrix(ZZ['y'], 2, 2, [1,2,3,4]))
3877
+ Traceback (most recent call last):
3878
+ ...
3879
+ TypeError: unsupported operand parent(s) for *:
3880
+ 'Univariate Polynomial Ring in x over Integer Ring' and
3881
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
3882
+ sage: parent(ZZ['x'](1) * matrix(QQ['y'], 2, 2, [1,2,3,4]))
3883
+ Traceback (most recent call last):
3884
+ ...
3885
+ TypeError: unsupported operand parent(s) for *:
3886
+ 'Univariate Polynomial Ring in x over Integer Ring' and
3887
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
3888
+ sage: parent(QQ['x'](1) * matrix(ZZ['y'], 2, 2, [1,2,3,4]))
3889
+ Traceback (most recent call last):
3890
+ ...
3891
+ TypeError: unsupported operand parent(s) for *:
3892
+ 'Univariate Polynomial Ring in x over Rational Field' and
3893
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
3894
+ sage: parent(QQ['x'](1) * matrix(QQ['y'], 2, 2, [1,2,3,4]))
3895
+ Traceback (most recent call last):
3896
+ ...
3897
+ TypeError: unsupported operand parent(s) for *:
3898
+ 'Univariate Polynomial Ring in x over Rational Field' and
3899
+ 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
3900
+
3901
+ Examples with matrices having matrix coefficients::
3902
+
3903
+ sage: m = matrix # needs sage.modules
3904
+ sage: a = m([[m([[1,2],[3,4]]),m([[5,6],[7,8]])],[m([[9,10],[11,12]]),m([[13,14],[15,16]])]]) # needs sage.modules
3905
+ sage: 3 * a # needs sage.modules
3906
+ [[ 3 6]
3907
+ [ 9 12] [15 18]
3908
+ [21 24]]
3909
+ [[27 30]
3910
+ [33 36] [39 42]
3911
+ [45 48]]
3912
+
3913
+ sage: m = matrix # needs sage.modules
3914
+ sage: a = m([[m([[1,2],[3,4]]),m([[5,6],[7,8]])],[m([[9,10],[11,12]]),m([[13,14],[15,16]])]]) # needs sage.modules
3915
+ sage: a * 3 # needs sage.modules
3916
+ [[ 3 6]
3917
+ [ 9 12] [15 18]
3918
+ [21 24]]
3919
+ [[27 30]
3920
+ [33 36] [39 42]
3921
+ [45 48]]
3922
+ """
3923
+ cdef int cl = classify_elements(left, right)
3924
+ if HAVE_SAME_PARENT(cl):
3925
+ # If they are matrices with the same parent, they had
3926
+ # better be square for the product to be defined.
3927
+ if (<Matrix>left)._nrows == (<Matrix>left)._ncols:
3928
+ return (<Matrix>left)._matrix_times_matrix_(<Matrix>right)
3929
+ else:
3930
+ parent = (<Matrix>left)._parent
3931
+ raise TypeError("unsupported operand parent(s) for *: '{}' and '{}'".format(parent, parent))
3932
+
3933
+ if BOTH_ARE_ELEMENT(cl):
3934
+ return coercion_model.bin_op(left, right, mul)
3935
+
3936
+ cdef long value
3937
+ cdef int err = -1
3938
+ try:
3939
+ # Special case multiplication with C long
3940
+ integer_check_long_py(right, &value, &err)
3941
+ if not err:
3942
+ return (<Element>left)._mul_long(value)
3943
+ integer_check_long_py(left, &value, &err)
3944
+ if not err:
3945
+ return (<Element>right)._mul_long(value)
3946
+ return coercion_model.bin_op(left, right, mul)
3947
+ except TypeError:
3948
+ return NotImplemented
3949
+
3950
+ def __truediv__(left, right):
3951
+ """
3952
+ Division of the matrix ``left`` by the matrix or scalar
3953
+ ``right``.
3954
+
3955
+ EXAMPLES::
3956
+
3957
+ sage: # needs sage.modules
3958
+ sage: a = matrix(ZZ, 2, range(4))
3959
+ sage: operator.truediv(a, 5)
3960
+ [ 0 1/5]
3961
+ [2/5 3/5]
3962
+ sage: a = matrix(ZZ, 2, range(4))
3963
+ sage: b = matrix(ZZ, 2, [1,1,0,5])
3964
+ sage: operator.truediv(a, b)
3965
+ [ 0 1/5]
3966
+ [ 2 1/5]
3967
+ sage: c = matrix(QQ, 2, [3,2,5,7])
3968
+ sage: operator.truediv(c, a)
3969
+ [-5/2 3/2]
3970
+ [-1/2 5/2]
3971
+
3972
+ TESTS::
3973
+
3974
+ sage: # needs sage.modules
3975
+ sage: a = matrix(ZZ, [[1, 2], [0, 3]])
3976
+ sage: b = matrix(ZZ, 3, 2, range(6))
3977
+ sage: x = b / a; x
3978
+ [ 0 1/3]
3979
+ [ 2 -1/3]
3980
+ [ 4 -1]
3981
+ sage: x == b * ~a
3982
+ True
3983
+ sage: a = matrix(ZZ, [[1, 2], [0, 3], [1, 5]])
3984
+ sage: (b / a) * a == b
3985
+ True
3986
+ """
3987
+ if isinstance(right, Matrix):
3988
+ return right.solve_left(left)
3989
+ return coercion_model.bin_op(left, right, truediv)
3990
+
3991
+ cdef _vector_times_matrix_(matrix_right, Vector vector_left):
3992
+ raise TypeError
3993
+
3994
+ cdef _matrix_times_vector_(matrix_left, Vector vector_right):
3995
+ raise TypeError
3996
+
3997
+ cdef _matrix_times_matrix_(left, Matrix right):
3998
+ raise TypeError
3999
+
4000
+
4001
+ def is_Matrix(x):
4002
+ from sage.misc.superseded import deprecation_cython
4003
+ deprecation_cython(38077, "The function is_Matrix is deprecated; use 'isinstance(..., Matrix)' instead.")
4004
+ return isinstance(x, Matrix)
4005
+
4006
+
4007
+ def is_IntegralDomainElement(x):
4008
+ """
4009
+ Return ``True`` if x is of type IntegralDomainElement.
4010
+ """
4011
+ from sage.misc.superseded import deprecation_cython
4012
+ deprecation_cython(38077, "The function is_IntegralDomainElement is deprecated; use 'isinstance(..., IntegralDomainElement)' instead.")
4013
+ return isinstance(x, IntegralDomainElement)
4014
+
4015
+
4016
+ cdef class IntegralDomainElement(CommutativeRingElement):
4017
+ def is_nilpotent(self):
4018
+ return self.is_zero()
4019
+
4020
+
4021
+ def is_DedekindDomainElement(x):
4022
+ """
4023
+ Return ``True`` if x is of type DedekindDomainElement.
4024
+ """
4025
+ from sage.misc.superseded import deprecation_cython
4026
+ deprecation_cython(38077, "The function is_DedekindDomainElement is deprecated; use 'isinstance(..., DedekindDomainElement)' instead.")
4027
+ return isinstance(x, DedekindDomainElement)
4028
+
4029
+
4030
+ cdef class DedekindDomainElement(IntegralDomainElement):
4031
+ pass
4032
+
4033
+
4034
+ def is_PrincipalIdealDomainElement(x):
4035
+ """
4036
+ Return ``True`` if x is of type PrincipalIdealDomainElement.
4037
+ """
4038
+ from sage.misc.superseded import deprecation_cython
4039
+ deprecation_cython(38077, "The function is_PrincipalIdealDomainElement is deprecated; use 'isinstance(..., PrincipalIdealDomainElement)' instead.")
4040
+ return isinstance(x, PrincipalIdealDomainElement)
4041
+
4042
+
4043
+ cdef class PrincipalIdealDomainElement(DedekindDomainElement):
4044
+ def gcd(self, right):
4045
+ r"""
4046
+ Return the greatest common divisor of ``self`` and ``other``.
4047
+
4048
+ TESTS:
4049
+
4050
+ :issue:`30849`::
4051
+
4052
+ sage: 2.gcd(pari(3)) # needs sage.libs.pari
4053
+ 1
4054
+ sage: type(2.gcd(pari(3))) # needs sage.libs.pari
4055
+ <class 'sage.rings.integer.Integer'>
4056
+
4057
+ sage: 2.gcd(pari('1/3')) # needs sage.libs.pari
4058
+ 1/3
4059
+ sage: type(2.gcd(pari('1/3'))) # needs sage.libs.pari
4060
+ <class 'sage.rings.rational.Rational'>
4061
+
4062
+ sage: import gmpy2
4063
+ sage: 2.gcd(gmpy2.mpz(3))
4064
+ 1
4065
+ sage: type(2.gcd(gmpy2.mpz(3)))
4066
+ <class 'sage.rings.integer.Integer'>
4067
+
4068
+ sage: 2.gcd(gmpy2.mpq(1,3))
4069
+ 1/3
4070
+ sage: type(2.gcd(pari('1/3'))) # needs sage.libs.pari
4071
+ <class 'sage.rings.rational.Rational'>
4072
+ """
4073
+ # NOTE: in order to handle nicely pari or gmpy2 integers we do not rely only on coercion
4074
+ if not isinstance(right, Element):
4075
+ right = py_scalar_to_element(right)
4076
+ if not isinstance(right, Element):
4077
+ right = right.sage()
4078
+ if not ((<Element>right)._parent is self._parent):
4079
+ from sage.arith.misc import GCD as gcd
4080
+ return coercion_model.bin_op(self, right, gcd)
4081
+ return self._gcd(right)
4082
+
4083
+ def lcm(self, right):
4084
+ """
4085
+ Return the least common multiple of ``self`` and ``right``.
4086
+
4087
+ TESTS:
4088
+
4089
+ :issue:`30849`::
4090
+
4091
+ sage: 2.lcm(pari(3)) # needs sage.libs.pari
4092
+ 6
4093
+ sage: type(2.lcm(pari(3))) # needs sage.libs.pari
4094
+ <class 'sage.rings.integer.Integer'>
4095
+
4096
+ sage: 2.lcm(pari('1/3')) # needs sage.libs.pari
4097
+ 2
4098
+ sage: type(2.lcm(pari('1/3'))) # needs sage.libs.pari
4099
+ <class 'sage.rings.rational.Rational'>
4100
+
4101
+ sage: import gmpy2
4102
+ sage: 2.lcm(gmpy2.mpz(3))
4103
+ 6
4104
+ sage: type(2.lcm(gmpy2.mpz(3)))
4105
+ <class 'sage.rings.integer.Integer'>
4106
+ """
4107
+ # NOTE: in order to handle nicely pari or gmpy2 integers we do not rely only on coercion
4108
+ if not isinstance(right, Element):
4109
+ right = py_scalar_to_element(right)
4110
+ if not isinstance(right, Element):
4111
+ right = right.sage()
4112
+ if not ((<Element>right)._parent is self._parent):
4113
+ from sage.arith.functions import lcm
4114
+ return coercion_model.bin_op(self, right, lcm)
4115
+ return self._lcm(right)
4116
+
4117
+ # This is pretty nasty low level stuff. The idea is to speed up construction
4118
+ # of EuclideanDomainElements (in particular Integers) by skipping some tp_new
4119
+ # calls up the inheritance tree.
4120
+ PY_SET_TP_NEW(EuclideanDomainElement, Element)
4121
+
4122
+
4123
+ def is_EuclideanDomainElement(x):
4124
+ """
4125
+ Return ``True`` if x is of type EuclideanDomainElement.
4126
+ """
4127
+ from sage.misc.superseded import deprecation_cython
4128
+ deprecation_cython(38077, "The function is_EuclideanDomainElement is deprecated; use 'isinstance(..., EuclideanDomainElement)' instead.")
4129
+ return isinstance(x, EuclideanDomainElement)
4130
+
4131
+
4132
+ cdef class EuclideanDomainElement(PrincipalIdealDomainElement):
4133
+
4134
+ def degree(self):
4135
+ raise NotImplementedError
4136
+
4137
+ def leading_coefficient(self):
4138
+ raise NotImplementedError
4139
+
4140
+ def quo_rem(self, other):
4141
+ raise NotImplementedError
4142
+
4143
+ cpdef _floordiv_(self, right):
4144
+ """
4145
+ Quotient of division of ``self`` by ``other``. This is denoted ``//``.
4146
+
4147
+ This default implementation assumes that ``quo_rem`` has been
4148
+ implemented.
4149
+
4150
+ EXAMPLES::
4151
+
4152
+ sage: cython( # needs sage.misc.cython
4153
+ ....: '''
4154
+ ....: from sage.structure.element cimport EuclideanDomainElement
4155
+ ....: cdef class MyElt(EuclideanDomainElement):
4156
+ ....: def quo_rem(self, other):
4157
+ ....: return self._parent.var('quo,rem')
4158
+ ....: ''')
4159
+ sage: e = MyElt(SR) # needs sage.misc.cython sage.symbolic
4160
+ sage: e // e # needs sage.misc.cython sage.symbolic
4161
+ quo
4162
+ """
4163
+ Q, _ = self.quo_rem(right)
4164
+ return Q
4165
+
4166
+ cpdef _mod_(self, other):
4167
+ """
4168
+ Remainder of division of ``self`` by ``other``.
4169
+
4170
+ This default implementation assumes that ``quo_rem`` has been
4171
+ implemented.
4172
+
4173
+ EXAMPLES::
4174
+
4175
+ sage: R.<x> = ZZ[]
4176
+ sage: x % (x+1)
4177
+ -1
4178
+ sage: (x^3 + x - 1) % (x^2 - 1)
4179
+ 2*x - 1
4180
+
4181
+ ::
4182
+
4183
+ sage: cython( # needs sage.misc.cython
4184
+ ....: '''
4185
+ ....: from sage.structure.element cimport EuclideanDomainElement
4186
+ ....: cdef class MyElt(EuclideanDomainElement):
4187
+ ....: def quo_rem(self, other):
4188
+ ....: return self._parent.var('quo,rem')
4189
+ ....: ''')
4190
+ sage: e = MyElt(SR) # needs sage.misc.cython sage.symbolic
4191
+ sage: e % e # needs sage.misc.cython sage.symbolic
4192
+ rem
4193
+ """
4194
+ _, R = self.quo_rem(other)
4195
+ return R
4196
+
4197
+
4198
+ def is_FieldElement(x):
4199
+ """
4200
+ Return ``True`` if x is of type FieldElement.
4201
+ """
4202
+ from sage.misc.superseded import deprecation_cython
4203
+ deprecation_cython(38077, "The function is_FieldElement is deprecated; use 'isinstance(..., FieldElement)' instead.")
4204
+ return isinstance(x, FieldElement)
4205
+
4206
+
4207
+ cdef class FieldElement(CommutativeRingElement):
4208
+ cpdef _floordiv_(self, right):
4209
+ """
4210
+ Return the quotient of ``self`` and ``other``. Since these are field
4211
+ elements, the floor division is exactly the same as usual division.
4212
+
4213
+ EXAMPLES::
4214
+
4215
+ sage: # needs sage.rings.number_field
4216
+ sage: x = polygen(ZZ, 'x')
4217
+ sage: K.<b> = NumberField(x^4 + x^2 + 2/3)
4218
+ sage: c = (1+b) // (1-b); c
4219
+ 3/4*b^3 + 3/4*b^2 + 3/2*b + 1/2
4220
+ sage: (1+b) / (1-b) == c
4221
+ True
4222
+ sage: c * (1-b)
4223
+ b + 1
4224
+ """
4225
+ return self._div_(right)
4226
+
4227
+ def is_unit(self):
4228
+ r"""
4229
+ Return ``True`` if ``self`` is a unit in its parent ring.
4230
+
4231
+ EXAMPLES::
4232
+
4233
+ sage: a = 2/3; a.is_unit()
4234
+ True
4235
+
4236
+ On the other hand, 2 is not a unit, since its parent is `\ZZ`.
4237
+
4238
+ ::
4239
+
4240
+ sage: a = 2; a.is_unit()
4241
+ False
4242
+ sage: parent(a)
4243
+ Integer Ring
4244
+
4245
+ However, a is a unit when viewed as an element of QQ::
4246
+
4247
+ sage: a = QQ(2); a.is_unit()
4248
+ True
4249
+ """
4250
+ return not not self
4251
+
4252
+ def _lcm(self, FieldElement other):
4253
+ """
4254
+ Return the least common multiple of ``self`` and ``other``.
4255
+ """
4256
+ if self.is_zero() and other.is_zero():
4257
+ return self
4258
+ else:
4259
+ return self._parent(1)
4260
+
4261
+ def quo_rem(self, right):
4262
+ r"""
4263
+ Return the quotient and remainder obtained by dividing ``self`` by
4264
+ ``right``. Since this element lives in a field, the remainder is always
4265
+ zero and the quotient is ``self/right``.
4266
+
4267
+ TESTS:
4268
+
4269
+ Test if :issue:`8671` is fixed::
4270
+
4271
+ sage: # needs sage.libs.pari sage.libs.singular
4272
+ sage: R.<x,y> = QQ[]
4273
+ sage: S.<a,b> = R.quo(y^2 + 1)
4274
+ sage: S.is_field = lambda: False
4275
+ sage: F = Frac(S); u = F.one()
4276
+ sage: u.quo_rem(u)
4277
+ (1, 0)
4278
+ """
4279
+ if not isinstance(right, FieldElement) or not (parent(right) is self._parent):
4280
+ right = self.parent()(right)
4281
+ return self/right, 0
4282
+
4283
+ def divides(self, FieldElement other):
4284
+ r"""
4285
+ Check whether ``self`` divides ``other``, for field elements.
4286
+
4287
+ Since this is a field, all values divide all other values,
4288
+ except that zero does not divide any nonzero values.
4289
+
4290
+ EXAMPLES::
4291
+
4292
+ sage: # needs fpylll sage.rings.number_field sage.symbolic
4293
+ sage: K.<rt3> = QQ[sqrt(3)]
4294
+ sage: K(0).divides(rt3)
4295
+ False
4296
+ sage: rt3.divides(K(17))
4297
+ True
4298
+ sage: K(0).divides(K(0))
4299
+ True
4300
+ sage: rt3.divides(K(0))
4301
+ True
4302
+ """
4303
+ if not (other._parent is self._parent):
4304
+ other = self.parent()(other)
4305
+ return bool(self) or other.is_zero()
4306
+
4307
+ def canonical_associate(self):
4308
+ """
4309
+ Return a canonical associate.
4310
+
4311
+ EXAMPLES::
4312
+
4313
+ sage: R.<x,y>=QQ[]; k=R.fraction_field()
4314
+ sage: (x/y).canonical_associate()
4315
+ (1, x/y)
4316
+ sage: (0).canonical_associate()
4317
+ (0, 1)
4318
+ """
4319
+ P = self.parent()
4320
+ if self.is_zero():
4321
+ return (P.zero(), P.one())
4322
+ return (P.one(), self)
4323
+
4324
+
4325
+ def is_AlgebraElement(x):
4326
+ """
4327
+ Return ``True`` if x is of type AlgebraElement.
4328
+
4329
+ TESTS::
4330
+
4331
+ sage: from sage.structure.element import is_AlgebraElement
4332
+ sage: is_AlgebraElement(1)
4333
+ doctest:warning...
4334
+ DeprecationWarning: The function is_AlgebraElement is deprecated; use 'isinstance(..., AlgebraElement)' instead.
4335
+ See https://github.com/sagemath/sage/issues/38077 for details.
4336
+ False
4337
+ sage: R.<x,y> = FreeAlgebra(QQ, 2) # needs sage.combinat sage.modules
4338
+ sage: is_AlgebraElement(x * y) # needs sage.combinat sage.modules
4339
+ True
4340
+
4341
+ """
4342
+ from sage.misc.superseded import deprecation_cython
4343
+ deprecation_cython(38077, "The function is_AlgebraElement is deprecated; use 'isinstance(..., AlgebraElement)' instead.")
4344
+ return isinstance(x, AlgebraElement)
4345
+
4346
+
4347
+ cdef class AlgebraElement(RingElement):
4348
+ pass
4349
+
4350
+
4351
+ def is_CommutativeAlgebraElement(x):
4352
+ """
4353
+ Return ``True`` if x is of type CommutativeAlgebraElement.
4354
+ """
4355
+ from sage.misc.superseded import deprecation_cython
4356
+ deprecation_cython(38077, "The function is_CommutativeAlgebraElement is deprecated; use 'isinstance(..., CommutativeAlgebraElement)' instead.")
4357
+ return isinstance(x, CommutativeAlgebraElement)
4358
+
4359
+
4360
+ cdef class CommutativeAlgebraElement(CommutativeRingElement):
4361
+ pass
4362
+
4363
+
4364
+ ##############################################
4365
+
4366
+ def is_InfinityElement(x):
4367
+ """
4368
+ Return ``True`` if x is of type InfinityElement.
4369
+
4370
+ TESTS::
4371
+
4372
+ sage: from sage.structure.element import is_InfinityElement
4373
+ sage: is_InfinityElement(1)
4374
+ doctest:warning...
4375
+ DeprecationWarning: The function is_InfinityElement is deprecated; use 'isinstance(..., InfinityElement)' instead.
4376
+ See https://github.com/sagemath/sage/issues/38077 for details.
4377
+ False
4378
+
4379
+ sage: is_InfinityElement(oo)
4380
+ True
4381
+ """
4382
+ from sage.misc.superseded import deprecation_cython
4383
+ deprecation_cython(38077, "The function is_InfinityElement is deprecated; use 'isinstance(..., InfinityElement)' instead.")
4384
+ return isinstance(x, InfinityElement)
4385
+
4386
+
4387
+ cdef class InfinityElement(RingElement):
4388
+ def __invert__(self):
4389
+ from sage.rings.integer_ring import ZZ
4390
+ return ZZ(0)
4391
+
4392
+
4393
+ ###############################################################################
4394
+ #
4395
+ # Coercion of elements
4396
+ #
4397
+ ###############################################################################
4398
+
4399
+ cpdef canonical_coercion(x, y):
4400
+ """
4401
+ ``canonical_coercion(x,y)`` is what is called before doing an
4402
+ arithmetic operation between ``x`` and ``y``. It returns a pair ``(z,w)``
4403
+ such that ``z`` is got from ``x`` and ``w`` from ``y`` via canonical coercion and
4404
+ the parents of ``z`` and ``w`` are identical.
4405
+
4406
+ EXAMPLES::
4407
+
4408
+ sage: A = Matrix([[0, 1], [1, 0]]) # needs sage.modules
4409
+ sage: canonical_coercion(A, 1) # needs sage.modules
4410
+ (
4411
+ [0 1] [1 0]
4412
+ [1 0], [0 1]
4413
+ )
4414
+ """
4415
+ return coercion_model.canonical_coercion(x, y)
4416
+
4417
+
4418
+ cpdef bin_op(x, y, op):
4419
+ return coercion_model.bin_op(x, y, op)
4420
+
4421
+
4422
+ # Make coercion_model accessible as Python object
4423
+ globals()["coercion_model"] = coercion_model
4424
+
4425
+
4426
+ def get_coercion_model():
4427
+ """
4428
+ Return the global coercion model.
4429
+
4430
+ EXAMPLES::
4431
+
4432
+ sage: import sage.structure.element as e
4433
+ sage: cm = e.get_coercion_model()
4434
+ sage: cm
4435
+ <sage.structure.coerce.CoercionModel object at ...>
4436
+ sage: cm is coercion_model
4437
+ True
4438
+ """
4439
+ return coercion_model
4440
+
4441
+
4442
+ def coercion_traceback(dump=True):
4443
+ r"""
4444
+ This function is very helpful in debugging coercion errors. It prints
4445
+ the tracebacks of all the errors caught in the coercion detection. Note
4446
+ that failure is cached, so some errors may be omitted the second time
4447
+ around (as it remembers not to retry failed paths for speed reasons.
4448
+
4449
+ For performance and caching reasons, exception recording must be
4450
+ explicitly enabled before using this function.
4451
+
4452
+ EXAMPLES::
4453
+
4454
+ sage: cm = sage.structure.element.get_coercion_model()
4455
+ sage: cm.record_exceptions()
4456
+ sage: 1 + 1/5
4457
+ 6/5
4458
+ sage: coercion_traceback() # Should be empty, as all went well.
4459
+ sage: 1/5 + GF(5).gen()
4460
+ Traceback (most recent call last):
4461
+ ...
4462
+ TypeError: unsupported operand parent(s) for +:
4463
+ 'Rational Field' and 'Finite Field of size 5'
4464
+ sage: coercion_traceback()
4465
+ Traceback (most recent call last):
4466
+ ...
4467
+ TypeError: no common canonical parent for objects with parents:
4468
+ 'Rational Field' and 'Finite Field of size 5'
4469
+ """
4470
+ if dump:
4471
+ for traceback in coercion_model.exception_stack():
4472
+ print(traceback)
4473
+ else:
4474
+ return coercion_model.exception_stack()
4475
+
4476
+
4477
+ def coerce_binop(method):
4478
+ r"""
4479
+ Decorator for a binary operator method for applying coercion to the
4480
+ arguments before calling the method.
4481
+
4482
+ Consider a parent class in the category framework, `S`, whose element class
4483
+ expose a method `binop`. If `a` and `b` are elements of `S`, then
4484
+ `a.binop(b)` behaves as expected. If `a` and `b` are not elements of `S`,
4485
+ but rather have a common parent `T` whose element class also exposes
4486
+ `binop`, we would rather expect `a.binop(b)` to compute `aa.binop(bb)`,
4487
+ where `aa = T(a)` and `bb = T(b)`. This decorator ensures that behaviour
4488
+ without having to otherwise modify the implementation of `binop` on the
4489
+ element class of `A`.
4490
+
4491
+ Since coercion will be attempted on the arguments of the decorated method, a
4492
+ `TypeError` will be thrown if there is no common parent between the
4493
+ elements. An `AttributeError` or `NotImplementedError` or similar will be
4494
+ thrown if there is a common parent of the arguments, but its element class
4495
+ does not implement a method of the same name as the decorated method.
4496
+
4497
+ EXAMPLES:
4498
+
4499
+ Sparse polynomial rings uses ``@coerce_binop`` on ``gcd``::
4500
+
4501
+ sage: S.<x> = PolynomialRing(ZZ, sparse=True)
4502
+ sage: f = x^2
4503
+ sage: g = x
4504
+ sage: f.gcd(g) #indirect doctest
4505
+ x
4506
+ sage: T = PolynomialRing(QQ, name='x', sparse=True)
4507
+ sage: h = 1/2*T(x)
4508
+ sage: u = f.gcd(h); u #indirect doctest
4509
+ x
4510
+ sage: u.parent() == T
4511
+ True
4512
+
4513
+ Another real example::
4514
+
4515
+ sage: R1 = QQ['x,y']
4516
+ sage: R2 = QQ['x,y,z']
4517
+ sage: f = R1(1)
4518
+ sage: g = R1(2)
4519
+ sage: h = R2(1)
4520
+ sage: f.gcd(g)
4521
+ 1
4522
+ sage: f.gcd(g, algorithm='modular')
4523
+ 1
4524
+ sage: f.gcd(h)
4525
+ 1
4526
+ sage: f.gcd(h, algorithm='modular')
4527
+ 1
4528
+ sage: h.gcd(f)
4529
+ 1
4530
+ sage: h.gcd(f, 'modular')
4531
+ 1
4532
+
4533
+ We demonstrate a small class using ``@coerce_binop`` on a method::
4534
+
4535
+ sage: from sage.structure.element import coerce_binop
4536
+ sage: class MyRational(Rational):
4537
+ ....: def __init__(self, value):
4538
+ ....: self.v = value
4539
+ ....: @coerce_binop
4540
+ ....: def test_add(self, other, keyword='z'):
4541
+ ....: return (self.v, other, keyword)
4542
+
4543
+ Calls func directly if the two arguments have the same parent::
4544
+
4545
+ sage: x = MyRational(1)
4546
+ sage: x.test_add(1/2)
4547
+ (1, 1/2, 'z')
4548
+ sage: x.test_add(1/2, keyword=3)
4549
+ (1, 1/2, 3)
4550
+
4551
+ Passes through coercion and does a method lookup if the left operand is not
4552
+ the same. If the common parent's element class does not have a method of the
4553
+ same name, an exception is raised::
4554
+
4555
+ sage: x.test_add(2)
4556
+ (1, 2, 'z')
4557
+ sage: x.test_add(2, keyword=3)
4558
+ (1, 2, 3)
4559
+ sage: x.test_add(CC(2))
4560
+ Traceback (most recent call last):
4561
+ ...
4562
+ AttributeError: 'sage.rings.complex_mpfr.ComplexNumber' object has no attribute 'test_add'...
4563
+
4564
+ TESTS:
4565
+
4566
+ Test that additional arguments given to the method do not override
4567
+ the ``self`` argument, see :issue:`21322`::
4568
+
4569
+ sage: f.gcd(g, 1)
4570
+ Traceback (most recent call last):
4571
+ ...
4572
+ TypeError: algorithm 1 not supported
4573
+ """
4574
+ @sage_wraps(method)
4575
+ def new_method(self, other, *args, **kwargs):
4576
+ if have_same_parent(self, other):
4577
+ return method(self, other, *args, **kwargs)
4578
+ else:
4579
+ a, b = coercion_model.canonical_coercion(self, other)
4580
+ if a is self:
4581
+ return method(a, b, *args, **kwargs)
4582
+ else:
4583
+ return getattr(a, method.__name__)(b, *args, **kwargs)
4584
+ return new_method