Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/structure/element.pyx
4045 views
1
r"""
2
Elements
3
4
AUTHORS:
5
6
- David Harvey (2006-10-16): changed CommutativeAlgebraElement to
7
derive from CommutativeRingElement instead of AlgebraElement
8
9
- David Harvey (2006-10-29): implementation and documentation of new
10
arithmetic architecture
11
12
- William Stein (2006-11): arithmetic architecture -- pushing it
13
through to completion.
14
15
- Gonzalo Tornaria (2007-06): recursive base extend for coercion --
16
lots of tests
17
18
- Robert Bradshaw (2007-2010): arithmetic operators and coercion
19
20
- Maarten Derickx (2010-07): added architecture for is_square and sqrt
21
22
The Abstract Element Class Hierarchy
23
------------------------------------
24
25
This is the abstract class hierarchy, i.e., these are all
26
abstract base classes.
27
28
::
29
30
SageObject
31
Element
32
ModuleElement
33
RingElement
34
CommutativeRingElement
35
IntegralDomainElement
36
DedekindDomainElement
37
PrincipalIdealDomainElement
38
EuclideanDomainElement
39
FieldElement
40
FiniteFieldElement
41
CommutativeAlgebraElement
42
AlgebraElement (note -- can't derive from module, since no multiple inheritance)
43
CommutativeAlgebra ??? (should be removed from element.pxd)
44
Matrix
45
InfinityElement
46
PlusInfinityElement
47
MinusInfinityElement
48
AdditiveGroupElement
49
Vector
50
51
MonoidElement
52
MultiplicativeGroupElement
53
ElementWithCachedMethod
54
55
56
How to Define a New Element Class
57
---------------------------------
58
59
Elements typically define a method ``_new_c``, e.g.,
60
61
::
62
63
cdef _new_c(self, defining data):
64
cdef FreeModuleElement_generic_dense x
65
x = PY_NEW(FreeModuleElement_generic_dense)
66
x._parent = self._parent
67
x._entries = v
68
69
that creates a new sibling very quickly from defining data
70
with assumed properties.
71
72
Sage has a special system in place for handling arithmetic operations
73
for all Element subclasses. There are various rules that must be
74
followed by both arithmetic implementers and callers.
75
76
A quick summary for the impatient:
77
78
- To implement addition for any Element class, override def _add_().
79
- If you want to add x and y, whose parents you know are IDENTICAL,
80
you may call _add_(x, y). This will be the fastest way to guarantee
81
that the correct implementation gets called. Of course you can still
82
always use "x + y".
83
84
Now in more detail. The aims of this system are to provide (1) an efficient
85
calling protocol from both Python and Cython, (2) uniform coercion semantics
86
across Sage, (3) ease of use, (4) readability of code.
87
88
We will take addition of RingElements as an example; all other operators
89
and classes are similar. There are four relevant functions.
90
91
- **def RingElement.__add__**
92
93
This function is called by Python or Pyrex when the binary "+" operator
94
is encountered. It ASSUMES that at least one of its arguments is a
95
RingElement; only a really twisted programmer would violate this
96
condition. It has a fast pathway to deal with the most common case
97
where the arguments have the same parent. Otherwise, it uses the coercion
98
module to work out how to make them have the same parent. After any
99
necessary coercions have been performed, it calls _add_ to dispatch to
100
the correct underlying addition implementation.
101
102
Note that although this function is declared as def, it doesn't have the
103
usual overheads associated with python functions (either for the caller
104
or for __add__ itself). This is because python has optimised calling
105
protocols for such special functions.
106
107
- **def RingElement._add_**
108
109
This is the function you should override to implement addition in a
110
python subclass of RingElement.
111
112
.. warning::
113
114
if you override this in a *Cython* class, it won't get called.
115
You should override _add_ instead. It is especially important to
116
keep this in mind whenever you move a class down from Python to
117
Cython.
118
119
The two arguments to this function are guaranteed to have the
120
SAME PARENT. Its return value MUST have the SAME PARENT as its
121
arguments.
122
123
If you want to add two objects from python, and you know that their
124
parents are the same object, you are encouraged to call this function
125
directly, instead of using "x + y".
126
127
The default implementation of this function is to call _add_,
128
so if no-one has defined a python implementation, the correct Pyrex
129
implementation will get called.
130
131
- **cpdef RingElement._add_**
132
133
This is the function you should override to implement addition in a
134
Pyrex subclass of RingElement.
135
136
The two arguments to this function are guaranteed to have the
137
SAME PARENT. Its return value MUST have the SAME PARENT as its
138
arguments.
139
140
The default implementation of this function is to raise a
141
NotImplementedError, which will happen if no-one has supplied
142
implementations of either _add_.
143
144
145
For speed, there are also **inplace** version of the arithmetic commands.
146
DD NOT call them directly, they may mutate the object and will be called
147
when and only when it has been determined that the old object will no longer
148
be accessible from the calling function after this operation.
149
150
- **def RingElement._iadd_**
151
152
This is the function you should override to inplace implement addition
153
in a Python subclass of RingElement.
154
155
The two arguments to this function are guaranteed to have the
156
SAME PARENT. Its return value MUST have the SAME PARENT as its
157
arguments.
158
159
The default implementation of this function is to call _add_,
160
so if no-one has defined a Python implementation, the correct Cython
161
implementation will get called.
162
"""
163
164
165
cdef extern from *:
166
ctypedef struct RefPyObject "PyObject":
167
int ob_refcnt
168
169
170
171
172
##################################################################
173
# Generic element, so all this functionality must be defined
174
# by any element. Derived class must call __init__
175
##################################################################
176
177
include "../ext/cdefs.pxi"
178
include "../ext/stdsage.pxi"
179
include "../ext/python.pxi"
180
181
import operator, types
182
import sys
183
import traceback
184
185
import sage.misc.sageinspect as sageinspect
186
187
cdef MethodType
188
from types import MethodType
189
190
from sage.categories.category import Category
191
from sage.structure.parent cimport Parent, AttributeErrorMessage
192
from sage.structure.parent import is_extension_type, getattr_from_other_class
193
from sage.misc.lazy_format import LazyFormat
194
195
# This classes uses element.pxd. To add data members, you
196
# must change that file.
197
198
def make_element(_class, _dict, parent):
199
"""
200
This function is only here to support old pickles.
201
202
Pickling functionality is moved to Element.{__getstate__,__setstate__}
203
functions.
204
"""
205
from sage.misc.pickle_old import make_element_old
206
return make_element_old(_class, _dict, parent)
207
208
def py_scalar_to_element(py):
209
from sage.rings.integer_ring import ZZ
210
from sage.rings.real_double import RDF
211
from sage.rings.complex_double import CDF
212
if PyInt_Check(py) or PyLong_Check(py):
213
return ZZ(py)
214
elif PyFloat_Check(py):
215
return RDF(py)
216
elif PyComplex_Check(py):
217
return CDF(py)
218
else:
219
raise TypeError, "Not a scalar"
220
221
def is_Element(x):
222
"""
223
Return True if x is of type Element.
224
225
EXAMPLES::
226
227
sage: from sage.structure.element import is_Element
228
sage: is_Element(2/3)
229
True
230
sage: is_Element(QQ^3)
231
False
232
"""
233
return IS_INSTANCE(x, Element)
234
235
cdef class Element(sage_object.SageObject):
236
"""
237
Generic element of a structure. All other types of elements
238
(RingElement, ModuleElement, etc) derive from this type.
239
240
Subtypes must either call __init__() to set _parent, or may
241
set _parent themselves if that would be more efficient.
242
"""
243
244
def __init__(self, parent):
245
r"""
246
INPUT:
247
248
- ``parent`` - a SageObject
249
"""
250
#if parent is None:
251
# raise RuntimeError, "bug -- can't set parent to None"
252
self._parent = parent
253
254
def _set_parent(self, parent):
255
r"""
256
INPUT:
257
258
- ``parent`` - a SageObject
259
"""
260
self._parent = parent
261
262
cdef _set_parent_c(self, Parent parent):
263
self._parent = parent
264
265
def _make_new_with_parent_c(self, Parent parent):
266
self._parent = parent
267
return self
268
269
270
def __getattr__(self, str name):
271
"""
272
Let cat be the category of the parent of ``self``. This
273
method emulates ``self`` being an instance of both ``Element``
274
and ``cat.element_class``, in that order, for attribute
275
lookup.
276
277
NOTE:
278
279
Attributes beginning with two underscores but not ending with
280
an unnderscore are considered private and are thus exempted
281
from the lookup in ``cat.element_class``.
282
283
EXAMPLES:
284
285
We test that ``1`` (an instance of the extension type
286
``Integer``) inherits the methods from the categories of
287
``ZZ``, that is from ``CommutativeRings().element_class``::
288
289
sage: 1.is_idempotent(), 2.is_idempotent()
290
(True, False)
291
292
This method is actually provided by the ``Magmas()`` super
293
category of ``CommutativeRings()``::
294
295
sage: 1.is_idempotent
296
<bound method EuclideanDomains.element_class.is_idempotent of 1>
297
sage: 1.is_idempotent.__module__
298
'sage.categories.magmas'
299
300
TESTS::
301
302
sage: 1.blah_blah
303
Traceback (most recent call last):
304
...
305
AttributeError: 'sage.rings.integer.Integer' object has no attribute 'blah_blah'
306
sage: Semigroups().example().an_element().is_idempotent
307
<bound method LeftZeroSemigroup_with_category.element_class.is_idempotent of 42>
308
sage: Semigroups().example().an_element().blah_blah
309
Traceback (most recent call last):
310
...
311
AttributeError: 'LeftZeroSemigroup_with_category.element_class' object has no attribute 'blah_blah'
312
313
We test that "private" attributes are not requested from the element class
314
of the category (trac ticket #10467)::
315
316
sage: C = EuclideanDomains()
317
sage: P.<x> = QQ[]
318
sage: C.element_class.__foo = 'bar'
319
sage: x.parent() in C
320
True
321
sage: x.__foo
322
Traceback (most recent call last):
323
...
324
AttributeError: 'sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint' object has no attribute '__foo'
325
326
"""
327
if (name.startswith('__') and not name.endswith('_')):
328
raise AttributeError, AttributeErrorMessage(self, name)
329
cdef Parent P = self._parent or self.parent()
330
if P is None or P._category is None:
331
raise AttributeError, AttributeErrorMessage(self, name)
332
return getattr_from_other_class(self, P._category.element_class, name)
333
334
def __dir__(self):
335
"""
336
Let cat be the category of the parent of ``self``. This method
337
emulates ``self`` being an instance of both ``Element`` and
338
``cat.element_class``, in that order, for attribute directory.
339
340
EXAMPLES::
341
342
sage: dir(1/2)
343
['N', ..., 'is_idempotent', 'is_integral', ...]
344
345
Caveat: dir on Integer's and some other extension types seem to ignore __dir__::
346
347
sage: 1.__dir__()
348
['N', ..., 'is_idempotent', 'is_integral', ...]
349
sage: dir(1) # todo: not implemented
350
['N', ..., 'is_idempotent', 'is_integral', ...]
351
"""
352
from sage.structure.parent import dir_with_other_class
353
return dir_with_other_class(self, self.parent().category().element_class)
354
355
def _repr_(self):
356
return "Generic element of a structure"
357
358
def __getstate__(self):
359
"""
360
Returns a tuple describing the state of your object.
361
362
This should return all information that will be required to unpickle
363
the object. The functionality for unpickling is implemented in
364
__setstate__().
365
366
TESTS::
367
368
sage: R.<x,y> = QQ[]
369
sage: i = ideal(x^2 - y^2 + 1)
370
sage: i.__getstate__()
371
(Monoid of ideals of Multivariate Polynomial Ring in x, y over Rational Field, {'_Ideal_generic__ring': Multivariate Polynomial Ring in x, y over Rational Field, '_Ideal_generic__gens': (x^2 - y^2 + 1,)})
372
"""
373
return (self._parent, self.__dict__)
374
375
def __setstate__(self, state):
376
"""
377
Initializes the state of the object from data saved in a pickle.
378
379
During unpickling __init__ methods of classes are not called, the saved
380
data is passed to the class via this function instead.
381
382
TESTS::
383
384
sage: R.<x,y> = QQ[]
385
sage: i = ideal(x); i
386
Ideal (x) of Multivariate Polynomial Ring in x, y over Rational Field
387
sage: S.<x,y,z> = ZZ[]
388
sage: i.__setstate__((R,{'_Ideal_generic__ring':S,'_Ideal_generic__gens': (S(x^2 - y^2 + 1),)}))
389
sage: i
390
Ideal (x^2 - y^2 + 1) of Multivariate Polynomial Ring in x, y, z over Integer Ring
391
"""
392
self._set_parent(state[0])
393
self.__dict__ = state[1]
394
395
def __copy__(self):
396
"""
397
Returns a copy of ``self``.
398
399
OUTPUT:
400
401
- a new object which is a copy of ``self``.
402
403
This implementation ensures that ``self.__dict__`` is properly copied
404
when it exists (typically for instances of classes deriving from
405
:class:`Element`).
406
407
TESTS::
408
409
sage: from sage.structure.element import Element
410
sage: el = Element(parent = ZZ)
411
sage: el1 = copy(el)
412
sage: el1 is el
413
False
414
415
sage: class Demo(Element): pass
416
sage: el = Demo(parent = ZZ)
417
sage: el.x = [1,2,3]
418
sage: el1 = copy(el)
419
sage: el1 is el
420
False
421
sage: el1.__dict__ is el.__dict__
422
False
423
"""
424
cls = self.__class__
425
res = cls.__new__(cls)
426
res._set_parent(self._parent)
427
try:
428
res.__dict__ = self.__dict__.copy()
429
except AttributeError:
430
pass
431
return res
432
433
def __hash__(self):
434
return hash(str(self))
435
436
def _im_gens_(self, codomain, im_gens):
437
"""
438
Return the image of self in codomain under the map that sends
439
the images of the generators of the parent of self to the
440
tuple of elements of im_gens.
441
"""
442
raise NotImplementedError
443
444
cdef base_extend_c(self, Parent R):
445
if HAS_DICTIONARY(self):
446
return self.base_extend(R)
447
else:
448
return self.base_extend_c_impl(R)
449
450
cdef base_extend_c_impl(self, Parent R):
451
cdef Parent V
452
V = self._parent.base_extend(R)
453
return (<Parent>V)._coerce_c(self)
454
455
def base_extend(self, R):
456
return self.base_extend_c_impl(R)
457
458
def base_ring(self):
459
"""
460
Returns the base ring of this element's parent (if that makes sense).
461
"""
462
return self._parent.base_ring()
463
464
def category(self):
465
from sage.categories.all import Elements
466
return Elements(self._parent)
467
468
469
def _test_category(self, **options):
470
"""
471
Run generic tests on the method :meth:`.category`.
472
473
See also: :class:`TestSuite`.
474
475
EXAMPLES::
476
477
sage: 3._test_category()
478
479
Let us now write a broken :meth:`.category` method::
480
481
sage: from sage.categories.examples.sets_cat import PrimeNumbers
482
sage: class CCls(PrimeNumbers):
483
... def an_element(self):
484
... return 18
485
sage: CC = CCls()
486
sage: CC._test_an_element()
487
Traceback (most recent call last):
488
...
489
AssertionError: self.an_element() is not in self
490
"""
491
from sage.categories.objects import Objects
492
tester = self._tester(**options)
493
sage_object.SageObject._test_category(self, tester = tester)
494
category = self.category()
495
# Tests that self inherits methods from the categories
496
if not is_extension_type(self.__class__):
497
# For usual Python classes, that should be done with
498
# standard inheritance
499
tester.assert_(isinstance(self, self.parent().category().element_class))
500
else:
501
# For extension types we just check that inheritance
502
# occurs on a dummy attribute of Sets().ElementMethods
503
tester.assert_(hasattr(self, "_dummy_attribute"))
504
505
def _test_eq(self, **options):
506
"""
507
Test that ``self`` is equal to ``self`` and different to ``None``.
508
509
See also: :class:`TestSuite`.
510
511
TESTS::
512
513
sage: from sage.structure.element import Element
514
sage: O = Element(Parent())
515
sage: O._test_eq()
516
517
Let us now write a broken class method::
518
519
sage: class CCls(Element):
520
... def __eq__(self, other):
521
... return True
522
sage: CCls(Parent())._test_eq()
523
Traceback (most recent call last):
524
...
525
AssertionError: broken equality: Generic element of a structure == None
526
527
Let us now break inequality::
528
529
sage: class CCls(Element):
530
... def __ne__(self, other):
531
... return True
532
sage: CCls(Parent())._test_eq()
533
Traceback (most recent call last):
534
...
535
AssertionError: broken non-equality: Generic element of a structure != itself
536
"""
537
tester = self._tester(**options)
538
# We don't use assertEqual / assertNonEqual in order to be
539
# 100% sure we indeed call the operators == and !=, whatever
540
# the version of Python is (see #11236)
541
tester.assertTrue(self == self,
542
LazyFormat("broken equality: %s == itself is False")%self)
543
tester.assertFalse(self == None,
544
LazyFormat("broken equality: %s == None")%self)
545
tester.assertFalse(self != self,
546
LazyFormat("broken non-equality: %s != itself")%self)
547
tester.assertTrue(self != None,
548
LazyFormat("broken non-equality: %s is not != None")%self)
549
550
def parent(self, x=None):
551
"""
552
Returns parent of this element; or, if the optional argument x is
553
supplied, the result of coercing x into the parent of this element.
554
"""
555
if x is None:
556
return self._parent
557
else:
558
return self._parent(x)
559
560
561
def subs(self, in_dict=None, **kwds):
562
"""
563
Substitutes given generators with given values while not touching
564
other generators. This is a generic wrapper around __call__.
565
The syntax is meant to be compatible with the corresponding method
566
for symbolic expressions.
567
568
INPUT:
569
570
- ``in_dict`` - (optional) dictionary of inputs
571
572
- ``**kwds`` - named parameters
573
574
OUTPUT:
575
576
- new object if substitution is possible, otherwise self.
577
578
EXAMPLES::
579
580
sage: x, y = PolynomialRing(ZZ,2,'xy').gens()
581
sage: f = x^2 + y + x^2*y^2 + 5
582
sage: f((5,y))
583
25*y^2 + y + 30
584
sage: f.subs({x:5})
585
25*y^2 + y + 30
586
sage: f.subs(x=5)
587
25*y^2 + y + 30
588
sage: (1/f).subs(x=5)
589
1/(25*y^2 + y + 30)
590
sage: Integer(5).subs(x=4)
591
5
592
"""
593
if not hasattr(self,'__call__'):
594
return self
595
parent=self._parent
596
# We should better not test for ParentWIthGens,
597
# as this is essentially deprecated.
598
#from sage.structure.parent_gens import is_ParentWithGens
599
#if not is_ParentWithGens(parent):
600
# return self
601
# Better: Duck typing!
602
try:
603
ngens = parent.ngens()
604
except (AttributeError, NotImplementedError, TypeError):
605
return self
606
variables=[]
607
# use "gen" instead of "gens" as a ParentWithGens is not
608
# required to have the latter
609
for i in xrange(0,ngens):
610
gen=parent.gen(i)
611
if kwds.has_key(str(gen)):
612
variables.append(kwds[str(gen)])
613
elif in_dict and in_dict.has_key(gen):
614
variables.append(in_dict[gen])
615
else:
616
variables.append(gen)
617
return self(*variables)
618
619
def numerical_approx (self, prec=None, digits=None):
620
"""
621
Return a numerical approximation of x with at least prec bits of
622
precision.
623
624
EXAMPLES::
625
626
sage: (2/3).n()
627
0.666666666666667
628
sage: pi.n(digits=10)
629
3.141592654
630
sage: pi.n(prec=20) # 20 bits
631
3.1416
632
"""
633
import sage.misc.functional
634
return sage.misc.functional.numerical_approx(self, prec=prec, digits=digits)
635
n=numerical_approx
636
N=n
637
638
def _mpmath_(self, prec=53, rounding=None):
639
"""
640
Evaluates numerically and returns an mpmath number.
641
Used as fallback for conversion by mpmath.mpmathify().
642
643
.. note::
644
645
Currently, the rounding mode is ignored.
646
647
EXAMPLES::
648
649
sage: from sage.libs.mpmath.all import mp, mpmathify
650
sage: mp.dps = 30
651
sage: 25._mpmath_(53)
652
mpf('25.0')
653
sage: mpmathify(3+4*I)
654
mpc(real='3.0', imag='4.0')
655
sage: mpmathify(1+pi)
656
mpf('4.14159265358979323846264338327933')
657
sage: (1+pi)._mpmath_(10)
658
mpf('4.140625')
659
sage: (1+pi)._mpmath_(mp.prec)
660
mpf('4.14159265358979323846264338327933')
661
"""
662
return self.n(prec)._mpmath_(prec=prec)
663
664
def substitute(self,in_dict=None,**kwds):
665
"""
666
This is an alias for self.subs().
667
668
INPUT:
669
670
- ``in_dict`` - (optional) dictionary of inputs
671
672
- ``**kwds`` - named parameters
673
674
OUTPUT:
675
676
- new object if substitution is possible, otherwise self.
677
678
EXAMPLES::
679
680
sage: x, y = PolynomialRing(ZZ,2,'xy').gens()
681
sage: f = x^2 + y + x^2*y^2 + 5
682
sage: f((5,y))
683
25*y^2 + y + 30
684
sage: f.substitute({x:5})
685
25*y^2 + y + 30
686
sage: f.substitute(x=5)
687
25*y^2 + y + 30
688
sage: (1/f).substitute(x=5)
689
1/(25*y^2 + y + 30)
690
sage: Integer(5).substitute(x=4)
691
5
692
"""
693
return self.subs(in_dict,**kwds)
694
695
cpdef _act_on_(self, x, bint self_on_left):
696
"""
697
Use this method to implement self acting on x.
698
699
Return None or raise a CoercionException if no
700
such action is defined here.
701
"""
702
return None
703
704
cpdef _acted_upon_(self, x, bint self_on_left):
705
"""
706
Use this method to implement self acted on by x.
707
708
Return None or raise a CoercionException if no
709
such action is defined here.
710
"""
711
return None
712
713
714
def __xor__(self, right):
715
raise RuntimeError, "Use ** for exponentiation, not '^', which means xor\n"+\
716
"in Python, and has the wrong precedence."
717
718
def __pos__(self):
719
return self
720
721
def _coeff_repr(self, no_space=True):
722
if self._is_atomic():
723
s = repr(self)
724
else:
725
s = "(%s)"%repr(self)
726
if no_space:
727
return s.replace(' ','')
728
return s
729
730
def _latex_coeff_repr(self):
731
try:
732
s = self._latex_()
733
except AttributeError:
734
s = str(self)
735
if self._is_atomic():
736
return s
737
else:
738
return "\\left(%s\\right)"%s
739
740
def _is_atomic(self):
741
"""
742
Return True if and only if parenthesis are not required when
743
*printing* out any of `x - s`, `x + s`, `x^s` and `x/s`.
744
745
EXAMPLES::
746
747
sage: n = 5; n._is_atomic()
748
True
749
sage: n = x+1; n._is_atomic()
750
False
751
"""
752
if self._parent.is_atomic_repr():
753
return True
754
s = str(self)
755
return s.find("+") == -1 and s.find("-") == -1 and s.find(" ") == -1
756
757
def __nonzero__(self):
758
r"""
759
Return True if self does not equal self.parent()(0).
760
761
Note that this is automatically called when converting to
762
boolean, as in the conditional of an if or while statement.
763
764
TESTS:
765
Verify that #5185 is fixed.
766
767
::
768
769
sage: v = vector({1: 1, 3: -1})
770
sage: w = vector({1: -1, 3: 1})
771
sage: v + w
772
(0, 0, 0, 0)
773
sage: (v+w).is_zero()
774
True
775
sage: bool(v+w)
776
False
777
sage: (v+w).__nonzero__()
778
False
779
"""
780
return self != self._parent.zero_element()
781
782
def is_zero(self):
783
"""
784
Return True if self equals self.parent()(0). The default
785
implementation is to fall back to 'not self.__nonzero__'.
786
787
.. warning::
788
789
Do not re-implement this method in your subclass but
790
implement __nonzero__ instead.
791
"""
792
return not self
793
794
def _cmp_(left, right):
795
return left._cmp_c_impl(right)
796
797
cdef _cmp(left, right):
798
"""
799
Compare left and right.
800
"""
801
global coercion_model
802
cdef int r
803
if not have_same_parent(left, right):
804
if left is None or left is Ellipsis:
805
return -1
806
elif right is None or right is Ellipsis:
807
return 1
808
try:
809
_left, _right = coercion_model.canonical_coercion(left, right)
810
if PY_IS_NUMERIC(_left):
811
return cmp(_left, _right)
812
else:
813
return _left._cmp_(_right)
814
except TypeError:
815
r = cmp(type(left), type(right))
816
if r == 0:
817
r = -1
818
return r
819
else:
820
if HAS_DICTIONARY(left):
821
left_cmp = left._cmp_
822
if PY_TYPE_CHECK(left_cmp, MethodType):
823
# it must have been overridden
824
return left_cmp(right)
825
826
return left._cmp_c_impl(right)
827
828
def _richcmp_(left, right, op):
829
return left._richcmp(right, op)
830
831
cdef _richcmp(left, right, int op):
832
"""
833
Compare left and right, according to the comparison operator op.
834
"""
835
global coercion_model
836
cdef int r
837
if not have_same_parent(left, right):
838
if left is None or left is Ellipsis:
839
return _rich_to_bool(op, -1)
840
elif right is None or right is Ellipsis:
841
return _rich_to_bool(op, 1)
842
try:
843
_left, _right = coercion_model.canonical_coercion(left, right)
844
if PY_IS_NUMERIC(_left):
845
return _rich_to_bool(op, cmp(_left, _right))
846
else:
847
return _left._richcmp_(_right, op)
848
except (TypeError, NotImplementedError):
849
r = cmp(type(left), type(right))
850
if r == 0:
851
r = -1
852
# Often things are compared against 0 (or 1), even when there
853
# is not a canonical coercion ZZ -> other
854
# Things should implement and/or use __nonzero__ and is_one()
855
# but we can't do that here as that calls this.
856
# The old coercion model would declare a coercion if 0 went in.
857
# (Though would fail with a TypeError for other values, thus
858
# contaminating the _has_coerce_map_from cache.)
859
from sage.rings.integer import Integer
860
try:
861
if PY_TYPE_CHECK(left, Element) and isinstance(right, (int, float, Integer)) and not right:
862
right = (<Element>left)._parent(right)
863
elif PY_TYPE_CHECK(right, Element) and isinstance(left, (int, float, Integer)) and not left:
864
left = (<Element>right)._parent(left)
865
else:
866
return _rich_to_bool(op, r)
867
except TypeError:
868
return _rich_to_bool(op, r)
869
870
if HAS_DICTIONARY(left): # fast check
871
left_cmp = left.__cmp__
872
if PY_TYPE_CHECK(left_cmp, MethodType):
873
# it must have been overridden
874
return _rich_to_bool(op, left_cmp(right))
875
876
return left._richcmp_c_impl(right, op)
877
878
cdef _rich_to_bool(self, int op, int r):
879
return _rich_to_bool(op, r)
880
881
####################################################################
882
# For a derived Cython class, you **must** put the following in
883
# your subclasses, in order for it to take advantage of the
884
# above generic comparison code. You must also define
885
# either _cmp_c_impl (if your subclass is totally ordered),
886
# _richcmp_c_impl (if your subclass is partially ordered), or both
887
# (if your class has both a total order and a partial order;
888
# then the total order will be available with cmp(), and the partial
889
# order will be available with the relation operators; in this case
890
# you must also define __cmp__ in your subclass).
891
# This is simply how Python works.
892
#
893
# For a *Python* class just define __cmp__ as always.
894
# But note that when this gets called you can assume that
895
# both inputs have identical parents.
896
#
897
# If your __cmp__ methods are not getting called, verify that the
898
# canonical_coercion(x,y) is not throwing errors.
899
#
900
####################################################################
901
def __richcmp__(left, right, int op):
902
return (<Element>left)._richcmp(right, op)
903
904
####################################################################
905
# If your subclass has both a partial order (available with the
906
# relation operators) and a total order (available with cmp()),
907
# you **must** put the following in your subclass.
908
#
909
# Note that in this case the total order defined by cmp() will
910
# not properly respect coercions.
911
####################################################################
912
def __cmp__(left, right):
913
return (<Element>left)._cmp(right)
914
915
cdef _richcmp_c_impl(left, Element right, int op):
916
if (<Element>left)._richcmp_c_impl == Element._richcmp_c_impl and \
917
(<Element>left)._cmp_c_impl == Element._cmp_c_impl:
918
# Not implemented, try some basic defaults
919
if op == Py_EQ:
920
return left is right
921
elif op == Py_NE:
922
return left is not right
923
return left._rich_to_bool(op, left._cmp_c_impl(right))
924
925
cdef int _cmp_c_impl(left, Element right) except -2:
926
### For derived SageX code, you *MUST* ALSO COPY the __richcmp__ above
927
### into your class!!! For Python code just use __cmp__.
928
raise NotImplementedError, "BUG: sort algorithm for elements of '%s' not implemented"%right.parent()
929
930
cdef inline bint _rich_to_bool(int op, int r):
931
if op == Py_LT: #<
932
return (r < 0)
933
elif op == Py_EQ: #==
934
return (r == 0)
935
elif op == Py_GT: #>
936
return (r > 0)
937
elif op == Py_LE: #<=
938
return (r <= 0)
939
elif op == Py_NE: #!=
940
return (r != 0)
941
elif op == Py_GE: #>=
942
return (r >= 0)
943
944
945
def is_ModuleElement(x):
946
"""
947
Return True if x is of type ModuleElement.
948
949
This is even faster than using isinstance inline.
950
951
EXAMPLES::
952
953
sage: from sage.structure.element import is_ModuleElement
954
sage: is_ModuleElement(2/3)
955
True
956
sage: is_ModuleElement((QQ^3).0)
957
True
958
sage: is_ModuleElement('a')
959
False
960
"""
961
return IS_INSTANCE(x, ModuleElement)
962
963
cdef class ElementWithCachedMethod(Element):
964
r"""
965
An element class that fully supports cached methods.
966
967
NOTE:
968
969
The :class:`~sage.misc.cachefunc.cached_method` decorator provides
970
a convenient way to automatically cache the result of a computation.
971
Since trac ticket #11115, the cached method decorator applied to a
972
method without optional arguments is faster than a hand-written cache
973
in Python, and a cached method without any arguments (except ``self``)
974
is actually faster than a Python method that does nothing more but
975
to return ``1``. A cached method can also be inherited from the parent
976
or element class of a category.
977
978
However, this holds true only if attribute assignment is supported.
979
If you write an extension class in Cython that does not accept attribute
980
assignment then a cached method inherited from the category will be
981
slower (for :class:`~sage.structure.parent.Parent`) or the cache would
982
even break (for :class:`Element`).
983
984
This class should be used if you write an element class, can not provide
985
it with attribute assignment, but want that it inherits a cached method
986
from the category. Under these conditions, your class should inherit
987
from this class rather than :class:`Element`. Then, the cache will work,
988
but certainly slower than with attribute assignment. Lazy attributes
989
work as well.
990
991
EXAMPLE:
992
993
We define three element extension classes. The first inherits from
994
:class:`Element`, the second from this class, and the third simply
995
is a Python class. We also define a parent class and, in Python, a
996
category whose element and parent classes define cached methods.
997
::
998
999
sage: cython_code = ["from sage.structure.element cimport Element, ElementWithCachedMethod",
1000
... "cdef class MyBrokenElement(Element):",
1001
... " cdef public object x",
1002
... " def __init__(self,P,x):",
1003
... " self.x=x",
1004
... " Element.__init__(self,P)",
1005
... " def __neg__(self):",
1006
... " return MyBrokenElement(self.parent(),-self.x)",
1007
... " def _repr_(self):",
1008
... " return '<%s>'%self.x",
1009
... " def __hash__(self):",
1010
... " return hash(self.x)",
1011
... " def __cmp__(left, right):",
1012
... " return (<Element>left)._cmp(right)",
1013
... " def __richcmp__(left, right, op):",
1014
... " return (<Element>left)._richcmp(right,op)",
1015
... " cdef int _cmp_c_impl(left, Element right) except -2:",
1016
... " return cmp(left.x,right.x)",
1017
... " def raw_test(self):",
1018
... " return -self",
1019
... "cdef class MyElement(ElementWithCachedMethod):",
1020
... " cdef public object x",
1021
... " def __init__(self,P,x):",
1022
... " self.x=x",
1023
... " Element.__init__(self,P)",
1024
... " def __neg__(self):",
1025
... " return MyElement(self.parent(),-self.x)",
1026
... " def _repr_(self):",
1027
... " return '<%s>'%self.x",
1028
... " def __hash__(self):",
1029
... " return hash(self.x)",
1030
... " def __cmp__(left, right):",
1031
... " return (<Element>left)._cmp(right)",
1032
... " def __richcmp__(left, right, op):",
1033
... " return (<Element>left)._richcmp(right,op)",
1034
... " cdef int _cmp_c_impl(left, Element right) except -2:",
1035
... " return cmp(left.x,right.x)",
1036
... " def raw_test(self):",
1037
... " return -self",
1038
... "class MyPythonElement(MyBrokenElement): pass",
1039
... "from sage.structure.parent cimport Parent",
1040
... "cdef class MyParent(Parent):",
1041
... " Element = MyElement"]
1042
sage: cython('\n'.join(cython_code))
1043
sage: cython_code = ["from sage.all import cached_method, cached_in_parent_method, Category, Objects",
1044
... "class MyCategory(Category):",
1045
... " @cached_method",
1046
... " def super_categories(self):",
1047
... " return [Objects()]",
1048
... " class ElementMethods:",
1049
... " @cached_method",
1050
... " def element_cache_test(self):",
1051
... " return -self",
1052
... " @cached_in_parent_method",
1053
... " def element_via_parent_test(self):",
1054
... " return -self",
1055
... " class ParentMethods:",
1056
... " @cached_method",
1057
... " def one(self):",
1058
... " return self.element_class(self,1)",
1059
... " @cached_method",
1060
... " def invert(self, x):",
1061
... " return -x"]
1062
sage: cython('\n'.join(cython_code))
1063
sage: C = MyCategory()
1064
sage: P = MyParent(category=C)
1065
sage: ebroken = MyBrokenElement(P,5)
1066
sage: e = MyElement(P,5)
1067
1068
The cached methods inherited by ``MyElement`` works::
1069
1070
sage: e.element_cache_test()
1071
<-5>
1072
sage: e.element_cache_test() is e.element_cache_test()
1073
True
1074
sage: e.element_via_parent_test()
1075
<-5>
1076
sage: e.element_via_parent_test() is e.element_via_parent_test()
1077
True
1078
1079
The other element class can only inherit a
1080
``cached_in_parent_method``, since the cache is stored in the
1081
parent. In fact, equal elements share the cache, even if they are
1082
of different types::
1083
1084
sage: e == ebroken
1085
True
1086
sage: type(e) == type(ebroken)
1087
False
1088
sage: ebroken.element_via_parent_test() is e.element_via_parent_test()
1089
True
1090
1091
However, the cache of the other inherited method breaks, although the method
1092
as such works::
1093
1094
sage: ebroken.element_cache_test()
1095
<-5>
1096
sage: ebroken.element_cache_test() is ebroken.element_cache_test()
1097
False
1098
1099
Since ``e`` and ``ebroken`` share the cache, when we empty it for one element
1100
it is empty for the other as well::
1101
1102
sage: b = ebroken.element_via_parent_test()
1103
sage: e.element_via_parent_test.clear_cache()
1104
sage: b is ebroken.element_via_parent_test()
1105
False
1106
1107
Note that the cache only breaks for elements that do no allow attribute assignment.
1108
A Python version of ``MyBrokenElement`` therefore allows for cached methods::
1109
1110
sage: epython = MyPythonElement(P,5)
1111
sage: epython.element_cache_test()
1112
<-5>
1113
sage: epython.element_cache_test() is epython.element_cache_test()
1114
True
1115
1116
"""
1117
def __getattr__(self, name):
1118
"""
1119
This getattr method ensures that cached methods and lazy attributes
1120
can be inherited from the element class of a category.
1121
1122
NOTE:
1123
1124
The use of cached methods is demonstrated in the main doc string of
1125
this class. Here, we demonstrate lazy attributes.
1126
1127
EXAMPLE::
1128
1129
sage: cython_code = ["from sage.structure.element cimport ElementWithCachedMethod",
1130
... "cdef class MyElement(ElementWithCachedMethod):",
1131
... " cdef public object x",
1132
... " def __init__(self,P,x):",
1133
... " self.x=x",
1134
... " ElementWithCachedMethod.__init__(self,P)",
1135
... " def _repr_(self):",
1136
... " return '<%s>'%self.x",
1137
... "from sage.structure.parent cimport Parent",
1138
... "cdef class MyParent(Parent):",
1139
... " Element = MyElement",
1140
... "from sage.all import cached_method, lazy_attribute, Category, Objects",
1141
... "class MyCategory(Category):",
1142
... " @cached_method",
1143
... " def super_categories(self):",
1144
... " return [Objects()]",
1145
... " class ElementMethods:",
1146
... " @lazy_attribute",
1147
... " def my_lazy_attr(self):",
1148
... " return 'lazy attribute of <%d>'%self.x"]
1149
sage: cython('\n'.join(cython_code))
1150
sage: C = MyCategory()
1151
sage: P = MyParent(category=C)
1152
sage: e = MyElement(P,5)
1153
sage: e.my_lazy_attr
1154
'lazy attribute of <5>'
1155
sage: e.my_lazy_attr is e.my_lazy_attr
1156
True
1157
1158
"""
1159
if name.startswith('__') and not name.endswith('_'):
1160
raise AttributeError, AttributeErrorMessage(self, name)
1161
try:
1162
return self.__cached_methods[name]
1163
except KeyError:
1164
attr = getattr_from_other_class(self,
1165
self._parent.category().element_class,
1166
name)
1167
self.__cached_methods[name] = attr
1168
return attr
1169
except TypeError:
1170
attr = getattr_from_other_class(self,
1171
self._parent.category().element_class,
1172
name)
1173
self.__cached_methods = {name : attr}
1174
return attr
1175
1176
cdef class ModuleElement(Element):
1177
"""
1178
Generic element of a module.
1179
"""
1180
1181
##################################################
1182
# Addition
1183
##################################################
1184
def __add__(left, right):
1185
"""
1186
Top-level addition operator for ModuleElements.
1187
1188
See extensive documentation at the top of element.pyx.
1189
"""
1190
# Try fast pathway if they are both ModuleElements and the parents
1191
# match.
1192
1193
# (We know at least one of the arguments is a ModuleElement. So if
1194
# their types are *equal* (fast to check) then they are both
1195
# ModuleElements. Otherwise use the slower test via PY_TYPE_CHECK.)
1196
if have_same_parent(left, right):
1197
# If we hold the only references to this object, we can
1198
# safely mutate it. NOTE the threshold is different by one
1199
# for __add__ and __iadd__.
1200
if (<RefPyObject *>left).ob_refcnt < inplace_threshold:
1201
return (<ModuleElement>left)._iadd_(<ModuleElement>right)
1202
else:
1203
return (<ModuleElement>left)._add_(<ModuleElement>right)
1204
1205
global coercion_model
1206
return coercion_model.bin_op(left, right, add)
1207
1208
cpdef ModuleElement _add_(left, ModuleElement right):
1209
raise TypeError, arith_error_message(left, right, add)
1210
1211
def __iadd__(ModuleElement self, right):
1212
if have_same_parent(self, right):
1213
if (<RefPyObject *>self).ob_refcnt <= inplace_threshold:
1214
return self._iadd_(<ModuleElement>right)
1215
else:
1216
return self._add_(<ModuleElement>right)
1217
else:
1218
global coercion_model
1219
return coercion_model.bin_op(self, right, iadd)
1220
1221
cpdef ModuleElement _iadd_(self, ModuleElement right):
1222
return self._add_(right)
1223
1224
##################################################
1225
# Subtraction
1226
##################################################
1227
1228
def __sub__(left, right):
1229
"""
1230
Top-level subtraction operator for ModuleElements.
1231
See extensive documentation at the top of element.pyx.
1232
"""
1233
if have_same_parent(left, right):
1234
if (<RefPyObject *>left).ob_refcnt < inplace_threshold:
1235
return (<ModuleElement>left)._isub_(<ModuleElement>right)
1236
else:
1237
return (<ModuleElement>left)._sub_(<ModuleElement>right)
1238
global coercion_model
1239
return coercion_model.bin_op(left, right, sub)
1240
1241
cpdef ModuleElement _sub_(left, ModuleElement right):
1242
# default implementation is to use the negation and addition
1243
# dispatchers:
1244
return left._add_(-right)
1245
1246
def __isub__(ModuleElement self, right):
1247
if have_same_parent(self, right):
1248
if (<RefPyObject *>self).ob_refcnt <= inplace_threshold:
1249
return self._isub_(<ModuleElement>right)
1250
else:
1251
return self._sub_(<ModuleElement>right)
1252
else:
1253
global coercion_model
1254
return coercion_model.bin_op(self, right, isub)
1255
1256
cpdef ModuleElement _isub_(self, ModuleElement right):
1257
return self._sub_(right)
1258
1259
##################################################
1260
# Negation
1261
##################################################
1262
1263
def __neg__(self):
1264
"""
1265
Top-level negation operator for ModuleElements, which
1266
may choose to implement _neg_ rather than __neg__ for
1267
consistency.
1268
"""
1269
return self._neg_()
1270
1271
cpdef ModuleElement _neg_(self):
1272
# default implementation is to try multiplying by -1.
1273
global coercion_model
1274
if self._parent._base is None:
1275
return coercion_model.bin_op(-1, self, mul)
1276
else:
1277
return coercion_model.bin_op(self._parent._base(-1), self, mul)
1278
1279
##################################################
1280
# Module element multiplication (scalars, etc.)
1281
##################################################
1282
def __mul__(left, right):
1283
if PyInt_CheckExact(right):
1284
return (<ModuleElement>left)._mul_long(PyInt_AS_LONG(right))
1285
if PyInt_CheckExact(left):
1286
return (<ModuleElement>right)._mul_long(PyInt_AS_LONG(left))
1287
if have_same_parent(left, right):
1288
raise arith_error_message(left, right, mul)
1289
# Always do this
1290
global coercion_model
1291
return coercion_model.bin_op(left, right, mul)
1292
1293
def __imul__(left, right):
1294
if have_same_parent(left, right):
1295
raise TypeError
1296
# Always do this
1297
global coercion_model
1298
return coercion_model.bin_op(left, right, imul)
1299
1300
# rmul -- left * self
1301
cpdef ModuleElement _rmul_(self, RingElement left):
1302
"""
1303
Default module left scalar multiplication, which is to try to
1304
canonically coerce the scalar to the integers and do that
1305
multiplication, which is always defined.
1306
1307
Returning None indicates that this action is not implemented here.
1308
"""
1309
return None
1310
1311
# lmul -- self * right
1312
1313
cpdef ModuleElement _lmul_(self, RingElement right):
1314
"""
1315
Default module left scalar multiplication, which is to try to
1316
canonically coerce the scalar to the integers and do that
1317
multiplication, which is always defined.
1318
1319
Returning None indicates that this action is not implemented here.
1320
"""
1321
return None
1322
1323
cdef ModuleElement _mul_long(self, long n):
1324
"""
1325
Generic path for multiplying by a C long, assumed to commute.
1326
"""
1327
return coercion_model.bin_op(self, n, mul)
1328
1329
cpdef ModuleElement _ilmul_(self, RingElement right):
1330
return self._lmul_(right)
1331
1332
cdef RingElement coerce_to_base_ring(self, x):
1333
if PY_TYPE_CHECK(x, Element) and (<Element>x)._parent is self._parent._base:
1334
return x
1335
try:
1336
return self._parent._base._coerce_c(x)
1337
except AttributeError:
1338
return self._parent._base(x)
1339
1340
##################################################
1341
# Other properties
1342
##################################################
1343
def order(self): ### DO NOT OVERRIDE THIS!!! Instead, override additive_order.
1344
"""
1345
Return the additive order of self.
1346
"""
1347
return self.additive_order()
1348
1349
def additive_order(self):
1350
"""
1351
Return the additive order of self.
1352
"""
1353
raise NotImplementedError
1354
1355
########################################################################
1356
# Monoid
1357
########################################################################
1358
1359
def is_MonoidElement(x):
1360
"""
1361
Return True if x is of type MonoidElement.
1362
"""
1363
return IS_INSTANCE(x, MonoidElement)
1364
1365
cdef class MonoidElement(Element):
1366
"""
1367
Generic element of a monoid.
1368
"""
1369
1370
#############################################################
1371
# Multiplication
1372
#############################################################
1373
def __mul__(left, right):
1374
"""
1375
Top-level multiplication operator for monoid elements.
1376
See extensive documentation at the top of element.pyx.
1377
"""
1378
global coercion_model
1379
if have_same_parent(left, right):
1380
return (<MonoidElement>left)._mul_(<MonoidElement>right)
1381
try:
1382
return coercion_model.bin_op(left, right, mul)
1383
except TypeError, msg:
1384
if isinstance(left, (int, long)) and left==1:
1385
return right
1386
elif isinstance(right, (int, long)) and right==1:
1387
return left
1388
raise
1389
1390
1391
cpdef MonoidElement _mul_(left, MonoidElement right):
1392
"""
1393
Cython classes should override this function to implement multiplication.
1394
See extensive documentation at the top of element.pyx.
1395
"""
1396
raise TypeError
1397
1398
#############################################################
1399
# Other generic functions that should be available to
1400
# any monoid element.
1401
#############################################################
1402
def order(self):
1403
"""
1404
Return the multiplicative order of self.
1405
"""
1406
return self.multiplicative_order()
1407
1408
def multiplicative_order(self):
1409
"""
1410
Return the multiplicative order of self.
1411
"""
1412
raise NotImplementedError
1413
1414
def __pow__(self, n, dummy):
1415
"""
1416
Return the (integral) power of self.
1417
"""
1418
if dummy is not None:
1419
raise RuntimeError, "__pow__ dummy argument not used"
1420
return generic_power_c(self,n,None)
1421
1422
def __nonzero__(self):
1423
return True
1424
1425
def is_AdditiveGroupElement(x):
1426
"""
1427
Return True if x is of type AdditiveGroupElement.
1428
"""
1429
return IS_INSTANCE(x, AdditiveGroupElement)
1430
1431
cdef class AdditiveGroupElement(ModuleElement):
1432
"""
1433
Generic element of an additive group.
1434
"""
1435
def order(self):
1436
"""
1437
Return additive order of element
1438
"""
1439
return self.additive_order()
1440
1441
def __invert__(self):
1442
raise NotImplementedError, "multiplicative inverse not defined for additive group elements"
1443
1444
cpdef ModuleElement _rmul_(self, RingElement left):
1445
return self._lmul_(left)
1446
1447
cpdef ModuleElement _lmul_(self, RingElement right):
1448
"""
1449
Default module left scalar multiplication, which is to try to
1450
canonically coerce the scalar to the integers and do that
1451
multiplication, which is always defined.
1452
1453
Returning None indicates this action is not implemented.
1454
"""
1455
return None
1456
1457
def is_MultiplicativeGroupElement(x):
1458
"""
1459
Return True if x is of type MultiplicativeGroupElement.
1460
"""
1461
return IS_INSTANCE(x, MultiplicativeGroupElement)
1462
1463
cdef class MultiplicativeGroupElement(MonoidElement):
1464
"""
1465
Generic element of a multiplicative group.
1466
"""
1467
def order(self):
1468
"""
1469
Return the multiplicative order of self.
1470
"""
1471
return self.multiplicative_order()
1472
1473
def _add_(self, x):
1474
raise ArithmeticError, "addition not defined in a multiplicative group"
1475
1476
def __div__(left, right):
1477
if have_same_parent(left, right):
1478
return left._div_(right)
1479
global coercion_model
1480
return coercion_model.bin_op(left, right, div)
1481
1482
cpdef MultiplicativeGroupElement _div_(self, MultiplicativeGroupElement right):
1483
"""
1484
Cython classes should override this function to implement division.
1485
See extensive documentation at the top of element.pyx.
1486
"""
1487
return self * ~right
1488
1489
def __invert__(self):
1490
if self.is_one():
1491
return self
1492
return 1/self
1493
1494
1495
def is_RingElement(x):
1496
"""
1497
Return True if x is of type RingElement.
1498
"""
1499
return IS_INSTANCE(x, RingElement)
1500
1501
cdef class RingElement(ModuleElement):
1502
##################################################
1503
def is_one(self):
1504
return self == self._parent.one_element()
1505
1506
##################################
1507
# Fast long add/sub path.
1508
##################################
1509
1510
def __add__(left, right):
1511
"""
1512
Top-level addition operator for RingElements.
1513
1514
See extensive documentation at the top of element.pyx.
1515
"""
1516
if have_same_parent(left, right):
1517
if (<RefPyObject *>left).ob_refcnt < inplace_threshold:
1518
return (<ModuleElement>left)._iadd_(<ModuleElement>right)
1519
else:
1520
return (<ModuleElement>left)._add_(<ModuleElement>right)
1521
if PyInt_CheckExact(right):
1522
return (<RingElement>left)._add_long(PyInt_AS_LONG(right))
1523
elif PyInt_CheckExact(left):
1524
return (<RingElement>right)._add_long(PyInt_AS_LONG(left))
1525
return coercion_model.bin_op(left, right, add)
1526
1527
cdef RingElement _add_long(self, long n):
1528
"""
1529
Generic path for adding a C long, assumed to commute.
1530
"""
1531
return coercion_model.bin_op(self, n, add)
1532
1533
def __sub__(left, right):
1534
"""
1535
Top-level subtraction operator for RingElements.
1536
1537
See extensive documentation at the top of element.pyx.
1538
"""
1539
cdef long n
1540
if have_same_parent(left, right):
1541
if (<RefPyObject *>left).ob_refcnt < inplace_threshold:
1542
return (<ModuleElement>left)._isub_(<ModuleElement>right)
1543
else:
1544
return (<ModuleElement>left)._sub_(<ModuleElement>right)
1545
if PyInt_CheckExact(right):
1546
n = PyInt_AS_LONG(right)
1547
# See UNARY_NEG_WOULD_OVERFLOW in Python's intobject.c
1548
if (n == 0) | (<unsigned long>n != 0 - <unsigned long>n):
1549
return (<RingElement>left)._add_long(-n)
1550
return coercion_model.bin_op(left, right, sub)
1551
1552
##################################
1553
# Multiplication
1554
##################################
1555
1556
cpdef ModuleElement _lmul_(self, RingElement right):
1557
# We return None to invoke the default action of coercing into self
1558
return None
1559
1560
cpdef ModuleElement _rmul_(self, RingElement left):
1561
# We return None to invoke the default action of coercing into self
1562
return None
1563
1564
def __mul__(left, right):
1565
"""
1566
Top-level multiplication operator for ring elements.
1567
See extensive documentation at the top of element.pyx.
1568
1569
AUTHOR:
1570
1571
- Gonzalo Tornaria (2007-06-25) - write base-extending test cases and fix them
1572
1573
TESTS:
1574
1575
Here we test (scalar * vector) multiplication::
1576
1577
sage: x, y = var('x, y')
1578
1579
sage: parent(ZZ(1)*vector(ZZ,[1,2]))
1580
Ambient free module of rank 2 over the principal ideal domain Integer Ring
1581
sage: parent(QQ(1)*vector(ZZ,[1,2]))
1582
Vector space of dimension 2 over Rational Field
1583
sage: parent(ZZ(1)*vector(QQ,[1,2]))
1584
Vector space of dimension 2 over Rational Field
1585
sage: parent(QQ(1)*vector(QQ,[1,2]))
1586
Vector space of dimension 2 over Rational Field
1587
1588
sage: parent(QQ(1)*vector(ZZ[x],[1,2]))
1589
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
1590
sage: parent(ZZ[x](1)*vector(QQ,[1,2]))
1591
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
1592
1593
sage: parent(QQ(1)*vector(ZZ[x][y],[1,2]))
1594
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1595
sage: parent(ZZ[x][y](1)*vector(QQ,[1,2]))
1596
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1597
1598
sage: parent(QQ[x](1)*vector(ZZ[x][y],[1,2]))
1599
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1600
sage: parent(ZZ[x][y](1)*vector(QQ[x],[1,2]))
1601
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1602
1603
sage: parent(QQ[y](1)*vector(ZZ[x][y],[1,2]))
1604
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1605
sage: parent(ZZ[x][y](1)*vector(QQ[y],[1,2]))
1606
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1607
1608
sage: parent(ZZ[x](1)*vector(ZZ[y],[1,2]))
1609
Traceback (most recent call last):
1610
...
1611
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
1612
sage: parent(ZZ[x](1)*vector(QQ[y],[1,2]))
1613
Traceback (most recent call last):
1614
...
1615
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
1616
sage: parent(QQ[x](1)*vector(ZZ[y],[1,2]))
1617
Traceback (most recent call last):
1618
...
1619
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
1620
sage: parent(QQ[x](1)*vector(QQ[y],[1,2]))
1621
Traceback (most recent call last):
1622
...
1623
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
1624
1625
Here we test (scalar * matrix) multiplication::
1626
1627
sage: parent(ZZ(1)*matrix(ZZ,2,2,[1,2,3,4]))
1628
Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
1629
sage: parent(QQ(1)*matrix(ZZ,2,2,[1,2,3,4]))
1630
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
1631
sage: parent(ZZ(1)*matrix(QQ,2,2,[1,2,3,4]))
1632
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
1633
sage: parent(QQ(1)*matrix(QQ,2,2,[1,2,3,4]))
1634
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
1635
1636
sage: parent(QQ(1)*matrix(ZZ[x],2,2,[1,2,3,4]))
1637
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
1638
sage: parent(ZZ[x](1)*matrix(QQ,2,2,[1,2,3,4]))
1639
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
1640
1641
sage: parent(QQ(1)*matrix(ZZ[x][y],2,2,[1,2,3,4]))
1642
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1643
sage: parent(ZZ[x][y](1)*matrix(QQ,2,2,[1,2,3,4]))
1644
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1645
1646
sage: parent(QQ[x](1)*matrix(ZZ[x][y],2,2,[1,2,3,4]))
1647
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1648
sage: parent(ZZ[x][y](1)*matrix(QQ[x],2,2,[1,2,3,4]))
1649
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1650
1651
sage: parent(QQ[y](1)*matrix(ZZ[x][y],2,2,[1,2,3,4]))
1652
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1653
sage: parent(ZZ[x][y](1)*matrix(QQ[y],2,2,[1,2,3,4]))
1654
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
1655
1656
sage: parent(ZZ[x](1)*matrix(ZZ[y],2,2,[1,2,3,4]))
1657
Traceback (most recent call last):
1658
...
1659
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
1660
sage: parent(ZZ[x](1)*matrix(QQ[y],2,2,[1,2,3,4]))
1661
Traceback (most recent call last):
1662
...
1663
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
1664
sage: parent(QQ[x](1)*matrix(ZZ[y],2,2,[1,2,3,4]))
1665
Traceback (most recent call last):
1666
...
1667
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
1668
sage: parent(QQ[x](1)*matrix(QQ[y],2,2,[1,2,3,4]))
1669
Traceback (most recent call last):
1670
...
1671
TypeError: unsupported operand parent(s) for '*': 'Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
1672
1673
"""
1674
# Try fast pathway if they are both RingElements and the parents match.
1675
# (We know at least one of the arguments is a RingElement. So if their
1676
# types are *equal* (fast to check) then they are both RingElements.
1677
# Otherwise use the slower test via PY_TYPE_CHECK.)
1678
if have_same_parent(left, right):
1679
if (<RefPyObject *>left).ob_refcnt < inplace_threshold:
1680
return (<RingElement>left)._imul_(<RingElement>right)
1681
else:
1682
return (<RingElement>left)._mul_(<RingElement>right)
1683
if PyInt_CheckExact(right):
1684
return (<ModuleElement>left)._mul_long(PyInt_AS_LONG(right))
1685
elif PyInt_CheckExact(left):
1686
return (<ModuleElement>right)._mul_long(PyInt_AS_LONG(left))
1687
return coercion_model.bin_op(left, right, mul)
1688
1689
cpdef RingElement _mul_(self, RingElement right):
1690
"""
1691
Cython classes should override this function to implement multiplication.
1692
See extensive documentation at the top of element.pyx.
1693
"""
1694
raise TypeError, arith_error_message(self, right, mul)
1695
1696
def __imul__(left, right):
1697
if have_same_parent(left, right):
1698
if (<RefPyObject *>left).ob_refcnt <= inplace_threshold:
1699
return (<RingElement>left)._imul_(<RingElement>right)
1700
else:
1701
return (<RingElement>left)._mul_(<RingElement>right)
1702
1703
global coercion_model
1704
return coercion_model.bin_op(left, right, imul)
1705
1706
cpdef RingElement _imul_(RingElement self, RingElement right):
1707
return self._mul_(right)
1708
1709
def __pow__(self, n, dummy):
1710
"""
1711
Return the (integral) power of self.
1712
1713
EXAMPLE::
1714
1715
sage: a = Integers(389)['x']['y'](37)
1716
sage: p = sage.structure.element.RingElement.__pow__
1717
sage: p(a,2)
1718
202
1719
sage: p(a,2,1)
1720
Traceback (most recent call last):
1721
...
1722
RuntimeError: __pow__ dummy argument not used
1723
sage: p(a,388)
1724
1
1725
sage: p(a,2^120)
1726
81
1727
sage: p(a,0)
1728
1
1729
sage: p(a,1) == a
1730
True
1731
sage: p(a,2) * p(a,3) == p(a,5)
1732
True
1733
sage: p(a,3)^2 == p(a,6)
1734
True
1735
sage: p(a,57) * p(a,43) == p(a,100)
1736
True
1737
sage: p(a,-1) == 1/a
1738
True
1739
sage: p(a,200) * p(a,-64) == p(a,136)
1740
True
1741
sage: p(2, 1/2)
1742
Traceback (most recent call last):
1743
...
1744
NotImplementedError: non-integral exponents not supported
1745
1746
TESTS::
1747
1748
These aren't testing this code, but they are probably good to have around.
1749
1750
sage: 2r**(SR(2)-1-1r)
1751
1
1752
sage: 2r^(1/2)
1753
sqrt(2)
1754
1755
Exponent overflow should throw an OverflowError (trac #2956)::
1756
1757
sage: K.<x,y> = AA[]
1758
sage: x^(2^64 + 12345)
1759
Traceback (most recent call last):
1760
...
1761
OverflowError: Exponent overflow (2147483648).
1762
1763
Another example from trac #2956; this should overflow on x32
1764
and succeed on x64::
1765
1766
sage: K.<x,y> = ZZ[]
1767
sage: (x^12345)^54321
1768
x^670592745 # 64-bit
1769
Traceback (most recent call last): # 32-bit
1770
... # 32-bit
1771
OverflowError: Exponent overflow (670592745). # 32-bit
1772
1773
"""
1774
if dummy is not None:
1775
raise RuntimeError, "__pow__ dummy argument not used"
1776
return generic_power_c(self,n,None)
1777
1778
##################################
1779
# Division
1780
##################################
1781
1782
def __truediv__(self, right):
1783
# in sage all divs are true
1784
if not PY_TYPE_CHECK(self, Element):
1785
return coercion_model.bin_op(self, right, div)
1786
return self.__div__(right)
1787
1788
def __div__(self, right):
1789
"""
1790
Top-level multiplication operator for ring elements.
1791
See extensive documentation at the top of element.pyx.
1792
"""
1793
if have_same_parent(self, right):
1794
if (<RefPyObject *>self).ob_refcnt < inplace_threshold:
1795
return (<RingElement>self)._idiv_(<RingElement>right)
1796
else:
1797
return (<RingElement>self)._div_(<RingElement>right)
1798
global coercion_model
1799
return coercion_model.bin_op(self, right, div)
1800
1801
cpdef RingElement _div_(self, RingElement right):
1802
"""
1803
Cython classes should override this function to implement division.
1804
See extensive documentation at the top of element.pyx.
1805
"""
1806
try:
1807
return self._parent.fraction_field()(self, right)
1808
except AttributeError:
1809
if not right:
1810
raise ZeroDivisionError, "Cannot divide by zero"
1811
else:
1812
raise TypeError, arith_error_message(self, right, div)
1813
1814
def __idiv__(self, right):
1815
"""
1816
Top-level division operator for ring elements.
1817
See extensive documentation at the top of element.pyx.
1818
"""
1819
if have_same_parent(self, right):
1820
if (<RefPyObject *>self).ob_refcnt <= inplace_threshold:
1821
return (<RingElement>self)._idiv_(<RingElement>right)
1822
else:
1823
return (<RingElement>self)._div_(<RingElement>right)
1824
global coercion_model
1825
return coercion_model.bin_op(self, right, idiv)
1826
1827
cpdef RingElement _idiv_(RingElement self, RingElement right):
1828
return self._div_(right)
1829
1830
def __invert__(self):
1831
if self.is_one():
1832
return self
1833
return 1/self
1834
1835
1836
def order(self):
1837
"""
1838
Return the additive order of self.
1839
1840
This is deprecated; use ``additive_order`` instead.
1841
1842
EXAMPLES::
1843
1844
sage: a = Integers(12)(5)
1845
sage: a.order()
1846
doctest... DeprecationWarning: The function order is deprecated for ring elements; use additive_order or multiplicative_order instead.
1847
12
1848
"""
1849
# deprecation added 2009-05
1850
from sage.misc.misc import deprecation
1851
deprecation("The function order is deprecated for ring elements; use additive_order or multiplicative_order instead.")
1852
return self.additive_order()
1853
1854
def additive_order(self):
1855
"""
1856
Return the additive order of self.
1857
"""
1858
raise NotImplementedError
1859
1860
def multiplicative_order(self):
1861
r"""
1862
Return the multiplicative order of self, if self is a unit, or raise
1863
``ArithmeticError`` otherwise.
1864
"""
1865
if not self.is_unit():
1866
raise ArithmeticError, "self (=%s) must be a unit to have a multiplicative order."
1867
raise NotImplementedError
1868
1869
def is_unit(self):
1870
if self == 1 or self == -1:
1871
return True
1872
raise NotImplementedError
1873
1874
def is_nilpotent(self):
1875
"""
1876
Return True if self is nilpotent, i.e., some power of self
1877
is 0.
1878
"""
1879
if self.is_unit():
1880
return False
1881
if self.is_zero():
1882
return True
1883
raise NotImplementedError
1884
1885
def abs(self):
1886
"""
1887
Return the absolute value of self. (This just calls the __abs__
1888
method, so it is equivalent to the abs() built-in function.)
1889
1890
EXAMPLES::
1891
1892
sage: RR(-1).abs()
1893
1.00000000000000
1894
sage: ZZ(-1).abs()
1895
1
1896
sage: CC(I).abs()
1897
1.00000000000000
1898
sage: Mod(-15, 37).abs()
1899
Traceback (most recent call last):
1900
...
1901
ArithmeticError: absolute valued not defined on integers modulo n.
1902
"""
1903
return self.__abs__()
1904
1905
1906
1907
def is_CommutativeRingElement(x):
1908
"""
1909
Return True if x is of type CommutativeRingElement.
1910
"""
1911
return IS_INSTANCE(x, CommutativeRingElement)
1912
1913
cdef class CommutativeRingElement(RingElement):
1914
def _im_gens_(self, codomain, im_gens):
1915
if len(im_gens) == 1 and self._parent.gen(0) == 1:
1916
return codomain(self)
1917
raise NotImplementedError
1918
1919
def inverse_mod(self, I):
1920
r"""
1921
Return an inverse of self modulo the ideal `I`, if defined,
1922
i.e., if `I` and self together generate the unit ideal.
1923
"""
1924
raise NotImplementedError
1925
1926
def divides(self, x):
1927
"""
1928
Return True if self divides x.
1929
1930
EXAMPLES::
1931
1932
sage: P.<x> = PolynomialRing(QQ)
1933
sage: x.divides(x^2)
1934
True
1935
sage: x.divides(x^2+2)
1936
False
1937
sage: (x^2+2).divides(x)
1938
False
1939
sage: P.<x> = PolynomialRing(ZZ)
1940
sage: x.divides(x^2)
1941
True
1942
sage: x.divides(x^2+2)
1943
False
1944
sage: (x^2+2).divides(x)
1945
False
1946
1947
Ticket \#5347 has been fixed::
1948
1949
sage: K = GF(7)
1950
sage: K(3).divides(1)
1951
True
1952
sage: K(3).divides(K(1))
1953
True
1954
1955
::
1956
1957
sage: R = Integers(128)
1958
sage: R(0).divides(1)
1959
False
1960
sage: R(0).divides(0)
1961
True
1962
sage: R(0).divides(R(0))
1963
True
1964
sage: R(1).divides(0)
1965
True
1966
sage: R(121).divides(R(120))
1967
True
1968
sage: R(120).divides(R(121))
1969
Traceback (most recent call last):
1970
...
1971
ZeroDivisionError: reduction modulo right not defined.
1972
1973
If x has different parent than `self`, they are first coerced to a
1974
common parent if possible. If this coercion fails, it returns a
1975
TypeError. This fixes \#5759
1976
1977
::
1978
sage: Zmod(2)(0).divides(Zmod(2)(0))
1979
True
1980
sage: Zmod(2)(0).divides(Zmod(2)(1))
1981
False
1982
sage: Zmod(5)(1).divides(Zmod(2)(1))
1983
Traceback (most recent call last):
1984
...
1985
TypeError: no common canonical parent for objects with parents: 'Ring of integers modulo 5' and 'Ring of integers modulo 2'
1986
sage: Zmod(35)(4).divides(Zmod(7)(1))
1987
True
1988
sage: Zmod(35)(7).divides(Zmod(7)(1))
1989
False
1990
"""
1991
#Check if the parents are the same:
1992
1993
if have_same_parent(self, x):
1994
# First we test some generic conditions:
1995
try:
1996
if x.is_zero():
1997
return True # everything divides 0
1998
except (AttributeError, NotImplementedError):
1999
pass
2000
2001
try:
2002
if self.is_zero():
2003
return False # 0 divides nothing else
2004
except (AttributeError, NotImplementedError):
2005
pass
2006
2007
try:
2008
if self.is_unit():
2009
return True # units divide everything
2010
except (AttributeError, NotImplementedError):
2011
pass
2012
2013
try:
2014
if self.is_one():
2015
return True # 1 divides everything
2016
# (is_unit() may not be implemented)
2017
except (AttributeError, NotImplementedError):
2018
pass
2019
2020
return (x % self) == 0
2021
2022
else:
2023
#Different parents, use coercion
2024
global coercion_model
2025
a, b = coercion_model.canonical_coercion(self, x)
2026
return a.divides(b)
2027
2028
def mod(self, I):
2029
r"""
2030
Return a representative for self modulo the ideal I (or the ideal
2031
generated by the elements of I if I is not an ideal.)
2032
2033
EXAMPLE: Integers
2034
Reduction of 5 modulo an ideal::
2035
2036
sage: n = 5
2037
sage: n.mod(3*ZZ)
2038
2
2039
2040
Reduction of 5 modulo the ideal generated by 3::
2041
2042
sage: n.mod(3)
2043
2
2044
2045
Reduction of 5 modulo the ideal generated by 15 and 6, which is `(3)`.
2046
2047
::
2048
2049
sage: n.mod([15,6])
2050
2
2051
2052
2053
EXAMPLE: Univariate polynomials
2054
2055
::
2056
2057
sage: R.<x> = PolynomialRing(QQ)
2058
sage: f = x^3 + x + 1
2059
sage: f.mod(x + 1)
2060
-1
2061
2062
When little is implemented about a given ring, then mod may
2063
return simply return `f`. For example, reduction is not
2064
implemented for `\ZZ[x]` yet. (TODO!)
2065
2066
sage: R.<x> = PolynomialRing(ZZ)
2067
sage: f = x^3 + x + 1
2068
sage: f.mod(x + 1)
2069
x^3 + x + 1
2070
2071
2072
EXAMPLE: Multivariate polynomials
2073
We reduce a polynomial in two variables modulo a polynomial
2074
and an ideal::
2075
2076
sage: R.<x,y,z> = PolynomialRing(QQ, 3)
2077
sage: (x^2 + y^2 + z^2).mod(x+y+z)
2078
2*y^2 + 2*y*z + 2*z^2
2079
2080
Notice above that `x` is eliminated. In the next example,
2081
both `y` and `z` are eliminated::
2082
2083
sage: (x^2 + y^2 + z^2).mod( (x - y, y - z) )
2084
3*z^2
2085
sage: f = (x^2 + y^2 + z^2)^2; f
2086
x^4 + 2*x^2*y^2 + y^4 + 2*x^2*z^2 + 2*y^2*z^2 + z^4
2087
sage: f.mod( (x - y, y - z) )
2088
9*z^4
2089
2090
In this example `y` is eliminated::
2091
2092
sage: (x^2 + y^2 + z^2).mod( (x^3, y - z) )
2093
x^2 + 2*z^2
2094
"""
2095
from sage.rings.all import is_Ideal
2096
if not is_Ideal(I) or not I.ring() is self._parent:
2097
I = self._parent.ideal(I)
2098
#raise TypeError, "I = %s must be an ideal in %s"%(I, self.parent())
2099
return I.reduce(self)
2100
2101
##################################################
2102
# square roots
2103
##################################################
2104
2105
def is_square(self, root=False):
2106
"""
2107
Returns whether or not ring element is a square. If the optional
2108
argument root is True, then also returns the square root (or None,
2109
if the it is not a square).
2110
2111
INPUT:
2112
2113
2114
- ``root`` - whether or not to also return a square
2115
root (default: False)
2116
2117
2118
OUTPUT:
2119
2120
2121
- ``bool`` - whether or not a square
2122
2123
- ``object`` - (optional) an actual square root if
2124
found, and None otherwise.
2125
2126
2127
EXAMPLES::
2128
2129
sage: R.<x> = PolynomialRing(QQ)
2130
sage: f = 12*(x+1)^2 * (x+3)^2
2131
sage: f.is_square()
2132
False
2133
sage: f.is_square(root=True)
2134
(False, None)
2135
sage: h = f/3
2136
sage: h.is_square()
2137
True
2138
sage: h.is_square(root=True)
2139
(True, 2*x^2 + 8*x + 6)
2140
2141
.. NOTE:
2142
2143
This is the is_square implementation for general commutative ring
2144
elements. It's implementation is to raise a NotImplementedError.
2145
The function definition is here to show what functionality is expected and
2146
provide a general framework.
2147
"""
2148
raise NotImplementedError("is_square() not implemented for elements of %s" %self.parent())
2149
2150
2151
def sqrt(self, extend = True, all = False, name=None ):
2152
"""
2153
It computes the square root.
2154
2155
INPUT:
2156
2157
- ``extend`` - Whether to make a ring extension containing a square root if self is not a square (default: True)
2158
2159
- ``all`` - Whether to return a list of all square roots or just a square root (default: False)
2160
2161
- ``name`` - Required when extend=True and self is not a square. This will be the name of the generator extension.
2162
2163
OUTPUT:
2164
2165
- if all=False it returns a square root. (throws an error if extend=False and self is not a square)
2166
2167
- if all=True it returns a list of all the square roots (could be empty if extend=False and self is not a square)
2168
2169
ALGORITHM:
2170
2171
It uses is_square(root=true) for the hard part of the work, the rest is just wrapper code.
2172
2173
EXAMPLES::
2174
2175
sage: R.<x> = ZZ[]
2176
sage: (x^2).sqrt()
2177
x
2178
sage: f=x^2-4*x+4; f.sqrt(all=True)
2179
[x - 2, -x + 2]
2180
sage: sqrtx=x.sqrt(name="y"); sqrtx
2181
y
2182
sage: sqrtx^2
2183
x
2184
sage: x.sqrt(all=true,name="y")
2185
[y, -y]
2186
sage: x.sqrt(extend=False,all=True)
2187
[]
2188
sage: x.sqrt()
2189
Traceback (most recent call last):
2190
...
2191
TypeError: Polynomial is not a square. You must specify the name of the square root when using the default extend = True
2192
sage: x.sqrt(extend=False)
2193
Traceback (most recent call last):
2194
...
2195
ValueError: trying to take square root of non-square x with extend = False
2196
2197
TESTS::
2198
2199
sage: f = (x+3)^2; f.sqrt()
2200
x + 3
2201
sage: f = (x+3)^2; f.sqrt(all=True)
2202
[x + 3, -x - 3]
2203
sage: f = (x^2 - x + 3)^2; f.sqrt()
2204
x^2 - x + 3
2205
sage: f = (x^2 - x + 3)^6; f.sqrt()
2206
x^6 - 3*x^5 + 12*x^4 - 19*x^3 + 36*x^2 - 27*x + 27
2207
sage: g = (R.random_element(15))^2
2208
sage: g.sqrt()^2 == g
2209
True
2210
2211
sage: R.<x> = GF(250037)[]
2212
sage: f = x^2/(x+1)^2; f.sqrt()
2213
x/(x + 1)
2214
sage: f = 9 * x^4 / (x+1)^2; f.sqrt()
2215
3*x^2/(x + 1)
2216
sage: f = 9 * x^4 / (x+1)^2; f.sqrt(all=True)
2217
[3*x^2/(x + 1), 250034*x^2/(x + 1)]
2218
2219
sage: R.<x> = QQ[]
2220
sage: a = 2*(x+1)^2 / (2*(x-1)^2); a.sqrt()
2221
(2*x + 2)/(2*x - 2)
2222
sage: sqrtx=(1/x).sqrt(name="y"); sqrtx
2223
y
2224
sage: sqrtx^2
2225
1/x
2226
sage: (1/x).sqrt(all=true,name="y")
2227
[y, -y]
2228
sage: (1/x).sqrt(extend=False,all=True)
2229
[]
2230
sage: (1/(x^2-1)).sqrt()
2231
Traceback (most recent call last):
2232
...
2233
TypeError: Polynomial is not a square. You must specify the name of the square root when using the default extend = True
2234
sage: (1/(x^2-3)).sqrt(extend=False)
2235
Traceback (most recent call last):
2236
...
2237
ValueError: trying to take square root of non-square 1/(x^2 - 3) with extend = False
2238
2239
"""
2240
#This code is very general, it works for all integral domains that have the
2241
#is_square(root = True) option
2242
2243
from sage.rings.integral_domain import is_IntegralDomain
2244
P=self._parent
2245
is_sqr, sq_rt = self.is_square( root = True )
2246
if is_sqr:
2247
if all:
2248
if not is_IntegralDomain(P):
2249
raise NotImplementedError('sqrt() with all=True is only implemented for integral domains, not for %s' % P)
2250
if P.characteristic()==2 or sq_rt==0:
2251
#0 has only one square root, and in charasteristic 2 everything also has only 1 root
2252
return [ sq_rt ]
2253
return [ sq_rt, -sq_rt ]
2254
return sq_rt
2255
#from now on we know that self is not a square
2256
if not is_IntegralDomain(P):
2257
raise NotImplementedError('sqrt() of non squares is only implemented for integral domains, not for %s' % P)
2258
if not extend:
2259
#all square roots of a non-square should be an empty list
2260
if all:
2261
return []
2262
raise ValueError, 'trying to take square root of non-square %s with extend = False' % self
2263
2264
if name == None:
2265
raise TypeError ("Polynomial is not a square. You must specify the name of the square root when using the default extend = True")
2266
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
2267
PY = PolynomialRing(P,'y')
2268
y = PY.gen()
2269
sq_rt = PY.quotient(y**2-self, names = name)(y)
2270
if all:
2271
if P.characteristic() == 2:
2272
return [ sq_rt ]
2273
return [ sq_rt, -sq_rt ]
2274
return sq_rt
2275
2276
##############################################
2277
2278
cdef class Vector(ModuleElement):
2279
cdef bint is_sparse_c(self):
2280
raise NotImplementedError
2281
2282
cdef bint is_dense_c(self):
2283
raise NotImplementedError
2284
2285
def __imul__(left, right):
2286
if have_same_parent(left, right):
2287
return (<Vector>left)._dot_product_(<Vector>right)
2288
# Always do this
2289
global coercion_model
2290
return coercion_model.bin_op(left, right, imul)
2291
2292
2293
def __mul__(left, right):
2294
"""
2295
Multiplication of vector by vector, matrix, or scalar
2296
2297
AUTHOR:
2298
2299
- Gonzalo Tornaria (2007-06-21) - write test cases and fix them
2300
2301
.. note::
2302
2303
scalar * vector is implemented (and tested) in class RingElement
2304
matrix * vector is implemented (and tested) in class Matrix
2305
2306
TESTS:
2307
2308
Here we test (vector * vector) multiplication::
2309
2310
sage: x, y = var('x, y')
2311
2312
sage: parent(vector(ZZ,[1,2])*vector(ZZ,[1,2]))
2313
Integer Ring
2314
sage: parent(vector(ZZ,[1,2])*vector(QQ,[1,2]))
2315
Rational Field
2316
sage: parent(vector(QQ,[1,2])*vector(ZZ,[1,2]))
2317
Rational Field
2318
sage: parent(vector(QQ,[1,2])*vector(QQ,[1,2]))
2319
Rational Field
2320
2321
sage: parent(vector(QQ,[1,2,3,4])*vector(ZZ[x],[1,2,3,4]))
2322
Univariate Polynomial Ring in x over Rational Field
2323
sage: parent(vector(ZZ[x],[1,2,3,4])*vector(QQ,[1,2,3,4]))
2324
Univariate Polynomial Ring in x over Rational Field
2325
2326
sage: parent(vector(QQ,[1,2,3,4])*vector(ZZ[x][y],[1,2,3,4]))
2327
Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2328
sage: parent(vector(ZZ[x][y],[1,2,3,4])*vector(QQ,[1,2,3,4]))
2329
Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2330
2331
sage: parent(vector(QQ[x],[1,2,3,4])*vector(ZZ[x][y],[1,2,3,4]))
2332
Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2333
sage: parent(vector(ZZ[x][y],[1,2,3,4])*vector(QQ[x],[1,2,3,4]))
2334
Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2335
2336
sage: parent(vector(QQ[y],[1,2,3,4])*vector(ZZ[x][y],[1,2,3,4]))
2337
Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2338
sage: parent(vector(ZZ[x][y],[1,2,3,4])*vector(QQ[y],[1,2,3,4]))
2339
Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2340
2341
sage: parent(vector(ZZ[x],[1,2,3,4])*vector(ZZ[y],[1,2,3,4]))
2342
Traceback (most recent call last):
2343
...
2344
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
2345
sage: parent(vector(ZZ[x],[1,2,3,4])*vector(QQ[y],[1,2,3,4]))
2346
Traceback (most recent call last):
2347
...
2348
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
2349
sage: parent(vector(QQ[x],[1,2,3,4])*vector(ZZ[y],[1,2,3,4]))
2350
Traceback (most recent call last):
2351
...
2352
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
2353
sage: parent(vector(QQ[x],[1,2,3,4])*vector(QQ[y],[1,2,3,4]))
2354
Traceback (most recent call last):
2355
...
2356
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
2357
2358
Here we test (vector * matrix) multiplication::
2359
2360
sage: parent(vector(ZZ,[1,2])*matrix(ZZ,2,2,[1,2,3,4]))
2361
Ambient free module of rank 2 over the principal ideal domain Integer Ring
2362
sage: parent(vector(QQ,[1,2])*matrix(ZZ,2,2,[1,2,3,4]))
2363
Vector space of dimension 2 over Rational Field
2364
sage: parent(vector(ZZ,[1,2])*matrix(QQ,2,2,[1,2,3,4]))
2365
Vector space of dimension 2 over Rational Field
2366
sage: parent(vector(QQ,[1,2])*matrix(QQ,2,2,[1,2,3,4]))
2367
Vector space of dimension 2 over Rational Field
2368
2369
sage: parent(vector(QQ,[1,2])*matrix(ZZ[x],2,2,[1,2,3,4]))
2370
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2371
sage: parent(vector(ZZ[x],[1,2])*matrix(QQ,2,2,[1,2,3,4]))
2372
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2373
2374
sage: parent(vector(QQ,[1,2])*matrix(ZZ[x][y],2,2,[1,2,3,4]))
2375
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2376
sage: parent(vector(ZZ[x][y],[1,2])*matrix(QQ,2,2,[1,2,3,4]))
2377
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2378
2379
sage: parent(vector(QQ[x],[1,2])*matrix(ZZ[x][y],2,2,[1,2,3,4]))
2380
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2381
sage: parent(vector(ZZ[x][y],[1,2])*matrix(QQ[x],2,2,[1,2,3,4]))
2382
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2383
2384
sage: parent(vector(QQ[y],[1,2])*matrix(ZZ[x][y],2,2,[1,2,3,4]))
2385
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2386
sage: parent(vector(ZZ[x][y],[1,2])*matrix(QQ[y],2,2,[1,2,3,4]))
2387
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2388
2389
sage: parent(vector(ZZ[x],[1,2])*matrix(ZZ[y],2,2,[1,2,3,4]))
2390
Traceback (most recent call last):
2391
...
2392
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
2393
sage: parent(vector(ZZ[x],[1,2])*matrix(QQ[y],2,2,[1,2,3,4]))
2394
Traceback (most recent call last):
2395
...
2396
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
2397
sage: parent(vector(QQ[x],[1,2])*matrix(ZZ[y],2,2,[1,2,3,4]))
2398
Traceback (most recent call last):
2399
...
2400
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
2401
sage: parent(vector(QQ[x],[1,2])*matrix(QQ[y],2,2,[1,2,3,4]))
2402
Traceback (most recent call last):
2403
...
2404
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
2405
2406
Here we test (vector * scalar) multiplication::
2407
2408
sage: parent(vector(ZZ,[1,2])*ZZ(1))
2409
Ambient free module of rank 2 over the principal ideal domain Integer Ring
2410
sage: parent(vector(QQ,[1,2])*ZZ(1))
2411
Vector space of dimension 2 over Rational Field
2412
sage: parent(vector(ZZ,[1,2])*QQ(1))
2413
Vector space of dimension 2 over Rational Field
2414
sage: parent(vector(QQ,[1,2])*QQ(1))
2415
Vector space of dimension 2 over Rational Field
2416
2417
sage: parent(vector(QQ,[1,2])*ZZ[x](1))
2418
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2419
sage: parent(vector(ZZ[x],[1,2])*QQ(1))
2420
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2421
2422
sage: parent(vector(QQ,[1,2])*ZZ[x][y](1))
2423
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2424
sage: parent(vector(ZZ[x][y],[1,2])*QQ(1))
2425
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2426
2427
sage: parent(vector(QQ[x],[1,2])*ZZ[x][y](1))
2428
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2429
sage: parent(vector(ZZ[x][y],[1,2])*QQ[x](1))
2430
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2431
2432
sage: parent(vector(QQ[y],[1,2])*ZZ[x][y](1))
2433
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2434
sage: parent(vector(ZZ[x][y],[1,2])*QQ[y](1))
2435
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2436
2437
sage: parent(vector(ZZ[x],[1,2])*ZZ[y](1))
2438
Traceback (most recent call last):
2439
...
2440
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Integer Ring'
2441
sage: parent(vector(ZZ[x],[1,2])*QQ[y](1))
2442
Traceback (most recent call last):
2443
...
2444
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Rational Field'
2445
sage: parent(vector(QQ[x],[1,2])*ZZ[y](1))
2446
Traceback (most recent call last):
2447
...
2448
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Integer Ring'
2449
sage: parent(vector(QQ[x],[1,2])*QQ[y](1))
2450
Traceback (most recent call last):
2451
...
2452
TypeError: unsupported operand parent(s) for '*': 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Rational Field'
2453
2454
"""
2455
if have_same_parent(left, right):
2456
return (<Vector>left)._dot_product_(<Vector>right)
2457
# Always do this
2458
global coercion_model
2459
return coercion_model.bin_op(left, right, mul)
2460
2461
cpdef Element _dot_product_(Vector left, Vector right):
2462
raise TypeError, arith_error_message(left, right, mul)
2463
2464
cpdef Vector _pairwise_product_(Vector left, Vector right):
2465
raise TypeError, "unsupported operation for '%s' and '%s'"%(parent_c(left), parent_c(right))
2466
2467
def __div__(self, right):
2468
if PY_IS_NUMERIC(right):
2469
right = py_scalar_to_element(right)
2470
if PY_TYPE_CHECK(right, RingElement):
2471
# Let __mul__ do the job
2472
return self.__mul__(~right)
2473
if PY_TYPE_CHECK(right, Vector):
2474
try:
2475
W = right.parent().submodule([right])
2476
return W.coordinates(self)[0] / W.coordinates(right)[0]
2477
except ArithmeticError:
2478
if right.is_zero():
2479
raise ZeroDivisionError, "division by zero vector"
2480
else:
2481
raise ArithmeticError, "vector is not in free module"
2482
raise TypeError, arith_error_message(self, right, div)
2483
2484
def _magma_init_(self, magma):
2485
"""
2486
Return string that evaluates in Magma to something equivalent
2487
to this vector.
2488
2489
EXAMPLES::
2490
2491
sage: v = vector([1,2,3])
2492
sage: v._magma_init_(magma) # optional - magma
2493
'_sage_[...]![1,2,3]'
2494
sage: mv = magma(v); mv # optional - magma
2495
(1 2 3)
2496
sage: mv.Type() # optional - magma
2497
ModTupRngElt
2498
sage: mv.Parent() # optional - magma
2499
Full RSpace of degree 3 over Integer Ring
2500
2501
sage: v = vector(QQ, [1/2, 3/4, 5/6])
2502
sage: mv = magma(v); mv # optional - magma
2503
(1/2 3/4 5/6)
2504
sage: mv.Type() # optional - magma
2505
ModTupFldElt
2506
sage: mv.Parent() # optional - magma
2507
Full Vector space of degree 3 over Rational Field
2508
2509
A more demanding example::
2510
2511
sage: R.<x,y,z> = QQ[]
2512
sage: v = vector([x^3, y, 2/3*z + x/y])
2513
sage: magma(v) # optional - magma
2514
( x^3 y (2/3*y*z + x)/y)
2515
sage: magma(v).Parent() # optional - magma
2516
Full Vector space of degree 3 over Multivariate rational function field of rank 3 over Rational Field
2517
"""
2518
V = magma(self._parent)
2519
v = [x._magma_init_(magma) for x in self.list()]
2520
return '%s![%s]'%(V.name(), ','.join(v))
2521
2522
def is_Vector(x):
2523
return IS_INSTANCE(x, Vector)
2524
2525
cdef class Matrix(AlgebraElement):
2526
2527
cdef bint is_sparse_c(self):
2528
raise NotImplementedError
2529
2530
cdef bint is_dense_c(self):
2531
raise NotImplementedError
2532
2533
def __imul__(left, right):
2534
if have_same_parent(left, right):
2535
return (<Matrix>left)._matrix_times_matrix_(<Matrix>right)
2536
else:
2537
global coercion_model
2538
return coercion_model.bin_op(left, right, imul)
2539
2540
cpdef RingElement _mul_(left, RingElement right):
2541
"""
2542
TESTS::
2543
2544
sage: m = matrix
2545
sage: a = m([[m([[1,2],[3,4]]),m([[5,6],[7,8]])],[m([[9,10],[11,12]]),m([[13,14],[15,16]])]])
2546
sage: 3*a
2547
[[ 3 6]
2548
[ 9 12] [15 18]
2549
[21 24]]
2550
[[27 30]
2551
[33 36] [39 42]
2552
[45 48]]
2553
2554
sage: m = matrix
2555
sage: a = m([[m([[1,2],[3,4]]),m([[5,6],[7,8]])],[m([[9,10],[11,12]]),m([[13,14],[15,16]])]])
2556
sage: a*3
2557
[[ 3 6]
2558
[ 9 12] [15 18]
2559
[21 24]]
2560
[[27 30]
2561
[33 36] [39 42]
2562
[45 48]]
2563
"""
2564
if have_same_parent(left, right):
2565
return (<Matrix>left)._matrix_times_matrix_(<Matrix>right)
2566
else:
2567
global coercion_model
2568
return coercion_model.bin_op(left, right, mul)
2569
2570
def __mul__(left, right):
2571
"""
2572
Multiplication of matrix by matrix, vector, or scalar
2573
2574
AUTHOR:
2575
2576
- Gonzalo Tornaria (2007-06-25) - write test cases and fix them
2577
2578
.. note::
2579
2580
scalar * matrix is implemented (and tested) in class RingElement
2581
vector * matrix is implemented (and tested) in class Vector
2582
2583
TESTS:
2584
2585
Here we test (matrix * matrix) multiplication::
2586
2587
sage: x, y = var('x, y')
2588
2589
sage: parent(matrix(ZZ,2,2,[1,2,3,4])*matrix(ZZ,2,2,[1,2,3,4]))
2590
Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
2591
sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(ZZ,2,2,[1,2,3,4]))
2592
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2593
sage: parent(matrix(ZZ,2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4]))
2594
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2595
sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4]))
2596
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2597
2598
sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(ZZ[x],2,2,[1,2,3,4]))
2599
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
2600
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4]))
2601
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
2602
2603
sage: parent(matrix(QQ,2,2,[1,2,3,4])*matrix(ZZ[x][y],2,2,[1,2,3,4]))
2604
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2605
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*matrix(QQ,2,2,[1,2,3,4]))
2606
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2607
2608
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*matrix(ZZ[x][y],2,2,[1,2,3,4]))
2609
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2610
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*matrix(QQ[x],2,2,[1,2,3,4]))
2611
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2612
2613
sage: parent(matrix(QQ[y],2,2,[1,2,3,4])*matrix(ZZ[x][y],2,2,[1,2,3,4]))
2614
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2615
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*matrix(QQ[y],2,2,[1,2,3,4]))
2616
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2617
2618
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*matrix(ZZ[y],2,2,[1,2,3,4]))
2619
Traceback (most recent call last):
2620
...
2621
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
2622
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*matrix(QQ[y],2,2,[1,2,3,4]))
2623
Traceback (most recent call last):
2624
...
2625
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
2626
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*matrix(ZZ[y],2,2,[1,2,3,4]))
2627
Traceback (most recent call last):
2628
...
2629
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Integer Ring'
2630
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*matrix(QQ[y],2,2,[1,2,3,4]))
2631
Traceback (most recent call last):
2632
...
2633
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Rational Field'
2634
2635
Here we test (matrix * vector) multiplication::
2636
2637
sage: parent(matrix(ZZ,2,2,[1,2,3,4])*vector(ZZ,[1,2]))
2638
Ambient free module of rank 2 over the principal ideal domain Integer Ring
2639
sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(ZZ,[1,2]))
2640
Vector space of dimension 2 over Rational Field
2641
sage: parent(matrix(ZZ,2,2,[1,2,3,4])*vector(QQ,[1,2]))
2642
Vector space of dimension 2 over Rational Field
2643
sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(QQ,[1,2]))
2644
Vector space of dimension 2 over Rational Field
2645
2646
sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(ZZ[x],[1,2]))
2647
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2648
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*vector(QQ,[1,2]))
2649
Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2650
2651
sage: parent(matrix(QQ,2,2,[1,2,3,4])*vector(ZZ[x][y],[1,2]))
2652
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2653
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*vector(QQ,[1,2]))
2654
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2655
2656
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*vector(ZZ[x][y],[1,2]))
2657
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2658
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*vector(QQ[x],[1,2]))
2659
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2660
2661
sage: parent(matrix(QQ[y],2,2,[1,2,3,4])*vector(ZZ[x][y],[1,2]))
2662
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2663
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*vector(QQ[y],[1,2]))
2664
Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2665
2666
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*vector(ZZ[y],[1,2]))
2667
Traceback (most recent call last):
2668
...
2669
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
2670
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*vector(QQ[y],[1,2]))
2671
Traceback (most recent call last):
2672
...
2673
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
2674
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*vector(ZZ[y],[1,2]))
2675
Traceback (most recent call last):
2676
...
2677
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the integral domain Univariate Polynomial Ring in y over Integer Ring'
2678
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*vector(QQ[y],[1,2]))
2679
Traceback (most recent call last):
2680
...
2681
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 2 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'
2682
2683
Here we test (matrix * scalar) multiplication::
2684
2685
sage: parent(matrix(ZZ,2,2,[1,2,3,4])*ZZ(1))
2686
Full MatrixSpace of 2 by 2 dense matrices over Integer Ring
2687
sage: parent(matrix(QQ,2,2,[1,2,3,4])*ZZ(1))
2688
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2689
sage: parent(matrix(ZZ,2,2,[1,2,3,4])*QQ(1))
2690
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2691
sage: parent(matrix(QQ,2,2,[1,2,3,4])*QQ(1))
2692
Full MatrixSpace of 2 by 2 dense matrices over Rational Field
2693
2694
sage: parent(matrix(QQ,2,2,[1,2,3,4])*ZZ[x](1))
2695
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
2696
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*QQ(1))
2697
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
2698
2699
sage: parent(matrix(QQ,2,2,[1,2,3,4])*ZZ[x][y](1))
2700
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2701
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*QQ(1))
2702
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2703
2704
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*ZZ[x][y](1))
2705
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2706
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*QQ[x](1))
2707
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2708
2709
sage: parent(matrix(QQ[y],2,2,[1,2,3,4])*ZZ[x][y](1))
2710
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2711
sage: parent(matrix(ZZ[x][y],2,2,[1,2,3,4])*QQ[y](1))
2712
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2713
2714
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*ZZ[y](1))
2715
Traceback (most recent call last):
2716
...
2717
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Integer Ring'
2718
sage: parent(matrix(ZZ[x],2,2,[1,2,3,4])*QQ[y](1))
2719
Traceback (most recent call last):
2720
...
2721
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Integer Ring' and 'Univariate Polynomial Ring in y over Rational Field'
2722
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*ZZ[y](1))
2723
Traceback (most recent call last):
2724
...
2725
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Integer Ring'
2726
sage: parent(matrix(QQ[x],2,2,[1,2,3,4])*QQ[y](1))
2727
Traceback (most recent call last):
2728
...
2729
TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Rational Field'
2730
2731
"""
2732
if have_same_parent(left, right):
2733
return (<Matrix>left)._matrix_times_matrix_(<Matrix>right)
2734
else:
2735
global coercion_model
2736
return coercion_model.bin_op(left, right, mul)
2737
2738
cdef Vector _vector_times_matrix_(matrix_right, Vector vector_left):
2739
raise TypeError
2740
2741
cdef Vector _matrix_times_vector_(matrix_left, Vector vector_right):
2742
raise TypeError
2743
2744
cdef Matrix _matrix_times_matrix_(left, Matrix right):
2745
raise TypeError
2746
2747
2748
2749
def is_Matrix(x):
2750
return IS_INSTANCE(x, Matrix)
2751
2752
def is_IntegralDomainElement(x):
2753
"""
2754
Return True if x is of type IntegralDomainElement.
2755
"""
2756
return IS_INSTANCE(x, IntegralDomainElement)
2757
2758
cdef class IntegralDomainElement(CommutativeRingElement):
2759
def is_nilpotent(self):
2760
return self.is_zero()
2761
2762
2763
def is_DedekindDomainElement(x):
2764
"""
2765
Return True if x is of type DedekindDomainElement.
2766
"""
2767
return IS_INSTANCE(x, DedekindDomainElement)
2768
2769
cdef class DedekindDomainElement(IntegralDomainElement):
2770
pass
2771
2772
def is_PrincipalIdealDomainElement(x):
2773
"""
2774
Return True if x is of type PrincipalIdealDomainElement.
2775
"""
2776
return IS_INSTANCE(x, PrincipalIdealDomainElement)
2777
2778
cdef class PrincipalIdealDomainElement(DedekindDomainElement):
2779
def lcm(self, right):
2780
"""
2781
Returns the least common multiple of self and right.
2782
"""
2783
if not PY_TYPE_CHECK(right, Element) or not ((<Element>right)._parent is self._parent):
2784
return coercion_model.bin_op(self, right, lcm)
2785
return self._lcm(right)
2786
2787
def gcd(self, right):
2788
"""
2789
Returns the gcd of self and right, or 0 if both are 0.
2790
"""
2791
if not PY_TYPE_CHECK(right, Element) or not ((<Element>right)._parent is self._parent):
2792
return coercion_model.bin_op(self, right, gcd)
2793
return self._gcd(right)
2794
2795
def xgcd(self, right):
2796
r"""
2797
Return the extended gcd of self and other, i.e., elements `r, s, t` such that
2798
.. math::
2799
2800
r = s \cdot self + t \cdot other.
2801
2802
.. note::
2803
2804
There is no guarantee on minimality of the cofactors. In
2805
the integer case, see documentation for Integer._xgcd() to
2806
obtain minimal cofactors.
2807
"""
2808
if not PY_TYPE_CHECK(right, Element) or not ((<Element>right)._parent is self._parent):
2809
return coercion_model.bin_op(self, right, xgcd)
2810
return self._xgcd(right)
2811
2812
2813
# This is pretty nasty low level stuff. The idea is to speed up construction
2814
# of EuclideanDomainElements (in particular Integers) by skipping some tp_new
2815
# calls up the inheritance tree.
2816
PY_SET_TP_NEW(EuclideanDomainElement, Element)
2817
2818
def is_EuclideanDomainElement(x):
2819
"""
2820
Return True if x is of type EuclideanDomainElement.
2821
"""
2822
return IS_INSTANCE(x, EuclideanDomainElement)
2823
2824
cdef class EuclideanDomainElement(PrincipalIdealDomainElement):
2825
2826
def degree(self):
2827
raise NotImplementedError
2828
2829
def _gcd(self, other):
2830
"""
2831
Return the greatest common divisor of self and other.
2832
2833
Algorithm 3.2.1 in Cohen, GTM 138.
2834
"""
2835
A = self
2836
B = other
2837
while not B.is_zero():
2838
Q, R = A.quo_rem(B)
2839
A = B
2840
B = R
2841
return A
2842
2843
def leading_coefficient(self):
2844
raise NotImplementedError
2845
2846
def quo_rem(self, other):
2847
raise NotImplementedError
2848
2849
def __divmod__(self, other):
2850
"""
2851
Return the quotient and remainder of self divided by other.
2852
2853
EXAMPLES::
2854
2855
sage: divmod(5,3)
2856
(1, 2)
2857
sage: divmod(25r,12)
2858
(2, 1)
2859
sage: divmod(25,12r)
2860
(2, 1)
2861
2862
"""
2863
if PY_TYPE_CHECK(self, Element):
2864
return self.quo_rem(other)
2865
else:
2866
x, y = canonical_coercion(self, other)
2867
return x.quo_rem(y)
2868
2869
def __floordiv__(self,right):
2870
"""
2871
Quotient of division of self by other. This is denoted //.
2872
"""
2873
Q, _ = self.quo_rem(right)
2874
return Q
2875
2876
def __mod__(self, other):
2877
"""
2878
Remainder of division of self by other.
2879
2880
EXAMPLES::
2881
2882
sage: R.<x> = ZZ[]
2883
sage: x % (x+1)
2884
-1
2885
sage: (x**3 + x - 1) % (x**2 - 1)
2886
2*x - 1
2887
"""
2888
_, R = self.quo_rem(other)
2889
return R
2890
2891
def is_FieldElement(x):
2892
"""
2893
Return True if x is of type FieldElement.
2894
"""
2895
return IS_INSTANCE(x, FieldElement)
2896
2897
cdef class FieldElement(CommutativeRingElement):
2898
2899
def __floordiv__(self, other):
2900
return self / other
2901
2902
def is_unit(self):
2903
"""
2904
Return True if self is a unit in its parent ring.
2905
2906
EXAMPLES::
2907
2908
sage: a = 2/3; a.is_unit()
2909
True
2910
2911
On the other hand, 2 is not a unit, since its parent is ZZ.
2912
2913
::
2914
2915
sage: a = 2; a.is_unit()
2916
False
2917
sage: parent(a)
2918
Integer Ring
2919
2920
However, a is a unit when viewed as an element of QQ::
2921
2922
sage: a = QQ(2); a.is_unit()
2923
True
2924
"""
2925
return not not self
2926
2927
def _gcd(self, FieldElement other):
2928
"""
2929
Return the greatest common divisor of self and other.
2930
"""
2931
if self.is_zero() and other.is_zero():
2932
return self
2933
else:
2934
return self._parent(1)
2935
2936
def _lcm(self, FieldElement other):
2937
"""
2938
Return the least common multiple of self and other.
2939
"""
2940
if self.is_zero() and other.is_zero():
2941
return self
2942
else:
2943
return self._parent(1)
2944
2945
def _xgcd(self, FieldElement other):
2946
R = self._parent
2947
if not self.is_zero():
2948
return R(1), ~self, R(0)
2949
elif not other.is_zero():
2950
return R(1), R(0), ~self
2951
else: # both are 0
2952
return self, self, self
2953
2954
2955
def quo_rem(self, right):
2956
r"""
2957
Return the quotient and remainder obtained by dividing `self` by
2958
`other`. Since this element lives in a field, the remainder is always
2959
zero and the quotient is `self/right`.
2960
2961
TESTS:
2962
2963
Test if #8671 is fixed::
2964
2965
sage: R.<x,y> = QQ[]
2966
sage: S.<a,b> = R.quo(y^2 + 1)
2967
sage: S.is_field = lambda : False
2968
sage: F = Frac(S); u = F.one_element()
2969
sage: u.quo_rem(u)
2970
(1, 0)
2971
"""
2972
if not isinstance(right, FieldElement) or not (parent(right) is self._parent):
2973
right = self.parent()(right)
2974
return self/right, 0
2975
2976
def divides(self, FieldElement other):
2977
r"""
2978
Check whether self divides other, for field elements.
2979
2980
Since this is a field, all values divide all other values,
2981
except that zero does not divide any non-zero values.
2982
2983
EXAMPLES::
2984
2985
sage: K.<rt3> = QQ[sqrt(3)]
2986
sage: K(0).divides(rt3)
2987
False
2988
sage: rt3.divides(K(17))
2989
True
2990
sage: K(0).divides(K(0))
2991
True
2992
sage: rt3.divides(K(0))
2993
True
2994
"""
2995
if not (other._parent is self._parent):
2996
other = self.parent()(other)
2997
return bool(self) or other.is_zero()
2998
2999
def is_AlgebraElement(x):
3000
"""
3001
Return True if x is of type AlgebraElement.
3002
"""
3003
return IS_INSTANCE(x, AlgebraElement)
3004
3005
cdef class AlgebraElement(RingElement):
3006
pass
3007
3008
def is_CommutativeAlgebraElement(x):
3009
"""
3010
Return True if x is of type CommutativeAlgebraElement.
3011
"""
3012
return IS_INSTANCE(x, CommutativeAlgebraElement)
3013
3014
cdef class CommutativeAlgebraElement(CommutativeRingElement):
3015
pass
3016
3017
def is_InfinityElement(x):
3018
"""
3019
Return True if x is of type InfinityElement.
3020
"""
3021
return IS_INSTANCE(x, InfinityElement)
3022
3023
cdef class InfinityElement(RingElement):
3024
def __invert__(self):
3025
from sage.rings.all import ZZ
3026
return ZZ(0)
3027
3028
cdef class PlusInfinityElement(InfinityElement):
3029
pass
3030
3031
cdef class MinusInfinityElement(InfinityElement):
3032
pass
3033
3034
include "coerce.pxi"
3035
3036
3037
#################################################################################
3038
#
3039
# Coercion of elements
3040
#
3041
#################################################################################
3042
3043
cpdef canonical_coercion(x, y):
3044
"""
3045
canonical_coercion(x,y) is what is called before doing an
3046
arithmetic operation between x and y. It returns a pair (z,w)
3047
such that z is got from x and w from y via canonical coercion and
3048
the parents of z and w are identical.
3049
3050
EXAMPLES::
3051
3052
sage: A = Matrix([[0,1],[1,0]])
3053
sage: canonical_coercion(A,1)
3054
(
3055
[0 1] [1 0]
3056
[1 0], [0 1]
3057
)
3058
"""
3059
global coercion_model
3060
return coercion_model.canonical_coercion(x,y)
3061
3062
cpdef bin_op(x, y, op):
3063
global coercion_model
3064
return coercion_model.bin_op(x,y,op)
3065
3066
3067
def coerce(Parent p, x):
3068
try:
3069
return p._coerce_c(x)
3070
except AttributeError:
3071
return p(x)
3072
3073
def coerce_cmp(x,y):
3074
global coercion_model
3075
cdef int c
3076
try:
3077
x, y = coercion_model.canonical_coercion(x, y)
3078
return cmp(x,y)
3079
except TypeError:
3080
c = cmp(type(x), type(y))
3081
if c == 0: c = -1
3082
return c
3083
3084
# We define this base class here to avoid circular cimports.
3085
cdef class CoercionModel:
3086
"""
3087
Most basic coercion scheme. If it doesn't already match, throw an error.
3088
"""
3089
cpdef canonical_coercion(self, x, y):
3090
if parent_c(x) is parent_c(y):
3091
return x,y
3092
raise TypeError, "no common canonical parent for objects with parents: '%s' and '%s'"%(parent_c(x), parent_c(y))
3093
3094
cpdef bin_op(self, x, y, op):
3095
if parent_c(x) is parent_c(y):
3096
return op(x,y)
3097
raise TypeError, arith_error_message(x,y,op)
3098
3099
import coerce
3100
cdef CoercionModel coercion_model = coerce.CoercionModel_cache_maps()
3101
3102
def get_coercion_model():
3103
"""
3104
Return the global coercion model.
3105
3106
EXAMPLES::
3107
3108
sage: import sage.structure.element as e
3109
sage: cm = e.get_coercion_model()
3110
sage: cm
3111
<sage.structure.coerce.CoercionModel_cache_maps object at ...>
3112
"""
3113
return coercion_model
3114
3115
def set_coercion_model(cm):
3116
global coercion_model
3117
coercion_model = cm
3118
3119
def coercion_traceback(dump=True):
3120
r"""
3121
This function is very helpful in debugging coercion errors. It prints
3122
the tracebacks of all the errors caught in the coercion detection. Note
3123
that failure is cached, so some errors may be omitted the second time
3124
around (as it remembers not to retry failed paths for speed reasons.
3125
3126
For performance and caching reasons, exception recording must be
3127
explicitly enabled before using this function.
3128
3129
EXAMPLES::
3130
3131
sage: cm = sage.structure.element.get_coercion_model()
3132
sage: cm.record_exceptions()
3133
sage: 1 + 1/5
3134
6/5
3135
sage: coercion_traceback() # Should be empty, as all went well.
3136
sage: 1/5 + GF(5).gen()
3137
Traceback (most recent call last):
3138
...
3139
TypeError: unsupported operand parent(s) for '+': 'Rational Field' and 'Finite Field of size 5'
3140
sage: coercion_traceback()
3141
Traceback (most recent call last):
3142
...
3143
TypeError: no common canonical parent for objects with parents: 'Rational Field' and 'Finite Field of size 5'
3144
"""
3145
if dump:
3146
for traceback in coercion_model.exception_stack():
3147
print traceback
3148
else:
3149
return coercion_model.exception_stack()
3150
3151
3152
cdef class NamedBinopMethod:
3153
"""
3154
A decorator to be used on binary operation methods that should operate
3155
on elements of the same parent. If the parents of the arguments differ,
3156
coercion is performed, then the method is re-looked up by name on the
3157
first argument.
3158
3159
In short, using the ``NamedBinopMethod`` (alias ``coerce_binop``) decorator
3160
on a method gives it the exact same semantics of the basic arithmetic
3161
operations like ``_add_``, ``_sub_``, etc. in that both operands are
3162
guaranteed to have exactly the same parent.
3163
"""
3164
cdef _self
3165
cdef _func
3166
cdef _name
3167
3168
def __init__(self, func, name=None, obj=None):
3169
"""
3170
TESTS::
3171
3172
sage: from sage.structure.element import NamedBinopMethod
3173
sage: NamedBinopMethod(gcd)(12, 15)
3174
3
3175
"""
3176
self._func = func
3177
if name is None:
3178
if isinstance(func, types.FunctionType):
3179
name = func.func_name
3180
if isinstance(func, types.UnboundMethodType):
3181
name = func.im_func.func_name
3182
else:
3183
name = func.__name__
3184
self._name = name
3185
self._self = obj
3186
3187
def __call__(self, x, y=None, **kwds):
3188
"""
3189
TESTS::
3190
3191
sage: from sage.structure.element import NamedBinopMethod
3192
sage: test_func = NamedBinopMethod(lambda x, y, **kwds: (x, y, kwds), '_add_')
3193
3194
Calls func directly if the two arguments have the same parent::
3195
3196
sage: test_func(1, 2)
3197
(1, 2, {})
3198
3199
Passes through coercion and does a method lookup if the
3200
left operand is not the same::
3201
3202
sage: test_func(0.5, 1)
3203
(0.500000000000000, 1.00000000000000, {})
3204
sage: test_func(1, 2, algorithm='fast')
3205
(1, 2, {'algorithm': 'fast'})
3206
sage: test_func(1, 1/2)
3207
3/2
3208
"""
3209
if y is None:
3210
if self._self is None:
3211
self._func(x, **kwds)
3212
else:
3213
x, y = self._self, x
3214
if not have_same_parent(x, y):
3215
old_x = x
3216
x,y = coercion_model.canonical_coercion(x, y)
3217
if old_x is x:
3218
return self._func(x,y, *kwds)
3219
else:
3220
return getattr(x, self._name)(y, **kwds)
3221
else:
3222
return self._func(x,y, **kwds)
3223
3224
def __get__(self, obj, objtype):
3225
"""
3226
Used to transform from an unbound to a bound method.
3227
3228
TESTS::
3229
sage: from sage.structure.element import NamedBinopMethod
3230
sage: R.<x> = ZZ[]
3231
sage: isinstance(x.quo_rem, NamedBinopMethod)
3232
True
3233
sage: x.quo_rem(x)
3234
(1, 0)
3235
sage: type(x).quo_rem(x,x)
3236
(1, 0)
3237
"""
3238
return NamedBinopMethod(self._func, self._name, obj)
3239
3240
def _sage_doc_(self):
3241
"""
3242
Return the docstring of the wrapped object for introspection.
3243
3244
EXAMPLES::
3245
3246
sage: from sage.structure.element import NamedBinopMethod
3247
sage: g = NamedBinopMethod(gcd)
3248
sage: from sage.misc.sageinspect import sage_getdoc
3249
sage: sage_getdoc(g) == sage_getdoc(gcd)
3250
True
3251
"""
3252
return sageinspect._sage_getdoc_unformatted(self._func)
3253
3254
def _sage_src_(self):
3255
"""
3256
Returns the source of the wrapped object for introspection.
3257
3258
EXAMPLES::
3259
3260
sage: from sage.structure.element import NamedBinopMethod
3261
sage: g = NamedBinopMethod(gcd)
3262
sage: 'def gcd(' in g._sage_src_()
3263
True
3264
"""
3265
return sageinspect.sage_getsource(self._func)
3266
3267
def _sage_argspec_(self):
3268
"""
3269
Returns the argspec of the wrapped object for introspection.
3270
3271
EXAMPLES::
3272
3273
sage: from sage.structure.element import NamedBinopMethod
3274
sage: g = NamedBinopMethod(gcd)
3275
sage: g._sage_argspec_()
3276
ArgSpec(args=['a', 'b'], varargs=None, keywords='kwargs', defaults=(None,))
3277
"""
3278
return sageinspect.sage_getargspec(self._func)
3279
3280
coerce_binop = NamedBinopMethod
3281
3282
###############################################################################
3283
3284
def lcm(x,y):
3285
from sage.rings.arith import lcm
3286
return lcm(x,y)
3287
3288
def gcd(x,y):
3289
from sage.rings.arith import gcd
3290
return gcd(x,y)
3291
3292
def xgcd(x,y):
3293
from sage.rings.arith import xgcd
3294
return xgcd(x,y)
3295
3296
3297
3298
3299
######################
3300
3301
def generic_power(a, n, one=None):
3302
"""
3303
Computes `a^n`, where `n` is an integer, and `a` is an object which
3304
supports multiplication. Optionally an additional argument,
3305
which is used in the case that n == 0:
3306
3307
- ``one`` - the "unit" element, returned directly (can be anything)
3308
3309
If this is not supplied, int(1) is returned.
3310
3311
EXAMPLES::
3312
3313
sage: from sage.structure.element import generic_power
3314
sage: generic_power(int(12),int(0))
3315
1
3316
sage: generic_power(int(0),int(100))
3317
0
3318
sage: generic_power(Integer(10),Integer(0))
3319
1
3320
sage: generic_power(Integer(0),Integer(23))
3321
0
3322
sage: sum([generic_power(2,i) for i in range(17)]) #test all 4-bit combinations
3323
131071
3324
sage: F = Zmod(5)
3325
sage: a = generic_power(F(2), 5); a
3326
2
3327
sage: a.parent() is F
3328
True
3329
sage: a = generic_power(F(1), 2)
3330
sage: a.parent() is F
3331
True
3332
3333
sage: generic_power(int(5), 0)
3334
1
3335
"""
3336
3337
return generic_power_c(a,n,one)
3338
3339
cdef generic_power_c(a, nn, one):
3340
try:
3341
n = PyNumber_Index(nn)
3342
except TypeError:
3343
try:
3344
# Try harder, since many things coerce to Integer.
3345
from sage.rings.integer import Integer
3346
n = int(Integer(nn))
3347
except TypeError:
3348
raise NotImplementedError, "non-integral exponents not supported"
3349
3350
if not n:
3351
if one is None:
3352
if PY_TYPE_CHECK(a, Element):
3353
return (<Element>a)._parent.one()
3354
try:
3355
try:
3356
return a.parent().one()
3357
except AttributeError:
3358
return type(a)(1)
3359
except:
3360
return 1 #oops, the one sucks
3361
else:
3362
return one
3363
elif n < 0:
3364
# I don't think raising division by zero is really my job. It should
3365
# be the one of ~a. Moreover, this does not handle the case of monoids
3366
# with partially defined division (e.g. the multiplicative monoid of a
3367
# ring such as ZZ/12ZZ)
3368
# if not a:
3369
# raise ZeroDivisionError
3370
a = ~a
3371
n = -n
3372
3373
if n < 4:
3374
# These cases will probably be called often
3375
# and don't benefit from the code below
3376
if n == 1:
3377
return a
3378
elif n == 2:
3379
return a*a
3380
elif n == 3:
3381
return a*a*a
3382
3383
# check for idempotence, and store the result otherwise
3384
aa = a*a
3385
if aa == a:
3386
return a
3387
3388
# since we've computed a^2, let's start squaring there
3389
# so, let's keep the least-significant bit around, just
3390
# in case.
3391
m = n & 1
3392
n = n >> 1
3393
3394
# One multiplication can be saved by starting with
3395
# the second-smallest power needed rather than with 1
3396
# we've already squared a, so let's start there.
3397
apow = aa
3398
while n&1 == 0:
3399
apow = apow*apow
3400
n = n >> 1
3401
power = apow
3402
n = n >> 1
3403
3404
# now multiply that least-significant bit in...
3405
if m:
3406
power = power * a
3407
3408
# and this is straight from the book.
3409
while n != 0:
3410
apow = apow*apow
3411
if n&1 != 0:
3412
power = power*apow
3413
n = n >> 1
3414
3415
return power
3416
3417