source: sage/structure/element.pyx @ 4059:031e9f77862f

Revision 4059:031e9f77862f, 68.3 KB checked in by William Stein <wstein@…>, 6 years ago (diff)

snapshot -- Integrating the calculus package into the rest of SAGE; fixing doctests.

Line 
1r"""
2Elements
3
4AUTHORS:
5   -- David Harvey (2006-10-16): changed CommutativeAlgebraElement to derive
6   from CommutativeRingElement instead of AlgebraElement
7   -- David Harvey (2006-10-29): implementation and documentation of new
8   arithmetic architecture
9   -- William Stein (2006-11): arithmetic architecture -- pushing it through to completion.
10
11
12\subsection{The Abstract Element Class Heierarchy}
13This is the abstract class heierchary, i.e., these are all
14abstract base classes.
15\begin{verbatim}
16SageObject
17    Element
18        ModuleElement
19            AdditiveGroupElement
20
21        MonoidElement
22            MultiplicativeGroupElement
23
24        RingElement
25            CommutativeRingElement
26                IntegralDomainElement
27                    DedekindDomainElement
28                        PrincipalIdealDomainElement
29                            EuclideanDomainElement
30            FieldElement
31                FiniteFieldElement
32            AlgebraElement   (note -- can't derive from module, since no multiple inheritence)
33                CommutativeAlgebraElement
34            InfinityElement
35                PlusInfinityElement
36                MinusInfinityElement
37\end{verbatim}
38
39\subsection{How to Define a New Element Class}
40Elements typically define a method \code{_new_c}, e.g.,
41\begin{verbatim}
42    cdef _new_c(self, defining data):
43        cdef FreeModuleElement_generic_dense x
44        x = PY_NEW(FreeModuleElement_generic_dense)
45        x._parent = self._parent
46        x._entries = v
47\end{verbatim}
48that creates a new sibling very quickly from defining data
49with assumed properties. 
50
51SAGE has a special system in place for handling arithmetic operations
52for all Element subclasses. There are various rules that must be
53followed by both arithmetic implementors and callers.
54
55A quick summary for the impatient:
56\begin{itemize}
57 \item DO NOT OVERRIDE _add_c. EVER. THANKS.
58 \item DO NOT CALL _add_c_impl DIRECTLY.
59 \item To implement addition for a python class, override def _add_().
60 \item To implement addition for a pyrex class, override cdef _add_c_impl().
61 \item If you want to add x and y, whose parents you know are IDENTICAL,
62   you may call _add_(x, y) (from python or pyrex) or _add_c(x, y) (from
63   pyrex -- this will be faster). This will be the fastest way to guarantee
64   that the correct implementation gets called. Of course you can still
65   always use "x + y".
66\end{itemize}
67
68Now in more detail. The aims of this system are to provide (1) an efficient
69calling protocol from both python and pyrex, (2) uniform coercion semantics
70across SAGE, (3) ease of use, (4) readability of code.
71
72We will take addition of RingElements as an example; all other operators
73and classes are similar. There are four relevant functions.
74
75{\bf def RingElement.__add__}
76
77   This function is called by python or pyrex when the binary "+" operator
78   is encountered. It ASSUMES that at least one of its arguments is a
79   RingElement; only a really twisted programmer would violate this
80   condition. It has a fast pathway to deal with the most common case
81   where the arguments have the same parent. Otherwise, it uses the coercion
82   module to work out how to make them have the same parent. After any
83   necessary coercions have been performed, it calls _add_c to dispatch to
84   the correct underlying addition implementation.
85
86   Note that although this function is declared as def, it doesn't have the
87   usual overheads associated with python functions (either for the caller
88   or for __add__ itself). This is because python has optimised calling
89   protocols for such special functions.
90
91{\bf cdef RingElement._add_c}
92
93   DO ***NOT*** OVERRIDE THIS FUNCTION.
94
95   The two arguments to this function MUST have the SAME PARENT.
96   Its return value MUST have the SAME PARENT as its arguments.
97
98   If you want to add two objects from pyrex, and you know that their
99   parents are the same object, you are encouraged to call this function
100   directly, instead of using "x + y".
101
102   This function dispatches to either _add_ or _add_c_impl as appropriate.
103   It takes necessary steps to decide whether a pyrex implementation of
104   _add_c_impl has been overridden by some python implementation of _add_.
105   The code is optimised in favour of reaching _add_c_impl as soon as
106   possible.
107
108{\bf def RingElement._add_}
109
110   This is the function you should override to implement addition in a
111   python subclass of RingElement.
112
113   WARNING: if you override this in a *pyrex* class, it won't get called.
114   You should override _add_c_impl instead. It is especially important to
115   keep this in mind whenever you move a class down from python to pyrex.
116
117   The two arguments to this function are guaranteed to have the
118   SAME PARENT. Its return value MUST have the SAME PARENT as its
119   arguments.
120
121   If you want to add two objects from python, and you know that their
122   parents are the same object, you are encouraged to call this function
123   directly, instead of using "x + y".
124
125   The default implementation of this function is to call _add_c_impl,
126   so if no-one has defined a python implementation, the correct pyrex
127   implementation will get called.
128
129{\bf cdef RingElement._add_c_impl}
130
131   This is the function you should override to implement addition in a
132   pyrex subclass of RingElement.
133
134   The two arguments to this function are guaranteed to have the
135   SAME PARENT. Its return value MUST have the SAME PARENT as its
136   arguments.
137
138   DO ***NOT*** CALL THIS FUNCTION DIRECTLY.
139
140   (Exception: you know EXACTLY what you are doing, and you know exactly
141   which implementation you are trying to call; i.e. you're not trying to
142   write generic code. In particular, if you call this directly, your code
143   will not work correctly if you run it on a python class derived from
144   a pyrex class where someone has redefined _add_ in python.)
145
146   The default implementation of this function is to raise a
147   NotImplementedError, which will happen if no-one has supplied
148   implementations of either _add_ or _add_c_impl.
149
150"""
151
152
153##################################################################
154# Generic element, so all this functionality must be defined
155# by any element.  Derived class must call __init__
156##################################################################
157
158include "../ext/cdefs.pxi"
159include "../ext/stdsage.pxi"
160include "../ext/python.pxi"
161
162import operator
163
164from sage.structure.parent      cimport Parent
165from sage.structure.parent_base cimport ParentWithBase
166
167# This classes uses element.pxd.  To add data members, you
168# must change that file.
169
170def make_element(_class, _dict, parent):
171    """
172    Used for unpickling Element objects (and subclasses).
173
174    This should work for any Python class deriving from Element, as long
175    as it doesn't implement some screwy __new__() method.
176
177    See also Element.__reduce__().
178    """
179    new_object = _class.__new__(_class)
180    new_object._set_parent(parent)
181    new_object.__dict__ = _dict
182    return new_object
183
184
185   
186def is_Element(x):
187    """
188    Return True if x is of type Element.
189   
190    EXAMPLES:
191        sage: is_Element(2/3)
192        True
193        sage: is_Element(QQ^3)
194        False
195    """
196    return IS_INSTANCE(x, Element)
197
198cdef class Element(sage_object.SageObject):
199    """
200    Generic element of a structure. All other types of elements
201    (RingElement, ModuleElement, etc) derive from this type.
202
203    Subtypes must either call __init__() to set _parent, or may
204    set _parent themselves if that would be more efficient.
205    """
206   
207    def __init__(self, parent):
208        r"""
209        INPUT:
210            parent -- a SageObject
211        """
212        #if parent is None:
213        #    raise RuntimeError, "bug -- can't set parent to None"
214        self._parent = parent
215   
216    def _set_parent(self, parent):
217        r"""
218        INPUT:
219            parent -- a SageObject
220        """
221        self._parent = parent
222
223    cdef _set_parent_c(self, ParentWithBase parent):
224        self._parent = parent
225   
226    def _repr_(self):
227        return "Generic element of a structure"
228
229    def __reduce__(self):
230        return (make_element, (self.__class__, self.__dict__, self._parent))
231
232    def __hash__(self):
233        return hash(str(self))
234
235    def _im_gens_(self, codomain, im_gens):
236        """
237        Return the image of self in codomain under the map that sends
238        the images of the generators of the parent of self to the
239        tuple of elements of im_gens.
240        """
241        raise NotImplementedError
242           
243    cdef base_extend_c(self, ParentWithBase R):
244        if HAS_DICTIONARY(self):
245            return self.base_extend(R)
246        else:
247            return self.base_extend_c_impl(R)
248       
249    cdef base_extend_c_impl(self, ParentWithBase R):
250        cdef ParentWithBase V
251        V = self._parent.base_extend(R)
252        return (<Parent>V)._coerce_c(self)
253
254    def base_extend(self, R):
255        return self.base_extend_c_impl(R)
256
257    def base_ring(self):
258        """
259        Returns the base ring of this element's parent (if that makes sense).
260        """
261        return self._parent.base_ring()
262
263    def category(self):
264        from sage.categories.category import Elements
265        return Elements(self._parent)
266
267    def parent(self, x=None):
268        """
269        Returns parent of this element; or, if the optional argument x is
270        supplied, the result of coercing x into the parent of this element.
271        """
272        if x is None:
273            return self._parent
274        else:
275            return self._parent(x)
276
277    def __xor__(self, right):
278        raise RuntimeError, "Use ** for exponentiation, not '^', which means xor\n"+\
279              "in Python, and has the wrong precedence."
280
281    def _coeff_repr(self, no_space=True):
282        if self._is_atomic():
283            s = repr(self)
284        else:
285            s = "(%s)"%repr(self)
286        if no_space:
287            return s.replace(' ','')
288        return s
289
290    def _latex_coeff_repr(self):
291        try:
292            s = self._latex_()
293        except AttributeError:
294            s = str(self)
295        if self._is_atomic():
296            return s
297        else:
298            return "\\left(%s\\right)"%s
299   
300    def _is_atomic(self):
301        """
302        Return True if and only if parenthesis are not required when
303        *printing* out any of $x - s$, $x + s$, $x^s$ and $x/s$.
304
305        EXAMPLES:
306            sage: n = 5; n._is_atomic()
307            True
308            sage: n = x+1; n._is_atomic()
309            False
310        """
311        if self._parent.is_atomic_repr():
312            return True
313        s = str(self)
314        return PyBool_FromLong(s.find("+") == -1 and s.find("-") == -1 and s.find(" ") == -1)
315
316    def __nonzero__(self):
317        """
318        Return True if self does not equal self.parent()(0).
319        """
320        return PyBool_FromLong(self != self._parent(0))
321
322    def is_zero(self):
323        """
324        Return True if self equals self.parent()(0). The default
325        implementation is to fall back to 'not self.__nonzero__'.
326
327        NOTE: Do not re-implement this method in your subclass but
328        implement __nonzero__ instead.
329        """
330        return PyBool_FromLong(not self)
331
332    def _cmp_(left, right):
333        return left._cmp(right)
334
335    cdef _cmp(left, right):
336        """
337        Compare left and right.
338        """
339        cdef int r
340        if not have_same_parent(left, right):
341            try:
342                _left, _right = canonical_coercion_c(left, right)
343                if PY_IS_NUMERIC(_left):
344                    return cmp(_left, _right)
345                else:
346                    return _left._cmp_(_right)
347            except TypeError:
348                r = cmp(type(left), type(right))
349                if r == 0:
350                    r = -1
351                return r
352        else:
353            return left._cmp_c_impl(right)
354
355    def _richcmp_(left, right, op):
356        return left._richcmp(right, op)
357
358    cdef _richcmp(left, right, int op):
359        """
360        Compare left and right, according to the comparison operator op.
361        """
362        cdef int r
363        if not have_same_parent(left, right):
364            try:
365                _left, _right = canonical_coercion_c(left, right)
366                if PY_IS_NUMERIC(_left):
367                    r = cmp(_left, _right)
368                else:
369                    return _left._richcmp_(_right, op)
370            except (TypeError, NotImplementedError):
371                r = cmp(type(left), type(right))
372                if r == 0:
373                    r = -1
374        else:
375            if HAS_DICTIONARY(left):   # fast check
376                r = left.__cmp__(right)
377            else:
378                return left._richcmp_c_impl(right, op)
379
380        return left._rich_to_bool(op, r)
381
382    cdef _rich_to_bool(self, int op, int r):
383        if op == 0:  #<
384            return PyBool_FromLong(r  < 0)
385        elif op == 2: #==
386            return PyBool_FromLong(r == 0)
387        elif op == 4: #>
388            return PyBool_FromLong(r  > 0)
389        elif op == 1: #<=
390            return PyBool_FromLong(r <= 0)
391        elif op == 3: #!=
392            return PyBool_FromLong(r != 0)
393        elif op == 5: #>=
394            return PyBool_FromLong(r >= 0)
395
396    ####################################################################
397    # For a derived Pyrex class, you **must** put the following in
398    # your subclasses, in order for it to take advantage of the
399    # above generic comparison code.  You must also define
400    # either _cmp_c_impl (if your subclass is totally ordered),
401    # _richcmp_c_impl (if your subclass is partially ordered), or both
402    # (if your class has both a total order and a partial order;
403    # then the total order will be available with cmp(), and the partial
404    # order will be available with the relation operators; in this case
405    # you must also define __cmp__ in your subclass).
406    # This is simply how Python works.
407    #
408    # For a *Python* class just define __cmp__ as always.
409    # But note that when this gets called you can assume that
410    # both inputs have identical parents.
411    ####################################################################
412    def __richcmp__(left, right, int op):
413        return (<Element>left)._richcmp(right, op)
414   
415    ####################################################################
416    # If your subclass has both a partial order (available with the
417    # relation operators) and a total order (available with cmp()),
418    # you **must** put the following in your subclass.
419    #
420    # Note that in this case the total order defined by cmp() will
421    # not properly respect coercions.
422    ####################################################################
423    def __cmp__(left, right):
424        return (<Element>left)._cmp(right)
425
426    cdef _richcmp_c_impl(left, Element right, int op):
427        return left._rich_to_bool(op, left._cmp_c_impl(right))
428
429    cdef int _cmp_c_impl(left, Element right) except -2:
430        ### For derived SAGEX code, you *MUST* ALSO COPY the __richcmp__ above
431        ### into your class!!!  For Python code just use __cmp__.
432        raise NotImplementedError, "BUG: sort algorithm for elements of '%s' not implemented"%right.parent()
433
434def is_ModuleElement(x):
435    """
436    Return True if x is of type ModuleElement.
437   
438    This is even faster than using isinstance inline.
439
440    EXAMPLES:
441        sage: is_ModuleElement(2/3)
442        True
443        sage: is_ModuleElement((QQ^3).0)
444        True
445        sage: is_ModuleElement('a')
446        False
447    """
448    return IS_INSTANCE(x, ModuleElement)
449
450
451cdef class ModuleElement(Element):
452    """
453    Generic element of a module.
454    """
455   
456    ##################################################
457    # Addition
458    ##################################################   
459    def __add__(left, right):
460        """
461        Top-level addition operator for ModuleElements.
462
463        See extensive documentation at the top of element.pyx.
464        """
465
466        # Try fast pathway if they are both ModuleElements and the parents
467        # match.
468
469        # (We know at least one of the arguments is a ModuleElement. So if
470        # their types are *equal* (fast to check) then they are both
471        # ModuleElements. Otherwise use the slower test via PY_TYPE_CHECK.)
472        if have_same_parent(left, right):
473            return (<ModuleElement>left)._add_c(<ModuleElement>right)
474        return bin_op_c(left, right, operator.add)
475
476    cdef ModuleElement _add_c(left, ModuleElement right):
477        """
478        Addition dispatcher for ModuleElements.
479
480        DO NOT OVERRIDE THIS FUNCTION.
481
482        See extensive documentation at the top of element.pyx.
483        """
484        if HAS_DICTIONARY(left):   # fast check
485            # TODO: this bit will be unnecessarily slow if someone derives
486            # from the pyrex class *without* overriding _add_, since then
487            # we'll be making an unnecessary python call to _add_, which will
488            # end up in _add_c_impl anyway. There must be a simple way to
489            # distinguish this situation. It's complicated because someone
490            # can even override it at the instance level (without overriding
491            # it in the class.)
492            return left._add_(right)
493        else:
494            # Must be a pure Pyrex class.
495            return left._add_c_impl(right)
496
497
498    cdef ModuleElement _add_c_impl(left, ModuleElement right):
499        """
500        Pyrex classes should override this function to implement addition.
501        DO NOT CALL THIS FUNCTION DIRECTLY.
502        See extensive documentation at the top of element.pyx.
503        """
504        raise TypeError, arith_error_message(left, right, operator.add)
505       
506
507    def _add_(ModuleElement left, ModuleElement right):
508        """
509        Python classes should override this function to implement addition.
510
511        See extensive documentation at the top of element.pyx.
512        """
513        return left._add_c_impl(right)
514
515    ##################################################
516    # Subtraction
517    ##################################################   
518
519    def __sub__(left, right):
520        """
521        Top-level subtraction operator for ModuleElements.
522        See extensive documentation at the top of element.pyx.
523        """
524        if have_same_parent(left, right):
525            return (<ModuleElement>left)._sub_c(<ModuleElement>right)
526        return bin_op_c(left, right, operator.sub)
527
528    cdef ModuleElement _sub_c(left, ModuleElement right):
529        """
530        Subtraction dispatcher for ModuleElements.
531
532        DO NOT OVERRIDE THIS FUNCTION.
533
534        See extensive documentation at the top of element.pyx.
535        """
536       
537        if HAS_DICTIONARY(left):   # fast check
538            return left._sub_(right)
539        else:
540            # Must be a pure Pyrex class.
541            return left._sub_c_impl(right)
542
543
544    cdef ModuleElement _sub_c_impl(left, ModuleElement right):
545        """
546        Pyrex classes should override this function to implement subtraction.
547
548        DO NOT CALL THIS FUNCTION DIRECTLY.
549
550        See extensive documentation at the top of element.pyx.
551        """
552        # default implementation is to use the negation and addition
553        # dispatchers:
554        return left._add_c(right._neg_c())
555       
556
557    def _sub_(ModuleElement left, ModuleElement right):
558        """
559        Python classes should override this function to implement subtraction.
560
561        See extensive documentation at the top of element.pyx.
562        """
563        return left._sub_c_impl(right)
564       
565    ##################################################
566    # Negation
567    ##################################################   
568
569    def __neg__(self):
570        """
571        Top-level negation operator for ModuleElements.
572        See extensive documentation at the top of element.pyx.
573        """
574        # We ASSUME that self is a ModuleElement. No type checks.
575        return (<ModuleElement>self)._neg_c()
576
577
578    cdef ModuleElement _neg_c(self):
579        """
580        Negation dispatcher for ModuleElements.
581        DO NOT OVERRIDE THIS FUNCTION.
582        See extensive documentation at the top of element.pyx.
583        """
584       
585        if HAS_DICTIONARY(self):   # fast check
586            return self._neg_()
587        else:
588            # Must be a pure Pyrex class.
589            return self._neg_c_impl()
590
591
592    cdef ModuleElement _neg_c_impl(self):
593        """
594        Pyrex classes should override this function to implement negation.
595        DO NOT CALL THIS FUNCTION DIRECTLY.
596        See extensive documentation at the top of element.pyx.
597        """
598        # default implementation is to try multiplying by -1.
599        return bin_op_c(self._parent._base(-1), self, operator.mul)
600       
601
602    def _neg_(ModuleElement self):
603        """
604        Python classes should override this function to implement negation.
605
606        See extensive documentation at the top of element.pyx.
607        """
608        return self._neg_c_impl()
609
610    ##################################################
611    # Module element multiplication (scalars, etc.)
612    ##################################################
613    def __mul__(left, right):
614        return module_element_generic_multiply_c(left, right)
615   
616    cdef ModuleElement _multiply_by_scalar(self, right):
617        # self * right,  where right need not be a ring element in the base ring
618        # This does type checking and canonical coercion then calls _lmul_c_impl.
619        if PY_TYPE_CHECK(right, Element):
620            if (<Element>right)._parent is self._parent._base:
621                # No coercion needed
622                return self._lmul_c(right)
623            else:
624                # Otherwise we do an explicit canonical coercion.
625                try:
626                    return self._lmul_c( self._parent._base._coerce_c(right) )
627                except TypeError:
628                    # that failed -- try to base extend right then do the multiply:
629                    self = self.base_extend((<RingElement>right)._parent)
630                    return (<ModuleElement>self)._lmul_c(right)
631        else:
632            # right is not an element at all
633            return (<ModuleElement>self)._lmul_c(self._parent._base._coerce_c(right))
634
635    cdef ModuleElement _rmultiply_by_scalar(self, left):
636        # left * self, where left need not be a ring element in the base ring
637        # This does type checking and canonical coercion then calls _rmul_c_impl.
638        #
639        # INPUT:
640        #    self -- a module element
641        #    left -- a scalar
642        # OUTPUT:
643        #    left * self
644        #
645        if PY_TYPE_CHECK(left, Element):
646            if (<Element>left)._parent is self._parent._base:
647                # No coercion needed
648                return self._rmul_c(left)
649            else:
650                # Otherwise we do an explicit canonical coercion.
651                try:
652                    return self._rmul_c(self._parent._base._coerce_c(left))
653                except TypeError:
654                    # that failed -- try to base extend self then do the multiply:
655                    self = self.base_extend((<RingElement>left)._parent)
656                    return (<ModuleElement>self)._rmul_c(left)
657        else:
658            # now left is not an element at all.
659            return (<ModuleElement>self)._rmul_c(self._parent._base._coerce_c(left))
660
661    cdef ModuleElement _lmul_nonscalar_c(left, right):
662        # Compute the product left * right, where right is assumed to be a nonscalar (so no coercion)
663        # This is a last resort.
664        if HAS_DICTIONARY(left):
665            return left._lmul_nonscalar(right)
666        else:
667            return left._lmul_nonscalar_c_impl(right)
668       
669    cdef ModuleElement _lmul_nonscalar_c_impl(left, right):
670        raise TypeError
671
672    def _lmul_nonscalar(left, right):
673        return left._lmul_nonscalar_c_impl(right)
674   
675    cdef ModuleElement _rmul_nonscalar_c(right, left):
676        if HAS_DICTIONARY(right):
677            return right._rmul_nonscalar(left)
678        else:
679            return right._rmul_nonscalar_c_impl(left)
680       
681    cdef ModuleElement _rmul_nonscalar_c_impl(right, left):
682        raise TypeError
683
684    def _rmul_nonscalar(right, left):
685        return right._rmul_nonscalar_c_impl(left)
686       
687
688    # rmul -- left * self
689    cdef ModuleElement _rmul_c(self, RingElement left):
690        """
691        DO NOT OVERRIDE THIS FUNCTION.  OK to call.
692        """
693        if HAS_DICTIONARY(self):
694            return self._rmul_(left)
695        else:
696            return self._rmul_c_impl(left)
697
698    cdef ModuleElement _rmul_c_impl(self, RingElement left):
699        """
700        Default module left scalar multiplication, which is to try to
701        canonically coerce the scalar to the integers and do that
702        multiplication, which is always defined.
703        """
704        n = int(left)
705        if n != left:
706            raise TypeError, "left (=%s) must be an integer."%left
707        a = self
708        if n < 0:
709            a = -a
710            n = -n
711        sum = None
712        asum = a
713        while True:
714            if n&1 > 0:
715                if sum is None:
716                    sum = asum
717                else:
718                    sum += asum
719            n = n >> 1
720            if n != 0:
721                asum += asum
722            else:
723                break
724        if sum is None:
725            return self._parent(0)
726        return sum
727
728    def _rmul_(self, left):
729        return self._rmul_c_impl(left)
730
731
732    # lmul -- self * right
733       
734    cdef ModuleElement _lmul_c(self, RingElement right):
735        """
736        DO NOT OVERRIDE THIS FUNCTION.
737        """
738        if HAS_DICTIONARY(self):
739            return self._lmul_(right)
740        else:
741            return self._lmul_c_impl(right)
742       
743    cdef ModuleElement _lmul_c_impl(self, RingElement right):
744        """
745        Default module right scalar multiplication, which is to try to
746        canonically coerce the scalar to the integers and do that
747        multiplication, which is always defined.
748        """
749        return self._rmul_c(right)
750
751    def _lmul_(self, right):
752        return self._lmul_c_impl(right)
753       
754    cdef RingElement coerce_to_base_ring(self, x):
755        if PY_TYPE_CHECK(x, Element) and (<Element>x)._parent is self._parent._base:
756            return x
757        try:
758            return self._parent._base._coerce_c(x)
759        except AttributeError:
760            return self._parent._base(x)
761
762    ##################################################
763    # Other properties
764    ##################################################
765    def order(self):              ### DO NOT OVERRIDE THIS!!! Instead, override additive_order.
766        """
767        Return the additive order of self.
768        """
769        return self.additive_order()   
770
771    def additive_order(self):
772        """
773        Return the additive order of self.
774        """
775        raise NotImplementedError
776   
777def module_element_generic_multiply(left, right):
778    return module_element_generic_multiply_c(left, right)
779
780cdef module_element_generic_multiply_c(left, right):
781    cdef int is_element
782    if PY_TYPE_CHECK(right, ModuleElement) and not PY_TYPE_CHECK(right, RingElement):
783        # do left * (a module element right)
784        is_element = PY_TYPE_CHECK(left, Element)
785        if is_element  and  (<Element>left)._parent is (<ModuleElement>right)._parent._base:
786            # No coercion needed
787            return (<ModuleElement>right)._rmul_c(left)
788        else:
789            try:
790                return (<ModuleElement>right)._rmul_nonscalar_c(left)
791            except TypeError:
792                pass
793            # Otherwise we have to do an explicit canonical coercion.
794            try:
795                return (<ModuleElement>right)._rmul_c(
796                    (<Parent>(<ModuleElement>right)._parent._base)._coerce_c(left))
797            except TypeError:
798                if is_element:
799                    # that failed -- try to base extend right then do the multiply:
800                    right = right.base_extend((<RingElement>left)._parent)
801                    return (<ModuleElement>right)._rmul_c(left)
802    else:
803        # do (module element left) * right
804        # This is the symmetric case of above.
805        is_element = PY_TYPE_CHECK(right, Element)
806        if is_element  and  (<Element>right)._parent is (<ModuleElement>left)._parent._base:
807            # No coercion needed
808            return (<ModuleElement>left)._lmul_c(right)
809        else:
810            try:
811                return (<ModuleElement>left)._lmul_nonscalar_c(right)
812            except TypeError:
813                pass
814            # Otherwise we have to do an explicit canonical coercion.
815            try:
816                return (<ModuleElement>left)._lmul_c(
817                    (<Parent>(<ModuleElement>left)._parent._base)._coerce_c(right))
818            except TypeError:
819                if is_element:
820                    # that failed -- try to base extend right then do the multiply:
821                    left = left.base_extend((<RingElement>right)._parent)
822                    return (<ModuleElement>left)._rmul_c(right)
823    raise TypeError
824
825########################################################################
826# Monoid
827########################################################################
828
829def is_MonoidElement(x):
830    """
831    Return True if x is of type MonoidElement.
832    """
833    return IS_INSTANCE(x, MonoidElement)
834
835cdef class MonoidElement(Element):
836    """
837    Generic element of a monoid.
838    """
839
840    #############################################################
841    # Multiplication
842    #############################################################
843    def __mul__(left, right):
844        """
845        Top-level multiplication operator for monoid elements.
846        See extensive documentation at the top of element.pyx.
847        """
848        if have_same_parent(left, right):
849            return (<MonoidElement>left)._mul_c(<MonoidElement>right)
850        try:
851            return bin_op_c(left, right, operator.mul)
852        except TypeError, msg:
853            if isinstance(left, (int, long)) and left==1:
854                return right
855            elif isinstance(right, (int, long)) and right==1:
856                return left
857            raise TypeError, msg
858               
859           
860           
861
862    cdef MonoidElement _mul_c(left, MonoidElement right):
863        """
864        Multiplication dispatcher for RingElements.
865        DO NOT OVERRIDE THIS FUNCTION.
866        See extensive documentation at the top of element.pyx.
867        """       
868        if HAS_DICTIONARY(left):   # fast check
869            return left._mul_(right)
870        else:
871            return left._mul_c_impl(right)
872       
873       
874    cdef MonoidElement _mul_c_impl(left, MonoidElement right):
875        """
876        Pyrex classes should override this function to implement multiplication.
877        DO NOT CALL THIS FUNCTION DIRECTLY.
878        See extensive documentation at the top of element.pyx.
879        """
880        raise TypeError
881
882    def _mul_(left, right):
883        return left._mul_c_impl(right)
884
885    #############################################################
886    # Other generic functions that should be available to
887    # any monoid element.
888    #############################################################
889    def order(self):
890        """
891        Return the multiplicative order of self.
892        """
893        return self.multiplicative_order()
894
895    def multiplicative_order(self):
896        """
897        Return the multiplicative order of self.
898        """
899        raise NotImplementedError
900   
901    def __pow__(self, nn, dummy):
902        """
903        Return the (integral) power of self.
904        """
905        cdef int cn
906
907        n = int(nn)
908        if n != nn:
909            raise NotImplementedError, "non-integral exponents not supported"
910
911        a = self
912        if n < 0:
913            n = -n
914            a = ~self
915
916        if n < 4:
917            # These cases will probably be called often
918            # and don't benifit from the code below
919            cn = n
920            if cn == 0:
921                return (<Element>a)._parent(1)
922            elif cn == 1:
923                return a
924            elif cn == 2:
925                return a*a
926            elif cn == 3:
927                return a*a*a
928               
929        # One multiplication can be saved by starting with
930        # the smallest power needed rather than with 1
931        apow = a
932        while n&1 == 0:
933            apow = apow*apow
934            n = n >> 1
935        power = apow
936        n = n >> 1
937       
938        while n != 0:
939            apow = apow*apow
940            if n&1 != 0: power = power*apow
941            n = n >> 1
942           
943        return power
944
945
946def is_AdditiveGroupElement(x):
947    """
948    Return True if x is of type AdditiveGroupElement.
949    """
950    return IS_INSTANCE(x, AdditiveGroupElement)
951
952cdef class AdditiveGroupElement(ModuleElement):
953    """
954    Generic element of an additive group.
955    """
956    def order(self):
957        """
958        Return additive order of element
959        """
960        return self.additive_order()
961
962    def __invert__(self):
963        raise NotImplementedError, "multiplicative inverse not defined for additive group elements"
964   
965    cdef ModuleElement _rmul_c_impl(self, RingElement left):
966        return self._lmul_c_impl(left)
967       
968    cdef ModuleElement _lmul_c_impl(self, RingElement right):
969        cdef int m
970        try:
971            m = int(right)  # a little worrisome.
972            if m<0:
973                return (-self)*(-m)
974            if m==1:
975                return self
976            P = self.scheme()(0)
977            if m==0:
978                return P
979            power = P
980            i = 0
981            apow2 = self
982            while ((m>>i) > 0):
983                if((m>>i) & 1):
984                    power = power + apow2
985                apow2 = apow2 + apow2
986                i = i + 1
987            return power
988        except OverflowError:
989            m0 = int(right)
990            if m0<0:
991                return (-self)*(-m0)
992            if m0==1:
993                return self
994            P = self.scheme()(0)
995            if m0==0:
996                return P
997            power = P
998            i = 0
999            apow2 = self
1000            while ((m0>>i) > 0):
1001                if((m0>>i) & 1):
1002                    power = power + apow2
1003                apow2 = apow2 + apow2
1004                i = i + 1
1005            return power
1006
1007def is_MultiplicativeGroupElement(x):
1008    """
1009    Return True if x is of type MultiplicativeGroupElement.
1010    """
1011    return IS_INSTANCE(x, MultiplicativeGroupElement)
1012
1013cdef class MultiplicativeGroupElement(MonoidElement):
1014    """
1015    Generic element of a multiplicative group.
1016    """
1017    def order(self):
1018        """
1019        Return the multiplicative order of self.
1020        """
1021        return self.multiplicative_order()
1022
1023    def _add_(self, x):
1024        raise ArithmeticError, "addition not defined in a multiplicative group"
1025
1026    def __div__(left, right):
1027        if have_same_parent(left, right):
1028            return left._div_(right)
1029        return bin_op_c(left, right, operator.div)
1030   
1031    cdef MultiplicativeGroupElement _div_c(self, MultiplicativeGroupElement right):
1032        """
1033        Multiplication dispatcher for MultiplicativeGroupElements.
1034        DO NOT OVERRIDE THIS FUNCTION.
1035        See extensive documentation at the top of element.pyx.
1036        """
1037        if HAS_DICTIONARY(self):   # fast check
1038            return self._div_(right)
1039        else:
1040            return self._div_c_impl(right)
1041
1042    cdef MultiplicativeGroupElement _div_c_impl(self, MultiplicativeGroupElement right):
1043        """
1044        Pyrex classes should override this function to implement division.
1045        DO NOT CALL THIS FUNCTION DIRECTLY.
1046        See extensive documentation at the top of element.pyx.
1047        """
1048        return self._parent.fraction_field()(self, right)
1049
1050    def _div_(MultiplicativeGroupElement self, MultiplicativeGroupElement right):
1051        """
1052        Python classes should override this function to implement division.
1053        """
1054        return self._div_c_impl(right)
1055   
1056
1057    def __invert__(self):
1058        return 1/self
1059
1060
1061def is_RingElement(x):
1062    """
1063    Return True if x is of type RingElement.
1064    """
1065    return IS_INSTANCE(x, RingElement)
1066
1067cdef class RingElement(ModuleElement):
1068    ##################################################
1069    def is_one(self):
1070        return PyBool_FromLong(self == self.parent()(1))
1071
1072    ##################################
1073    # Multiplication
1074    ##################################
1075
1076    # The default behavior for scalars is just to coerce into the parent ring.
1077    cdef ModuleElement _lmul_c_impl(self, RingElement right):
1078        return self._mul_c(<RingElement>(self._parent(right)))
1079
1080    cdef ModuleElement _rmul_c_impl(self, RingElement left):
1081        return (<RingElement>(self._parent)(left))._mul_c(self)
1082
1083    def __mul__(self, right):
1084        """
1085        Top-level multiplication operator for ring elements.
1086        See extensive documentation at the top of element.pyx.
1087        """
1088        # Try fast pathway if they are both RingElements and the parents match.
1089        # (We know at least one of the arguments is a RingElement. So if their
1090        # types are *equal* (fast to check) then they are both RingElements.
1091        # Otherwise use the slower test via PY_TYPE_CHECK.)
1092        if have_same_parent(self, right):
1093            return (<RingElement>self)._mul_c(<RingElement>right)
1094
1095        if not (PY_TYPE_CHECK(self, Element) and PY_TYPE_CHECK(right, Element)):
1096            # one of self or right is not even an Element.
1097            return bin_op_c(self, right, operator.mul)
1098
1099        # Now we can assume both self and right are of a class that derives
1100        # from Element (so they have a parent).  If one is a ModuleElement,
1101        # do some special code.
1102        if PY_TYPE_CHECK(self, ModuleElement) and PY_TYPE_CHECK(right, ModuleElement):
1103            # We may assume both are module elements.
1104            if (<Element>self)._parent is (<Element>right)._parent._base:
1105                return (<ModuleElement>right)._rmul_c(self)
1106            elif (<Element>self)._parent._base is (<Element>right)._parent:
1107                return (<ModuleElement>self)._lmul_c(right)
1108            if not PY_TYPE_CHECK(right, RingElement):
1109                # Now self must be a ring element:
1110                # If the parent is the same as the base ring, good
1111                if (<RingElement>self)._parent is (<ModuleElement>right)._parent._base:
1112                    return (<ModuleElement>right)._rmul_c(self)
1113                elif PY_TYPE_CHECK(right, Matrix):
1114                    return (<Matrix>right)._rmultiply_by_scalar(left)
1115                else:
1116                    # Otherwise we have to do an explicit canonical coercion.
1117                    try:
1118                        return (<ModuleElement>right)._rmul_c(
1119                            (<Parent>(<ModuleElement>right)._parent._base)._coerce_c(self))
1120                    except TypeError:
1121                        # that failed -- try to base extend right then do the multiply:
1122                        right = right.base_extend((<RingElement>self)._parent)
1123                        return (<ModuleElement>right)._rmul_c(self)
1124            elif PY_TYPE_CHECK(right, Matrix):  # matrix is a ring element
1125                return (<Matrix>right)._rmultiply_by_scalar(self)
1126       
1127        # General case.
1128        return bin_op_c(self, right, operator.mul)
1129
1130    cdef RingElement _mul_c(self, RingElement right):
1131        """
1132        Multiplication dispatcher for RingElements.
1133        DO NOT OVERRIDE THIS FUNCTION.
1134        See extensive documentation at the top of element.pyx.
1135        """       
1136        if HAS_DICTIONARY(self):   # fast check
1137            return self._mul_(right)
1138        else:
1139            return self._mul_c_impl(right)
1140
1141    cdef RingElement _mul_c_impl(self, RingElement right):
1142        """
1143        Pyrex classes should override this function to implement multiplication.
1144        DO NOT CALL THIS FUNCTION DIRECTLY.
1145        See extensive documentation at the top of element.pyx.
1146        """
1147        raise TypeError, arith_error_message(self, right, operator.mul)
1148
1149    def _mul_(RingElement self, RingElement right):
1150        """
1151        Python classes should override this function to implement multiplication.
1152        See extensive documentation at the top of element.pyx.       
1153        """
1154        return self._mul_c_impl(right)
1155       
1156    def __pow__(self, m, dummy):
1157        """
1158        Retern the (integral) power of self.
1159       
1160        EXAMPLE:
1161            sage: a = Integers(389)['x']['y'](37)
1162            sage: a^2
1163            202
1164            sage: a^388
1165            1
1166            sage: a^(2^120)
1167            81
1168            sage: a^0
1169            1
1170            sage: a^1 == a
1171            True
1172            sage: a^2 * a^3 == a^5
1173            True
1174            sage: (a^3)^2 == a^6
1175            True
1176            sage: a^57 * a^43 == a^100
1177            True
1178            sage: a^(-1) == 1/a
1179            True
1180            sage: a^200 * a^(-64) == a^136
1181            True
1182        """
1183        cdef int cn
1184
1185        n = int(m)
1186        if n != m:
1187            raise ValueError, "n must be an integer"
1188
1189        if n < 0:
1190            n = -n
1191            a = ~self
1192        else:
1193            a = self
1194
1195        if n < 4:
1196            # These cases will probably be called often
1197            # and don't benifit from the code below
1198            cn = n
1199            if cn == 0:
1200                return (<Element>a)._parent(1)
1201            elif cn == 1:
1202                return a
1203            elif cn == 2:
1204                return a*a
1205            elif cn == 3:
1206                return a*a*a
1207               
1208        # One multiplication can be saved by starting with
1209        # the smallest power needed rather than with 1
1210        apow = a
1211        while n&1 == 0:
1212            apow = apow*apow
1213            n = n >> 1
1214        power = apow
1215        n = n >> 1
1216       
1217        while n != 0:
1218            apow = apow*apow
1219            if n&1 != 0: power = power*apow
1220            n = n >> 1
1221           
1222        return power
1223
1224
1225    ##################################
1226    # Division
1227    ##################################   
1228   
1229    def __truediv__(self, right):
1230        # in sage all divs are true
1231        if not PY_TYPE_CHECK(self, Element):
1232            return bin_op_c(self, right, operator.div)
1233        return self.__div__(right)
1234
1235    def __div__(self, right):
1236        """
1237        Top-level multiplication operator for ring elements.
1238        See extensive documentation at the top of element.pyx.
1239        """
1240        if have_same_parent(self, right):
1241            return (<RingElement>self)._div_c(<RingElement>right)
1242        return bin_op_c(self, right, operator.div)
1243
1244           
1245
1246    cdef RingElement _div_c(self, RingElement right):
1247        """
1248        Multiplication dispatcher for RingElements.
1249        DO NOT OVERRIDE THIS FUNCTION.
1250        See extensive documentation at the top of element.pyx.
1251        """
1252        if HAS_DICTIONARY(self):   # fast check
1253            return self._div_(right)
1254        else:
1255            return self._div_c_impl(right)
1256
1257    cdef RingElement _div_c_impl(self, RingElement right):
1258        """
1259        Pyrex classes should override this function to implement division.
1260        DO NOT CALL THIS FUNCTION DIRECTLY.
1261        See extensive documentation at the top of element.pyx.
1262        """
1263        try:
1264            return self._parent.fraction_field()(self, right)
1265        except AttributeError:
1266            raise TypeError, arith_error_message(self, right, operator.div)
1267
1268    def _div_(RingElement self, RingElement right):
1269        """
1270        Python classes should override this function to implement division.
1271        """
1272        return self._div_c_impl(right)
1273
1274    def __pos__(self):
1275        return self
1276
1277    def __invert__(self):
1278        return 1/self
1279
1280    ##################################################
1281
1282    def order(self):
1283        """
1284        Return the additive order of self.
1285        """
1286        return self.additive_order()
1287
1288    def additive_order(self):
1289        """
1290        Return the additive order of self.
1291        """
1292        raise NotImplementedError
1293
1294    def multiplicative_order(self):
1295        r"""
1296        Return the multiplicative order of self, if self is a unit, or raise
1297        \code{ArithmeticError} otherwise.
1298        """
1299        if not self.is_unit():
1300            raise ArithmeticError, "self (=%s) must be a unit to have a multiplicative order."
1301        raise NotImplementedError
1302
1303    def is_unit(self):
1304        if self == 1 or self == -1:
1305            return True
1306        raise NotImplementedError
1307
1308    def is_nilpotent(self):
1309        """
1310        Return True if self is nilpotent, i.e., some power of self
1311        is 0.
1312        """
1313        if self.is_unit():
1314            return False
1315        if self.is_zero():
1316            return True
1317        raise NotImplementedError
1318
1319
1320
1321
1322def is_CommutativeRingElement(x):
1323    """
1324    Return True if x is of type CommutativeRingElement.
1325    """
1326    return IS_INSTANCE(x, CommutativeRingElement)
1327
1328cdef class CommutativeRingElement(RingElement):
1329    def _im_gens_(self, codomain, im_gens):
1330        if len(im_gens) == 1 and self.parent().gen(0) == 1:
1331            return codomain(self)
1332        raise NotImplementedError
1333   
1334    def inverse_mod(self, I):
1335        r"""
1336        Return an inverse of self modulo the ideal $I$, if defined,
1337        i.e., if $I$ and self together generate the unit ideal.
1338        """
1339        raise NotImplementedError
1340   
1341    def mod(self, I):
1342        r"""
1343        Return a representative for self modulo the ideal I (or the ideal
1344        generated by the elements of I if I is not an ideal.)
1345
1346        EXAMPLE:  Integers
1347        Reduction of 5 modulo an ideal:
1348            sage: n = 5
1349            sage: n.mod(3*ZZ)
1350            2
1351
1352        Reduction of 5 modulo the ideal generated by 3.
1353            sage: n.mod(3)
1354            2
1355
1356        Reduction of 5 modulo the ideal generated by 15 and 6, which is $(3)$.           
1357            sage: n.mod([15,6])
1358            2
1359
1360
1361        EXAMPLE: Univiate polynomials
1362            sage: R.<x> = PolynomialRing(QQ)
1363            sage: f = x^3 + x + 1
1364            sage: f.mod(x + 1)
1365            -1
1366
1367        When little is implemented about a given ring, then mod may
1368        return simply return $f$.  For example, reduction is not
1369        implemented for $\Z[x]$ yet. (TODO!)
1370       
1371            sage: R.<x> = PolynomialRing(ZZ)
1372            sage: f = x^3 + x + 1
1373            sage: f.mod(x + 1)
1374            x^3 + x + 1
1375           
1376       
1377
1378        EXAMPLE: Multivariate polynomials
1379        We reduce a polynomial in two variables modulo a polynomial
1380        and an ideal:
1381            sage: R.<x,y,z> = PolynomialRing(QQ, 3)
1382            sage: (x^2 + y^2 + z^2).mod(x+y+z)
1383            2*z^2 + 2*y*z + 2*y^2
1384
1385        Notice above that $x$ is eliminated.  In the next example,
1386        both $y$ and $z$ are eliminated.
1387           
1388            sage: (x^2 + y^2 + z^2).mod( (x - y, y - z) )
1389            3*z^2
1390            sage: f = (x^2 + y^2 + z^2)^2; f
1391            z^4 + 2*y^2*z^2 + y^4 + 2*x^2*z^2 + 2*x^2*y^2 + x^4
1392            sage: f.mod( (x - y, y - z) )
1393            9*z^4
1394
1395        In this example $y$ is eliminated.
1396            sage: (x^2 + y^2 + z^2).mod( (x^3, y - z) )
1397            2*z^2 + x^2
1398        """
1399        from sage.rings.all import is_Ideal
1400        if not is_Ideal(I) or not I.ring() is self.parent():
1401            I = self.parent().ideal(I)
1402            #raise TypeError, "I = %s must be an ideal in %s"%(I, self.parent())
1403        return I.reduce(self)
1404
1405cdef class Vector(ModuleElement):
1406    cdef int is_sparse_c(self):
1407        raise NotImplementedError
1408   
1409    cdef int is_dense_c(self):
1410        raise NotImplementedError
1411   
1412    def __mul__(left, right):
1413        if PY_TYPE_CHECK(left, Vector):
1414            # left is the vector
1415            # Possibilities:
1416            #     left * matrix
1417            if PY_TYPE_CHECK(right, Matrix):
1418                return (<Matrix>right)._vector_times_matrix_c(<Vector>left)
1419            #     left * vector
1420            if PY_TYPE_CHECK(right, Vector):
1421                return (<Vector>left)._vector_times_vector_c(<Vector>right)
1422            #     left * scalar
1423            return (<ModuleElement>left)._multiply_by_scalar(right)
1424           
1425        else:
1426            # right is the vector
1427            # Possibilities:
1428            #     matrix * right
1429            if PY_TYPE_CHECK(left, Matrix):
1430                return (<Matrix>left)._matrix_times_vector_c(<Vector>right)
1431            #     vector * right
1432            if PY_TYPE_CHECK(left, Vector):
1433                return (<Vector>left)._vector_times_vector_c(<Vector>right)
1434            #     scalar * right
1435            return (<ModuleElement>right)._rmultiply_by_scalar(left)
1436
1437    cdef Vector _vector_times_vector_c(Vector left, Vector right):
1438        if left._degree != right._degree:
1439            raise TypeError, "incompatible degrees"
1440        left, right = canonical_base_coercion_c(left, right)
1441        if HAS_DICTIONARY(left):
1442            return left._vector_times_vector(right)
1443        else:
1444            return left._vector_times_vector_c_impl(right)
1445    cdef Vector _vector_times_vector_c_impl(Vector left, Vector right):
1446        raise TypeError,arith_error_message(left, right, operator.mul)
1447   
1448    def  _vector_times_vector(left, right):
1449        return self.vector_time_vector_c_impl(right)
1450
1451    def __div__(self, right):
1452        if PY_TYPE_CHECK(self, Vector):
1453            right = (<Vector>self)._parent._base._coerce_c(right)
1454            return (<Vector>self)._lmul_c(~right)
1455        raise TypeError, arith_error_message(self, right, operator.div)
1456       
1457
1458cdef have_same_base(Element x, Element y):
1459    return x._parent._base is y._parent._base
1460
1461
1462def is_Vector(x):
1463    return IS_INSTANCE(x, Vector)
1464
1465cdef class Matrix(AlgebraElement):
1466    cdef int is_sparse_c(self):
1467        raise NotImplementedError
1468   
1469    cdef int is_dense_c(self):
1470        raise NotImplementedError
1471   
1472    def __mul__(left, right):
1473        if PY_TYPE_CHECK(left, Matrix):
1474            # left is the matrix
1475            # Possibilities:
1476            #     left * matrix
1477            if PY_TYPE_CHECK(right, Matrix):
1478                return (<Matrix>left)._matrix_times_matrix_c(<Vector>right)
1479            #     left * vector
1480            if PY_TYPE_CHECK(right, Vector):
1481                return (<Matrix>left)._matrix_times_vector_c(<Vector>right)
1482            #     left * scalar
1483            return (<Matrix>left)._multiply_by_scalar(right)
1484           
1485        else:
1486            # right is the matrix
1487            # Possibilities:
1488            #     matrix * right
1489            if PY_TYPE_CHECK(left, Matrix):
1490                return (<Matrix>left)._matrix_times_matrix_c(<Matrix>right)
1491            #     vector * right
1492            if PY_TYPE_CHECK(left, Vector):
1493                return (<Matrix>right)._vector_times_matrix_c(<Vector>left)
1494            #     scalar * right
1495            return (<Matrix>right)._rmultiply_by_scalar(left)
1496       
1497    cdef Vector _vector_times_matrix_c(matrix_right, Vector vector_left):
1498        if vector_left._degree != matrix_right._nrows:
1499            raise TypeError, "incompatible dimensions"
1500        matrix_right, vector_left = canonical_base_coercion_c(matrix_right, vector_left)
1501        sl = vector_left.is_sparse_c(); sr = matrix_right.is_sparse_c()
1502        if sl != sr:  # one is dense and one is sparse
1503            if sr:  # vector is dense and matrix is sparse
1504                vector_left = vector_left.sparse_vector()
1505            else:
1506                # vector is sparse and matrix is dense
1507                vector_left = vector_left.dense_vector()
1508        if HAS_DICTIONARY(matrix_right):
1509            return matrix_right._vector_times_matrix(vector_left)           
1510        else:
1511            return matrix_right._vector_times_matrix_c_impl(vector_left)
1512       
1513    cdef Vector _vector_times_matrix_c_impl(matrix_right, Vector vector_left):
1514        raise TypeError
1515   
1516    def _vector_times_matrix(matrix_right, vector_left):
1517        return matrix_right._vector_times_matrix_c_impl(vector_left)
1518
1519    cdef Vector _matrix_times_vector_c(matrix_left, Vector vector_right):
1520        if matrix_left._ncols != vector_right._degree:
1521            raise TypeError, "incompatible dimensions"
1522        matrix_left, vector_right = canonical_base_coercion_c(matrix_left, vector_right)
1523        sl = matrix_left.is_sparse_c(); sr = vector_right.is_sparse_c()
1524        if sl != sr:  # one is dense and one is sparse
1525            if sl:  # vector is dense and matrix is sparse
1526                vector_right = vector_right.sparse_vector()
1527            else:
1528                # vector is sparse and matrix is dense
1529                vector_right = vector_right.dense_vector()
1530        if HAS_DICTIONARY(matrix_left):
1531            return matrix_left._matrix_times_vector(vector_right)
1532        else:
1533            return matrix_left._matrix_times_vector_c_impl(vector_right)
1534           
1535    cdef Vector _matrix_times_vector_c_impl(matrix_left, Vector vector_right):
1536        raise TypeError
1537    def _matrix_times_vector(matrix_left, vector_right):
1538        return matrix_left._matrix_times_vector_c_impl(vector_right)
1539
1540       
1541    cdef Matrix _matrix_times_matrix_c(left, Matrix right):
1542        cdef int sl, sr
1543        if left._ncols != right._nrows:
1544            raise TypeError, "incompatible dimensions"
1545        left, right = canonical_base_coercion_c(left, right)
1546        sl = left.is_sparse_c(); sr = right.is_sparse_c()
1547        if sl != sr:  # is dense and one is sparse
1548            if sr:  # left is dense
1549                right = right.dense_matrix()
1550            else:
1551                left = left.dense_matrix()
1552        if HAS_DICTIONARY(left):
1553            return left._matrix_times_matrix(right)
1554        else:
1555            return left._matrix_times_matrix_c_impl(right)
1556       
1557    cdef Matrix _matrix_times_matrix_c_impl(left, Matrix right):
1558        raise TypeError
1559    def _matrix_time_matrix(left, right):
1560        return left._matrix_times_matrix_c_impl(right)
1561   
1562
1563def is_Matrix(x):
1564    return IS_INSTANCE(x, Matrix)
1565
1566def is_IntegralDomainElement(x):
1567    """
1568    Return True if x is of type IntegralDomainElement.
1569    """
1570    return IS_INSTANCE(x, IntegralDomainElement)
1571
1572cdef class IntegralDomainElement(CommutativeRingElement):
1573    def is_nilpotent(self):
1574        return self.is_zero()
1575
1576
1577def is_DedekindDomainElement(x):
1578    """
1579    Return True if x is of type DedekindDomainElement.
1580    """
1581    return IS_INSTANCE(x, DedekindDomainElement)
1582
1583cdef class DedekindDomainElement(IntegralDomainElement):
1584    pass
1585       
1586def is_PrincipalIdealDomainElement(x):
1587    """
1588    Return True if x is of type PrincipalIdealDomainElement.
1589    """
1590    return IS_INSTANCE(x, PrincipalIdealDomainElement)
1591
1592cdef class PrincipalIdealDomainElement(DedekindDomainElement):
1593    def lcm(self, right):
1594        """
1595        Returns the least common multiple of self and right.
1596        """
1597        if not PY_TYPE_CHECK(right, Element) or not ((<Element>right)._parent is self._parent):
1598            return bin_op_c(self, right, lcm)
1599        return self._lcm(right)
1600
1601    def gcd(self, right):
1602        """
1603        Returns the gcd of self and right, or 0 if both are 0.
1604        """
1605        if not PY_TYPE_CHECK(right, Element) or not ((<Element>right)._parent is self._parent):
1606            return bin_op_c(self, right, gcd)
1607        return self._gcd(right)
1608
1609    def xgcd(self, right):
1610        r"""
1611        Return the extended gcd of self and other, i.e., elements $r, s, t$ such that
1612        $$
1613           r = s \cdot self + t \cdot other.
1614        $$
1615        """
1616        if not PY_TYPE_CHECK(right, Element) or not ((<Element>right)._parent is self._parent):
1617            return bin_op_c(self, right, xgcd)
1618        return self._xgcd(right)
1619
1620
1621# This is pretty nasty low level stuff. The idea is to speed up construction
1622# of EuclideanDomainElements (in particular Integers) by skipping some tp_new
1623# calls up the inheritance tree.
1624PY_SET_TP_NEW(EuclideanDomainElement, Element)
1625
1626def is_EuclideanDomainElement(x):
1627    """
1628    Return True if x is of type EuclideanDomainElement.
1629    """
1630    return IS_INSTANCE(x, EuclideanDomainElement)
1631
1632cdef class EuclideanDomainElement(PrincipalIdealDomainElement):
1633
1634    def degree(self):
1635        raise NotImplementedError
1636
1637    def _gcd(self, other):
1638        """
1639        Return the greatest common divisor of self and other.
1640
1641        Algorithm 3.2.1 in Cohen, GTM 138.
1642        """
1643        A = self
1644        B = other
1645        while not B.is_zero():
1646            Q, R = A.quo_rem(B)
1647            A = B
1648            B = R
1649        return A
1650
1651    def leading_coefficient(self):
1652        raise NotImplementedError
1653
1654    def quo_rem(self, other):
1655        raise NotImplementedError
1656
1657    def __floordiv__(self,right):
1658        """
1659        Quotient of division of self by other.  This is denoted //.
1660        """
1661        Q, _ = self.quo_rem(right)
1662        return Q
1663       
1664    def __mod__(self, other):
1665        """
1666        Remainder of division of self by other.
1667       
1668        EXAMPLES:
1669            sage: R.<x> = ZZ[]
1670            sage: x % (x+1)
1671            -1
1672            sage: (x**3 + x - 1) % (x**2 - 1)
1673            2*x - 1
1674        """
1675        _, R = self.quo_rem(other)
1676        return R
1677       
1678def is_FieldElement(x):
1679    """
1680    Return True if x is of type FieldElement.
1681    """
1682    return IS_INSTANCE(x, FieldElement)
1683
1684cdef class FieldElement(CommutativeRingElement):
1685
1686    def is_unit(self):
1687        """
1688        Return True if self is a unit in its parent ring.
1689       
1690        EXAMPLES:
1691            sage: a = 2/3; a.is_unit()
1692            True
1693
1694        On the other hand, 2 is not a unit, since its parent is ZZ.
1695            sage: a = 2; a.is_unit()
1696            False
1697            sage: parent(a)
1698            Integer Ring
1699
1700        However, a is a unit when viewed as an element of QQ:
1701            sage: a = QQ(2); a.is_unit()
1702            True
1703        """
1704        return PyBool_FromLong(not self.is_zero())
1705   
1706    def _gcd(self, FieldElement other):
1707        """
1708        Return the greatest common divisor of self and other.
1709        """
1710        if self.is_zero() and other.is_zero():
1711            return self
1712        else:
1713            return self.parent()(1)
1714
1715    def _lcm(self, FieldElement other):
1716        """
1717        Return the least common multiple of self and other.
1718        """
1719        if self.is_zero() and other.is_zero():
1720            return self
1721        else:
1722            return self.parent()(1)
1723
1724    def _xgcd(self, FieldElement other):
1725        R = self.parent()
1726        if not self.is_zero():
1727            return R(1), ~self, R(0)
1728        elif not other.is_zero():
1729            return R(1), R(0), ~self
1730        else: # both are 0
1731            return self, self, self
1732       
1733
1734    def quo_rem(self, right):
1735        if not isinstance(right, FieldElement) or not (right.parent() is self.parent()):
1736            right = self.parent()(right)
1737        return self/right, 0
1738
1739## def is_FiniteFieldElement(x):
1740##     """
1741##     Return True if x is of type FiniteFieldElement.
1742##     """
1743##     return IS_INSTANCE(x, FiniteFieldElement)
1744
1745cdef class FiniteFieldElement(FieldElement):
1746    pass
1747   
1748def is_AlgebraElement(x):
1749    """
1750    Return True if x is of type AlgebraElement.
1751    """
1752    return IS_INSTANCE(x, AlgebraElement)
1753
1754cdef class AlgebraElement(RingElement):
1755    pass
1756
1757def is_CommutativeAlgebraElement(x):
1758    """
1759    Return True if x is of type CommutativeAlgebraElement.
1760    """
1761    return IS_INSTANCE(x, CommutativeAlgebraElement)
1762
1763cdef class CommutativeAlgebraElement(CommutativeRingElement):
1764    pass   
1765
1766def is_InfinityElement(x):
1767    """
1768    Return True if x is of type InfinityElement.
1769    """
1770    return IS_INSTANCE(x, InfinityElement)
1771
1772cdef class InfinityElement(RingElement):
1773    pass
1774
1775cdef class PlusInfinityElement(InfinityElement):
1776    pass
1777
1778cdef class MinusInfinityElement(InfinityElement):
1779    pass
1780
1781
1782cdef inline int have_same_parent(left, right):
1783    """
1784    Return nonzero true value if and only if left and right are
1785    elements and have the same parent.
1786    """
1787    # (We know at least one of the arguments is an Element. So if
1788    # their types are *equal* (fast to check) then they are both
1789    # Elements.  Otherwise use the slower test via PY_TYPE_CHECK.)
1790    if PY_TYPE(left) is PY_TYPE(right):
1791        return (<Element>left)._parent is (<Element>right)._parent
1792       
1793    if PY_TYPE_CHECK(right, Element) and PY_TYPE_CHECK(left, Element):
1794        return (<Element>left)._parent is (<Element>right)._parent
1795
1796    return 0
1797           
1798
1799
1800
1801
1802
1803#################################################################################
1804#
1805#  Coercion of elements
1806#
1807#################################################################################
1808import __builtin__
1809import operator
1810
1811cimport sage.modules.module
1812import  sage.modules.module
1813
1814#################################################################################
1815# parent
1816#################################################################################
1817cdef parent_c(x):
1818    if PY_TYPE_CHECK(x,Element):
1819        return (<Element>x)._parent
1820    return <object>PY_TYPE(x)
1821
1822def parent(x):
1823    return parent_c(x)
1824
1825#################################################################################
1826# coerce
1827#################################################################################
1828def coerce(Parent p, x):
1829    try:
1830        return p._coerce_c(x)
1831    except AttributeError:
1832        return p(x)
1833
1834           
1835#################################################################################
1836# canonical coercion of two ring elements into one of their parents.
1837#################################################################################
1838cdef _verify_canonical_coercion_c(x, y):
1839    if not have_same_parent(x,y):
1840        raise RuntimeError, """There is a bug in the coercion code in SAGE.
1841Both x (=%s) and y (=%s) are supposed to have identical parents but they don't.
1842In fact, x has parent '%s'
1843whereas y has parent '%s'"""%(x,y,parent_c(x),parent_c(y))
1844    return x, y
1845
1846def canonical_coercion(x, y):
1847    """
1848    canonical_coercion(x,y) is what is called before doing an
1849    arithmetic operation between x and y.  It returns a pair (z,w)
1850    such that z is got from x and w from y via canonical coercion and
1851    the parents of z and w are identical.
1852
1853    EXAMPLES:
1854        sage: A = Matrix([[0,1],[1,0]])
1855        sage: canonical_coercion(A,1)
1856        ([0 1]
1857        [1 0], [1 0]
1858        [0 1])
1859    """
1860    return canonical_coercion_c(x,y)
1861
1862cdef canonical_coercion_c(x, y):
1863    cdef int i
1864    xp = parent_c(x)
1865    yp = parent_c(y)
1866    if xp is yp:
1867        return x, y
1868
1869    if PY_IS_NUMERIC(x):
1870        try:
1871            x = yp(x)
1872        except TypeError:
1873            y = x.__class__(y)
1874            return x, y
1875        # Calling this every time incurs overhead -- however, if a mistake
1876        # gets through then one can get infinite loops in C code hence core
1877        # dumps.  And users define _coerce_ and __call__ for rings, which
1878        # can easily have bugs in it, i.e., not really make the element
1879        # have the correct parent.  Thus this check is *crucial*.
1880        return _verify_canonical_coercion_c(x,y)
1881   
1882    elif PY_IS_NUMERIC(y):
1883        try:
1884            y = xp(y)
1885        except TypeError:
1886            x = y.__class__(x)
1887            return x, y           
1888        return _verify_canonical_coercion_c(x,y)
1889
1890    try:
1891        if xp.has_coerce_map_from(yp):
1892            y = (<Parent>xp)._coerce_c(y)
1893            return _verify_canonical_coercion_c(x,y)
1894    except AttributeError:
1895        pass
1896    try:
1897        if yp.has_coerce_map_from(xp):
1898            x = (<Parent>yp)._coerce_c(x)
1899            return _verify_canonical_coercion_c(x,y)
1900    except AttributeError:
1901        pass
1902    raise TypeError, "no common canonical parent for objects with parents: '%s' and '%s'"%(xp, yp)
1903
1904cdef canonical_base_coercion_c(Element x, Element y):
1905    if not have_same_base(x, y):
1906        if (<Parent> x._parent._base).has_coerce_map_from_c(y._parent._base):
1907            # coerce all elements of y to the base ring of x
1908            y = y.base_extend_c(x._parent._base)
1909        elif (<Parent> y._parent._base).has_coerce_map_from_c(x._parent._base):
1910            # coerce x to have elements in the base ring of y
1911            x = x.base_extend_c(y._parent._base)
1912    return x,y
1913
1914def canonical_base_coercion(x, y):
1915    try:
1916        xb = x.base_ring()
1917    except AttributeError:
1918        #raise TypeError, "unable to find base ring for %s (parent: %s)"%(x,x.parent())
1919        raise TypeError, "unable to find base ring"
1920    try:
1921        yb = y.base_ring()
1922    except AttributeError:
1923        raise TypeError, "unable to find base ring"
1924        #raise TypeError, "unable to find base ring for %s (parent: %s)"%(y,y.parent())
1925    try:
1926        b = canonical_coercion_c(xb(0),yb(0))[0].parent()
1927    except TypeError:
1928        raise TypeError, "unable to find base ring"
1929        #raise TypeError, "unable to find a common base ring for %s (base ring: %s) and %s (base ring %s)"%(x,xb,y,yb)
1930    return x.change_ring(b), y.change_ring(b)
1931
1932
1933D = {'mul':'*', 'add':'+', 'sub':'-', 'div':'/'}
1934cdef arith_error_message(x, y, op):
1935    try:
1936        n = D[op.__name__]
1937    except KeyError:
1938        n = op.__name__
1939    return "unsupported operand parent(s) for '%s': '%s' and '%s'"%(n, parent_c(x), parent_c(y))
1940   
1941def bin_op(x, y, op):
1942    return bin_op_c(x,y,op)
1943
1944cdef bin_op_c(x, y, op):
1945    """
1946    Compute x op y, where coercion of x and y works according to
1947    SAGE's coercion rules.
1948    """
1949    # Try canonical element coercion.
1950    try:
1951        x1, y1 = canonical_coercion_c(x, y)
1952        return op(x1,y1)       
1953    except TypeError, msg:
1954        #print msg  # this can be useful for debugging.
1955        if not op is operator.mul:
1956            raise TypeError, arith_error_message(x,y,op)
1957
1958    # If the op is multiplication, then some other algebra multiplications
1959    # may be defined
1960   
1961    # 2. Try scalar multiplication.
1962    # No way to multiply x and y using the ``coerce into a canonical
1963    # parent'' rule.
1964    # The next rule to try is scalar multiplication by coercing
1965    # into the base ring.
1966    cdef int x_is_modelt, y_is_modelt
1967
1968    y_is_modelt = PY_TYPE_CHECK(y, ModuleElement)
1969    if y_is_modelt:
1970        # First try to coerce x into the base ring of y if y is an element.
1971        try:
1972            R = (<ModuleElement> y)._parent._base
1973            if R is None:
1974                raise RuntimeError, "base of '%s' must be set to a ring (but it is None)!"%((<ModuleElement> y)._parent)
1975            x = (<Parent>R)._coerce_c(x)
1976            return (<ModuleElement> y)._rmul_c(x)     # the product x * y
1977        except TypeError, msg:
1978            pass
1979
1980    x_is_modelt = PY_TYPE_CHECK(x, ModuleElement)
1981    if x_is_modelt:
1982        # That did not work.  Try to coerce y into the base ring of x.
1983        try:
1984            R = (<ModuleElement> x)._parent._base
1985            if R is None:
1986                raise RuntimeError, "base of '%s' must be set to a ring (but it is None)!"%((<ModuleElement> x)._parent)           
1987            y = (<Parent> R)._coerce_c(y)
1988            return (<ModuleElement> x)._lmul_c(y)    # the product x * y
1989        except TypeError:
1990            pass
1991
1992    if y_is_modelt and x_is_modelt:
1993        # 3. Both canonical coercion failed, but both are module elements.
1994        # Try base extending the right object by the parent of the left
1995
1996        ## TODO -- WORRY -- only unambiguous if one succeeds!
1997        if  PY_TYPE_CHECK(x, RingElement):
1998            try:
1999                return x * y.base_extend((<RingElement>x)._parent)
2000            except (TypeError, AttributeError), msg:
2001                pass
2002        # Also try to base extending the left object by the parent of the right
2003        if  PY_TYPE_CHECK(y, RingElement):
2004            try:
2005                return y * x.base_extend((<Element>y)._parent)
2006            except (TypeError, AttributeError), msg:
2007                pass
2008
2009    # 4. Try _l_action or _r_action.
2010    # Test to see if an _r_action or _l_action is
2011    # defined on either side.
2012    try:
2013        return x._l_action(y)
2014    except (AttributeError, TypeError):   
2015        pass
2016    try:
2017        return y._r_action(x)
2018    except (AttributeError, TypeError):
2019        pass
2020
2021    raise TypeError, arith_error_message(x,y,op)
2022
2023def coerce_cmp(x,y): 
2024    cdef int c
2025    try:
2026        x, y = canonical_coercion_c(x, y)
2027        return cmp(x,y)       
2028    except TypeError:
2029        c = cmp(type(x), type(y))
2030        if c == 0: c = -1
2031        return c
2032
2033
2034
2035###############################################################################
2036
2037def lcm(x,y):
2038    from sage.rings.arith import lcm
2039    return lcm(x,y)
2040
2041def gcd(x,y):
2042    from sage.rings.arith import gcd
2043    return gcd(x,y)
2044
2045def xgcd(x,y):
2046    from sage.rings.arith import xgcd
2047    return xgcd(x,y)
2048
2049
2050
2051
2052######################
2053
2054def generic_power(m, dummy):
2055    return generic_power_c(m, dummy)
2056
2057cdef generic_power_c(m, dummy):
2058    cdef int cn
2059
2060    n = int(m)
2061    if n != m:
2062        raise ValueError, "n must be an integer"
2063
2064    if n < 0:
2065        n = -n
2066        a = ~self
2067    else:
2068        a = self
2069
2070    if n < 4:
2071        # These cases will probably be called often
2072        # and don't benifit from the code below
2073        cn = n
2074        if cn == 0:
2075            return (<Element>a)._parent(1)
2076        elif cn == 1:
2077            return a
2078        elif cn == 2:
2079            return a*a
2080        elif cn == 3:
2081            return a*a*a
2082
2083    # One multiplication can be saved by starting with
2084    # the smallest power needed rather than with 1
2085    apow = a
2086    while n&1 == 0:
2087        apow = apow*apow
2088        n = n >> 1
2089    power = apow
2090    n = n >> 1
2091
2092    while n != 0:
2093        apow = apow*apow
2094        if n&1 != 0: power = power*apow
2095        n = n >> 1
2096
2097    return power
2098
Note: See TracBrowser for help on using the repository browser.