source: sage/rings/number_field/number_field.py @ 6778:3807f9188e2d

Revision 6778:3807f9188e2d, 163.9 KB checked in by David Roe <roed@…>, 6 years ago (diff)

big merge

Line 
1r"""
2Number Fields
3
4AUTHORS:
5   -- William Stein (2004, 2005): initial version
6   -- Steven Sivek (2006-05-12): added support for relative extensions
7   -- William Stein (2007-09-04): major rewrite and documentation
8
9NOTE:
10
11    Unlike in PARI/GP, class group computations *in SAGE* do *not* by
12    default assume the Generalized Riemann Hypothesis.  To do class
13    groups computations not provably correctly you must often pass the
14    flag proof=False to functions or call the function
15    \code{proof.number_field(False)}.  It can easily take 1000's of
16    times longer to do computations with \code{proof=True} (the
17    default).
18
19This example follows one in the Magma reference manual:
20    sage: K.<y> = NumberField(x^4 - 420*x^2 + 40000)
21    sage: z = y^5/11; z
22    420/11*y^3 - 40000/11*y
23    sage: R.<y> = PolynomialRing(K)
24    sage: f = y^2 + y + 1
25    sage: L.<a> = K.extension(f); L
26    Number Field in a with defining polynomial y^2 + y + 1 over its base field
27    sage: KL.<b> = NumberField([x^4 - 420*x^2 + 40000, x^2 + x + 1]); KL
28    Number Field in b0 with defining polynomial x^4 + (-420)*x^2 + 40000 over its base field
29
30We do some arithmetic in a tower of relative number fields:
31    sage: K.<cuberoot2> = NumberField(x^3 - 2)
32    sage: L.<cuberoot3> = K.extension(x^3 - 3)
33    sage: S.<sqrt2> = L.extension(x^2 - 2)
34    sage: S
35    Number Field in sqrt2 with defining polynomial x^2 + -2 over its base field
36    sage: sqrt2 * cuberoot3
37    cuberoot3*sqrt2
38    sage: (sqrt2 + cuberoot3)^5
39    (20*cuberoot3^2 + 15*cuberoot3 + 4)*sqrt2 + 3*cuberoot3^2 + 20*cuberoot3 + 60
40    sage: cuberoot2 + cuberoot3
41    cuberoot3 + cuberoot2
42    sage: cuberoot2 + cuberoot3 + sqrt2
43    sqrt2 + cuberoot3 + cuberoot2
44    sage: (cuberoot2 + cuberoot3 + sqrt2)^2
45    (2*cuberoot3 + 2*cuberoot2)*sqrt2 + cuberoot3^2 + 2*cuberoot2*cuberoot3 + cuberoot2^2 + 2
46    sage: cuberoot2 + sqrt2
47    sqrt2 + cuberoot2
48    sage: a = S(cuberoot2); a
49    cuberoot2
50    sage: a.parent()
51    Number Field in sqrt2 with defining polynomial x^2 + -2 over its base field
52
53WARNING: Doing arithmetic in towers of relative fields that depends on
54canonical coercions is currently VERY SLOW.  It is much better to
55explicitly coerce all elements into a common field, then do arithmetic
56with them there (which is quite fast).
57
58TESTS:
59    sage: y = polygen(QQ,'y'); K.<beta> = NumberField([y^3 - 3, y^2 - 2])
60    sage: K(y^10)
61    (-3024*beta1 + 1530)*beta0^2 + (-2320*beta1 + 5067)*beta0 + -3150*beta1 + 7592
62"""
63
64# TODO:
65#   * relative over relative
66
67#*****************************************************************************
68#       Copyright (C) 2004, 2005, 2006, 2007 William Stein <wstein@gmail.com>
69#
70#  Distributed under the terms of the GNU General Public License (GPL)
71#
72#    This code is distributed in the hope that it will be useful,
73#    but WITHOUT ANY WARRANTY; without even the implied warranty of
74#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
75#    General Public License for more details.
76#
77#  The full text of the GPL is available at:
78#
79#                  http://www.gnu.org/licenses/
80#*****************************************************************************
81
82from __future__ import with_statement
83from sage.structure.parent_gens import localvars
84
85# There will be one running instance of GP for all
86# number field calculations that use the interpreter.
87from sage.interfaces.gp import Gp
88
89import sage.libs.ntl.all as ntl
90import sage.libs.pari.all as pari
91import sage.interfaces.gap
92import sage.misc.preparser
93import sage.rings.arith
94
95import sage.rings.complex_field
96import sage.rings.real_mpfr
97import sage.rings.complex_double
98import sage.rings.real_double
99
100import sage.rings.ring
101from sage.misc.latex import latex_variable_name, latex_varify
102
103from class_group import ClassGroup
104from galois_group import GaloisGroup
105#import order
106
107from sage.structure.element import is_Element
108from sage.structure.sequence import Sequence
109
110import sage.structure.parent_gens
111
112from sage.structure.proof.proof import get_flag
113import maps
114
115def proof_flag(t):
116    """
117    Used for easily determining the correct proof flag to use.
118    """
119    return get_flag(t, "number_field")
120
121_gp = None
122def gp():
123    """
124    Return the unique copy of the gp (PARI) interpreter
125    used for number field computations.
126
127    EXAMPLES:
128        sage: from sage.rings.number_field.number_field import gp
129        sage: gp()
130        GP/PARI interpreter
131    """
132    global _gp
133    if not _gp is None:
134        return _gp
135    else:
136        _gp = Gp()
137        return _gp
138
139import operator
140
141import weakref
142
143from sage.misc.latex import latex
144
145import sage.rings.arith as arith
146import sage.rings.rational_field as rational_field
147import sage.rings.integer_ring as integer_ring
148import sage.rings.infinity as infinity
149import sage.rings.rational as rational
150import sage.rings.integer as integer
151import sage.rings.polynomial.polynomial_ring as polynomial_ring
152import sage.rings.polynomial.polynomial_element as polynomial_element
153import sage.rings.ideal as ideal
154import sage.rings.complex_field
155import sage.groups.abelian_gps.abelian_group
156
157from sage.structure.parent_gens import ParentWithGens
158import number_field_element
159import number_field_element_quadratic
160from number_field_ideal import convert_from_zk_basis, is_NumberFieldIdeal
161
162import sage.rings.number_field.number_field_ideal_rel
163
164from sage.libs.all import pari, pari_gen
165
166QQ = rational_field.RationalField()
167ZZ = integer_ring.IntegerRing()
168
169_nf_cache = {}
170def NumberField(polynomial, name=None, check=True, names=None, cache=True):
171    r"""
172    Return {\em the} number field defined by the given irreducible
173    polynomial and with variable with the given name.  If check is
174    True (the default), also verify that the defining polynomial is
175    irreducible and over Q.
176
177    INPUT:
178        polynomial -- a polynomial over QQ or a number field, or
179                      a list of polynomials.
180        name -- a string (default: 'a'), the name of the generator
181        check -- bool (default: True); do type checking and
182                 irreducibility checking.
183
184    EXAMPLES:
185        sage: z = QQ['z'].0
186        sage: K = NumberField(z^2 - 2,'s'); K
187        Number Field in s with defining polynomial z^2 - 2
188        sage: s = K.0; s
189        s
190        sage: s*s   
191        2
192        sage: s^2
193        2
194
195    EXAMPLES: Constructing a relative number field
196        sage: K.<a> = NumberField(x^2 - 2)
197        sage: R.<t> = K[]
198        sage: L.<b> = K.extension(t^3+t+a); L
199        Number Field in b with defining polynomial t^3 + t + a over its base field
200        sage: L.absolute_field('c')
201        Number Field in c with defining polynomial x^6 + 2*x^4 + x^2 - 2
202        sage: a*b
203        a*b
204        sage: L(a)
205        a
206        sage: L.lift_to_base(b^3 + b)
207        -a
208
209    Constructing another number field:
210        sage: k.<i> = NumberField(x^2 + 1)
211        sage: R.<z> = k[]
212        sage: m.<j> = NumberField(z^3 + i*z + 3)
213        sage: m
214        Number Field in j with defining polynomial z^3 + i*z + 3 over its base field
215   
216    Number fields are globally unique.
217        sage: K.<a>= NumberField(x^3-5)     
218        sage: a^3
219        5
220        sage: L.<a>= NumberField(x^3-5)
221        sage: K is L
222        True
223
224    Having different defining polynomials makes them fields different:
225        sage: x = polygen(QQ, 'x'); y = polygen(QQ, 'y')
226        sage: k.<a> = NumberField(x^2 + 3)
227        sage: m.<a> = NumberField(y^2 + 3)
228        sage: k
229        Number Field in a with defining polynomial x^2 + 3
230        sage: m
231        Number Field in a with defining polynomial y^2 + 3
232
233    An example involving a variable name that defines a function in
234    PARI:
235        sage: theta = polygen(QQ, 'theta')
236        sage: M.<z> = NumberField([theta^3 + 4, theta^2 + 3]); M
237        Number Field in z0 with defining polynomial theta^3 + 4 over its base field       
238    """
239    if name is None and names is None:
240        raise TypeError, "You must specify the name of the generator."
241    if not names is None:
242        name = names
243
244    if isinstance(polynomial, (list, tuple)):
245        return NumberFieldTower(polynomial, name)
246       
247    name = sage.structure.parent_gens.normalize_names(1, name)
248
249    if not isinstance(polynomial, polynomial_element.Polynomial):
250        try:
251            polynomial = polynomial.polynomial(QQ)
252        except (AttributeError, TypeError):
253            raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial)
254
255    #if all:
256    #    return [NumberField(f, name=name, check=check, names=names) for f, _ in polynomial.factor()]
257
258    if cache:
259        key = (polynomial, name)
260        if _nf_cache.has_key(key):
261            K = _nf_cache[key]()
262            if not K is None: return K
263
264    R = polynomial.base_ring()
265    if R == ZZ:
266        polynomial = QQ['x'](polynomial)
267    elif isinstance(R, NumberField_generic):
268        S = R.extension(polynomial, name, check=check)
269        if cache:
270            _nf_cache[key] = weakref.ref(S)
271        return S
272       
273    if polynomial.degree() == 2:
274        K = NumberField_quadratic(polynomial, name, check)
275    else:
276        K = NumberField_absolute(polynomial, name, None, check)
277
278    if cache:
279        _nf_cache[key] = weakref.ref(K)
280    return K
281
282
283def NumberFieldTower(v, names, check=True):
284    """
285    Return the tower of number fields defined by the polynomials or
286    number fields in the list v.
287
288    This is the field constructed first from v[0], then over that
289    field from v[1], etc.  If all is False, then each v[i] must be
290    irreducible over the previous fields.  Otherwise a list of all
291    possible fields defined by all those polynomials is output.
292   
293    If names defines a variable name a, say, then the generators of
294    the intermediate number fields are a0, a1, a2, ...
295
296    INPUT:
297        v -- a list of polynomials or number fields
298        names -- variable names
299        check -- bool (default: True) only relevant if all is False.
300               Then check irreducibility of each input polynomial.
301               
302    OUTPUT:
303        a single number field or a list of number fields
304
305    EXAMPLES:
306        sage: k.<a,b,c> = NumberField([x^2 + 1, x^2 + 3, x^2 + 5]); k
307        Number Field in a with defining polynomial x^2 + 1 over its base field
308        sage: a^2
309        -1
310        sage: b^2
311        -3
312        sage: c^2
313        -5
314        sage: (a+b+c)^2
315        (2*b + 2*c)*a + 2*c*b + -9
316
317    The Galois group is a product of 3 groups of order 2:
318        sage: k.galois_group()
319        Galois group PARI group [8, 1, 3, "E(8)=2[x]2[x]2"] of degree 8 of the number field Number Field in a with defining polynomial x^2 + 1 over its base field
320       
321
322    Repeatedly calling base_field allows us to descend the internally
323    constructed tower of fields:
324        sage: k.base_field()
325        Number Field in b with defining polynomial x^2 + 3 over its base field
326        sage: k.base_field().base_field()
327        Number Field in c with defining polynomial x^2 + 5
328        sage: k.base_field().base_field().base_field()
329        Rational Field
330
331    In the following examle the second polynomial reducible over the first, so
332    we get an error:
333        sage: v = NumberField([x^3 - 2, x^3 - 2], names='a')
334        Traceback (most recent call last):
335        ...
336        ValueError: defining polynomial (x^3 + -2) must be irreducible
337
338    We mix polynomial parent rings:
339        sage: k.<y> = QQ[]
340        sage: m = NumberField([y^3 - 3, x^2 + x + 1, y^3 + 2], 'beta')
341        sage: m
342        Number Field in beta0 with defining polynomial y^3 + -3 over its base field
343        sage: m.base_field ()
344        Number Field in beta1 with defining polynomial x^2 + x + 1 over its base field
345
346    A tower of quadratic fields:
347        sage: K.<a> = NumberField([x^2 + 3, x^2 + 2, x^2 + 1])
348        sage: K
349        Number Field in a0 with defining polynomial x^2 + 3 over its base field
350        sage: K.base_field()
351        Number Field in a1 with defining polynomial x^2 + 2 over its base field
352        sage: K.base_field().base_field()
353        Number Field in a2 with defining polynomial x^2 + 1
354
355    A bigger tower of quadratic fields.
356        sage: K.<a2,a3,a5,a7> = NumberField([x^2 + p for p in [2,3,5,7]]); K
357        Number Field in a2 with defining polynomial x^2 + 2 over its base field
358        sage: a2^2
359        -2
360        sage: a3^2
361        -3
362        sage: (a2+a3+a5+a7)^3
363        ((6*a5 + 6*a7)*a3 + 6*a7*a5 + -47)*a2 + (6*a7*a5 + -45)*a3 + (-41)*a5 + -37*a7
364    """
365    # there is an "all" option below -- we do not use it, since
366    # I couldn't get it to work with PARI reliably, and it isn't
367    # very useful in practice.
368    try:
369        names = sage.structure.parent_gens.normalize_names(len(v), names)
370    except IndexError:
371        names = sage.structure.parent_gens.normalize_names(1, names)
372        if len(v) > 1:
373            names = ['%s%s'%(names[0], i) for i in range(len(v))]
374   
375    if not isinstance(v, (list, tuple)):
376        raise TypeError, "v must be a list or tuple"
377    if len(v) == 0:
378        return QQ
379    if len(v) == 1:
380        #if all:
381        #    f = v[0]
382        #    if not isinstance(f, polynomial_element.Polynomial):
383        #        f = QQ['x'](v[0])
384        #    F = f.factor()
385        #    return [NumberField(F[i][0], names='%s%s'%(names[0],str(i))) for i in range(len(F))]
386        #else:
387        return NumberField(v[0], names=names)
388    f = v[0]
389    w = NumberFieldTower(v[1:], names=names[1:])
390    if isinstance(f, polynomial_element.Polynomial):
391        var = f.name()
392    else:
393        var = 'x'
394
395    name = names[0]
396    #if all:
397    #    R = w[0][var]  # polynomial ring           
398    #else:
399    R = w[var]  # polynomial ring   
400
401    f = R(f)
402    i = 0
403
404    sep = chr(ord(name[0]) + 1)
405    #if all:
406    #    z = []
407    #    for k in w:
408    #        for g, _ in f.factor():
409    #            z.append(k.extension(g, names='%s%s%s'%(name, sep, str(i)), check=False))
410    #            i += 1
411    #    return z
412    #else:
413    return w.extension(f, name, check=check)
414
415
416def QuadraticField(D, names, check=True):
417    """
418    Return a quadratic field obtained by adjoining a square root of
419    $D$ to the rational numbers, where $D$ is not a perfect square.
420
421    INPUT:
422        D -- a rational number
423        name -- variable name
424        check -- bool (default: True)
425
426    OUTPUT:
427        A number field defined by a quadratic polynomial.
428
429    EXAMPLES:
430        sage: QuadraticField(3, 'a')
431        Number Field in a with defining polynomial x^2 - 3
432        sage: K.<theta> = QuadraticField(3); K
433        Number Field in theta with defining polynomial x^2 - 3
434        sage: QuadraticField(9, 'a')
435        Traceback (most recent call last):
436        ...
437        ValueError: D must not be a perfect square.
438        sage: QuadraticField(9, 'a', check=False)
439        Number Field in a with defining polynomial x^2 - 9
440
441    Quadratic number fields derive from general number fields.
442        sage: type(K)
443        <class 'sage.rings.number_field.number_field.NumberField_quadratic'>
444        sage: is_NumberField(K)
445        True
446    """
447    D = QQ(D)
448    if check:
449        if D.is_square():
450            raise ValueError, "D must not be a perfect square."
451    R = polynomial_ring.PolynomialRing(QQ, 'x')
452    f = R([-D, 0, 1])
453    return NumberField(f, names, check=False)
454
455def is_AbsoluteNumberField(x):
456    """
457    Return True if x is an absolute number field.
458
459    EXAMPLES:
460        sage: is_AbsoluteNumberField(NumberField(x^2+1,'a'))
461        True
462        sage: is_AbsoluteNumberField(NumberField([x^3 + 17, x^2+1],'a'))
463        False
464
465    The rationals are a number field, but they're not of the absolute number field class.
466        sage: is_AbsoluteNumberField(QQ)
467        False
468    """
469    return isinstance(x, NumberField_absolute)
470
471def is_QuadraticField(x):
472    r"""
473    Return True if x is of the quadratic {\em number} field type.
474
475    EXAMPLES:
476        sage: is_QuadraticField(QuadraticField(5,'a'))
477        True
478        sage: is_QuadraticField(NumberField(x^2 - 5, 'b'))
479        True
480        sage: is_QuadraticField(NumberField(x^3 - 5, 'b'))
481        False
482
483    A quadratic field specially refers to a number field, not a finite
484    field:
485        sage: is_QuadraticField(GF(9,'a'))
486        False
487    """
488    return isinstance(x, NumberField_quadratic)
489
490def is_RelativeNumberField(x):
491    """
492    Return True if x is a relative number field.
493
494    EXAMPLES:
495        sage: is_RelativeNumberField(NumberField(x^2+1,'a'))
496        False
497        sage: k.<a> = NumberField(x^3 - 2)
498        sage: l.<b> = k.extension(x^3 - 3); l
499        Number Field in b with defining polynomial x^3 + -3 over its base field
500        sage: is_RelativeNumberField(l)
501        True
502        sage: is_RelativeNumberField(QQ)
503        False       
504    """
505    return isinstance(x, NumberField_relative)
506
507_cyclo_cache = {}
508def CyclotomicField(n, names=None):
509    r"""
510    Return the n-th cyclotomic field, where n is a positive integer.
511
512    INPUT:
513        n -- a positive integer
514        names -- name of generator (optional -- defaults to zetan).
515
516    EXAMPLES:
517    We create the $7$th cyclotomic field $\QQ(\zeta_7)$ with the
518    default generator name.
519        sage: k = CyclotomicField(7); k
520        Cyclotomic Field of order 7 and degree 6
521        sage: k.gen()
522        zeta7
523
524    Cyclotomic fields are of a special type.
525        sage: type(k)
526        <class 'sage.rings.number_field.number_field.NumberField_cyclotomic'>
527
528    We can specify a different generator name as follows.
529        sage: k.<z7> = CyclotomicField(7); k
530        Cyclotomic Field of order 7 and degree 6
531        sage: k.gen()
532        z7
533
534    The $n$ must be an integer.
535        sage: CyclotomicField(3/2)
536        Traceback (most recent call last):
537        ...
538        TypeError: no coercion of this rational to integer
539
540    The degree must be positive.
541        sage: CyclotomicField(0)
542        Traceback (most recent call last):
543        ...
544        ValueError: n (=0) must be a positive integer
545
546    The special case $n=1$ does \emph{not} return the rational numbers:
547        sage: CyclotomicField(1)
548        Cyclotomic Field of order 1 and degree 1   
549    """
550    n = ZZ(n)
551    if n <= 0:
552        raise ValueError, "n (=%s) must be a positive integer"%n
553   
554    if names is None:
555        names = "zeta%s"%n
556    names = sage.structure.parent_gens.normalize_names(1, names)
557    key = (n, names)
558    if _cyclo_cache.has_key(key):
559        K = _cyclo_cache[key]()
560        if not K is None: return K
561    K = NumberField_cyclotomic(n, names)
562    _cyclo_cache[key] = weakref.ref(K)
563    return K
564
565def is_CyclotomicField(x):
566    """
567    Return True if x is a cyclotomic field, i.e., of the special
568    cyclotomic field class.  This function does not return True
569    for a number field that just happens to be isomorphic to a
570    cyclotomic field.
571
572    EXAMPLES:
573        sage: is_CyclotomicField(NumberField(x^2 + 1,'zeta4'))
574        False
575        sage: is_CyclotomicField(CyclotomicField(4))
576        True
577        sage: is_CyclotomicField(CyclotomicField(1))
578        True
579        sage: is_CyclotomicField(QQ)
580        False
581        sage: is_CyclotomicField(7)
582        False
583    """
584    return isinstance(x, NumberField_cyclotomic)
585
586
587
588import number_field_base
589
590is_NumberField = number_field_base.is_NumberField
591
592class NumberField_generic(number_field_base.NumberField):
593    """
594    EXAMPLES:
595        sage: K.<a> = NumberField(x^3 - 2); K
596        Number Field in a with defining polynomial x^3 - 2
597        sage: loads(K.dumps()) == K
598        True
599    """
600    def __init__(self, polynomial, name,
601                 latex_name=None, check=True):
602        """
603        Create a number field.
604
605        EXAMPLES:
606            sage: NumberField(x^97 - 19, 'a')
607            Number Field in a with defining polynomial x^97 - 19
608
609        If you use check=False, you avoid checking irreducibility of
610        the defining polynomial, which can save time.
611            sage: K.<a> = NumberField(x^2 - 1, check=False)
612
613        It can also be dangerous:
614            sage: (a-1)*(a+1)
615            0       
616        """
617        ParentWithGens.__init__(self, QQ, name)
618        if not isinstance(polynomial, polynomial_element.Polynomial):
619            raise TypeError, "polynomial (=%s) must be a polynomial"%repr(polynomial)
620       
621        if check:
622            if not polynomial.is_irreducible():
623                raise ValueError, "defining polynomial (%s) must be irreducible"%polynomial
624            if not polynomial.parent().base_ring() == QQ:
625                raise TypeError, "polynomial must be defined over rational field"
626            if not polynomial.is_monic():
627                raise NotImplementedError, "number fields for non-monic polynomials not yet implemented."
628
629        self._assign_names(name)
630        if latex_name is None:
631            self.__latex_variable_name = latex_variable_name(self.variable_name())
632        else:
633            self.__latex_variable_name = latex_name
634        self.__polynomial = polynomial
635        self.__pari_bnf_certified = False
636
637    def _Hom_(self, codomain, cat=None):
638        """
639        Return homset of homomorphisms from self to the number field codomain.
640
641        The cat option is currently ignored.
642
643        EXAMPLES:
644        This function is implicitly caled by the Hom method or function.
645            sage: K.<i> = NumberField(x^2 + 1); K
646            Number Field in i with defining polynomial x^2 + 1
647            sage: K.Hom(K)
648            Automorphism group of Number Field in i with defining polynomial x^2 + 1
649            sage: Hom(K, QuadraticField(-1, 'b'))
650            Set of field embeddings from Number Field in i with defining polynomial x^2 + 1 to Number Field in b with defining polynomial x^2 + 1
651        """
652        import morphism
653        return morphism.NumberFieldHomset(self, codomain)
654
655    def _set_structure(self, from_self, to_self, unsafe_force_change=False):
656        # Note -- never call this on a cached number field, since
657        # that could eventually lead to problems.
658        if unsafe_force_change:
659            self.__from_self = from_self
660            self.__to_self = to_self
661            return
662        try:
663            self.__from_self
664        except AttributeError:
665            self.__from_self = from_self
666            self.__to_self = to_self
667        else:
668            raise ValueError, "number field structure is immutable."
669
670    def structure(self):
671        """
672        Return fixed isomorphism or embedding structure on self.
673
674        This is used to record various isomorphisms or embeddings
675        that arise naturally in other constructions.
676
677        EXAMPLES:
678            sage: K.<z> = NumberField(x^2 + 3)
679            sage: L.<a> = K.absolute_field(); L
680            Number Field in a with defining polynomial x^2 + 3
681            sage: L.structure()
682            (Number field isomorphism from Number Field in a with defining polynomial x^2 + 3 to Number Field in z with defining polynomial x^2 + 3 given by variable name change,
683             Number field isomorphism from Number Field in z with defining polynomial x^2 + 3 to Number Field in a with defining polynomial x^2 + 3 given by variable name change)
684        """
685        try:
686            if self.__to_self is not None:
687                return self.__from_self, self.__to_self
688            else:
689                return self.__from_self, self.__to_self
690        except AttributeError:
691            f = self.hom(self)
692            self._set_structure(f,f)
693            return f, f
694
695    def primitive_element(self):
696        r"""
697        Return a primitive element for this field, i.e., an element
698        that generates it over $\QQ$.
699
700        EXAMPLES:
701            sage: K.<a> = NumberField(x^3 + 2)
702            sage: K.primitive_element()
703            a
704            sage: K.<a,b,c> = NumberField([x^2-2,x^2-3,x^2-5])
705            sage: K.primitive_element()
706            a + (-1)*b + c
707            sage: alpha = K.primitive_element(); alpha
708            a + (-1)*b + c
709            sage: alpha.minpoly()
710            x^2 + (2*b + -2*c)*x + (-2*c)*b + 6
711            sage: alpha.absolute_minpoly()
712            x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576
713        """
714        try:
715            return self.__primitive_element
716        except AttributeError:
717            pass
718        K = self.absolute_field('a')
719        from_K, to_K = K.structure()
720        self.__primitive_element = from_K(K.gen())
721        return self.__primitive_element
722
723    def subfield(self, alpha, name=None):
724        r"""
725        Return an absolute number field K isomorphic to QQ(alpha) and
726        a map from K to self that sends the generator of K to alpha.
727
728        INPUT:
729            alpha -- an element of self, or something that coerces
730                     to an element of self.
731
732        OUTPUT:
733            K -- a number field
734            from_K -- a homomorphism from K to self that sends the
735                      generator of K to alpha.
736
737        EXAMPLES:
738            sage: K.<a> = NumberField(x^4 - 3); K
739            Number Field in a with defining polynomial x^4 - 3
740            sage: H, from_H = K.subfield(a^2, name='b')
741            sage: H
742            Number Field in b with defining polynomial x^2 - 3
743            sage: from_H(H.0)
744            a^2
745            sage: from_H
746            Ring morphism:
747              From: Number Field in b with defining polynomial x^2 - 3
748              To:   Number Field in a with defining polynomial x^4 - 3
749              Defn: b |--> a^2
750
751
752        You can also view a number field as having a different
753        generator by just chosing the input to generate the
754        whole filed; for that it is better to use
755        \code{self.change_generator}, which gives isomorphisms
756        in both directions.
757        """
758        if name is None:
759            name = self.variable_name() + '0'
760        beta = self(alpha)
761        f = beta.minpoly()
762        K = NumberField(f, names=name)
763        from_K = K.hom([beta])
764        return K, from_K
765
766    def change_generator(self, alpha, name=None):
767        r"""
768        Given the number field self, construct another isomorphic
769        number field $K$ generated by the element alpha of self, along
770        with isomorphisms from $K$ to self and from self to $K$.
771       
772        EXAMPLES:
773            sage: K.<i> = NumberField(x^2 + 1); K
774            Number Field in i with defining polynomial x^2 + 1
775            sage: L.<i> = NumberField(x^2 + 1); L
776            Number Field in i with defining polynomial x^2 + 1
777            sage: K, from_K, to_K = L.change_generator(i/2 + 3)
778            sage: K
779            Number Field in i0 with defining polynomial x^2 - 6*x + 37/4
780            sage: from_K
781            Ring morphism:
782              From: Number Field in i0 with defining polynomial x^2 - 6*x + 37/4
783              To:   Number Field in i with defining polynomial x^2 + 1
784              Defn: i0 |--> 1/2*i + 3
785            sage: to_K
786            Ring morphism:
787              From: Number Field in i with defining polynomial x^2 + 1
788              To:   Number Field in i0 with defining polynomial x^2 - 6*x + 37/4
789              Defn: i |--> 2*i0 - 6
790
791        We compute the image of the generator $\sqrt{-1}$ of $L$.
792            sage: to_K(L.0)
793            2*i0 - 6
794
795        Note that he image is indeed a square root of -1.
796            sage: to_K(L.0)^2
797            -1
798            sage: from_K(to_K(L.0))
799            i
800            sage: to_K(from_K(K.0))
801            i0
802        """
803        alpha = self(alpha)
804        K, from_K = self.subfield(alpha, name=name)
805        if K.degree() != self.degree():
806            raise ValueError, "alpha must generate a field of degree %s, but alpha generates a subfield of degree %s"%(self.degree(), K.degree())
807        # Now compute to_K, which is an isomorphism
808        # from self to K such that from_K(to_K(x)) == x for all x,
809        # and to_K(from_K(y)) == y.
810        # To do this, we must compute the image of self.gen()
811        # under to_K.   This means writing self.gen() as a
812        # polynomial in alpha, which is possible by the degree
813        # check above.  This latter we do by linear algebra.
814        phi = alpha.coordinates_in_terms_of_powers()
815        c = phi(self.gen())
816        to_K = self.hom([K(c)])
817        return K, from_K, to_K
818
819    def is_absolute(self):
820        raise NotImplementedError
821
822    def is_relative(self):
823        """
824        EXAMPLES:
825            sage: K.<a> = NumberField(x^10 - 2)
826            sage: K.is_absolute()
827            True
828            sage: K.is_relative()
829            False
830        """       
831        return not self.is_absolute()
832       
833    def absolute_field(self, names):
834        """
835        Returns self as an absolute extension over QQ.
836
837        OUTPUT:
838            K -- this number field (since it is already absolute)
839
840        Also, \code{K.structure()} returns from_K and to_K, where
841        from_K is an isomorphism from K to self and to_K is an isomorphism
842        from self to K.
843
844        EXAMPLES:
845            sage: K = CyclotomicField(5)
846            sage: K.absolute_field('a')
847            Number Field in a with defining polynomial x^4 + x^3 + x^2 + x + 1
848        """
849        try:
850            return self.__absolute_field[names]
851        except KeyError:
852            pass
853        except AttributeError:
854            self.__absolute_field = {}
855        K = NumberField(self.defining_polynomial(), names, cache=False)
856        K._set_structure(maps.NameChangeMap(K, self), maps.NameChangeMap(self, K))
857        self.__absolute_field[names] = K
858        return K
859
860    def is_isomorphic(self, other):
861        """
862        Return True if self is isomorphic as a number field to other.
863       
864        EXAMPLES:
865            sage: k.<a> = NumberField(x^2 + 1)
866            sage: m.<b> = NumberField(x^2 + 4)
867            sage: k.is_isomorphic(m)
868            True
869            sage: m.<b> = NumberField(x^2 + 5)
870            sage: k.is_isomorphic (m)
871            False
872
873            sage: k = NumberField(x^3 + 2, 'a')
874            sage: k.is_isomorphic(NumberField((x+1/3)^3 + 2, 'b'))
875            True
876            sage: k.is_isomorphic(NumberField(x^3 + 4, 'b'))
877            True
878            sage: k.is_isomorphic(NumberField(x^3 + 5, 'b'))
879            False           
880        """
881        if not isinstance(other, NumberField_generic):
882            raise ValueError, "other must be a generic number field."
883        t = self.pari_polynomial().nfisisom(other.pari_polynomial())
884        return t != 0
885
886    def complex_embeddings(self, prec=53):
887        r"""
888        Return all homomorphisms of this number field into the
889        approximate complex field with precision prec.
890
891        If prec is 53 (the default), then the complex double field is
892        used; otherwise the arbitrary precision (but slow) complex
893        field is used.  If you want 53-bit arbitrary precision then
894        do \code{self.embeddings(ComplexField(53))}.
895
896        EXAMPLES:
897            sage: k.<a> = NumberField(x^5 + x + 17)
898            sage: v = k.complex_embeddings()
899            sage: [phi(k.0^2) for phi in v] # random low order bits
900            [2.97572074038 + 1.73496602657e-16*I, -2.40889943716 + 1.90254105304*I, -2.40889943716 - 1.90254105304*I, 0.921039066973 + 3.07553311885*I, 0.921039066973 - 3.07553311885*I]
901            sage: K.<a> = NumberField(x^3 + 2)
902            sage: K.complex_embeddings() # random low order bits
903            [Ring morphism:
904              From: Number Field in a with defining polynomial x^3 + 2
905              To:   Complex Double Field
906              Defn: a |--> -1.25992104989 - 3.88578058619e-16*I,
907            ...]
908            sage: K.complex_embeddings(100)
909            [Ring morphism:
910              From: Number Field in a with defining polynomial x^3 + 2
911              To:   Complex Field with 100 bits of precision
912              Defn: a |--> -1.2599210498948731647672106073,
913            ...]
914        """
915        if prec == 53:
916            CC = sage.rings.complex_double.CDF
917        else:
918            CC = sage.rings.complex_field.ComplexField(prec)
919        return self.embeddings(CC)
920
921    def real_embeddings(self, prec=53):
922        r"""
923        Return all homomorphisms of this number field into the
924        approximate real field with precision prec.
925
926        If prec is 53 (the default), then the real double field is
927        used; otherwise the arbitrary precision (but slow) real field
928        is used.
929
930        EXAMPLES:
931            sage: K.<a> = NumberField(x^3 + 2)
932            sage: K.real_embeddings()
933            [Ring morphism:
934              From: Number Field in a with defining polynomial x^3 + 2
935              To:   Real Double Field
936              Defn: a |--> -1.25992104989]
937            sage: K.real_embeddings(16)
938            [Ring morphism:
939              From: Number Field in a with defining polynomial x^3 + 2
940              To:   Real Field with 16 bits of precision
941              Defn: a |--> -1.260]
942            sage: K.real_embeddings(100)
943            [Ring morphism:
944              From: Number Field in a with defining polynomial x^3 + 2
945              To:   Real Field with 100 bits of precision
946              Defn: a |--> -1.2599210498948731647672106073]
947        """
948        if prec == 53:
949            K = sage.rings.real_double.RDF
950        else:
951            K = sage.rings.real_mpfr.RealField(prec)
952        return self.embeddings(K)
953
954    def latex_variable_name(self, name=None):
955        """
956        Return the latex representation of the variable name for
957        this number field.
958
959        EXAMPLES:
960            sage: NumberField(x^2 + 3, 'a').latex_variable_name()
961            'a'
962            sage: NumberField(x^3 + 3, 'theta3').latex_variable_name()
963            '\\theta_{3}'
964            sage: CyclotomicField(5).latex_variable_name()
965            '\\zeta_{5}'
966        """
967        if name is None:
968            return self.__latex_variable_name
969        else:
970            self.__latex_variable_name = name
971
972    def _repr_(self):
973        """
974        Return string representation of this number field.
975
976        EXAMPLES:
977            sage: k.<a> = NumberField(x^13 - (2/3)*x + 3)
978            sage: k._repr_()
979            'Number Field in a with defining polynomial x^13 - 2/3*x + 3'       
980        """
981        return "Number Field in %s with defining polynomial %s"%(
982                   self.variable_name(), self.polynomial())
983
984    def _latex_(self):
985        r"""
986        Return latex representation of this number field.  This is viewed
987        as a polynomial quotient ring over a field.
988
989        EXAMPLES:
990            sage: k.<a> = NumberField(x^13 - (2/3)*x + 3)
991            sage: k._latex_()
992            '\\mathbf{Q}[a]/(a^{13} - \\frac{2}{3}a + 3)'
993            sage: latex(k)
994            \mathbf{Q}[a]/(a^{13} - \frac{2}{3}a + 3)
995
996        Numbered variables are often correctly typeset:
997            sage: k.<theta25> = NumberField(x^25+x+1)
998            sage: print k._latex_()
999            \mathbf{Q}[\theta_{25}]/(\theta_{25}^{25} + \theta_{25} + 1)           
1000        """
1001        return "%s[%s]/(%s)"%(latex(QQ), self.latex_variable_name(),
1002                              self.polynomial()._latex_(self.latex_variable_name()))
1003
1004    def __call__(self, x):
1005        """
1006        Coerce x into this number field.
1007
1008        EXAMPLES:
1009            sage: K.<a> = NumberField(x^3 + 17)
1010            sage: K(a) is a
1011            True
1012            sage: K('a^2 + 2/3*a + 5')
1013            a^2 + 2/3*a + 5
1014            sage: K('1').parent()
1015            Number Field in a with defining polynomial x^3 + 17
1016            sage: K(3/5).parent()
1017            Number Field in a with defining polynomial x^3 + 17       
1018        """
1019        if isinstance(x, number_field_element.NumberFieldElement):
1020            if x.parent() is self:
1021                return x
1022            elif x.parent() == self:
1023                return self._element_class(self, x.polynomial())
1024            elif isinstance(x, number_field_element.OrderElement_absolute) or isinstance(x, number_field_element.OrderElement_relative):
1025                if x.parent().number_field() is self:
1026                    return self._element_class(self, x)
1027                x = x.parent().number_field()(x)
1028            return self._coerce_from_other_number_field(x)
1029        elif isinstance(x,str):
1030            return self._coerce_from_str(x)
1031        return self._coerce_non_number_field_element_in(x)
1032
1033    def _coerce_from_str(self, x):
1034        """
1035        Coerce a string representation of an element of this
1036        number field into this number field.
1037
1038        INPUT:
1039            x -- string
1040
1041        EXAMPLES:
1042            sage: k.<theta25> = NumberField(x^3+(2/3)*x+1)
1043            sage: k._coerce_from_str('theta25^3 + (1/3)*theta25')
1044            -1/3*theta25 - 1
1045
1046        This function is called by the coerce method when it gets a string
1047        as input:
1048            sage: k('theta25^3 + (1/3)*theta25')
1049            -1/3*theta25 - 1       
1050        """
1051        # provide string coercion, as
1052        # for finite fields
1053        w = sage.misc.all.sage_eval(x,locals=\
1054                                  {self.variable_name():self.gen()})
1055        if not (is_Element(w) and w.parent() is self):
1056            return self(w)
1057        else:
1058            return w       
1059
1060    def _coerce_from_other_number_field(self, x):
1061        """
1062        Coerce a number field element x into this number field.
1063
1064        In most cases this currently doesn't work (since it is
1065        barely implemented) -- it only works for constants.
1066
1067        INPUT:
1068            x -- an element of some number field
1069
1070        EXAMPLES:
1071            sage: K.<a> = NumberField(x^3 + 2)
1072            sage: L.<b> = NumberField(x^2 + 1)
1073            sage: K._coerce_from_other_number_field(L(2/3))
1074            2/3       
1075        """
1076        f = x.polynomial()
1077        if f.degree() <= 0:
1078            return self._element_class(self, f[0])
1079        # todo: more general coercion if embedding have been asserted
1080        raise TypeError, "Cannot coerce %s into %s"%(x,self)       
1081   
1082    def _coerce_non_number_field_element_in(self, x):
1083        """
1084        Coerce a non-number field element x into this number field.
1085
1086        INPUT:
1087            x -- a non number field element x, e.g., a list, integer,
1088            rational, or polynomial.
1089
1090        EXAMPLES:
1091            sage: K.<a> = NumberField(x^3 + 2/3)
1092            sage: K._coerce_non_number_field_element_in(-7/8)
1093            -7/8
1094            sage: K._coerce_non_number_field_element_in([1,2,3])
1095            3*a^2 + 2*a + 1
1096
1097        The list is just turned into a polynomial in the generator.
1098            sage: K._coerce_non_number_field_element_in([0,0,0,1,1])
1099            -2/3*a - 2/3
1100
1101        Not any polynomial coerces in, e.g., not this one in characteristic 7.
1102            sage: f = GF(7)['y']([1,2,3]); f
1103            3*y^2 + 2*y + 1
1104            sage: K._coerce_non_number_field_element_in(f)
1105            Traceback (most recent call last):
1106            ...
1107            TypeError
1108        """
1109        if isinstance(x, (int, long, rational.Rational,
1110                              integer.Integer, pari_gen,
1111                              list)):
1112            return self._element_class(self, x)
1113       
1114        try:
1115            if isinstance(x, polynomial_element.Polynomial):
1116                return self._element_class(self, x)
1117           
1118            return self._element_class(self, x._rational_())
1119        except (TypeError, AttributeError), msg:
1120            pass
1121        raise TypeError
1122
1123    def _coerce_impl(self, x):
1124        """
1125        Canonical coercion of x into self.
1126
1127        Currently integers, rationals, and this field itself coerce
1128        canonical into this field.
1129
1130        EXAMPLES:
1131            sage: S.<y> = NumberField(x^3 + x + 1)
1132            sage: S._coerce_impl(int(4))
1133            4
1134            sage: S._coerce_impl(long(7))
1135            7
1136            sage: S._coerce_impl(-Integer(2))
1137            -2
1138            sage: z = S._coerce_impl(-7/8); z, type(z)
1139            (-7/8, <type 'sage.rings.number_field.number_field_element.NumberFieldElement_absolute'>)
1140            sage: S._coerce_impl(y) is y
1141            True
1142
1143        There are situations for which one might imagine canonical
1144        coercion could make sense (at least after fixing choices), but
1145        which aren't yet implemented:
1146            sage: K.<a> = QuadraticField(2)
1147            sage: K._coerce_impl(sqrt(2))
1148            Traceback (most recent call last):
1149            ...
1150            TypeError
1151        """
1152        if isinstance(x, (rational.Rational, integer.Integer, int, long)):
1153            return self._element_class(self, x)
1154        elif isinstance(x, number_field_element.NumberFieldElement):
1155            from sage.rings.number_field.order import is_NumberFieldOrder
1156            if x.parent() is self:
1157                return x
1158            elif is_NumberFieldOrder(x.parent()) and x.parent().number_field() is self:
1159                return self._element_class(self, x.polynomial())
1160            elif x.parent() == self:
1161                return self._element_class(self, x.list())
1162        raise TypeError
1163
1164    def category(self):
1165        """
1166        Return the category of number fields.
1167
1168        EXAMPLES:
1169            sage: NumberField(x^2 + 3, 'a').category()
1170            Category of number fields
1171            sage: category(NumberField(x^2 + 3, 'a'))
1172            Category of number fields
1173
1174        The special types of number fields, e.g., quadratic fields,
1175        don't have their own category:
1176            sage: QuadraticField(2,'d').category()
1177            Category of number fields
1178        """
1179        from sage.categories.all import NumberFields
1180        return NumberFields()
1181
1182    def __cmp__(self, other):
1183        """
1184        Compare a number field with something else.
1185
1186        INPUT:
1187            other -- arbitrary Python object.
1188           
1189        If other is not a number field, then the types of self and
1190        other are compared.  If both are number fields, then the
1191        variable names are compared.  If those are the same, then the
1192        underlying defining polynomials are compared.  If the
1193        polynomials are the same, the number fields are considered
1194        ``equal'', but need not be identical.  Coercion between equal
1195        number fields is allowed. 
1196
1197        EXAMPLES:
1198            sage: k.<a> = NumberField(x^3 + 2); m.<b> = NumberField(x^3 + 2)
1199            sage: cmp(k,m)
1200            -1
1201            sage: cmp(m,k)
1202            1
1203            sage: k == QQ
1204            False
1205            sage: k.<a> = NumberField(x^3 + 2); m.<a> = NumberField(x^3 + 2)
1206            sage: k is m
1207            True
1208            sage: m = loads(dumps(k))
1209            sage: k is m
1210            False
1211            sage: k == m
1212            True       
1213        """
1214        if not isinstance(other, NumberField_generic):
1215            return cmp(type(self), type(other))
1216        c = cmp(self.variable_name(), other.variable_name())
1217        if c: return c
1218        return cmp(self.__polynomial, other.__polynomial)
1219
1220    def _ideal_class_(self):
1221        """
1222        Return the Python class used in defining ideals of the ring of
1223        integes of this number field.
1224
1225        This function is required by the general ring/ideal machinery.
1226
1227        EXAMPLES:
1228            sage: NumberField(x^2 + 2, 'c')._ideal_class_()
1229            <class 'sage.rings.number_field.number_field_ideal.NumberFieldIdeal'>
1230        """
1231        return sage.rings.number_field.number_field_ideal.NumberFieldIdeal
1232
1233    def ideal(self, *gens, **kwds):
1234        r"""
1235        Return the ideal in $\mathcal{O}_K$ generated by gens.  This
1236        overrides the \code{sage.rings.ring.Field} method to use the
1237        \code{sage.rings.ring.Ring} one instead, since we're not really
1238        concerned with ideals in a field but in its ring of integers.
1239
1240        INPUT:
1241            gens -- a list of generators, or a number field ideal.
1242
1243        EXAMPLES:
1244            sage: K.<a> = NumberField(x^3-2)
1245            sage: K.ideal([a])
1246            Fractional ideal (a) of Number Field in a with defining polynomial x^3 - 2
1247
1248        One can also input in a number field ideal itself.
1249            sage: K.ideal(K.ideal(a))
1250            Fractional ideal (a) of Number Field in a with defining polynomial x^3 - 2
1251        """
1252        if len(gens) == 1 and isinstance(gens[0], (list, tuple)):
1253            gens = gens[0]
1254        if len(gens) == 1 and is_NumberFieldIdeal(gens[0]):
1255            I = gens[0]
1256            if I.number_field() == self:
1257                return I
1258            else:
1259                gens = I.gens()
1260        return sage.rings.ring.Ring.ideal(self, gens, **kwds)
1261
1262    def _is_valid_homomorphism_(self, codomain, im_gens):
1263        """
1264        Return whether or not there is a homomorphism defined by the
1265        given images of generators.
1266
1267        To do this we just check that the elements of the image of the
1268        given generator (im_gens always has length 1) satisfies the
1269        relation of the defining poly of this field.
1270
1271        EXAMPLES:
1272            sage: k.<a> = NumberField(x^2 - 3)
1273            sage: k._is_valid_homomorphism_(QQ, [0])
1274            False
1275            sage: k._is_valid_homomorphism_(k, [])
1276            False
1277            sage: k._is_valid_homomorphism_(k, [a])
1278            True
1279            sage: k._is_valid_homomorphism_(k, [-a])
1280            True
1281            sage: k._is_valid_homomorphism_(k, [a+1])
1282            False       
1283        """
1284        try:
1285            if len(im_gens) != 1:
1286                return False
1287            # We need that elements of the base ring of the polynomial
1288            # ring map canonically into codomain.
1289            codomain._coerce_(rational.Rational(1))
1290            f = self.defining_polynomial()
1291            return codomain(f(im_gens[0])) == 0
1292        except (TypeError, ValueError):
1293            return False
1294
1295    def pari_polynomial(self):
1296        """
1297        PARI polynomial corresponding to polynomial that defines
1298        this field.   This is always a polynomial in the variable "x".
1299
1300        EXAMPLES:
1301            sage: y = polygen(QQ)
1302            sage: k.<a> = NumberField(y^2 - 3/2*y + 5/3)
1303            sage: k.pari_polynomial()
1304            x^2 - 3/2*x + 5/3       
1305        """
1306        try:
1307            return self.__pari_polynomial
1308        except AttributeError:
1309            poly = self.polynomial()
1310            with localvars(poly.parent(), 'x'):
1311                self.__pari_polynomial = poly._pari_()
1312            return self.__pari_polynomial
1313
1314    def pari_nf(self):
1315        """
1316        PARI number field corresponding to this field.
1317
1318        This is the number field constructed using nfinit.
1319        This is the same as the number field got by doing
1320        pari(self) or gp(self).
1321
1322        EXAMPLES:
1323            sage: k.<a> = NumberField(x^4 - 3*x + 7); k
1324            Number Field in a with defining polynomial x^4 - 3*x + 7
1325            sage: k.pari_nf()[:4]
1326            [x^4 - 3*x + 7, [0, 2], 85621, 1]
1327            sage: pari(k)[:4]
1328            [x^4 - 3*x + 7, [0, 2], 85621, 1]       
1329
1330            sage: k.<a> = NumberField(x^4 - 3/2*x + 5/3); k
1331            Number Field in a with defining polynomial x^4 - 3/2*x + 5/3
1332            sage: k.pari_nf()
1333            Traceback (most recent call last):
1334            ...
1335            TypeError: Unable to coerce number field defined by non-integral polynomial to PARI.
1336            sage: pari(k)
1337            Traceback (most recent call last):
1338            ...
1339            TypeError: Unable to coerce number field defined by non-integral polynomial to PARI.
1340            sage: gp(k)
1341            Traceback (most recent call last):
1342            ...
1343            TypeError: Unable to coerce number field defined by non-integral polynomial to PARI.
1344        """
1345        if self.defining_polynomial().denominator() != 1:
1346            raise TypeError, "Unable to coerce number field defined by non-integral polynomial to PARI."
1347        try:
1348            return self.__pari_nf
1349        except AttributeError:
1350            f = self.pari_polynomial()
1351            self.__pari_nf = f.nfinit()
1352            return self.__pari_nf
1353
1354    def _pari_init_(self):
1355        """
1356        Needed for conversion of number field to PARI.
1357
1358        This only works if the defining polynomial of this number
1359        field is integral and monic.
1360       
1361        EXAMPLES:
1362            sage: k = NumberField(x^2 + x + 1, 'a')
1363            sage: k._pari_init_()
1364            'nfinit(x^2 + x + 1)'
1365            sage: k._pari_()
1366            [x^2 + x + 1, [0, 1], -3, 1, ... [1, x], [1, 0; 0, 1], [1, 0, 0, -1; 0, 1, 1, -1]]
1367            sage: pari(k)
1368            [x^2 + x + 1, [0, 1], -3, 1, ...[1, x], [1, 0; 0, 1], [1, 0, 0, -1; 0, 1, 1, -1]]
1369        """
1370        if self.defining_polynomial().denominator() != 1:
1371            raise TypeError, "Unable to coerce number field defined by non-integral polynomial to PARI."
1372        return 'nfinit(%s)'%self.pari_polynomial()
1373
1374    def pari_bnf(self, certify=False, units=True):
1375        """
1376        PARI big number field corresponding to this field.
1377
1378        EXAMPLES:
1379            sage: k.<a> = NumberField(x^2 + 1); k
1380            Number Field in a with defining polynomial x^2 + 1
1381            sage: len(k.pari_bnf())
1382            10
1383            sage: k.pari_bnf()[:4]
1384            [[;], matrix(0,7), [;], ...]
1385            sage: len(k.pari_nf())
1386            9       
1387        """
1388        if self.defining_polynomial().denominator() != 1:
1389            raise TypeError, "Unable to coerce number field defined by non-integral polynomial to PARI."
1390        try:
1391            if certify:
1392                self.pari_bnf_certify()
1393            return self.__pari_bnf
1394        except AttributeError:
1395            f = self.pari_polynomial()
1396            if units:
1397                self.__pari_bnf = f.bnfinit(1)
1398            else:
1399                self.__pari_bnf = f.bnfinit()
1400            if certify:
1401                self.pari_bnf_certify()
1402            return self.__pari_bnf
1403
1404    def pari_bnf_certify(self):
1405        """
1406        Run the PARI bnfcertify function to ensure the correctness of answers.
1407
1408        If this function returns True (and doesn't raise a
1409        ValueError), then certification succeeded, and results that
1410        use the PARI bnf structure with this field are supposed to be
1411        correct.
1412
1413        WARNING: I wouldn't trust this to mean that everything
1414        computed involving this number field is actually correct.
1415
1416        EXAMPLES:
1417            sage: k.<a> = NumberField(x^7 + 7); k
1418            Number Field in a with defining polynomial x^7 + 7
1419            sage: k.pari_bnf_certify()
1420            True
1421        """
1422        if self.defining_polynomial().denominator() != 1:
1423            raise TypeError, "Unable to coerce number field defined by non-integral polynomial to PARI."
1424        if not self.__pari_bnf_certified:
1425            if self.pari_bnf(certify=False, units=True).bnfcertify() != 1:
1426                raise ValueError, "The result is not correct according to bnfcertify"
1427            self.__pari_bnf_certified = True
1428        return self.__pari_bnf_certified
1429
1430    def characteristic(self):
1431        """
1432        Return the characteristic of this number field, which is
1433        of course 0.
1434
1435        EXAMPLES:
1436            sage: k.<a> = NumberField(x^99 + 2); k
1437            Number Field in a with defining polynomial x^99 + 2
1438            sage: k.characteristic()
1439            0       
1440        """
1441        return 0
1442
1443    def class_group(self, proof=None, names='c'):
1444        r"""
1445        Return the class group of the ring of integers of this number field.
1446
1447        INPUT:
1448            proof -- if True then compute the classgroup provably correctly.
1449                     Default is True.  Call number_field_proof to change
1450                     this default globally.
1451            names -- names of the generators of this class group.
1452
1453        OUTPUT:
1454            The class group of this number field.
1455           
1456        EXAMPLES:
1457            sage: K.<a> = NumberField(x^2 + 23)
1458            sage: G = K.class_group(); G
1459            Class group of order 3 with structure C3 of Number Field in a with defining polynomial x^2 + 23
1460            sage: G.0
1461            Fractional ideal class (2, 1/2*a - 1/2) of Number Field in a with defining polynomial x^2 + 23
1462            sage: G.gens()
1463            [Fractional ideal class (2, 1/2*a - 1/2) of Number Field in a with defining polynomial x^2 + 23]
1464
1465            sage: G.number_field()
1466            Number Field in a with defining polynomial x^2 + 23
1467            sage: G is K.class_group()
1468            True
1469            sage: G is K.class_group(proof=False)
1470            False
1471            sage: G.gens()
1472            [Fractional ideal class (2, 1/2*a - 1/2) of Number Field in a with defining polynomial x^2 + 23]
1473
1474        There can be multiple generators:
1475            sage: k.<a> = NumberField(x^2 + 20072)
1476            sage: G = k.class_group(); G
1477            Class group of order 76 with structure C38 x C2 of Number Field in a with defining polynomial x^2 + 20072
1478            sage: G.gens()
1479            [Fractional ideal class (41, a + 10) of Number Field in a with defining polynomial x^2 + 20072, Fractional ideal class (2, -1/2*a) of Number Field in a with defining polynomial x^2 + 20072]
1480            sage: G.0
1481            Fractional ideal class (41, a + 10) of Number Field in a with defining polynomial x^2 + 20072
1482            sage: G.0^20
1483            Fractional ideal class (43, a + 3) of Number Field in a with defining polynomial x^2 + 20072
1484            sage: G.0^38
1485            Trivial principal fractional ideal class of Number Field in a with defining polynomial x^2 + 20072
1486            sage: G.1
1487            Fractional ideal class (2, -1/2*a) of Number Field in a with defining polynomial x^2 + 20072
1488            sage: G.1^2
1489            Trivial principal fractional ideal class of Number Field in a with defining polynomial x^2 + 20072
1490
1491        Class groups of Hecke polynomials tend to be very small:
1492            sage: f = ModularForms(97, 2).T(2).charpoly()
1493            sage: f.factor()
1494            (x - 3) * (x^3 + 4*x^2 + 3*x - 1) * (x^4 - 3*x^3 - x^2 + 6*x - 1)
1495            sage: for g,_ in f.factor(): print NumberField(g,'a').class_group().order()
1496            ...
1497            1
1498            1
1499            1
1500        """
1501        proof = proof_flag(proof)
1502        try:
1503            return self.__class_group[proof, names]
1504        except KeyError:
1505            pass
1506        except AttributeError:
1507            self.__class_group = {}
1508        k = self.pari_bnf(proof)
1509        cycle_structure = eval(str(k.getattr('clgp.cyc')))
1510
1511        # First gens is a pari list of pari gens
1512        gens = k.getattr('clgp.gen')
1513        R    = self.polynomial_ring()
1514
1515        # Next gens is a list of ideals.
1516        gens = [self.ideal([self(R(convert_from_zk_basis(self, y))) for y in x]) for x in gens]
1517       
1518        G    = ClassGroup(cycle_structure, names, self, gens)       
1519        self.__class_group[proof,names] = G
1520        return G
1521
1522    def class_number(self, proof=None):
1523        """
1524        Return the class number of this number field, as an integer.
1525
1526        INPUT:
1527            proof -- bool (default: True unless you called number_field_proof)
1528
1529        EXAMPLES:
1530            sage: NumberField(x^2 + 23, 'a').class_number()
1531            3
1532            sage: NumberField(x^2 + 163, 'a').class_number()
1533            1
1534            sage: NumberField(x^3 + x^2 + 997*x + 1, 'a').class_number(proof=False)
1535            1539
1536        """
1537        proof = proof_flag(proof)       
1538        return self.class_group(proof).order()
1539
1540    def composite_fields(self, other, names=None):
1541        """
1542        List of all possible composite number fields formed from self
1543        and other.
1544
1545        INPUT:
1546            other -- a number field
1547            names -- generator name for composite fields
1548
1549        OUTPUT:
1550            list -- list of the composite fields.
1551
1552        EXAMPLES:
1553            sage: K.<a> = NumberField(x^4 - 2)
1554            sage: K.composite_fields(K)
1555            [Number Field in a0 with defining polynomial x^4 - 162,
1556             Number Field in a1 with defining polynomial x^4 - 2,
1557             Number Field in a2 with defining polynomial x^8 + 28*x^4 + 2500]
1558            sage: k.<a> = NumberField(x^3 + 2)
1559            sage: m.<b> = NumberField(x^3 + 2)
1560            sage: k.composite_fields(m, 'c')
1561            [Number Field in c0 with defining polynomial x^3 - 2,
1562             Number Field in c1 with defining polynomial x^6 - 40*x^3 + 1372]
1563        """
1564        if names is None:
1565            sv = self.variable_name(); ov = other.variable_name()
1566            names = sv + (ov if ov != sv else "")
1567        if not isinstance(other, NumberField_generic):
1568            raise TypeError, "other must be a number field."
1569        f = self.pari_polynomial()
1570        g = other.pari_polynomial()
1571        C = f.polcompositum(g)
1572        R = self.polynomial().parent()
1573        C = [R(h) for h in C]
1574        if len(C) == 1:
1575            return [NumberField(C[0], names)]
1576        else:
1577            name = sage.structure.parent_gens.normalize_names(1, names)[0]
1578            return [NumberField(C[i], name + str(i)) for i in range(len(C))]
1579
1580    def absolute_degree(self):
1581        return self.polynomial().degree()
1582           
1583    def degree(self):
1584        """
1585        Return the degree of this number field.
1586
1587        EXAMPLES:
1588            sage: NumberField(x^3 + x^2 + 997*x + 1, 'a').degree()
1589            3
1590            sage: NumberField(x + 1, 'a').degree()
1591            1
1592            sage: NumberField(x^997 + 17*x + 3, 'a', check=False).degree()
1593            997
1594        """
1595        return self.polynomial().degree()
1596
1597    def different(self):
1598        r"""
1599        Compute the different fractional ideal of this number field.
1600
1601        The different is the set of all $x$ in $K$ such that the trace
1602        of $xy$ is an integer for all $y \in O_K$.
1603
1604        EXAMPLES:
1605            sage: k.<a> = NumberField(x^2 + 23)
1606            sage: d = k.different()
1607            sage: d        # random sign in output
1608            Fractional ideal (-a) of Number Field in a with defining polynomial x^2 + 23
1609            sage: d.norm()
1610            23
1611            sage: k.disc()
1612            -23
1613
1614        The different is cached:
1615            sage: d is k.different()
1616            True
1617
1618        Another example:
1619            sage: k.<b> = NumberField(x^2 - 123)
1620            sage: d = k.different(); d
1621            Fractional ideal (2*b) of Number Field in b with defining polynomial x^2 - 123
1622            sage: d.norm()
1623            492
1624            sage: k.disc()
1625            492
1626        """
1627        try:
1628            return self.__different
1629       
1630        except AttributeError:
1631           
1632            diff = self.pari_nf().getattr('diff')
1633            zk_basis = self.pari_nf().getattr('zk')
1634            basis_elts = zk_basis * diff
1635            R = self.polynomial().parent()
1636            self.__different = self.ideal([ self(R(x)) for x in basis_elts ])
1637            return self.__different
1638
1639    def discriminant(self, v=None):
1640        """
1641        Returns the discriminant of the ring of integers of the number field,
1642        or if v is specified, the determinant of the trace pairing
1643        on the elements of the list v.
1644
1645        INPUT:
1646            v (optional) -- list of element of this number field
1647        OUTPUT:
1648            Integer if v is omitted, and Rational otherwise.
1649
1650        EXAMPLES:
1651            sage: K.<t> = NumberField(x^3 + x^2 - 2*x + 8)
1652            sage: K.disc()
1653            -503
1654            sage: K.disc([1, t, t^2])
1655            -2012
1656            sage: K.disc([1/7, (1/5)*t, (1/3)*t^2])
1657            -2012/11025
1658            sage: (5*7*3)^2
1659            11025
1660        """
1661        if v == None:
1662            try:
1663                return self.__disc
1664            except AttributeError:
1665                self.__disc = ZZ(str(self.pari_polynomial().nfdisc()))
1666                return self.__disc
1667        else:
1668            return QQ(self.trace_pairing(v).det())
1669
1670    def disc(self, v=None):
1671        """
1672        Shortcut for self.discriminant.
1673
1674        EXAMPLES:
1675            sage: k.<b> = NumberField(x^2 - 123)
1676            sage: k.disc()
1677            492
1678        """
1679        return self.discriminant(v=v)
1680
1681    def elements_of_norm(self, n, proof=None):
1682        r"""
1683        Return a list of solutions modulo units of positive norm to
1684        $Norm(a) = n$, where a can be any integer in this number field.
1685
1686        INPUT:
1687            proof -- default: True, unless you called number_field_proof and
1688            set it otherwise.
1689
1690        EXAMPLES:
1691            sage: K.<a> = NumberField(x^2+1)
1692            sage: K.elements_of_norm(3)
1693            []
1694            sage: K.elements_of_norm(50)
1695            [7*a - 1, -5*a + 5, a - 7]           # 32-bit
1696            [7*a - 1, -5*a + 5, -7*a - 1]        # 64-bit
1697        """
1698        proof = proof_flag(proof)       
1699        B = self.pari_bnf(proof).bnfisintnorm(n)
1700        R = self.polynomial().parent()
1701        return [self(QQ['x'](R(g))) for g in B]
1702
1703    def extension(self, poly, name=None, names=None, check=True):
1704        """
1705        Return the relative extension of this field by a given polynomial.
1706
1707        EXAMPLES:
1708            sage: K.<a> = NumberField(x^3 - 2)
1709            sage: R.<t> = K[]
1710            sage: L.<b> = K.extension(t^2 + a); L
1711            Number Field in b with defining polynomial t^2 + a over its base field
1712           
1713        We create another extension.
1714            sage: k.<a> = NumberField(x^2 + 1); k
1715            Number Field in a with defining polynomial x^2 + 1
1716            sage: y = var('y')
1717            sage: m.<b> = k.extension(y^2 + 2); m
1718            Number Field in b with defining polynomial y^2 + 2 over its base field
1719           
1720        Note that b is a root of $y^2 + 2$:
1721            sage: b.minpoly()
1722            x^2 + 2
1723            sage: b.minpoly('z')
1724            z^2 + 2
1725
1726        A relative extension of a relative extension.
1727            sage: k.<a> = NumberField([x^2 + 1, x^3 + x + 1])
1728            sage: R.<z> = k[]
1729            sage: L.<b> = NumberField(z^3 + 3 + a); L
1730            Number Field in b with defining polynomial z^3 + a0 + 3 over its base field
1731        """
1732        if not isinstance(poly, polynomial_element.Polynomial):
1733            try:
1734                poly = poly.polynomial(self)
1735            except (AttributeError, TypeError):
1736                raise TypeError, "polynomial (=%s) must be a polynomial."%repr(poly)
1737        if not names is None:
1738            name = names
1739        if isinstance(name, tuple):
1740            name = name[0]
1741        if name is None:
1742            raise TypeError, "the variable name must be specified."
1743        return NumberField_relative(self, poly, str(name), check=check)
1744
1745    def factor_integer(self, n):
1746        r"""
1747        Ideal factorization of the principal ideal of the ring
1748        of integers generated by $n$.
1749
1750        EXAMPLE:
1751        Here we show how to factor gaussian integers.
1752        First we form a number field defined by $x^2 + 1$:
1753 
1754            sage: K.<I> = NumberField(x^2 + 1); K
1755            Number Field in I with defining polynomial x^2 + 1
1756           
1757        Here are the factors:
1758           
1759            sage: fi, fj = K.factor_integer(13); fi,fj
1760            ((Fractional ideal (-3*I - 2) of Number Field in I with defining polynomial x^2 + 1, 1), (Fractional ideal (3*I - 2) of Number Field in I with defining polynomial x^2 + 1, 1))
1761           
1762        Now we extract the reduced form of the generators:
1763
1764            sage: zi = fi[0].gens_reduced()[0]; zi
1765            -3*I - 2
1766            sage: zj = fj[0].gens_reduced()[0]; zj
1767            3*I - 2
1768           
1769        We recover the integer that was factor in $\Z[i]$
1770           
1771            sage: zi*zj
1772            13
1773           
1774        AUTHOR:
1775            -- Alex Clemesha (2006-05-20): examples
1776        """
1777        return self.ideal(n).factor()
1778
1779    def gen(self, n=0):
1780        """
1781        Return the generator for this number field.
1782
1783        INPUT:
1784            n -- must be 0 (the default), or an exception is raised.
1785
1786        EXAMPLES:
1787            sage: k.<theta> = NumberField(x^14 + 2); k
1788            Number Field in theta with defining polynomial x^14 + 2
1789            sage: k.gen()
1790            theta
1791            sage: k.gen(1)
1792            Traceback (most recent call last):
1793            ...
1794            IndexError: Only one generator.           
1795        """
1796        if n != 0:
1797            raise IndexError, "Only one generator."
1798        try:
1799            return self.__gen
1800        except AttributeError:
1801            if self.__polynomial != None:
1802                X = self.__polynomial.parent().gen()
1803            else:
1804                X = PolynomialRing(rational_field.RationalField()).gen()
1805            self.__gen = self._element_class(self, X)
1806            return self.__gen
1807
1808    def is_field(self):
1809        """
1810        Return True since a number field is a field.
1811
1812        EXAMPLES:
1813            sage: NumberField(x^5 + x + 3, 'c').is_field()
1814            True       
1815        """
1816        return True
1817
1818    def is_galois(self):
1819        r"""
1820        Return True if this relative number field is a Galois extension of $\QQ$.
1821
1822        EXAMPLES:
1823            sage: NumberField(cyclotomic_polynomial(5),'a').is_galois()
1824            True       
1825            sage: NumberField(x^2 + 1, 'i').is_galois()
1826            True
1827            sage: NumberField(x^3 + 2, 'a').is_galois()
1828            False
1829        """
1830        return self.galois_group(pari_group=True).group().order() == self.degree()
1831
1832    def galois_group(self, pari_group = True, use_kash=False):
1833        r"""
1834        Return the Galois group of the Galois closure of this number
1835        field as an abstract group.
1836
1837        For more (important!) documentation, so the documentation
1838        for Galois groups of polynomials over $\QQ$, e.g., by
1839        typing \code{K.polynomial().galois_group?}, where $K$
1840        is a number field.
1841
1842        To obtain actual field automorphisms that can be applied to
1843        elements, use \code{End(K).list()} and
1844        \code{K.galois_closure()} together (see example below).
1845
1846        EXAMPLES:
1847            sage: k.<b> = NumberField(x^2 - 14)
1848            sage: k.galois_group ()
1849            Galois group PARI group [2, -1, 1, "S2"] of degree 2 of the number field Number Field in b with defining polynomial x^2 - 14
1850       
1851            sage: NumberField(x^3-2, 'a').galois_group(pari_group=True)
1852            Galois group PARI group [6, -1, 2, "S3"] of degree 3 of the number field Number Field in a with defining polynomial x^3 - 2
1853           
1854            sage: NumberField(x-1, 'a').galois_group(pari_group=False)    # optional database_gap package
1855            Galois group Transitive group number 1 of degree 1 of the number field Number Field in a with defining polynomial x - 1
1856            sage: NumberField(x^2+2, 'a').galois_group(pari_group=False)  # optional database_gap package
1857            Galois group Transitive group number 1 of degree 2 of the number field Number Field in a with defining polynomial x^2 + 2
1858            sage: NumberField(x^3-2, 'a').galois_group(pari_group=False)  # optional database_gap package
1859            Galois group Transitive group number 2 of degree 3 of the number field Number Field in a with defining polynomial x^3 - 2
1860
1861        EXPLICIT GALOIS GROUP:
1862        We compute the Galois group as an explicit group of
1863        automorphisms of the Galois closure of a field.
1864
1865            sage: K.<a> = NumberField(x^3 - 2)
1866            sage: L.<b> = K.galois_closure(); L
1867            Number Field in b1 with defining polynomial x^6 + 40*x^3 + 1372
1868            sage: G = End(L); G
1869            Automorphism group of Number Field in b1 with defining polynomial x^6 + 40*x^3 + 1372
1870            sage: G.list()
1871            [
1872            Ring endomorphism of Number Field in b1 with defining polynomial x^6 + 40*x^3 + 1372
1873              Defn: b1 |--> b1,
1874            ...
1875            Ring endomorphism of Number Field in b1 with defining polynomial x^6 + 40*x^3 + 1372
1876              Defn: b1 |--> -2/63*b1^4 - 31/63*b1
1877            ]
1878            sage: G[1](b)
1879            1/36*b1^4 + 1/18*b1
1880        """
1881        try:
1882            return self.__galois_group[pari_group, use_kash]
1883        except KeyError:
1884            pass
1885        except AttributeError:
1886            self.__galois_group = {}
1887           
1888        G = self.polynomial().galois_group(pari_group = pari_group, use_kash = use_kash)
1889        H = GaloisGroup(G, self)
1890        self.__galois_group[pari_group, use_kash] = H
1891        return H
1892
1893
1894    def integral_basis(self):
1895        """
1896        Return a list of elements of this number field that are a basis
1897        for the full ring of integers.
1898
1899        EXAMPLES:
1900            sage: K.<a> = NumberField(x^5 + 10*x + 1)
1901            sage: K.integral_basis()
1902            [1, a, a^2, a^3, a^4]
1903
1904        Next we compute the ring of integers of a cubic field in which 2
1905        is an "essential discriminant divisor", so the ring of integers
1906        is not generated by a single element.
1907            sage: K.<a> = NumberField(x^3 + x^2 - 2*x + 8)
1908            sage: K.integral_basis()
1909            [1, a, 1/2*a^2 + 1/2*a]
1910        """
1911        try:
1912            return self.__integral_basis
1913        except AttributeError:
1914            f = self.pari_polynomial()
1915            B = f.nfbasis()
1916            R = self.polynomial().parent()
1917            self.__integral_basis = [self(R(g).list()) for g in B]
1918        return self.__integral_basis
1919
1920    def narrow_class_group(self, proof=None):
1921        r"""
1922        Return the narrow class group of this field.
1923
1924        INPUT:
1925            proof -- default: None (use the global proof setting, which defaults to True).
1926       
1927        EXAMPLES:
1928            sage: NumberField(x^3+x+9, 'a').narrow_class_group()
1929            Multiplicative Abelian Group isomorphic to C2
1930        """
1931        proof = proof_flag(proof)       
1932        try:
1933            return self.__narrow_class_group
1934        except AttributeError:
1935            k = self.pari_bnf(proof)
1936            s = str(k.bnfnarrow())
1937            s = s.replace(";",",")
1938            s = eval(s)
1939            self.__narrow_class_group = sage.groups.abelian_gps.abelian_group.AbelianGroup(s[1])
1940        return self.__narrow_class_group
1941
1942    def ngens(self):
1943        """
1944        Return the number of generators of this number field (always 1).
1945
1946        OUTPUT:
1947            the python integer 1.
1948       
1949        EXAMPLES:
1950            sage: NumberField(x^2 + 17,'a').ngens()
1951            1
1952            sage: NumberField(x + 3,'a').ngens()
1953            1
1954            sage: k.<a> = NumberField(x + 3)
1955            sage: k.ngens()
1956            1
1957            sage: k.0
1958            -3
1959        """
1960        return 1
1961
1962    def order(self):
1963        """
1964        Return the order of this number field (always +infinity).
1965
1966        OUTPUT:
1967            always positive infinity
1968
1969        EXAMPLES:
1970            sage: NumberField(x^2 + 19,'a').order()
1971            +Infinity
1972        """
1973        return infinity.infinity
1974       
1975    def polynomial_ntl(self):
1976        """
1977        Return defining polynomial of this number field
1978        as a pair, an ntl polynomial and a denominator.
1979
1980        This is used mainly to implement some internal arithmetic.
1981
1982        EXAMPLES:
1983            sage: NumberField(x^2 + (2/3)*x - 9/17,'a').polynomial_ntl()
1984            ([-27 34 51], 51)
1985        """
1986        try:
1987            return (self.__polynomial_ntl, self.__denominator_ntl)
1988        except AttributeError:
1989            self.__denominator_ntl = ntl.ZZ()
1990            den = self.polynomial().denominator()
1991            self.__denominator_ntl.set_from_sage_int(ZZ(den))
1992            self.__polynomial_ntl = ntl.ZZX((self.polynomial()*den).list())
1993        return (self.__polynomial_ntl, self.__denominator_ntl)
1994
1995    def polynomial(self):
1996        """
1997        Return the defining polynomial of this number field.
1998
1999        This is exactly the same as \code{self.defining_polynomal()}.
2000
2001        EXAMPLES:
2002            sage: NumberField(x^2 + (2/3)*x - 9/17,'a').polynomial()
2003            x^2 + 2/3*x - 9/17       
2004        """
2005        return self.__polynomial
2006
2007    def defining_polynomial(self):   # do not overload this -- overload polynomial instead
2008        """
2009        Return the defining polynomial of this number field.
2010
2011        This is exactly the same as \code{self.polynomal()}.
2012
2013        EXAMPLES:
2014            sage: k5.<z> = CyclotomicField(5)
2015            sage: k5.defining_polynomial()
2016            x^4 + x^3 + x^2 + x + 1
2017            sage: y = polygen(QQ,'y')
2018            sage: k.<a> = NumberField(y^9 - 3*y + 5); k
2019            Number Field in a with defining polynomial y^9 - 3*y + 5
2020            sage: k.defining_polynomial()
2021            y^9 - 3*y + 5
2022        """
2023        return self.polynomial()
2024
2025    def polynomial_ring(self):
2026        """
2027        Return the polynomial ring that we view this number field as being
2028        a quotient of (by a principal ideal).
2029
2030        EXAMPLES:
2031        An example with an absolute field:
2032            sage: k.<a> = NumberField(x^2 + 3)
2033            sage: y = polygen(QQ, 'y')
2034            sage: k.<a> = NumberField(y^2 + 3)
2035            sage: k.polynomial_ring()
2036            Univariate Polynomial Ring in y over Rational Field
2037
2038        An example with a relative field:
2039            sage: y = polygen(QQ, 'y')
2040            sage: M.<a> = NumberField([y^3 + 97, y^2 + 1]); M
2041            Number Field in a0 with defining polynomial y^3 + 97 over its base field
2042            sage: M.polynomial_ring()
2043            Univariate Polynomial Ring in y over Number Field in a1 with defining polynomial y^2 + 1
2044        """
2045        return self.polynomial().parent()
2046
2047    def polynomial_quotient_ring(self):
2048        """
2049        Return the polynomial quotient ring isomorphic to this number field.
2050
2051        EXAMPLES:
2052            sage: K = NumberField(x^3 + 2*x - 5, 'alpha')
2053            sage: K.polynomial_quotient_ring()
2054            Univariate Quotient Polynomial Ring in alpha over Rational Field with modulus x^3 + 2*x - 5
2055        """
2056        return self.polynomial_ring().quotient(self.polynomial(), self.variable_name())
2057       
2058    def regulator(self, proof=None):
2059        """
2060        Return the regulator of this number field.
2061
2062        Note that PARI computes the regulator to higher precision than
2063        the SAGE default.
2064
2065        INPUT:
2066            proof -- default: True, unless you set it otherwise.
2067
2068        EXAMPLES:
2069            sage: NumberField(x^2-2, 'a').regulator()
2070            0.88137358701954305
2071            sage: NumberField(x^4+x^3+x^2+x+1, 'a').regulator()
2072            0.96242365011920694
2073        """
2074        proof = proof_flag(proof)
2075        try:
2076            return self.__regulator
2077        except AttributeError:
2078            k = self.pari_bnf(proof)
2079            s = str(k.getattr('reg'))
2080            self.__regulator = eval(s)
2081        return self.__regulator
2082
2083    def residue_field(self, prime, name = None, check = False):
2084        """
2085        Return the residue field of this number field at a given prime, ie $O_K / p O_K$.
2086
2087        INPUT:
2088            prime -- a prime ideal of the maximal order in this number field.
2089            name -- the name of the variable in the residue field
2090            check -- whether or not to check the primality of prime.
2091        OUTPUT:
2092            The residue field at this prime.
2093
2094        EXAMPLES:
2095        sage: R.<x> = QQ[]
2096        sage: K.<a> = NumberField(x^4+3*x^2-17)
2097        sage: P = K.ideal(61).factor()[0][0]
2098        sage: K.residue_field(P)
2099        Residue field of Fractional ideal (-2*a^2 + 1) of Number Field in a with defining polynomial x^4 + 3*x^2 - 17
2100        """
2101        import sage.rings.residue_field
2102        return sage.rings.residue_field.ResidueField(prime)
2103
2104    def signature(self):
2105        """
2106        Return (r1, r2), where r1 and r2 are the number of real embeddings
2107        and pairs of complex embeddings of this field, respectively.
2108
2109        EXAMPLES:
2110            sage: NumberField(x^2+1, 'a').signature()
2111            (0, 1)
2112            sage: NumberField(x^3-2, 'a').signature()
2113            (1, 1)
2114            sage: CyclotomicField(7).signature()
2115            (0, 3)
2116        """
2117        r1, r2 = self.pari_nf().getattr('sign')
2118        return (ZZ(r1), ZZ(r2))
2119
2120    def trace_pairing(self, v):
2121        """
2122        Return the matrix of the trace pairing on the elements of the
2123        list $v$.
2124
2125        EXAMPLES:
2126            sage: K.<zeta3> = NumberField(x^2 + 3)
2127            sage: K.trace_pairing([1,zeta3])
2128            [ 2  0]
2129            [ 0 -6]
2130        """
2131        import sage.matrix.matrix_space
2132        A = sage.matrix.matrix_space.MatrixSpace(self.base_ring(), len(v))(0)
2133        for i in range(len(v)):
2134            for j in range(i,len(v)):
2135                t = (self(v[i]*v[j])).trace()
2136                A[i,j] = t
2137                A[j,i] = t
2138        return A
2139
2140    def uniformizer(self, P, others = "positive"):
2141        """
2142        Returns an element of self with valuation 1 at P.
2143
2144        INPUT:
2145        self -- a number field
2146        P -- a prime ideal of self
2147        others -- either "positive" (default), in which case the element will have
2148                  non-negative valuation at all other primes of self,
2149                  or "negative", in which case the element will have non-positive
2150                  valuation at all other primes of self.
2151        """
2152        if not is_NumberFieldIdeal(P):
2153            P = self.ideal(P)
2154        if not P.is_prime():
2155            raise ValueError, "P must be prime"
2156        if others == "negative":
2157            P = ~P
2158        elif others != "positive":
2159            raise ValueError, "others must be 'positive' or 'negative'"
2160        nf = self.pari_nf()
2161        a = self(nf.idealappr(P.pari_hnf()))
2162        if others == "negative":
2163            a = ~a
2164        return a
2165
2166    def units(self, proof=None):
2167        """
2168        Return generators for the unit group modulo torsion.
2169
2170        ALGORITHM: Uses PARI's bnfunit command.
2171
2172        INPUTS:
2173            proof -- default: True
2174       
2175        EXAMPLES:
2176            sage: x = QQ['x'].0
2177            sage: A = x^4 - 10*x^3 + 20*5*x^2 - 15*5^2*x + 11*5^3
2178            sage: K = NumberField(A, 'a')
2179            sage: K.units()
2180            [8/275*a^3 - 12/55*a^2 + 15/11*a - 2]
2181        """
2182        proof = proof_flag(proof)
2183        try:
2184            return self.__units
2185        except AttributeError:
2186            B = self.pari_bnf(proof).bnfunit()
2187            R = self.polynomial().parent()
2188            self.__units = [self(R(g)) for g in B]
2189            return self.__units
2190
2191    def zeta(self, n=2, all=False):
2192        """
2193        Return an n-th root of unity in this field.  If all is True,
2194        return all of them.
2195
2196        INPUT:
2197            n -- positive integer
2198            all -- bool, default: False.  If True, return a list
2199                   of all n-th roots of 1)
2200
2201        If there are no n-th roots of unity in self (and all is
2202        False), this function raises an ArithmeticError exception.
2203
2204        EXAMPLES:
2205            sage: K.<z> = NumberField(x^2 + 3)
2206            sage: K.zeta(1)
2207            1
2208            sage: K.zeta(2)
2209            -1
2210            sage: K.zeta(2, all=True)
2211            [-1]
2212            sage: K.zeta(3)
2213            1/2*z - 1/2           
2214            sage: K.zeta(3, all=True)
2215            [1/2*z - 1/2, -1/2*z - 1/2]
2216            sage: K.zeta(4)
2217            Traceback (most recent call last):
2218            ...
2219            ArithmeticError: There are no 4-th roots of unity self.
2220
2221            sage: r.<x> = QQ[]
2222            sage: K.<b> = NumberField(x^2+1)
2223            sage: K.zeta(4)
2224            b
2225            sage: K.zeta(4,all=True)
2226            [b, -b]
2227            sage: K.zeta(3)
2228            Traceback (most recent call last):
2229            ...
2230            ArithmeticError: There are no 3-rd roots of unity self.
2231            sage: K.zeta(3,all=True)
2232            []           
2233        """
2234        n = ZZ(n)
2235        if n <= 0:
2236            raise ValueError, "n (=%s) must be positive"%n
2237        if n == 1:
2238            if all:
2239                return [self(1)]
2240            else:
2241                return self(1)
2242        elif n == 2:
2243            if all:
2244                return [self(-1)]
2245            else:
2246                return self(-1)
2247        else:
2248            field = self.absolute_field('a')
2249            from_field = field.structure()[0]
2250            f = field.polynomial_ring().cyclotomic_polynomial(n)
2251            F = field['x'](f)
2252            R = F.roots()
2253            if len(R) == 0:
2254                if all:
2255                    return []
2256                else:
2257                    if n == 1:
2258                        th = 'st'
2259                    elif n == 2:
2260                        th = 'nd'
2261                    elif n == 3:
2262                        th = 'rd'
2263                    else:
2264                        th = 'th'
2265                    raise ArithmeticError, "There are no %s-%s roots of unity self."%(n,th)
2266            if all:
2267                return [from_field(r[0]) for r in R]
2268            else:
2269                return from_field(R[0][0])
2270   
2271    def zeta_coefficients(self, n):
2272        """
2273        Compute the first n coefficients of the Dedekind zeta function
2274        of this field as a Dirichlet series.
2275
2276        EXAMPLE:
2277            sage: x = QQ['x'].0
2278            sage: NumberField(x^2+1, 'a').zeta_coefficients(10)
2279            [1, 1, 0, 1, 2, 0, 0, 1, 1, 2]
2280        """
2281        return self.pari_nf().dirzetak(n)
2282
2283
2284class NumberField_absolute(NumberField_generic):
2285
2286    def __init__(self, polynomial, name, latex_name=None, check=True):
2287        NumberField_generic.__init__(self, polynomial, name, latex_name, check)
2288        self._element_class = number_field_element.NumberFieldElement_absolute
2289
2290    def base_field(self):
2291        return QQ
2292
2293    def is_absolute(self):
2294        """
2295        EXAMPLES:
2296            sage: K = CyclotomicField(5)
2297            sage: K.is_absolute()
2298            True
2299        """
2300        return True
2301   
2302    def absolute_polynomial(self):
2303        r"""
2304        Return absolute polynomial that defines this absolute field.
2305        This is the same as \code{self.polynomial()}.
2306
2307        EXAMPLES:
2308            sage: K.<a> = NumberField(x^2 + 1)
2309            sage: K.absolute_polynomial ()
2310            x^2 + 1
2311        """
2312        return self.polynomial()
2313
2314    def __reduce__(self):
2315        """
2316        TESTS:
2317            sage: Z = var('Z')
2318            sage: K.<w> = NumberField(Z^3 + Z + 1)
2319            sage: L = loads(dumps(K))
2320            sage: print L
2321            Number Field in w with defining polynomial Z^3 + Z + 1
2322            sage: print L == K
2323            True
2324        """
2325        return NumberField_absolute_v1, (self.polynomial(), self.variable_name(), self.latex_variable_name())
2326
2327    def optimized_representation(self, names=None, both_maps=True):
2328        """
2329        Return a field isomorphic to self with a better defining
2330        polynomial if possible, along with field isomorphisms from the
2331        new field to self and from self to the new field.
2332
2333        EXAMPLES:
2334        We construct a compositum of 3 quadratic fields, then find an optimized
2335        representation and transform elements back and forth.
2336            sage: K = NumberField([x^2 + p for p in [5, 3, 2]],'a').absolute_field('b'); K
2337            Number Field in b with defining polynomial x^8 + 40*x^6 + 352*x^4 + 960*x^2 + 576
2338            sage: L, from_L, to_L = K.optimized_representation()
2339            sage: L    # your answer may different, since algorithm is random
2340            Number Field in a14 with defining polynomial x^8 + 4*x^6 + 7*x^4 + 36*x^2 + 81
2341            sage: to_L(K.0)   # random
2342            4/189*a14^7 - 1/63*a14^6 + 1/27*a14^5 + 2/9*a14^4 - 5/27*a14^3 + 8/9*a14^2 + 3/7*a14 + 3/7
2343            sage: from_L(L.0)   # random
2344            1/1152*a1^7 + 1/192*a1^6 + 23/576*a1^5 + 17/96*a1^4 + 37/72*a1^3 + 5/6*a1^2 + 55/24*a1 + 3/4
2345
2346        The transformation maps are mutually inverse isomorphisms.
2347            sage: from_L(to_L(K.0))
2348            b
2349            sage: to_L(from_L(L.0))     # random
2350            a14
2351        """
2352        return self.optimized_subfields(degree=self.degree(), name=names, both_maps=both_maps)[0]
2353
2354    def optimized_subfields(self, degree=0, name=None, both_maps=True):
2355        """
2356        Return optimized representations of many (but *not* necessarily
2357        all!)  subfields of self of degree 0, or of all possible
2358        degrees if degree is 0.
2359       
2360        EXAMPLES:
2361            sage: K = NumberField([x^2 + p for p in [5, 3, 2]],'a').absolute_field('b'); K
2362            Number Field in b with defining polynomial x^8 + 40*x^6 + 352*x^4 + 960*x^2 + 576
2363            sage: L = K.optimized_subfields(name='b')
2364            sage: L[0][0]
2365            Number Field in b0 with defining polynomial x - 1
2366            sage: L[1][0]
2367            Number Field in b1 with defining polynomial x^2 - x + 1
2368            sage: [z[0] for z in L]          # random -- since algorithm is random
2369            [Number Field in b0 with defining polynomial x - 1,
2370             Number Field in b1 with defining polynomial x^2 - x + 1,
2371             Number Field in b2 with defining polynomial x^4 - 5*x^2 + 25,
2372             Number Field in b3 with defining polynomial x^4 - 2*x^2 + 4,
2373             Number Field in b4 with defining polynomial x^8 + 4*x^6 + 7*x^4 + 36*x^2 + 81]
2374
2375        We examine one of the optimized subfields in more detail:
2376             sage: M, from_M, to_M = L[2]
2377             sage: M                             # random
2378             Number Field in b2 with defining polynomial x^4 - 5*x^2 + 25
2379             sage: from_M     # may be slightly random
2380             Ring morphism:
2381               From: Number Field in b2 with defining polynomial x^4 - 5*x^2 + 25
2382               To:   Number Field in a1 with defining polynomial x^8 + 40*x^6 + 352*x^4 + 960*x^2 + 576
2383               Defn: b2 |--> -5/1152*a1^7 + 1/96*a1^6 - 97/576*a1^5 + 17/48*a1^4 - 95/72*a1^3 + 17/12*a1^2 - 53/24*a1 - 1
2384
2385        The to_M map is None, since there is no map from K to M:
2386             sage: to_M
2387
2388        We apply the from_M map to the generator of M, which gives a rather
2389        large element of $K$:
2390             sage: from_M(M.0)          # random
2391             -5/1152*a1^7 + 1/96*a1^6 - 97/576*a1^5 + 17/48*a1^4 - 95/72*a1^3 + 17/12*a1^2 - 53/24*a1 - 1
2392
2393        Nevertheless, that large-ish element lies in a degree 4 subfield:
2394             sage: from_M(M.0).minpoly()   # random
2395             x^4 - 5*x^2 + 25
2396        """
2397        return self._subfields_helper(degree=degree,name=name,
2398                                      both_maps=both_maps,optimize=True)
2399
2400    def change_name(self, names):
2401        r"""
2402        Return number field isomorphic to self but with the given
2403        generator name.
2404
2405        INPUT:
2406            names -- should be exactly one variable name.
2407
2408        Also, \code{K.structure()} returns from_K and to_K, where
2409        from_K is an isomorphism from K to self and to_K is an
2410        isomorphism from self to K.
2411
2412        EXAMPLES:
2413            sage: K.<z> = NumberField(x^2 + 3); K
2414            Number Field in z with defining polynomial x^2 + 3
2415            sage: L.<ww> = K.change_name()
2416            sage: L
2417            Number Field in ww with defining polynomial x^2 + 3
2418            sage: L.structure()[0]
2419            Number field isomorphism from Number Field in ww with defining polynomial x^2 + 3 to Number Field in z with defining polynomial x^2 + 3 given by variable name change
2420            sage: L.structure()[0](ww + 5/3)
2421            z + 5/3
2422        """
2423        return self.absolute_field(names)
2424
2425    def subfields(self, degree=0, name=None):
2426        """
2427        EXAMPLES:
2428            sage: K.<a> = NumberField( [x^3 - 2, x^2 + x + 1] );
2429            sage: K = K.absolute_field('b')
2430            sage: S = K.subfields()
2431            sage: len(S)
2432            6
2433            sage: [k[0].polynomial() for k in S]
2434            [x - 3,
2435             x^2 - 3*x + 9,
2436             x^3 - 3*x^2 + 3*x + 1,
2437             x^3 - 3*x^2 + 3*x + 1,
2438             x^3 - 3*x^2 + 3*x - 17,
2439             x^6 - 3*x^5 + 6*x^4 - 11*x^3 + 12*x^2 + 3*x + 1]
2440        """
2441        return self._subfields_helper(degree=degree, name=name,
2442                                      both_maps=True, optimize=False)
2443
2444    def _subfields_helper(self, degree=0, name=None, both_maps=True, optimize=False):
2445        if name is None:
2446            name = self.variable_names()
2447        name = sage.structure.parent_gens.normalize_names(1, name)[0]
2448        try:
2449            return self.__subfields[name, degree, both_maps, optimize]
2450        except AttributeError:
2451            self.__subfields = {}
2452        except KeyError:
2453            pass
2454        f = pari(self.polynomial())
2455        if optimize:
2456            v = f.polred(2)
2457            elts = v[0]; polys = v[1]
2458        else:
2459            v = f.nfsubfields(degree)
2460            elts = [x[1] for x in v]; polys = [x[0] for x in v]
2461           
2462        R = self.polynomial_ring()
2463
2464        ans = []
2465        for i in range(len(elts)):
2466            f = R(polys[i])
2467            if not (degree == 0 or f.degree() == degree):
2468                continue
2469            a = self(R(elts[i]))
2470            K = NumberField(f, names=name + str(i))
2471
2472            from_K = K.hom([a])    # check=False here ??   would be safe unless there are bugs.
2473
2474            if both_maps and K.degree() == self.degree():
2475                g = K['x'](self.polynomial())
2476                v = g.roots()
2477                a = from_K(K.gen())
2478                for i in range(len(v)):
2479                    r = g.roots()[i][0]
2480                    to_K = self.hom([r])    # check=False here ??
2481                    if to_K(a) == K.gen():
2482                        break
2483            else:
2484                to_K = None
2485            ans.append((K, from_K, to_K))
2486        ans = Sequence(ans, immutable=True, cr=True)
2487        self.__subfields[name, degree, both_maps, optimize] = ans
2488        return ans
2489
2490
2491    def maximal_order(self):
2492        """
2493        Return the maximal order, i.e., the ring of integers, associated
2494        to this number field.
2495
2496        EXAMPLES:
2497
2498        In this example, the maximal order cannot be generated
2499        by a single element.
2500            sage: k.<a> = NumberField(x^3 + x^2 - 2*x+8)
2501            sage: o = k.maximal_order()
2502            sage: o
2503            Order with module basis 1, 1/2*a^2 + 1/2*a, a^2 in Number Field in a with defining polynomial x^3 + x^2 - 2*x + 8
2504        """
2505        try:
2506            return self.__maximal_order
2507        except AttributeError:
2508            B = self.integral_basis()
2509            import sage.rings.number_field.order as order
2510            O = order.absolute_order_from_module_generators(B,
2511                     check_integral=False, check_rank=False,
2512                     check_is_ring=False, is_maximal=True)
2513            self.__maxima_order = O
2514            return O
2515
2516    def order(self, *gens, **kwds):
2517        r"""
2518        Return the order with given ring generators in the maximal
2519        order of this number field.
2520
2521        INPUT:
2522            gens -- list of elements of self; if no generators are
2523                    given, just returns the cardinality of this number
2524                    field (oo) for consistency.
2525            check_is_integral -- bool (default: True), whether to check
2526                  that each generator is integral.
2527            check_rank -- bool (default: True), whether to check that
2528                  the ring generated by gens is of full rank.
2529            allow_subfield -- bool (default: False), if True and the generators
2530                  do not generate an order, i.e., they generate a subring
2531                  of smaller rank, instead of raising an error, return
2532                  an order in a smaller number field.
2533
2534        EXAMPLES:
2535            sage: k.<i> = NumberField(x^2 + 1)
2536            sage: k.order(2*i)
2537            Order with module basis 1, 2*i in Number Field in i with defining polynomial x^2 + 1
2538            sage: k.order(10*i)
2539            Order with module basis 1, 10*i in Number Field in i with defining polynomial x^2 + 1
2540            sage: k.order(3)
2541            Traceback (most recent call last):
2542            ...
2543            ValueError: the rank of the span of gens is wrong
2544            sage: k.order(i/2)
2545            Traceback (most recent call last):
2546            ...
2547            ValueError: each generator must be integral
2548
2549        Alternatively, an order can be constructed by adjoining
2550        elements to $\ZZ$:
2551       
2552        """
2553        if len(gens) == 0:
2554            return NumberField_generic.order(self)
2555        if len(gens) == 1 and isinstance(gens[0], (list, tuple)):
2556            gens = gens[0]
2557        gens = [self(x) for x in gens]
2558        import sage.rings.number_field.order as order
2559        return order.absolute_order_from_ring_generators(gens, **kwds)
2560
2561    def vector_space(self):
2562        """
2563        Return a vector space V and isomorphisms self --> V and V --> self.
2564
2565        OUTPUT:
2566            V -- a vector space over the rational numbers
2567            from_V -- an isomorphism from V to self
2568            to_V -- an isomorphism from self to V
2569
2570        EXAMPLES:
2571            sage: k.<a> = NumberField(x^3 + 2)
2572            sage: V, from_V, to_V  = k.vector_space()
2573            sage: from_V(V([1,2,3]))
2574            3*a^2 + 2*a + 1
2575            sage: to_V(1 + 2*a + 3*a^2)
2576            (1, 2, 3)
2577            sage: V
2578            Vector space of dimension 3 over Rational Field
2579            sage: to_V
2580            Isomorphism from Number Field in a with defining polynomial x^3 + 2 to Vector space of dimension 3 over Rational Field
2581            sage: from_V(to_V(2/3*a - 5/8))
2582            2/3*a - 5/8
2583            sage: to_V(from_V(V([0,-1/7,0])))
2584            (0, -1/7, 0)
2585        """
2586        try:
2587            return self.__vector_space
2588        except AttributeError:
2589            V = QQ**self.degree()
2590            from_V = maps.MapVectorSpaceToNumberField(V, self)
2591            to_V   = maps.MapNumberFieldToVectorSpace(self, V)
2592            self.__vector_space = (V, from_V, to_V)
2593            return self.__vector_space
2594
2595    def absolute_vector_space(self):
2596        r"""
2597        Return vector space over $\QQ$ corresponding to this number
2598        field, along with maps from that space to this number field
2599        and in the other direction.
2600
2601        For an absolute extension this is identical to
2602        \code{self.vector_space()}.
2603
2604        EXAMPLES:
2605            sage: K.<a> = NumberField(x^3 - 5)
2606            sage: K.absolute_vector_space()
2607            (Vector space of dimension 3 over Rational Field,
2608             Isomorphism from Vector space of dimension 3 over Rational Field to Number Field in a with defining polynomial x^3 - 5,
2609             Isomorphism from Number Field in a with defining polynomial x^3 - 5 to Vector space of dimension 3 over Rational Field)
2610        """
2611        return self.vector_space()
2612
2613    def galois_closure(self, names=None):
2614        """
2615        Return number field $K$ that is the Galois closure of self,
2616        i.e., is generated by all roots of the defining polynomial of
2617        self
2618
2619
2620        INPUT:
2621            names -- variable name for Galois closure
2622
2623        EXAMPLES:
2624            sage: K.<a> = NumberField(x^4 - 2)
2625            sage: L = K.galois_closure(); L
2626            Number Field in a2 with defining polynomial x^8 + 28*x^4 + 2500
2627            sage: K.galois_group().order()
2628            8
2629
2630            sage: phi = K.embeddings(L)[0]
2631            sage: phi(K.0)
2632            1/120*a2^5 + 19/60*a2
2633            sage: phi(K.0).minpoly()
2634            x^4 - 2
2635        """
2636        try:
2637            return self.__galois_closure
2638        except AttributeError:
2639            pass
2640        G = self.galois_group()
2641        K = self
2642        while K.degree() < G.order():
2643            K = K.composite_fields(self, names=names)[-1]
2644        self.__galois_closure = K
2645        return self.__galois_closure
2646
2647    def embeddings(self, K):
2648        """
2649        Compute all field embeddings of self into the field K (which
2650        need not even be a number field, e.g., it could be the complex
2651        numbers). This will return an identical result when given K as
2652        input again.
2653
2654        If possible, the most natural embedding of K into self
2655        is put first in the list.
2656
2657        INPUT:
2658            K -- a number field
2659
2660        EXAMPLES:
2661            sage: K.<a> = NumberField(x^3 - 2)
2662            sage: L = K.galois_closure(); L
2663            Number Field in a1 with defining polynomial x^6 + 40*x^3 + 1372
2664            sage: K.embeddings(L)[0]
2665            Ring morphism:
2666              From: Number Field in a with defining polynomial x^3 - 2
2667              To:   Number Field in a1 with defining polynomial x^6 + 40*x^3 + 1372
2668              Defn: a |--> 1/84*a1^4 + 13/42*a1
2669            sage: K.embeddings(L)  is K.embeddings(L)
2670            True
2671
2672        We embed a quadratic field into a cyclotomic field:
2673            sage: L.<a> = QuadraticField(-7)
2674            sage: K = CyclotomicField(7)
2675            sage: L.embeddings(K)
2676            [Ring morphism: ...
2677              Defn: a |--> 2*zeta7^4 + 2*zeta7^2 + 2*zeta7 + 1,
2678             Ring morphism: ...
2679              Defn: a |--> -2*zeta7^4 - 2*zeta7^2 - 2*zeta7 - 1]
2680
2681        We embed a cubic field in the complex numbers:
2682            sage: K.<a> = NumberField(x^3 - 2)
2683            sage: K.embeddings(CC)
2684            [Ring morphism:
2685              From: Number Field in a with defining polynomial x^3 - 2
2686              To:   Complex Field with 53 bits of precision
2687              Defn: a |--> -0.629960524947437 - 1.09112363597172*I,
2688             Ring morphism:
2689              From: Number Field in a with defining polynomial x^3 - 2
2690              To:   Complex Field with 53 bits of precision
2691              Defn: a |--> -0.629960524947437 + 1.09112363597172*I,
2692             Ring morphism:
2693              From: Number Field in a with defining polynomial x^3 - 2
2694              To:   Complex Field with 53 bits of precision
2695              Defn: a |--> 1.25992104989487]
2696        """
2697        try:
2698            return self.__embeddings[K]
2699        except AttributeError:
2700            self.__embeddings = {}
2701        except KeyError:
2702            pass
2703        f = K['x'](self.defining_polynomial())
2704        r = f.roots(); r.sort()
2705        v = [self.hom([e[0]], check=False) for e in r]
2706        # If there is an embedding that preserves variable names
2707        # then it is most natural, so we put it first.
2708        put_natural_embedding_first(v)
2709
2710        self.__embeddings[K] = Sequence(v, cr=True, immutable=True, check=False, universe=self.Hom(K))
2711        return v
2712
2713    def relativize(self, alpha, names):
2714        r"""
2715        Given an element alpha in self, return a relative number field
2716        $K$ isomorphic to self that is relative over the absolute field
2717        $\QQ(\alpha)$, along with isomorphisms from $K$ to self and
2718        from self to K.
2719
2720        INPUT:
2721            alpha -- an element of self.
2722            names -- 2-tuple of names of generator for output
2723                     field K and the subfield QQ(alpha)
2724                     names[0] generators K and names[1] QQ(alpha).
2725           
2726        OUTPUT:
2727            K   -- relative number field, map from K to self,
2728                   map from self to K.
2729
2730        Also, \code{K.structure()} returns from_K and to_K, where
2731        from_K is an isomorphism from K to self and to_K is an isomorphism
2732        from self to K.
2733
2734        EXAMPLES:
2735            sage: K.<a> = NumberField(x^10 - 2)
2736            sage: L.<c,d> = K.relativize(a^4 + a^2 + 2); L
2737            Number Field in c with defining polynomial x^2 + -1/5*d^4 + 8/5*d^3 - 23/5*d^2 + 7*d - 18/5 over its base field
2738            sage: c.absolute_minpoly()
2739            x^10 - 2
2740            sage: d.absolute_minpoly()
2741            x^5 - 10*x^4 + 40*x^3 - 90*x^2 + 110*x - 58
2742            sage: (a^4 + a^2 + 2).minpoly()
2743            x^5 - 10*x^4 + 40*x^3 - 90*x^2 + 110*x - 58
2744            sage: from_L, to_L = L.structure()
2745            sage: to_L(a)
2746            c
2747            sage: to_L(a^4 + a^2 + 2)
2748            d
2749            sage: from_L(to_L(a^4 + a^2 + 2))
2750            a^4 + a^2 + 2
2751        """
2752        # step 1: construct the abstract field generated by alpha.
2753        # step 2: make a relative extension of it.
2754        # step 3: construct isomorphisms
2755
2756        names = sage.structure.parent_gens.normalize_names(2, names)
2757
2758        # make sure alpha is in self
2759        alpha = self(alpha)
2760
2761        f = alpha.minpoly()
2762        L = NumberField(f, names[1])
2763
2764        g = self.defining_polynomial()
2765        h = L['x'](g)
2766        F = h.factor()
2767       
2768        for f, e in F:
2769            if L.degree() * f.degree() == self.degree():
2770                M = L.extension(f, names[0])
2771                beta = M(L.gen())
2772                try:
2773                    to_M = self.hom([M.gen(0)], M, check=True)  # be paranoid
2774                except TypeError:
2775                    continue
2776                if to_M(alpha) == beta:
2777                    # Bingo.
2778                    # We have now constructed a relative
2779                    # number field M, and an isomorphism
2780                    # self --> M that sends alpha to
2781                    # the generator of the intermediate field.
2782                    from_M = M.hom([self.gen()], self, check=True)
2783                    M._set_structure(from_M, to_M)  # don't have to
2784                                                    # worry about caching since relative number fields aren't cached.
2785                    return M
2786               
2787        assert False, "bug in relativize"
2788                   
2789
2790       
2791       
2792       
2793
2794           
2795       
2796       
2797
2798class NumberField_relative(NumberField_generic):
2799    """
2800    EXAMPLES:
2801        sage: K.<a> = NumberField(x^3 - 2)
2802        sage: t = K['x'].gen()
2803        sage: L.<b> = K.extension(t^2+t+a); L
2804        Number Field in b with defining polynomial x^2 + x + a over its base field
2805    """
2806    def __init__(self, base, polynomial, name,
2807                 latex_name=None, names=None, check=True):
2808        r"""
2809        INPUT:
2810            base -- the base field
2811            polynomial -- must be defined in the ring \code{K['x']}, where
2812                          K is the base field.
2813            name -- variable name
2814            latex_name -- latex variable name
2815            names --
2816            check -- whether to check irreducibility of polynomial.
2817
2818        EXAMPLES:
2819            sage: K.<x> = CyclotomicField(5)[]
2820            sage: W.<a> = NumberField(x^2 + 1)
2821            sage: W
2822            Number Field in a with defining polynomial x^2 + 1 over its base field
2823            sage: type(W)
2824            <class 'sage.rings.number_field.number_field.NumberField_relative'>
2825
2826        Test that check=False really skips the test:
2827            sage: W.<a> = NumberField(K.cyclotomic_polynomial(5), check=False)
2828            sage: W
2829            Number Field in a with defining polynomial x^4 + x^3 + x^2 + x + 1 over its base field
2830
2831        A relative extension of a relative extension:
2832            sage: x = var('x')
2833            sage: k.<a> = NumberField([x^2 + 2, x^2 + 1])
2834            sage: l.<b> = k.extension(x^2 + 3)
2835            sage: l
2836            Number Field in b with defining polynomial x^2 + 3 over its base field
2837            sage: l.base_field()
2838            Number Field in a0 with defining polynomial x^2 + 2 over its base field
2839            sage: l.base_field().base_field()
2840            Number Field in a1 with defining polynomial x^2 + 1
2841        """
2842        if not names is None: name = names
2843        if not is_NumberField(base):
2844            raise TypeError, "base (=%s) must be a number field"%base
2845        if not isinstance(polynomial, polynomial_element.Polynomial):
2846            try:
2847                polynomial = polynomial.polynomial(base)
2848            except (AttributeError, TypeError), msg:
2849                raise TypeError, "polynomial (=%s) must be a polynomial."%repr(polynomial)
2850        if name == base.variable_name():
2851            raise ValueError, "Base field and extension cannot have the same name"
2852        if polynomial.parent().base_ring() != base:
2853            polynomial = polynomial.change_ring(base)
2854            #raise ValueError, "The polynomial must be defined over the base field"
2855
2856        # Generate the nf and bnf corresponding to the base field
2857        # defined as polynomials in y, e.g. for rnfisfree
2858
2859        # Convert the polynomial defining the base field into a
2860        # polynomial in y to satisfy PARI's ordering requirements.
2861
2862        if base.is_relative():
2863            abs_base = base.absolute_field('a')
2864            from_abs_base, to_abs_base = abs_base.structure()
2865        else:
2866            abs_base = base
2867            from_abs_base = maps.IdentityMap(base)
2868            to_abs_base = maps.IdentityMap(base)
2869       
2870        self.__absolute_base_field = abs_base, from_abs_base, to_abs_base
2871        Qx = abs_base.polynomial().parent()
2872        Qy = (abs_base.polynomial().base_ring())['y']
2873        phi = Qx.hom([Qy.gen()])
2874        base_polynomial_y = phi(abs_base.polynomial())
2875       
2876        self.__base_nf = pari(base_polynomial_y).nfinit()
2877        self.__base_bnf = pari(base_polynomial_y).bnfinit()
2878
2879        # Use similar methods to convert the polynomial defining the
2880        # relative extension into a polynomial in x, with y denoting
2881        # the generator of the base field.
2882        # NOTE: This should be rewritten if there is a way to extend
2883        #       homomorphisms K -> K' to homomorphisms K[x] -> K'[x].
2884        base_field_y = NumberField(abs_base.polynomial(), 'y')
2885        Kx = base_field_y['x']
2886        i = abs_base.hom([base_field_y.gen()]) # inclusion K -> K' with a -> y
2887        rel_coeffs = [i(to_abs_base(c)) for c in polynomial.coeffs()]
2888        polynomial_y = Kx(rel_coeffs)
2889
2890        if check:
2891            if not polynomial_y.is_irreducible():
2892                raise ValueError, "defining polynomial (%s) must be irreducible"%polynomial
2893
2894
2895        self.__pari_relative_polynomial = pari(str(polynomial_y))
2896        self.__rnf = self.__base_nf.rnfinit(self.__pari_relative_polynomial)
2897       
2898        self.__base_field = base
2899        self.__relative_polynomial = polynomial
2900        self.__pari_bnf_certified = False
2901        self._element_class = number_field_element.NumberFieldElement_relative
2902
2903        self.__gens = [None]
2904       
2905        v = [None]
2906        K = base
2907        names = [name]
2908        while K != QQ:
2909            names.append(K.variable_name())
2910            v.append(K.gen())
2911            K = K.base_field()
2912
2913        self._assign_names(tuple(names), normalize=False)
2914       
2915        NumberField_generic.__init__(self, self.absolute_polynomial(), name=None,
2916                                     latex_name=latex_name, check=False)
2917
2918        v[0] = self._gen_relative()
2919        v = [self(x) for x in v]
2920        self.__gens = tuple(v)
2921
2922
2923    def change_name(self, names):
2924        r"""
2925        Return relative number field isomorphic to self but with the
2926        given generator names.
2927
2928        INPUT:
2929            names -- number of names should be at most the number of
2930                     generators of self, i.e., the number of steps in
2931                     the tower of relative fields.
2932
2933        Also, \code{K.structure()} returns from_K and to_K, where
2934        from_K is an isomorphism from K to self and to_K is an
2935        isomorphism from self to K.
2936
2937        EXAMPLES:
2938            sage: K.<a,b> = NumberField([x^4 + 3, x^2 + 2]); K
2939            Number Field in a with defining polynomial x^4 + 3 over its base field
2940            sage: L.<c,d> = K.change_name()
2941            sage: L
2942            Number Field in c with defining polynomial x^4 + 3 over its base field
2943            sage: L.base_field()
2944            Number Field in d with defining polynomial x^2 + 2
2945
2946        An example with a 3-level tower:
2947            sage: K.<a,b,c> = NumberField([x^2 + 17, x^2 + x + 1, x^3 - 2]); K
2948            Number Field in a with defining polynomial x^2 + 17 over its base field
2949            sage: L.<m,n,r> = K.change_name()
2950            sage: L
2951            Number Field in m with defining polynomial x^2 + 17 over its base field
2952            sage: L.base_field()
2953            Number Field in n with defining polynomial x^2 + x + 1 over its base field
2954            sage: L.base_field().base_field()
2955            Number Field in r with defining polynomial x^3 - 2
2956           
2957        """
2958        if len(names) == 0:
2959            names = self.variable_names()
2960        elif isinstance(names, str):
2961            names = names.split(',')
2962        K = self.base_field().change_name(tuple(names[1:]))
2963        L = K.extension(self.defining_polynomial(), names=names[0])
2964        return L
2965
2966    def is_absolute(self):
2967        """
2968        EXAMPLES:
2969            sage: K.<a,b> = NumberField([x^4 + 3, x^2 + 2]); K
2970            Number Field in a with defining polynomial x^4 + 3 over its base field
2971            sage: K.is_absolute()
2972            False
2973            sage: K.is_relative()
2974            True
2975        """
2976        return False
2977   
2978    def gens(self):
2979        return self.__gens
2980
2981    def ngens(self):
2982        return len(self.__gens)
2983
2984    def gen(self, n=0):
2985        if n < 0 or n >= len(self.__gens):
2986            raise IndexError, "invalid generator %s"%n
2987        return self.__gens[n]
2988       
2989    def galois_closure(self, names=None):
2990        """
2991        Return the absolute number field $K$ that is the Galois
2992        closure of self.
2993
2994        EXAMPLES:
2995        """
2996        K = self.absolute_field('a').galois_closure(names=names)
2997        if K.degree() == self.absolute_degree():
2998            return self
2999        return K
3000
3001    def absolute_degree(self):
3002        """
3003        EXAMPLES:
3004            sage: K.<a> = NumberField([x^2 + 3, x^2 + 2])
3005            sage: K.absolute_degree()
3006            4
3007            sage: K.degree()
3008            2
3009        """
3010        return self.absolute_polynomial().degree()
3011
3012    def __reduce__(self):
3013        """
3014        TESTS:
3015            sage: Z = var('Z')
3016            sage: K.<w> = NumberField(Z^3 + Z + 1)
3017            sage: L.<z> = K.extension(Z^3 + 2)
3018            sage: L = loads(dumps(K))
3019            sage: print L
3020            Number Field in w with defining polynomial Z^3 + Z + 1
3021            sage: print L == K
3022            True       
3023        """
3024        return NumberField_relative_v1, (self.__base_field, self.polynomial(), self.variable_name(),
3025                                          self.latex_variable_name())
3026
3027    def _repr_(self):
3028        """
3029        Return string representation of this relative number field.
3030
3031        The base field is not part of the string representation.  To
3032        find out what the base field is use \code{self.base_field()}.
3033
3034        EXAMPLES:
3035            sage: k.<a, b> = NumberField([x^5 + 2, x^7 + 3])
3036            sage: k
3037            Number Field in a with defining polynomial x^5 + 2 over its base field
3038            sage: k.base_field()
3039            Number Field in b with defining polynomial x^7 + 3
3040        """
3041       
3042        return "Number Field in %s with defining polynomial %s over its base field"%(self.variable_name(), self.polynomial())
3043       
3044        #return "Extension by %s of the Number Field in %s with defining polynomial %s"%(
3045        #self.polynomial(), self.base_field().variable_name(),
3046        #    self.base_field().polynomial())
3047
3048    def _Hom_(self, codomain, cat=None):
3049        """
3050        Return homset of homomorphisms from this relative number field
3051        to the codomain.
3052
3053        The cat option is currently ignored.   The result is not cached.
3054
3055        EXAMPLES:
3056        This function is implicitly caled by the Hom method or function.
3057            sage: K.<a,b> = NumberField([x^3 - 2, x^2+1])
3058            sage: K.Hom(K)
3059            Automorphism group of Number Field in a with defining polynomial x^3 + -2 over its base field
3060            sage: type(K.Hom(K))
3061            <class 'sage.rings.number_field.morphism.RelativeNumberFieldHomset'>
3062        """
3063        import morphism
3064        return morphism.RelativeNumberFieldHomset(self, codomain)
3065
3066    def _latex_(self):
3067        r"""
3068        Return a \LaTeX representation of the extension.
3069
3070        EXAMPLE:
3071            sage: x = QQ['x'].0
3072            sage: K.<a> = NumberField(x^3 - 2)
3073            sage: t = K['x'].gen()
3074            sage: K.extension(t^2+t+a, 'b')._latex_()
3075            '( \\mathbf{Q}[a]/(a^{3} - 2) )[b]/(b^{2} + b + a)'
3076        """
3077        return "( %s )[%s]/(%s)"%(latex(self.base_field()), self.latex_variable_name(),
3078                              self.polynomial()._latex_(self.latex_variable_name()))
3079
3080    def __call__(self, x):
3081        """
3082        Coerce x into this relative number field.
3083
3084        EXAMPLES:
3085        We construct the composite of three quadratic fields, then
3086        coerce from the quartic subfield of the relative extension:
3087       
3088            sage: k.<a,b,c> = NumberField([x^2 + 5, x^2 + 3, x^2 + 1])
3089            sage: m = k.base_field(); m
3090            Number Field in b with defining polynomial x^2 + 3 over its base field
3091            sage: k(m.0)
3092            b
3093            sage: k(2/3)
3094            2/3
3095            sage: k(m.0^4)
3096            9
3097        """
3098        if isinstance(x, number_field_element.NumberFieldElement):
3099            P = x.parent()
3100            from sage.rings.number_field.order import is_NumberFieldOrder
3101            if P is self:
3102                return x
3103            elif is_NumberFieldOrder(P) and P.number_field() is self:
3104                return self._element_class(self, x.polynomial())
3105            elif P == self:
3106                return self._element_class(self, x.polynomial())
3107            return self.__base_inclusion(self.base_field()(x))
3108
3109        if not isinstance(x, (int, long, rational.Rational,
3110                              integer.Integer, pari_gen,
3111                              polynomial_element.Polynomial,
3112                              list)):
3113            return self.base_field()(x)
3114       
3115        return self._element_class(self, x)
3116
3117    def _coerce_impl(self, x):
3118        """
3119        Canonical implicit coercion of x into self.
3120
3121        Elements of this field canonically coerce in, as does anything
3122        that coerces into the base field of this field.
3123
3124        EXAMPLES:
3125            sage: k.<a> = NumberField([x^5 + 2, x^7 + 3])
3126            sage: b = k(k.base_field().gen())
3127            sage: b = k._coerce_impl(k.base_field().gen())
3128            sage: b^7
3129            -3
3130            sage: k._coerce_impl(2/3)
3131            2/3
3132            sage: c = a + b  # this works
3133        """
3134        if isinstance(x, number_field_element.NumberFieldElement):
3135            from sage.rings.number_field.order import is_NumberFieldOrder
3136            if x.parent() is self:
3137                return x
3138            elif is_NumberFieldOrder(x.parent()) and x.parent().number_field() is self:
3139                return self._element_class(self, x.polynomial())
3140            else:
3141                return self.__base_inclusion(x)
3142               
3143        return self.__base_inclusion(self.base_field()._coerce_impl(x))
3144
3145    def __base_inclusion(self, element):
3146        """
3147        Given an element of the base field, give its inclusion into
3148        this extension in terms of the generator of this field.
3149
3150        This is called by the canonical coercion map on elements from
3151        the base field.
3152
3153        EXAMPLES:
3154            sage: k.<a> = NumberField([x^2 + 3, x^2 + 1])
3155            sage: m = k.base_field(); m
3156            Number Field in a1 with defining polynomial x^2 + 1
3157            sage: k._coerce_(m.0 + 2/3)
3158            a1 + 2/3
3159            sage: s = k._coerce_(m.0); s
3160            a1
3161            sage: s^2
3162            -1
3163
3164        This implicitly tests this coercion map:
3165            sage: K.<a> = NumberField([x^2 + p for p in [5,3,2]])
3166            sage: K._coerce_(K.base_field().0)
3167            a1
3168            sage: K._coerce_(K.base_field().0)^2
3169            -3
3170        """
3171        abs_base, from_abs_base, to_abs_base = self.absolute_base_field()
3172        # Write element in terms of the absolute base field
3173        element = self.base_field()._coerce_impl(element)
3174        element = to_abs_base(element)
3175        # Obtain the polynomial in y corresponding to element in terms of the absolute base
3176        f = element.polynomial('y')
3177        # Find an expression in terms of the absolute generator for self of element.
3178        expr_x = self.pari_rnf().rnfeltreltoabs(f._pari_())
3179        # Convert to a SAGE polynomial, then to one in gen(), and return it
3180        R = self.polynomial_ring()
3181        return self(R(expr_x))
3182   
3183    def _ideal_class_(self):
3184        """
3185        Return the Python class used to represent ideals of a relative
3186        number field.
3187       
3188        EXAMPLES:
3189            sage: k.<a> = NumberField([x^5 + 2, x^7 + 3])
3190            sage: k._ideal_class_ ()
3191            <class 'sage.rings.number_field.number_field_ideal_rel.NumberFieldIdeal_rel'>
3192        """
3193        return sage.rings.number_field.number_field_ideal_rel.NumberFieldIdeal_rel
3194
3195    def _pari_base_bnf(self, proof=None):
3196        """
3197        Return the PARI bnf (big number field) representation of the
3198        base field.
3199
3200        INPUT:
3201            proof -- bool (default: True) if True, certify correctness
3202                     of calculations (not assuming GRH).
3203
3204        EXAMPLES:
3205            sage: k.<a> = NumberField([x^3 + 2, x^2 + 2])
3206            sage: k._pari_base_bnf()
3207            [[;], matrix(0,9), [;], ... 0]
3208        """
3209        proof = proof_flag(proof)       
3210        # No need to certify the same field twice, so we'll just check
3211        # that the base field is certified.
3212        if proof:
3213            self.base_field().pari_bnf_certify()
3214        return self.__base_bnf
3215
3216    def _pari_base_nf(self):
3217        """
3218        Return the PARI number field representation of the base field.
3219
3220        EXAMPLES:
3221            sage: y = polygen(QQ,'y')
3222            sage: k.<a> = NumberField([y^3 + 2, y^2 + 2])
3223            sage: k._pari_base_nf()
3224            [y^2 + 2, [0, 1], -8, 1, ..., [1, 0, 0, -2; 0, 1, 1, 0]]
3225        """
3226        return self.__base_nf
3227
3228    def is_galois(self):
3229        r"""
3230        Return True if this relative number field is Galois over $\QQ$.
3231
3232        EXAMPLES:
3233            sage: k.<a> =NumberField([x^3 - 2, x^2 + x + 1])
3234            sage: k.is_galois()
3235            True
3236            sage: k.<a> =NumberField([x^3 - 2, x^2 + 1])
3237            sage: k.is_galois()
3238            False
3239        """
3240        return self.absolute_field('a').is_galois()
3241
3242    def vector_space(self):
3243        """
3244        Return vector space over the base field of self and isomorphisms
3245        from the vector space to self and in the other direction.
3246
3247        EXAMPLES:
3248            sage: K.<a,b,c> = NumberField([x^2 + 2, x^3 + 2, x^3 + 3]); K
3249            Number Field in a with defining polynomial x^2 + 2 over its base field
3250            sage: V, from_V, to_V = K.vector_space()
3251            sage: from_V(V.0)
3252            1
3253            sage: to_V(K.0)
3254            (0, 1)
3255            sage: from_V(to_V(K.0))
3256            a
3257            sage: to_V(from_V(V.0))
3258            (1, 0)
3259            sage: to_V(from_V(V.1))
3260            (0, 1)
3261
3262        The underlying vector space and maps is cached:
3263            sage: W, from_V, to_V = K.vector_space()
3264            sage: V is W
3265            True
3266        """
3267        try:
3268            return self.__vector_space
3269        except AttributeError:
3270            pass
3271        V = self.base_field()**self.degree()
3272        from_V = maps.MapRelativeVectorSpaceToRelativeNumberField(V, self)
3273        to_V   = maps.MapRelativeNumberFieldToRelativeVectorSpace(self, V)
3274        self.__vector_space = (V, from_V, to_V)
3275        return self.__vector_space
3276
3277    def absolute_vector_space(self):
3278        """
3279        EXAMPLES:
3280            sage: K.<a,b> = NumberField([x^3 + 3, x^3 + 2]); K
3281            Number Field in a with defining polynomial x^3 + 3 over its base field
3282            sage: V,from_V,to_V = K.absolute_vector_space(); V
3283            Vector space of dimension 9 over Rational Field
3284            sage: from_V
3285            Isomorphism from Vector space of dimension 9 over Rational Field to Number Field in a with defining polynomial x^3 + 3 over its base field
3286            sage: to_V
3287            Isomorphism from Number Field in a with defining polynomial x^3 + 3 over its base field to Vector space of dimension 9 over Rational Field
3288            sage: c = (a+1)^5; c
3289            7*a^2 + (-10)*a + -29
3290            sage: to_V(c)
3291            (-29, -712/9, 19712/45, 0, -14/9, 364/45, 0, -4/9, 119/45)
3292            sage: from_V(to_V(c))
3293            7*a^2 + (-10)*a + -29
3294            sage: from_V(3*to_V(b))
3295            3*b
3296        """
3297        try:
3298            return self.__absolute_vector_space
3299        except AttributeError:
3300            pass
3301        K = self.absolute_field('a')
3302        from_K, to_K = K.structure()
3303        V, from_V, to_V = K.vector_space()
3304        fr = maps.MapVectorSpaceToRelativeNumberField(V, self, from_V, from_K)
3305        to   = maps.MapRelativeNumberFieldToVectorSpace(self, V, to_K, to_V)
3306        ans = (V, fr, to)
3307        self.__absolute_vector_space = ans
3308        return ans
3309       
3310    def absolute_base_field(self):
3311        """
3312        Return the base field of this relative extension, but viewed
3313        as an absolute field over QQ.
3314
3315        EXAMPLES:
3316            sage: K.<a,b,c> = NumberField([x^2 + 2, x^3 + 3, x^3 + 2])
3317            sage: K
3318            Number Field in a with defining polynomial x^2 + 2 over its base field
3319            sage: K.base_field()
3320            Number Field in b with defining polynomial x^3 + 3 over its base field
3321            sage: K.absolute_base_field()[0]
3322            Number Field in a with defining polynomial x^9 + 3*x^6 + 165*x^3 + 1
3323            sage: K.base_field().absolute_field('z')
3324            Number Field in z with defining polynomial x^9 + 3*x^6 + 165*x^3 + 1
3325        """
3326        return self.__absolute_base_field
3327
3328    def _gen_relative(self):
3329        """
3330        Return root of defining polynomial, which is a generator of
3331        the relative number field over the base.
3332
3333        EXAMPLES:
3334            sage: k.<a> = NumberField(x^2+1); k
3335            Number Field in a with defining polynomial x^2 + 1
3336            sage: y = polygen(k)
3337            sage: m.<b> = k.extension(y^2+3); m
3338            Number Field in b with defining polynomial x^2 + 3 over its base field
3339            sage: c = m.gen(); c
3340            b
3341            sage: c^2 + 3
3342            0
3343        """
3344        try:
3345            return self.__gen_relative
3346        except AttributeError:
3347            rnf = self.pari_rnf()
3348            f = (pari('x') - rnf[10][2]*rnf[10][1]).lift()
3349            self.__gen_relative = self._element_class(self, f)
3350            return self.__gen_relative
3351       
3352    def pari_polynomial(self):
3353        """
3354        PARI polynomial corresponding to the polynomial over the
3355        rationals that defines this field as an absolute number field.
3356
3357        EXAMPLES:
3358            sage: k.<a, c> = NumberField([x^2 + 3, x^2 + 1])
3359            sage: k.pari_polynomial()
3360            x^4 + 8*x^2 + 4
3361            sage: k.defining_polynomial ()
3362            x^2 + 3
3363        """
3364        try:
3365            return self.__pari_polynomial
3366        except AttributeError:
3367            poly = self.absolute_polynomial()
3368            with localvars(poly.parent(), 'x'):
3369                self.__pari_polynomial = poly._pari_()
3370            return self.__pari_polynomial
3371
3372    def pari_rnf(self):
3373        """
3374        Return the PARI relative number field object associated
3375        to this relative extension.
3376
3377        EXAMPLES:
3378            sage: k.<a> = NumberField([x^4 + 3, x^2 + 2])
3379            sage: k.pari_rnf()
3380            [x^4 + 3, [], [[108, 0; 0, 108], [3, 0]~], ... 0]
3381        """
3382        return self.__rnf
3383
3384    def pari_relative_polynomial(self):
3385        """
3386        Return the PARI relative polynomial associated to this
3387        number field.  This is always a polynomial in x and y.
3388
3389        EXAMPLES:
3390            sage: k.<i> = NumberField(x^2 + 1)
3391            sage: m.<z> = k.extension(k['w']([i,0,1]))
3392            sage: m
3393            Number Field in z with defining polynomial w^2 + i over its base field
3394            sage: m.pari_relative_polynomial ()
3395            x^2 + y
3396        """
3397        return self.__pari_relative_polynomial
3398
3399    def absolute_generator(self):
3400        """
3401        Return the chosen generator over QQ for this relative number field.
3402
3403        EXAMPLES:
3404            sage: y = polygen(QQ,'y')
3405            sage: k.<a> = NumberField([y^2 + 2, y^4 + 3])
3406            sage: g = k.absolute_generator(); g
3407            a0 + -a1
3408            sage: g.minpoly()
3409            x^2 + 2*a1*x + a1^2 + 2
3410            sage: g.absolute_minpoly()
3411            x^8 + 8*x^6 + 30*x^4 - 40*x^2 + 49
3412        """
3413        try:
3414            return self.__abs_gen
3415        except AttributeError:
3416            self.__abs_gen = self._element_class(self, QQ['x'].gen())
3417            return self.__abs_gen
3418       
3419
3420    def absolute_field(self, names):
3421        r"""
3422        Return an absolute number field K that is isomorphic to this
3423        field along with a field-theoretic bijection from self to K
3424        and from K to self.
3425
3426        INPUT:
3427            names -- string; name of generator of the absolute field
3428           
3429        OUTPUT:
3430            K -- an absolute number field
3431
3432        Also, \code{K.structure()} returns from_K and to_K, where
3433        from_K is an isomorphism from K to self and to_K is an isomorphism
3434        from self to K.
3435
3436        EXAMPLES:
3437            sage: K.<a,b> = NumberField([x^4 + 3, x^2 + 2]); K
3438            Number Field in a with defining polynomial x^4 + 3 over its base field
3439            sage: L.<xyz> = K.absolute_field(); L
3440            Number Field in xyz with defining polynomial x^8 + 8*x^6 + 30*x^4 - 40*x^2 + 49
3441            sage: L.<c> = K.absolute_field(); L
3442            Number Field in c with defining polynomial x^8 + 8*x^6 + 30*x^4 - 40*x^2 + 49
3443
3444            sage: from_L, to_L = L.structure()
3445            sage: from_L
3446            Isomorphism from Number Field in c with defining polynomial x^8 + 8*x^6 + 30*x^4 - 40*x^2 + 49 to Number Field in a with defining polynomial x^4 + 3 over its base field
3447            sage: from_L(c)
3448            a + -b
3449            sage: to_L
3450            Isomorphism from Number Field in a with defining polynomial x^4 + 3 over its base field to Number Field in c with defining polynomial x^8 + 8*x^6 + 30*x^4 - 40*x^2 + 49
3451            sage: to_L(a)
3452            -5/182*c^7 - 87/364*c^5 - 185/182*c^3 + 323/364*c
3453            sage: to_L(b)
3454            -5/182*c^7 - 87/364*c^5 - 185/182*c^3 - 41/364*c
3455            sage: to_L(a)^4
3456            -3
3457            sage: to_L(b)^2
3458            -2
3459        """
3460        try:
3461            return self.__absolute_field[names]
3462        except KeyError:
3463            pass
3464        except AttributeError:
3465            self.__absolute_field = {}
3466        K = NumberField(self.absolute_polynomial(), names, cache=False)
3467        from_K = maps.MapAbsoluteToRelativeNumberField(K, self)
3468        to_K = maps.MapRelativeToAbsoluteNumberField(self, K)
3469        K._set_structure(from_K, to_K)
3470        self.__absolute_field[names] = K
3471        return K
3472
3473    def absolute_polynomial(self):
3474        r"""
3475        Return the polynomial over $\QQ$ that defines this field as an
3476        extension of the rational numbers.
3477
3478        EXAMPLES:
3479            sage: k.<a, b> = NumberField([x^2 + 1, x^3 + x + 1]); k
3480            Number Field in a with defining polynomial x^2 + 1 over its base field
3481            sage: k.absolute_polynomial()
3482            x^6 + 5*x^4 - 2*x^3 + 4*x^2 + 4*x + 1
3483        """
3484        try:
3485            return self.__absolute_polynomial
3486        except AttributeError:
3487            pbn = self._pari_base_nf()
3488            prp = self.pari_relative_polynomial()
3489            pari_poly = pbn.rnfequation(prp)
3490            R = QQ['x']
3491            self.__absolute_polynomial = R(pari_poly)
3492            return self.__absolute_polynomial
3493
3494    def base_field(self):
3495        """
3496        Return the base field of this relative number field.
3497
3498        EXAMPLES:
3499            sage: k.<a> = NumberField([x^3 + x + 1])
3500            sage: R.<z> = k[]
3501            sage: L.<b> = NumberField(z^3 + a)
3502            sage: L.base_field()
3503            Number Field in a with defining polynomial x^3 + x + 1
3504            sage: L.base_field() is k
3505            True
3506
3507        This is very useful because the print representation of
3508        a relative field doesn't describe the base field.
3509            sage: L
3510            Number Field in b with defining polynomial z^3 + a over its base field
3511        """
3512        return self.__base_field
3513
3514    def base_ring(self):
3515        """
3516        This is exactly the same as base_field.
3517
3518        EXAMPLES:
3519            sage: k.<a> = NumberField([x^2 + 1, x^3 + x + 1])
3520            sage: k.base_ring()
3521            Number Field in a1 with defining polynomial x^3 + x + 1
3522            sage: k.base_field()
3523            Number Field in a1 with defining polynomial x^3 + x + 1
3524        """
3525        return self.base_field()
3526
3527    def embeddings(self, K):
3528        """
3529        Compute all field embeddings of the relative number field self
3530        into the field K (which need not even be a number field, e.g.,
3531        it could be the complex numbers). This will return an
3532        identical result when given K as input again.
3533
3534        If possible, the most natural embedding of K into self
3535        is put first in the list.
3536
3537        INPUT:
3538            K -- a number field
3539
3540        EXAMPLES:
3541            sage: K.<a,b> = NumberField([x^3 - 2, x^2+1])
3542            sage: f = K.embeddings(CC); f
3543            [Relative number field morphism:
3544              From: Number Field in a with defining polynomial x^3 + -2 over its base field
3545              To:   Complex Field with 53 bits of precision
3546              Defn: a |--> -0.629960524947442 - 1.09112363597172*I
3547                    b |--> -0.00000000000000532907051820075 + 1.00000000000000*I,
3548              ...       
3549              To:   Complex Field with 53 bits of precision
3550              Defn: a |--> 1.25992104989487 + 0.000000000000000222044604925031*I
3551                    b |--> -1.00000000000000*I]
3552            sage: f[0](a)^3
3553            2.00000000000001 - 0.0000000000000279776202205539*I
3554            sage: f[0](b)^2
3555            -1.00000000000001 - 0.0000000000000106581410364015*I
3556            sage: f[0](a+b)
3557            -0.629960524947448 - 0.0911236359717185*I
3558        """
3559        try:
3560            return self.__embeddings[K]
3561        except AttributeError:
3562            self.__embeddings = {}
3563        except KeyError:
3564            pass
3565        L = self.absolute_field('a')
3566        E = L.embeddings(K)
3567        v = [self.hom(f, K) for f in E]
3568
3569        # If there is an embedding that preserves variable names
3570        # then it is most natural, so we put it first.
3571        put_natural_embedding_first(v)
3572       
3573        self.__embeddings[K] = Sequence(v, cr=True, immutable=True, check=False, universe=self.Hom(K))
3574        return v
3575
3576    def relative_discriminant(self, proof=None):
3577        r"""
3578        Return the relative discriminant of this extension $L/K$ as
3579        an ideal of $K$.  If you want the (rational) discriminant of
3580        $L/Q$, use e.g. \code{L.discriminant()}.
3581
3582        TODO: Note that this uses PARI's \code{rnfdisc} function, which
3583        according to the documentation takes an \code{nf} parameter in
3584        GP but a \code{bnf} parameter in the C library.  If the C
3585        library actually accepts an \code{nf}, then this function
3586        should be fixed and the \code{proof} parameter removed.
3587
3588        INPUT:
3589            proof -- (default: False)
3590
3591        EXAMPLE:
3592            sage: K.<i> = NumberField(x^2 + 1)
3593            sage: t = K['t'].gen()
3594            sage: L.<b> = K.extension(t^4 - i)
3595            sage: L.relative_discriminant()
3596            Fractional ideal (256) of Number Field in i with defining polynomial x^2 + 1
3597            sage: factor(L.discriminant())
3598            2^24
3599            sage: factor( L.relative_discriminant().norm() )
3600            2^16
3601        """
3602        proof = proof_flag(proof)
3603       
3604        bnf = self._pari_base_bnf(proof)
3605        K = self.base_field()
3606        R = K.polynomial().parent()
3607        D, d = bnf.rnfdisc(self.pari_relative_polynomial())
3608        return K.ideal([ K(R(x)) for x in convert_from_zk_basis(K, D) ])
3609
3610    def order(self, *gens, **kwds):
3611        """
3612        Return the order with given ring generators in the maximal
3613        order of this number field.
3614
3615        INPUT:
3616            gens -- list of elements of self; if no generators are
3617                    given, just returns the cardinality of this number
3618                    field (oo) for consistency.
3619            base -- base of the order, which must be an order in the base
3620                    field of the relative number field self. If not specified,
3621                    then the base defaults to the ring of integers of the
3622                    base field.
3623            check_is_integral -- bool (default: True), whether to check
3624                  that each generator is integral.
3625            check_rank -- bool (default: True), whether to check that
3626                  the ring generated by gens is of full rank.
3627            allow_subfield -- bool (default: False), if True and the generators
3628                  do not generate an order, i.e., they generate a subring
3629                  of smaller rank, instead of raising an error, return
3630                  an order in a smaller number field.
3631
3632        The base, check_is_integral, and check_rank inputs must be given as
3633        explicit keyword arguments.
3634
3635        EXAMPLES:
3636       
3637        """
3638        import sage.rings.number_field.order as order
3639        if len(gens) == 0:
3640            return NumberField_generic.order(self)
3641        if len(gens) == 1 and isinstance(gens[0], (list, tuple)):
3642            gens = gens[0]
3643        gens = [self(x) for x in gens]
3644        if kwds.has_key('base'):
3645            base = kwds['base']
3646            del kwds['base']
3647            if not order.is_NumberFieldOrder(base):
3648                raise TypeError, "base must be a number field order"
3649            if base.number_field() != self.base_field():
3650                raise ValueError, "base must be an order in the base field"
3651        else:
3652            base = self.base_field().maximal_order()
3653        return order.relative_order_from_ring_generators(gens, base, **kwds)
3654       
3655
3656    def galois_group(self, pari_group = True, use_kash=False):
3657        r"""
3658        Return the Galois group of the Galois closure of this number
3659        field as an abstract group.  Note that even though this is an
3660        extension $L/K$, the group will be computed as if it were $L/\QQ$.
3661
3662        For more (important!) documentation, so the documentation
3663        for Galois groups of polynomials over $\QQ$, e.g., by
3664        typing \code{K.polynomial().galois_group?}, where $K$
3665        is a number field.
3666
3667        EXAMPLE:
3668            sage: x = QQ['x'].0
3669            sage: K.<a> = NumberField(x^2 + 1)
3670            sage: R.<t> = PolynomialRing(K)
3671            sage: L = K.extension(t^5-t+a, 'b')
3672            sage: L.galois_group()
3673            Galois group PARI group [240, -1, 22, "S(5)[x]2"] of degree 10 of the number field Number Field in b with defining polynomial t^5 + (-1)*t + a over its base field
3674        """
3675        try:
3676            return self.__galois_group[pari_group, use_kash]
3677        except KeyError:
3678            pass
3679        except AttributeError:
3680            self.__galois_group = {}
3681           
3682        G = self.absolute_polynomial().galois_group(pari_group = pari_group,
3683                                                    use_kash = use_kash)
3684        H = GaloisGroup(G, self)
3685        self.__galois_group[pari_group, use_kash] = H
3686        return H
3687   
3688
3689    def is_free(self, proof=None):
3690        r"""
3691        Determine whether or not $L/K$ is free (i.e. if $\mathcal{O}_L$ is
3692        a free $\mathcal{O}_K$-module).
3693
3694        INPUT:
3695            proof -- default: True
3696
3697        EXAMPLES:
3698            sage: x = QQ['x'].0
3699            sage: K.<a> = NumberField(x^2+6)
3700            sage: L.<b> = K.extension(K['x'].gen()^2 + 3)    ## extend by x^2+3
3701            sage: L.is_free()
3702            False
3703        """
3704        proof = proof_flag(proof)       
3705        base_bnf = self._pari_base_bnf(proof)
3706        if base_bnf.rnfisfree(self.pari_relative_polynomial()) == 1:
3707            return True
3708        return False
3709
3710    def lift_to_base(self, element):
3711        """
3712        Lift an element of this extension into the base field if possible,
3713        or raise a ValueError if it is not possible.
3714
3715        EXAMPLES:
3716            sage: x = QQ['x'].0
3717            sage: K = NumberField(x^3 - 2, 'a')
3718            sage: R = K['x']
3719            sage: L = K.extension(R.gen()^2 - K.gen(), 'b')
3720            sage: b = L.gen()
3721            sage: L.lift_to_base(b^4)
3722            a^2
3723            sage: L.lift_to_base(b)
3724            Traceback (most recent call last):
3725            ...
3726            ValueError: The element b is not in the base field
3727        """
3728        poly_xy = self.pari_rnf().rnfeltabstorel( self(element)._pari_() )
3729        str_poly = str(poly_xy)
3730        if str_poly.find('x') >= 0:
3731            raise ValueError, "The element %s is not in the base field"%element
3732        # We convert to a string to avoid some serious nastiness with
3733        # PARI polynomials secretely thinkining they are in more variables
3734        # than they are.
3735        f = QQ['y'](str_poly)
3736        return self.base_field()(f.list())
3737
3738    def polynomial(self):
3739        """
3740        Return the defining polynomial of this number field.
3741
3742        EXAMPLES:
3743            sage: y = polygen(QQ,'y')
3744            sage: k.<a> = NumberField([y^2 + y + 1, x^3 + x + 1])
3745            sage: k.polynomial()
3746            y^2 + y + 1
3747
3748        This is the same as defining_polynomial:
3749            sage: k.defining_polynomial()
3750            y^2 + y + 1
3751
3752        Use absolute polynomial for a polynomial that defines the
3753        absolute extension.
3754            sage: k.absolute_polynomial()
3755            x^6 + 3*x^5 + 8*x^4 + 9*x^3 + 7*x^2 + 6*x + 3
3756        """
3757        return self.__relative_polynomial
3758
3759    def relativize(self, alpha, names):
3760        r"""
3761        Given an element alpha in self, return a relative number field
3762        $K$ isomorphic to self that is relative over the absolute field
3763        $\QQ(\alpha)$, along with isomorphisms from $K$ to self and
3764        from self to K.
3765
3766        INPUT:
3767            alpha -- an element of self.
3768            names -- name of generator for output field K.
3769           
3770        OUTPUT:
3771            K, from_K, to_K -- relative number field, map from K to self,
3772                               map from self to K.
3773
3774        EXAMPLES:
3775            sage: K.<a,b> = NumberField([x^4 + 3, x^2 + 2]); K
3776            Number Field in a with defining polynomial x^4 + 3 over its base field
3777            sage: L.<z,w> = K.relativize(a^2)
3778            sage: z^2
3779            z^2
3780            sage: w^2
3781            -3
3782            sage: L
3783            Number Field in z with defining polynomial x^4 + (-2*w + 4)*x^2 + 4*w + 1 over its base field
3784            sage: L.base_field()
3785            Number Field in w with defining polynomial x^2 + 3
3786        """
3787        K = self.absolute_field('a')
3788        from_K, to_K = K.structure()
3789        beta = to_K(alpha)
3790        S = K.relativize(beta, names)
3791        # Now S is the appropriate field,
3792        # but the structure maps attached to S
3793        # are isomorphisms with the absolute
3794        # field.  We have to compose them
3795        # with from_K and to_K to get
3796        # the appropriate maps.
3797        from_S, to_S = S.structure()
3798
3799        # Map from S to self:
3800        #   x |--> from_K(from_S(x))
3801        # Map from self to S:
3802        #   x |--> to_K(from_K(x))
3803        new_to_S = self.Hom(S)(to_S)
3804        a = from_S.abs_hom()
3805        W = a.domain()
3806        phi = W.hom([from_K(a(W.gen()))])
3807        new_from_S = S.Hom(self)(phi)
3808        S._set_structure(new_from_S, new_to_S, unsafe_force_change=True)
3809        return S
3810
3811class NumberField_cyclotomic(NumberField_absolute):
3812    """
3813    Create a cyclotomic extension of the rational field.
3814   
3815    The command CyclotomicField(n) creates the n-th cyclotomic
3816    field, got by adjoing an n-th root of unity to the rational
3817    field.
3818   
3819    EXAMPLES:
3820        sage: CyclotomicField(3)
3821        Cyclotomic Field of order 3 and degree 2
3822        sage: CyclotomicField(18)
3823        Cyclotomic Field of order 18 and degree 6
3824        sage: z = CyclotomicField(6).gen(); z
3825        zeta6
3826        sage: z^3
3827        -1
3828        sage: (1+z)^3
3829        6*zeta6 - 3
3830
3831        sage: K = CyclotomicField(197)
3832        sage: loads(K.dumps()) == K
3833        True
3834        sage: loads((z^2).dumps()) == z^2
3835        True
3836
3837        sage: cf12 = CyclotomicField( 12 )
3838        sage: z12 = cf12.0
3839        sage: cf6 = CyclotomicField( 6 )
3840        sage: z6 = cf6.0
3841        sage: FF = Frac( cf12['x'] )
3842        sage: x = FF.0
3843        sage: print z6*x^3/(z6 + x)
3844        zeta12^2*x^3/(x + zeta12^2)       
3845    """
3846    def __init__(self, n, names):
3847        """
3848        A cyclomotic field, i.e., a field obtained by adjoining an
3849        n-th root of unity to the rational numbers.
3850
3851        EXAMPLES:
3852            sage: k = CyclotomicField(3)
3853            sage: type(k)
3854            <class 'sage.rings.number_field.number_field.NumberField_cyclotomic'>       
3855        """
3856        f = QQ['x'].cyclotomic_polynomial(n)
3857        if names[0].startswith('zeta'):
3858            latex_name = "\\zeta_{%s}"%n
3859        else:
3860            latex_name = None
3861        NumberField_absolute.__init__(self, f,
3862                                     name= names,
3863                                     latex_name=latex_name,
3864                                     check=False)
3865#        self._element_class = NumberFieldElement_cyclotomic
3866        n = integer.Integer(n)
3867        zeta = self.gen()
3868        zeta._set_multiplicative_order(n)
3869        self.__zeta_order = n
3870
3871    def __reduce__(self):
3872        """
3873        TESTS:
3874            sage: K.<zeta7> = CyclotomicField(7)
3875            sage: L = loads(dumps(K))
3876            sage: print L
3877            Cyclotomic Field of order 7 and degree 6
3878            sage: print L == K
3879            True
3880        """
3881        return NumberField_cyclotomic_v1, (self.__zeta_order, self.variable_name())
3882
3883    def _repr_(self):
3884        r"""
3885        Return string representation of this cyclotomic field.
3886
3887        The ``order'' of the cyclotomic field $\QQ(\zeta_n)$ in the
3888        string output refers to the order of the $\zeta_n$, i.e., it
3889        is the integer $n$.  The degree is the degree of the field as
3890        an extension of $\QQ$.
3891
3892        EXAMPLES:
3893            sage: CyclotomicField(4)._repr_()
3894            'Cyclotomic Field of order 4 and degree 2'
3895            sage: CyclotomicField(400)._repr_()
3896            'Cyclotomic Field of order 400 and degree 160'
3897        """
3898        return "Cyclotomic Field of order %s and degree %s"%(
3899                self.zeta_order(), self.degree())
3900
3901    def _latex_(self):
3902        """
3903        Return the latex representation of this cyclotomic field.
3904
3905        EXAMPLES:
3906            sage: Z = CyclotomicField(4)
3907            sage: Z.gen()
3908            zeta4
3909            sage: latex(Z)
3910            \mathbf{Q}(\zeta_{4})
3911
3912        Latex printing respects the generator name.
3913            sage: k.<a> = CyclotomicField(4)
3914            sage: latex(k)
3915            \mathbf{Q}[a]/(a^{2} + 1)
3916            sage: k
3917            Cyclotomic Field of order 4 and degree 2
3918            sage: k.gen()
3919            a
3920        """
3921        v = self.latex_variable_name()
3922        if v.startswith('\\zeta_'):
3923            return "%s(%s)"%(latex(QQ), v)
3924        else:
3925            return NumberField_generic._latex_(self)
3926               
3927    def __call__(self, x):
3928        """
3929        Create an element of this cyclotomic field from $x$.
3930       
3931        EXAMPLES:
3932        The following example illustrates coercion from the cyclotomic
3933        field Q(zeta_42) to the cyclotomic field Q(zeta_6), in a case
3934        where such coercion is defined:
3935       
3936            sage: k42 = CyclotomicField(42)
3937            sage: k6 = CyclotomicField(6)
3938            sage: a = k42.gen(0)
3939            sage: b = a^7
3940            sage: b
3941            zeta42^7
3942            sage: k6(b)
3943            zeta6
3944            sage: b^2
3945            zeta42^7 - 1
3946            sage: k6(b^2)
3947            zeta6 - 1
3948
3949        Coercion of GAP cyclotomic elements is also supported.
3950        """
3951        if isinstance(x, number_field_element.NumberFieldElement):
3952            if isinstance(x.parent(), NumberField_cyclotomic):
3953                return self._coerce_from_other_cyclotomic_field(x)
3954            else:
3955                return self._coerce_from_other_number_field(x)
3956        elif sage.interfaces.gap.is_GapElement(x):
3957            return self._coerce_from_gap(x)
3958        elif isinstance(x,str):
3959            return self._coerce_from_str(x)
3960        else:
3961            return self._coerce_non_number_field_element_in(x)
3962
3963    # TODO:
3964    # The following is very nice and much more flexible / powerful.
3965    # However, it is simply not *consistent*, since it totally
3966    # breaks the doctests in eisenstein_submodule.py.
3967    # FIX THIS.
3968   
3969##     def _will_be_better_coerce_from_other_cyclotomic_field(self, x, only_canonical=False):
3970##         """
3971##         Coerce an element x of a cyclotomic field into self, if at all possible.
3972
3973##         INPUT:
3974##             x -- number field element
3975
3976##             only_canonical -- bool (default: False); Attempt to work,
3977##                    even in some cases when x is not in a subfield of
3978##                    the cyclotomics (as long as x is a root of unity).
3979
3980##         EXAMPLES:
3981##             sage: k5 = CyclotomicField(5)
3982##             sage: k3 = CyclotomicField(3)
3983##             sage: k15 = CyclotomicField(15)
3984##             sage: k15._coerce_from_other_cyclotomic_field(k3.gen())
3985##             zeta15^5
3986##             sage: k15._coerce_from_other_cyclotomic_field(k3.gen()^2 + 17/3)
3987##             -zeta15^5 + 14/3
3988##             sage: k3._coerce_from_other_cyclotomic_field(k15.gen()^5)
3989##             zeta3
3990##             sage: k3._coerce_from_other_cyclotomic_field(-2/3 * k15.gen()^5 + 2/3)
3991##             -2/3*zeta3 + 2/3
3992##         """
3993       
3994##         K = x.parent()
3995
3996##         if K is self:   
3997##             return x
3998##         elif K == self:
3999##             return self._element_class(self, x.polynomial())
4000##         n = K.zeta_order()
4001##         m = self.zeta_order()
4002##         print n, m, x
4003
4004
4005##         self_gen = self.gen()
4006
4007##         if m % n == 0:   # easy case
4008##             # pass this off to a method in the element class
4009##             # it can be done very quickly and easily by the pyrex<->NTL interface there
4010##             return x._lift_cyclotomic_element(self)
4011
4012##         # Whatever happens below, it has to be consistent with
4013##         #  zeta_r |---> (zeta_s)^m
4014
4015##         if m % 2 and not n%2:
4016##             m *= 2
4017##             self_gen = -self_gen
4018           
4019##         if only_canonical and m % n:
4020##             raise TypeError, "no canonical coercion"
4021
4022##         if not is_CyclotomicField(K):
4023##             raise TypeError, "x must be in a cyclotomic field"
4024       
4025##         v = x.list()
4026
4027##         # Find the smallest power r >= 1 of the generator g of K that is in self,
4028##         # i.e., find the smallest r such that g^r has order dividing m.
4029
4030##         d = sage.rings.arith.gcd(m,n)
4031##         r = n // d
4032
4033##         # Since we use the power basis for cyclomotic fields, if every
4034##         # v[i] with i not divisible by r is 0, then we're good.
4035
4036##         # If h generates self and has order m, then the element g^r
4037##         # maps to the power of self of order gcd(m,n)., i.e., h^(m/gcd(m,n))
4038##         #
4039##         z = self_gen**(m // d)
4040##         w = self(1)
4041
4042##         a = self(0)
4043##         for i in range(len(v)):
4044##             if i%r:
4045##                 if v[i]:
4046##                     raise TypeError, "element does not belong to cyclotomic field"
4047##             else:
4048##                 a += w*v[i]
4049##                 w *= z
4050##         return a
4051
4052    def _coerce_from_other_cyclotomic_field(self, x, only_canonical=False):
4053        """
4054        Coerce an element x of a cyclotomic field into self, if at all possible.
4055
4056        INPUT:
4057            x -- number field element
4058            only_canonical -- bool (default: False); Attempt to work, even in some
4059                   cases when x is not in a subfield of the cyclotomics (as long as x is
4060                   a root of unity).
4061        """
4062        K = x.parent()
4063        if K is self:
4064            return x
4065        elif K == self:
4066            return self._element_class(self, x.polynomial())
4067        n = K.zeta_order()
4068        m = self.zeta_order()
4069        if m % n == 0:   # easy case
4070            # pass this off to a method in the element class
4071            # it can be done very quickly and easily by the pyrex<->NTL interface there
4072            return x._lift_cyclotomic_element(self)
4073        else:
4074            if only_canonical:
4075                raise TypeError
4076            n = x.multiplicative_order()
4077            if m % n == 0:
4078                # Harder case.  E.g., x = (zeta_42)^7 and
4079                # self.__zeta = zeta_6, so it is possible to
4080                # coerce x in, but not zeta_42 in.
4081                # Algorithm:
4082                #    1. Compute self.__zeta as an element
4083                #       of K = parent of x.  Call this y.
4084                #    2. Write x as a power r of y.
4085                #       TODO: we do step two STUPIDLY.
4086                #    3. Return self.__zeta to the power r.
4087                y = K(self.zeta())
4088                z = y
4089                for r in xrange(y.multiplicative_order()):
4090                    if z == x:
4091                        return self.zeta()**(r+1)
4092                    z *= y
4093            raise TypeError, "Cannot coerce %s into %s"%(x,self)
4094        return self._element_class(self, g)
4095   
4096
4097    def _coerce_from_gap(self, x):
4098        """
4099        Attempt to coerce a GAP number field element into this cyclotomic field.
4100
4101        EXAMPLES:
4102            sage: k5.<z> = CyclotomicField(5)
4103            sage: gap('E(5)^7 + 3')
4104            -3*E(5)-2*E(5)^2-3*E(5)^3-3*E(5)^4
4105            sage: w = gap('E(5)^7 + 3')
4106            sage: z^7 + 3
4107            z^2 + 3
4108            sage: k5(w)
4109            z^2 + 3
4110        """
4111        s = str(x)
4112        i = s.find('E(')
4113        if i == -1:
4114            return self(rational.Rational(s))
4115        j = i + s[i:].find(')')
4116        n = int(s[i+2:j])
4117        if n == self.zeta_order():
4118            K = self
4119        else:
4120            K = CyclotomicField(n)
4121        zeta = K.gen()
4122        s = s.replace('E(%s)'%n,'zeta')
4123        s = sage.misc.all.sage_eval(s, locals={'zeta':K.gen()})
4124        if K is self:
4125            return s
4126        else:
4127            return self(s)
4128
4129    def _coerce_impl(self, x):
4130        """
4131        Canonical implicit coercion of x into self.
4132
4133        Elements of other compatible cyclotomic fields coerce in, as
4134        do elements of the rings that coerce to all number fields
4135        (e.g., integers, rationals).
4136
4137        EXAMPLES:
4138            sage: CyclotomicField(15)._coerce_impl(CyclotomicField(5).0 - 17/3)
4139            zeta15^3 - 17/3
4140            sage: K.<a> = CyclotomicField(16)
4141            sage: K(CyclotomicField(4).0)
4142            a^4
4143        """
4144        if isinstance(x, number_field_element.NumberFieldElement) and \
4145                isinstance(x.parent(), NumberField_cyclotomic):
4146            return self._coerce_from_other_cyclotomic_field(x, only_canonical=True)
4147        return NumberField_generic._coerce_impl(self, x)
4148
4149    def is_galois(self):
4150        """
4151        Return True since all cyclotomic fields are automatically Galois.
4152
4153        EXAMPLES:
4154            sage: CyclotomicField(29).is_galois()
4155            True
4156        """
4157        return True
4158
4159    def complex_embedding(self, prec=53):
4160        r"""
4161        Return the embedding of this cyclotomic field into the
4162        approximate complex field with precision prec obtained by
4163        sending the generator $\zeta$ of self to exp(2*pi*i/n), where
4164        $n$ is the multiplicative order of $\zeta$.
4165
4166        EXAMPLES:
4167            sage: C = CyclotomicField(4)
4168            sage: C.complex_embedding()
4169            Ring morphism:
4170              From: Cyclotomic Field of order 4 and degree 2
4171              To:   Complex Field with 53 bits of precision
4172              Defn: zeta4 |--> 6.12323399573677e-17 + 1.00000000000000*I
4173             
4174        Note in the example above that the way zeta is computed (using
4175        sin and cosine in MPFR) means that only the prec bits of the
4176        number after the decimal point are valid.
4177             
4178            sage: K = CyclotomicField(3)
4179            sage: phi = K.complex_embedding (10)
4180            sage: phi(K.0)
4181            -0.50 + 0.87*I
4182            sage: phi(K.0^3)
4183            1.0
4184            sage: phi(K.0^3 - 1)
4185            0
4186            sage: phi(K.0^3 + 7)
4187            8.0
4188        """
4189        CC = sage.rings.complex_field.ComplexField(prec)
4190        return self.hom([CC.zeta(self.zeta_order())], check=False)
4191
4192    def complex_embeddings(self, prec=53):
4193        r"""
4194        Return all embeddings of this cyclotomic field into the
4195        approximate complex field with precision prec.
4196
4197        EXAMPLES:
4198            sage: C = CyclotomicField(4)
4199            sage: C.complex_embeddings()
4200            [Ring morphism:
4201              From: Cyclotomic Field of order 4 and degree 2
4202              To:   Complex Field with 53 bits of precision
4203              Defn: zeta4 |--> 6.12323399573677e-17 + 1.00000000000000*I, Ring morphism:
4204              From: Cyclotomic Field of order 4 and degree 2
4205              To:   Complex Field with 53 bits of precision
4206              Defn: zeta4 |--> -0.000000000000000183697019872103 - 1.00000000000000*I]
4207        """
4208        CC = sage.rings.complex_field.ComplexField(prec)
4209        n = self.zeta_order()
4210        z = CC.zeta(self.zeta_order())
4211        X = [m for m in range(n) if sage.rings.arith.gcd(m,n) == 1]
4212        return [self.hom([z**n], check=False) for n in X]
4213
4214    def next_split_prime(self, p=2):
4215        """
4216        Return the next prime integer $p$ that splits completely in
4217        this cyclotomic field (and does not ramify).
4218
4219        EXAMPLES:
4220            sage: K.<z> = CyclotomicField(3)
4221            sage: K.next_split_prime(7)
4222            13           
4223        """
4224        n = self.zeta_order()
4225        while True:
4226            p = sage.rings.arith.next_prime(p)
4227            if p % n == 1:
4228                return p
4229
4230    def integral_basis(self):
4231        """
4232        Return a list of elements of this number field that are a basis
4233        for the full ring of integers.
4234
4235        This field is cyclomotic, so this is a trivial computation,
4236        since the power basis on the generator is an integral basis.
4237
4238        EXAMPLES:
4239            sage: CyclotomicField(5).integral_basis()
4240            [1, zeta5, zeta5^2, zeta5^3]
4241        """
4242        try:
4243            return self.__integral_basis
4244        except AttributeError:
4245            z = self.gen()
4246            a = self(1)
4247            B = []
4248            for n in xrange(self.degree()):
4249                B.append(a)
4250                a *= z
4251            self.__integral_basis = B
4252        return self.__integral_basis
4253       
4254               
4255    def zeta_order(self):
4256        """
4257        Return the order of the root of unity that generates this
4258        cyclotomic field.
4259       
4260        EXAMPLES:
4261            sage: CyclotomicField(1).zeta_order()
4262            1
4263            sage: CyclotomicField(4).zeta_order()
4264            4
4265            sage: CyclotomicField(5).zeta_order()
4266            5
4267            sage: CyclotomicField(389).zeta_order()
4268            389
4269        """
4270        return self.__zeta_order
4271       
4272    def _multiplicative_order_table(self):
4273        """
4274        Return a dictionary that maps powers of zeta to their order.
4275        This makes computing the orders of the elements of finite
4276        order in this field faster.
4277
4278        EXAMPLES:
4279            sage: v = CyclotomicField(6)._multiplicative_order_table()
4280            sage: w = v.items(); w.sort(); w
4281            [(-1, 2), (1, 1), (-x, 3), (-x + 1, 6), (x - 1, 3), (x, 6)]
4282        """
4283        try:
4284            return self.__multiplicative_order_table
4285        except AttributeError:
4286            t = {}
4287            x = self(1)
4288            n = self.zeta_order()
4289            m = 0
4290            zeta = self.zeta()
4291            # todo: this desperately needs to be optimized!!!
4292            for i in range(n):
4293                t[x.polynomial()] = n//arith.GCD(m,n)   # multiplicative_order of (zeta_n)**m
4294                x *= zeta
4295                m += 1
4296            self.__multiplicative_order_table = t
4297            return t
4298
4299    def zeta(self, n=None, all=False):
4300        """
4301        Returns an element of multiplicative order $n$ in this this
4302        number field, if there is one.  Raises a ValueError if there
4303        is not.
4304
4305        INPUT:
4306            n -- integer (default: None, returns element of maximal order)
4307            all -- bool (default: False) -- whether to return a list of
4308                        all n-th roots.
4309
4310        OUTPUT:
4311            root of unity or list
4312
4313        EXAMPLES:
4314            sage: k = CyclotomicField(7)
4315            sage: k.zeta()
4316            zeta7
4317            sage: k.zeta().multiplicative_order()
4318            7
4319            sage: k = CyclotomicField(49)
4320            sage: k.zeta().multiplicative_order()
4321            49
4322            sage: k.zeta(7).multiplicative_order()
4323            7
4324            sage: k.zeta()
4325            zeta49
4326            sage: k.zeta(7)
4327            zeta49^7
4328
4329            sage: K.<a> = CyclotomicField(5)
4330            sage: K.zeta(4)
4331            Traceback (most recent call last):
4332            ...
4333            ValueError: n (=4) does not divide order of generator
4334            sage: v = K.zeta(5, all=True); v
4335            [a, a^2, a^3, -a^3 - a^2 - a - 1]
4336            sage: [b^5 for b in v]
4337            [1, 1, 1, 1]           
4338        """
4339        if n is None:
4340            return self.gen()
4341        else:
4342            n = integer.Integer(n)
4343            z = self.gen()
4344            m = z.multiplicative_order()
4345            if m % n != 0:
4346                raise ValueError, "n (=%s) does not divide order of generator"%n
4347                # use generic method (factor cyclotomic polynomial)
4348                #  -- this is potentially really slow, so don't do it.
4349                #return field.Field.zeta(self, n, all=all)
4350            a = z**(m//n)
4351            if all:
4352                v = [a]
4353                b = a*a
4354                for i in range(2,n):
4355                    if sage.rings.arith.gcd(i, n) == 1:
4356                        v.append(b)
4357                    b = b * a
4358                return v
4359            else:
4360                return a
4361   
4362class NumberField_quadratic(NumberField_absolute):
4363    """
4364    Create a quadratic extension of the rational field.
4365   
4366    The command QuadraticExtension(a) creates the field Q(sqrt(a)).
4367   
4368    EXAMPLES:
4369        sage: QuadraticField(3, 'a')
4370        Number Field in a with defining polynomial x^2 - 3
4371        sage: QuadraticField(-4, 'b')
4372        Number Field in b with defining polynomial x^2 + 4
4373    """
4374    def __init__(self, polynomial, name=None, check=True):
4375        """
4376        Create a quadratic number field.
4377
4378        EXAMPLES:
4379            sage: k.<a> = QuadraticField(5, check=False); k
4380            Number Field in a with defining polynomial x^2 - 5
4381
4382        Don't do this:
4383            sage: k.<a> = QuadraticField(4, check=False); k
4384            Number Field in a with defining polynomial x^2 - 4
4385        """
4386        NumberField_absolute.__init__(self, polynomial, name=name, check=check)
4387        return 
4388        # optimized quadratic elements currently disabled -- they
4389        # break docs in the modular symbols / modular forms directory!!
4390        self._element_class = number_field_element_quadratic.NumberFieldElement_quadratic
4391        c, b, a = [rational.Rational(t) for t in self.defining_polynomial().list()]
4392        # set the generator
4393        D = b*b - 4*a*c
4394        d = D.numer().squarefree_part() * D.denom().squarefree_part()
4395        if d % 4 != 1:
4396            d *= 4
4397        self._NumberField_generic__disc = d
4398        parts = -b/(2*a), (D/d).sqrt()/(2*a)
4399        self._NumberField_generic__gen = self._element_class(self, parts)
4400       
4401    def __reduce__(self):
4402        """
4403        This is used in pickling quadratic number fields.
4404       
4405        TESTS:
4406            sage: K.<z7> = QuadraticField(7)
4407            sage: L = loads(dumps(K))
4408            sage: print L
4409            Number Field in z7 with defining polynomial x^2 - 7
4410            sage: print L == K
4411            True
4412        """
4413        return NumberField_quadratic_v1, (self.polynomial(), self.variable_name())
4414       
4415
4416    def is_galois(self):
4417        """
4418        Return True since all quadratic fields are automatically Galois.
4419
4420        EXAMPLES:
4421            sage: QuadraticField(1234,'d').is_galois()
4422            True       
4423        """
4424        return True
4425
4426    def class_number(self, proof=None):
4427        r"""
4428        Return the size of the class group of self.
4429
4430        If proof = False (*not* the default!) and the discriminant of the
4431        field is negative, then the following warning from the PARI
4432        manual applies: IMPORTANT WARNING: For $D<0$, this function
4433        may give incorrect results when the class group has a low
4434        exponent (has many cyclic factors), because implementing
4435        Shank's method in full generality slows it down immensely.
4436
4437        EXAMPLES:
4438            sage: QuadraticField(-23,'a').class_number()
4439            3
4440
4441        These are all the primes so that the class number of $\QQ(\sqrt{-p})$ is $1$:
4442            sage: [d for d in prime_range(2,300) if not is_square(d) and QuadraticField(-d,'a').class_number() == 1]
4443            [2, 3, 7, 11, 19, 43, 67, 163]
4444
4445        It is an open problem to \emph{prove} that there are infinity
4446        many positive square-free $d$ such that $\QQ(\sqrt{d})$ has
4447        class number $1$:n
4448            sage: len([d for d in range(2,200) if not is_square(d) and QuadraticField(d,'a').class_number() == 1])
4449            121
4450        """
4451        proof = proof_flag(proof)       
4452        try:
4453            return self.__class_number
4454        except AttributeError:
4455            D = self.discriminant()
4456            if D < 0 and proof:
4457                self.__class_number = pari("qfbclassno(%s,1)"%D).python()
4458            else:
4459                self.__class_number = pari("qfbclassno(%s)"%D).python()
4460            return self.__class_number
4461
4462    def hilbert_class_polynomial(self):
4463        r"""
4464        Returns a polynomial over $\QQ$ whose roots generate the
4465        Hilbert class field of this quadratic field.
4466
4467        \note{Computed using PARI via Schertz's method.  This
4468        implementation is quite fast.}
4469
4470        EXAMPLES:
4471            sage: K.<b> = QuadraticField(-23)
4472            sage: K.hilbert_class_polynomial()
4473            x^3 + x^2 - 1
4474
4475            sage: K.<a> = QuadraticField(-431)
4476            sage: K.class_number()
4477            21
4478            sage: K.hilbert_class_polynomial()
4479            x^21 + x^20 - 13*x^19 - 50*x^18 + 592*x^17 - 2403*x^16 + 5969*x^15 - 10327*x^14 + 13253*x^13 - 12977*x^12 + 9066*x^11 - 2248*x^10 - 5523*x^9 + 11541*x^8 - 13570*x^7 + 11315*x^6 - 6750*x^5 + 2688*x^4 - 577*x^3 + 9*x^2 + 15*x + 1
4480        """
4481        f = pari('quadhilbert(%s))'%self.discriminant())
4482        g = QQ['x'](f)
4483        return g
4484
4485    def hilbert_class_field(self, names):
4486        r"""
4487        Returns the Hilbert class field of this quadratic field as an
4488        absolute extension of $\QQ$.  For a polynomial that defines a
4489        relative extension see the \code{hilbert_class_polynomial}
4490        command.
4491
4492        \note{Computed using PARI via Schertz's method.  This implementation
4493        is amazingly fast.}       
4494
4495        EXAMPLES:
4496            sage: x = QQ['x'].0
4497            sage: K = NumberField(x^2 + 23, 'a')
4498            sage: K.hilbert_class_polynomial()
4499            x^3 + x^2 - 1
4500            sage: K.hilbert_class_field('h')
4501            Number Field in h with defining polynomial x^6 + 2*x^5 + 70*x^4 + 90*x^3 + 1631*x^2 + 1196*x + 12743
4502        """
4503        f = self.hilbert_class_polynomial()
4504        C = self.composite_fields(NumberField(f,'x'),names)
4505        assert len(C) == 1
4506        return C[0]
4507
4508def is_fundamental_discriminant(D):
4509    r"""
4510    Return True if the integer $D$ is a fundamental discriminant, i.e.,
4511    if $D \con 0,1\pmod{4}$, and $D\neq 0, 1$ and either (1) $D$ is square free
4512    or (2) we have $D\con 0\pmod{4}$ with $D/4 \con 2,3\pmod{4}$ and $D/4$
4513    square free.  These are exactly the discriminants of quadratic fields.
4514
4515    EXAMPLES:
4516        sage: [D for D in range(-15,15) if is_fundamental_discriminant(D)]
4517        [-15, -11, -8, -7, -4, -3, 5, 8, 12, 13]
4518        sage: [D for D in range(-15,15) if not is_square(D) and QuadraticField(D,'a').disc() == D]
4519        [-15, -11, -8, -7, -4, -3, 5, 8, 12, 13]
4520    """
4521    d = D % 4
4522    if not (d in [0,1]):
4523        return False
4524    return D != 1 and  D != 0 and \
4525           (arith.is_squarefree(D) or \
4526            (d == 0 and (D//4)%4 in [2,3] and arith.is_squarefree(D//4)))
4527
4528
4529###################
4530# For pickling
4531###################
4532
4533
4534def NumberField_absolute_v1(poly, name, latex_name):
4535    """
4536    This is used in pickling generic number fields.
4537   
4538    EXAMPLES:
4539        sage: from sage.rings.number_field.number_field import NumberField_generic_v1
4540        sage: R.<x> = QQ[]
4541        sage: NumberField_generic_v1(x^2 + 1, 'i', 'i')
4542        Number Field in i with defining polynomial x^2 + 1
4543    """
4544    return NumberField_absolute(poly, name, latex_name, check=False)
4545
4546NumberField_generic_v1 = NumberField_absolute_v1  # for historical reasons only (so old objects unpickle)
4547
4548def NumberField_relative_v1(base_field, poly, name, latex_name):
4549    """
4550    This is used in pickling relative fields.
4551   
4552    EXAMPLES:
4553        sage: from sage.rings.number_field.number_field import NumberField_relative_v1
4554        sage: R.<x> = CyclotomicField(3)[]
4555        sage: NumberField_relative_v1(CyclotomicField(3), x^2 + 7, 'a', 'a')
4556        Number Field in a with defining polynomial x^2 + 7 over its base field
4557    """
4558    return NumberField_relative(base_field, poly, name, latex_name, check=False)
4559
4560NumberField_extension_v1 = NumberField_relative_v1  # historical reasons only
4561
4562def NumberField_cyclotomic_v1(zeta_order, name):
4563    """
4564    This is used in pickling cyclotomic fields.
4565   
4566    EXAMPLES:
4567        sage: from sage.rings.number_field.number_field import NumberField_cyclotomic_v1
4568        sage: NumberField_cyclotomic_v1(5,'a')
4569        Cyclotomic Field of order 5 and degree 4
4570        sage: NumberField_cyclotomic_v1(5,'a').variable_name()
4571        'a'
4572    """
4573    return NumberField_cyclotomic(zeta_order, name)
4574
4575def NumberField_quadratic_v1(poly, name):
4576    """
4577    This is used in pickling quadratic fields.
4578   
4579    EXAMPLES:
4580        sage: from sage.rings.number_field.number_field import NumberField_quadratic_v1
4581        sage: R.<x> = QQ[]
4582        sage: NumberField_quadratic_v1(x^2 - 2, 'd')
4583        Number Field in d with defining polynomial x^2 - 2
4584    """
4585    return NumberField_quadratic(poly, name, check=False)
4586
4587
4588def put_natural_embedding_first(v):
4589    for i in range(len(v)):
4590        phi = v[i]
4591        a = str(list(phi.domain().gens()))
4592        b = str(list(phi.im_gens()))
4593        if a == b:
4594            v[i] = v[0]
4595            v[0] = phi
4596            return
4597       
Note: See TracBrowser for help on using the repository browser.