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