Path: blob/master/src/sage/modules/free_module_element.pyx
8815 views
r"""1Elements of free modules23AUTHORS:45- William Stein67- Josh Kantor89- Thomas Feulner (2012-11): Added :meth:`FreeModuleElement.hamming_weight` and10:meth:`FreeModuleElement_generic_sparse.hamming_weight`1112TODO: Change to use a get_unsafe / set_unsafe, etc., structure13exactly like with matrices, since we'll have to define a bunch of14special purpose implementations of vectors easily and15systematically.1617EXAMPLES: We create a vector space over `\QQ` and a18subspace of this space.1920::2122sage: V = QQ^523sage: W = V.span([V.1, V.2])2425Arithmetic operations always return something in the ambient space,26since there is a canonical map from `W` to `V` but27not from `V` to `W`.2829::3031sage: parent(W.0 + V.1)32Vector space of dimension 5 over Rational Field33sage: parent(V.1 + W.0)34Vector space of dimension 5 over Rational Field35sage: W.0 + V.136(0, 2, 0, 0, 0)37sage: W.0 - V.038(-1, 1, 0, 0, 0)3940Next we define modules over `\ZZ` and a finite41field.4243::4445sage: K = ZZ^546sage: M = GF(7)^54748Arithmetic between the `\QQ` and49`\ZZ` modules is defined, and the result is always50over `\QQ`, since there is a canonical coercion map51to `\QQ`.5253::5455sage: K.0 + V.156(1, 1, 0, 0, 0)57sage: parent(K.0 + V.1)58Vector space of dimension 5 over Rational Field5960Since there is no canonical coercion map to the finite field from61`\QQ` the following arithmetic is not defined::6263sage: V.0 + M.064Traceback (most recent call last):65...66TypeError: unsupported operand parent(s) for '+': 'Vector space of dimension 5 over Rational Field' and 'Vector space of dimension 5 over Finite Field of size 7'6768However, there is a map from `\ZZ` to the finite69field, so the following is defined, and the result is in the finite70field.7172::7374sage: w = K.0 + M.0; w75(2, 0, 0, 0, 0)76sage: parent(w)77Vector space of dimension 5 over Finite Field of size 778sage: parent(M.0 + K.0)79Vector space of dimension 5 over Finite Field of size 78081Matrix vector multiply::8283sage: MS = MatrixSpace(QQ,3)84sage: A = MS([0,1,0,1,0,0,0,0,1])85sage: V = QQ^386sage: v = V([1,2,3])87sage: v * A88(2, 1, 3)8990TESTS::9192sage: D = 4634193sage: u = 794sage: R = Integers(D)95sage: p = matrix(R,[[84, 97, 55, 58, 51]])96sage: 2*p.row(0)97(168, 194, 110, 116, 102)98"""99100import math101import operator102103include 'sage/ext/cdefs.pxi'104include 'sage/ext/stdsage.pxi'105from cpython.dict cimport *106from cpython.list cimport *107import sage.misc.misc as misc108import sage.misc.latex109110from sage.structure.sequence import Sequence111112from sage.structure.element cimport Element, ModuleElement, RingElement, Vector as element_Vector113from sage.structure.element import canonical_coercion114115import sage.rings.arith116117from sage.rings.infinity import Infinity118import sage.rings.integer119from sage.rings.integer_ring import ZZ120from sage.rings.real_double import RDF121from sage.rings.complex_double import CDF122from sage.misc.derivative import multi_derivative123124125# We use some cimports for very quick checking of Integer and Ring126# type to optimize vector(ring,n) for creating the zero vector.127from sage.rings.ring cimport Ring128from sage.rings.integer cimport Integer129130# We define our own faster is_Ring since is_Ring in the131# sage.rings.ring module is slow due to it doing an import every time,132# and creating a category. We should rarely hit the second case133# (is_Ring_slow below). Note that this function will slightly slow134# down in the very rare case when R is not of type Ring, but it is in135# the category of rings. But it gives a big speedup for the most136# common case when R is a Ring.137from sage.rings.ring import is_Ring as is_Ring_slow138cdef is_Ring(R):139return isinstance(R, Ring) or is_Ring_slow(R)140141#For the norm function, we cache a Sage integer "one"142__one__ = sage.rings.integer.Integer(1)143144def is_FreeModuleElement(x):145"""146EXAMPLES::147148sage: sage.modules.free_module_element.is_FreeModuleElement(0)149False150sage: sage.modules.free_module_element.is_FreeModuleElement(vector([1,2,3]))151True152"""153return isinstance(x, FreeModuleElement)154155def vector(arg0, arg1=None, arg2=None, sparse=None):156r"""157Return a vector or free module element with specified entries.158159CALL FORMATS:160161This constructor can be called in several different ways.162In each case, ``sparse=True`` or ``sparse=False`` can be163supplied as an option. ``free_module_element()`` is an164alias for ``vector()``.1651661. vector(object)1671682. vector(ring, object)1691703. vector(object, ring)1711724. vector(ring, degree, object)1731745. vector(ring, degree)1751766. vector(numpy_array)177178INPUT:179180- ``object`` - a list, dictionary, or other181iterable containing the entries of the vector, including182any object that is palatable to the ``Sequence`` constructor183184- ``ring`` - a base ring (or field) for the vector185space or free module, which contains all of the elements186187- ``degree`` - an integer specifying the number of188entries in the vector or free module element189190- ``numpy_array`` - a NumPy array with the desired entries191192- ``sparse`` - optional193194In call format 4, an error is raised if the ``degree`` does not match195the length of ``object`` so this call can provide some safeguards.196Note however that using this format when ``object`` is a dictionary197is unlikely to work properly.198199OUTPUT:200201An element of the vector space or free module with the given202base ring and implied or specified dimension or rank,203containing the specified entries and with correct degree.204205In call format 5, no entries are specified, so the element is206populated with all zeros.207208If the ``sparse`` option is not supplied, the output will209generally have a dense representation. The exception is if210``object`` is a dictionary, then the representation will be sparse.211212EXAMPLES::213214sage: v = vector([1,2,3]); v215(1, 2, 3)216sage: v.parent()217Ambient free module of rank 3 over the principal ideal domain Integer Ring218sage: v = vector([1,2,3/5]); v219(1, 2, 3/5)220sage: v.parent()221Vector space of dimension 3 over Rational Field222223All entries must *canonically* coerce to some common ring::224225sage: v = vector([17, GF(11)(5), 19/3]); v226Traceback (most recent call last):227...228TypeError: unable to find a common ring for all elements229230::231232sage: v = vector([17, GF(11)(5), 19]); v233(6, 5, 8)234sage: v.parent()235Vector space of dimension 3 over Finite Field of size 11236sage: v = vector([17, GF(11)(5), 19], QQ); v237(17, 5, 19)238sage: v.parent()239Vector space of dimension 3 over Rational Field240sage: v = vector((1,2,3), QQ); v241(1, 2, 3)242sage: v.parent()243Vector space of dimension 3 over Rational Field244sage: v = vector(QQ, (1,2,3)); v245(1, 2, 3)246sage: v.parent()247Vector space of dimension 3 over Rational Field248sage: v = vector(vector([1,2,3])); v249(1, 2, 3)250sage: v.parent()251Ambient free module of rank 3 over the principal ideal domain Integer Ring252253You can also use ``free_module_element``, which is254the same as ``vector``. ::255256sage: free_module_element([1/3, -4/5])257(1/3, -4/5)258259We make a vector mod 3 out of a vector over `\ZZ`. ::260261sage: vector(vector([1,2,3]), GF(3))262(1, 2, 0)263264The degree of a vector may be specified::265266sage: vector(QQ, 4, [1,1/2,1/3,1/4])267(1, 1/2, 1/3, 1/4)268269But it is an error if the degree and size of the list of entries270are mismatched::271272sage: vector(QQ, 5, [1,1/2,1/3,1/4])273Traceback (most recent call last):274...275ValueError: incompatible degrees in vector constructor276277Providing no entries populates the vector with zeros, but of course,278you must specify the degree since it is not implied. Here we use a279finite field as the base ring. ::280281sage: w = vector(FiniteField(7), 4); w282(0, 0, 0, 0)283sage: w.parent()284Vector space of dimension 4 over Finite Field of size 7285286The fastest method to construct a zero vector is to call the287:meth:`~sage.modules.free_module.FreeModule_generic.zero_vector`288method directly on a free module or vector space, since289vector(...) must do a small amount of type checking. Almost as290fast as the ``zero_vector()`` method is the291:func:`~sage.modules.free_module_element.zero_vector` constructor,292which defaults to the integers. ::293294sage: vector(ZZ, 5) # works fine295(0, 0, 0, 0, 0)296sage: (ZZ^5).zero_vector() # very tiny bit faster297(0, 0, 0, 0, 0)298sage: zero_vector(ZZ, 5) # similar speed to vector(...)299(0, 0, 0, 0, 0)300sage: z = zero_vector(5); z301(0, 0, 0, 0, 0)302sage: z.parent()303Ambient free module of rank 5 over304the principal ideal domain Integer Ring305306Here we illustrate the creation of sparse vectors by using a307dictionary. ::308309sage: vector({1:1.1, 3:3.14})310(0.000000000000000, 1.10000000000000, 0.000000000000000, 3.14000000000000)311312With no degree given, a dictionary of entries implicitly declares a313degree by the largest index (key) present. So you can provide a314terminal element (perhaps a zero?) to set the degree. But it is probably safer315to just include a degree in your construction. ::316317sage: v = vector(QQ, {0:1/2, 4:-6, 7:0}); v318(1/2, 0, 0, 0, -6, 0, 0, 0)319sage: v.degree()3208321sage: v.is_sparse()322True323sage: w = vector(QQ, 8, {0:1/2, 4:-6})324sage: w == v325True326327It is an error to specify a negative degree. ::328329sage: vector(RR, -4, [1.0, 2.0, 3.0, 4.0])330Traceback (most recent call last):331...332ValueError: cannot specify the degree of a vector as a negative integer (-4)333334It is an error to create a zero vector but not provide335a ring as the first argument. ::336337sage: vector('junk', 20)338Traceback (most recent call last):339...340TypeError: first argument must be base ring of zero vector, not junk341342And it is an error to specify an index in a dictionary343that is greater than or equal to a requested degree. ::344345sage: vector(ZZ, 10, {3:4, 7:-2, 10:637})346Traceback (most recent call last):347...348ValueError: dictionary of entries has a key (index) exceeding the requested degree349350Any 1 dimensional numpy array of type float or complex may be351passed to vector. The result will be a vector in the appropriate352dimensional vector space over the real double field or the complex353double field. The data in the array must be contiguous so354column-wise slices of numpy matrices will raise an exception. ::355356sage: import numpy357sage: x=numpy.random.randn(10)358sage: y=vector(x)359sage: v=numpy.random.randn(10)*numpy.complex(0,1)360sage: w=vector(v)361362If any of the arguments to vector have Python type int, long, real,363or complex, they will first be coerced to the appropriate Sage364objects. This fixes trac #3847. ::365366sage: v = vector([int(0)]); v367(0)368sage: v[0].parent()369Integer Ring370sage: v = vector(range(10)); v371(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)372sage: v[3].parent()373Integer Ring374sage: v = vector([float(23.4), int(2), complex(2+7*I), long(1)]); v375(23.4, 2.0, 2.0 + 7.0*I, 1.0)376sage: v[1].parent()377Complex Double Field378379If the argument is a vector, it doesn't change the base ring. This380fixes trac #6643. ::381382sage: K.<sqrt3> = QuadraticField(3)383sage: u = vector(K, (1/2, sqrt3/2) )384sage: vector(u).base_ring()385Number Field in sqrt3 with defining polynomial x^2 - 3386sage: v = vector(K, (0, 1) )387sage: vector(v).base_ring()388Number Field in sqrt3 with defining polynomial x^2 - 3389390Constructing a vector from a numpy array behaves as expected::391392sage: import numpy393sage: a=numpy.array([1,2,3])394sage: v=vector(a); v395(1, 2, 3)396sage: parent(v)397Ambient free module of rank 3 over the principal ideal domain Integer Ring398399Complex numbers can be converted naturally to a sequence of length 2. And400then to a vector. ::401402sage: c = CDF(2 + 3*I)403sage: v = vector(c); v404(2.0, 3.0)405406A generator, or other iterable, may also be supplied as input. Anything407that can be converted to a :class:`~sage.structure.sequence.Sequence` is408a possible input. ::409410sage: type(i^2 for i in range(3))411<type 'generator'>412sage: v = vector(i^2 for i in range(3)); v413(0, 1, 4)414415An empty list, without a ring given, will default to the integers. ::416417sage: x = vector([]); x418()419sage: x.parent()420Ambient free module of rank 0 over the principal ideal domain Integer Ring421"""422# We first efficiently handle the important special case of the zero vector423# over a ring. See trac 11657.424# !! PLEASE DO NOT MOVE THIS CODE LOWER IN THIS FUNCTION !!425if arg2 is None and is_Ring(arg0) and (isinstance(arg1, (int, long, Integer))):426return (arg0**arg1).zero_vector()427428# WARNING TO FUTURE OPTIMIZERS: The following two hasattr's take429# quite a significant amount of time.430if hasattr(arg0, '_vector_'):431return arg0._vector_(arg1)432433if hasattr(arg1, '_vector_'):434return arg1._vector_(arg0)435436# consider a possible degree specified in second argument437degree = None438maxindex = None439if sage.rings.integer.is_Integer(arg1) or isinstance(arg1,(int,long)):440if arg1 < 0:441raise ValueError("cannot specify the degree of a vector as a negative integer (%s)" % arg1)442if isinstance(arg2, dict):443maxindex = max([-1]+[index for index in arg2])444if not maxindex < arg1:445raise ValueError("dictionary of entries has a key (index) exceeding the requested degree")446# arg1 is now a legitimate degree447# With no arg2, we can try to return a zero vector448# else we size-check arg2 and slide it into arg1449degree = arg1450if arg2 is None:451if not is_Ring(arg0):452msg = "first argument must be base ring of zero vector, not {0}"453raise TypeError(msg.format(arg0))454else:455if not isinstance(arg2, dict) and len(arg2) != degree:456raise ValueError("incompatible degrees in vector constructor")457arg1 = arg2458459# Analyze arg0 and arg1 to create a ring (R) and entries (v)460if is_Ring(arg0):461R = arg0462v = arg1463elif is_Ring(arg1):464R = arg1465v = arg0466else:467v = arg0468R = None469470from numpy import ndarray471from free_module import VectorSpace472if isinstance(v,ndarray):473if len(v.shape)==1:474if str(v.dtype).count('float')==1:475V=VectorSpace(RDF,v.shape[0])476import vector_real_double_dense477_v=vector_real_double_dense.Vector_real_double_dense(V, v)478return _v479if str(v.dtype).count('complex')==1:480V=VectorSpace(CDF,v.shape[0])481import vector_complex_double_dense482_v=vector_complex_double_dense.Vector_complex_double_dense(V, v)483return _v484485if isinstance(v, dict):486if degree is None:487degree = max([-1]+[index for index in v])+1488if sparse is None:489sparse = True490else:491degree = None492if sparse is None:493sparse = False494495v, R = prepare(v, R, degree)496497if sparse:498import free_module # slow -- can we improve499return free_module.FreeModule(R, len(v), sparse=True)(v)500else:501return (R**len(v))(v)502503free_module_element = vector504505def prepare(v, R, degree=None):506r"""507Converts an object describing elements of a vector into a list of entries in a common ring.508509INPUT:510511- ``v`` - a dictionary with non-negative integers as keys,512or a list or other object that can be converted by the ``Sequence``513constructor514- ``R`` - a ring containing all the entries, possibly given as ``None``515- ``degree`` - a requested size for the list when the input is a dictionary,516otherwise ignored517518OUTPUT:519520A pair.521522The first item is a list of the values specified in the object ``v``.523If the object is a dictionary , entries are placed in the list524according to the indices that were their keys in the dictionary,525and the remainder of the entries are zero. The value of526``degree`` is assumed to be larger than any index provided527in the dictionary and will be used as the number of entries528in the returned list.529530The second item returned is a ring that contains all of531the entries in the list. If ``R`` is given, the entries532are coerced in. Otherwise a common ring is found. For533more details, see the534:class:`~sage.structure.sequence.Sequence` object. When ``v``535has no elements and ``R`` is ``None``, the ring returned is536the integers.537538539EXAMPLES::540541sage: from sage.modules.free_module_element import prepare542sage: prepare([1,2/3,5],None)543([1, 2/3, 5], Rational Field)544545sage: prepare([1,2/3,5],RR)546([1.00000000000000, 0.666666666666667, 5.00000000000000], Real Field with 53 bits of precision)547548sage: prepare({1:4, 3:-2}, ZZ, 6)549([0, 4, 0, -2, 0, 0], Integer Ring)550551sage: prepare({3:1, 5:3}, QQ, 6)552([0, 0, 0, 1, 0, 3], Rational Field)553554sage: prepare([1,2/3,'10',5],RR)555([1.00000000000000, 0.666666666666667, 10.0000000000000, 5.00000000000000], Real Field with 53 bits of precision)556557sage: prepare({},QQ, 0)558([], Rational Field)559560sage: prepare([1,2/3,'10',5],None)561Traceback (most recent call last):562...563TypeError: unable to find a common ring for all elements564565Some objects can be converted to sequences even if they are not always566thought of as sequences. ::567568sage: c = CDF(2+3*I)569sage: prepare(c, None)570([2.0, 3.0], Real Double Field)571572This checks a bug listed at Trac #10595. Without good evidence for a ring, the default573is the integers. ::574575sage: prepare([], None)576([], Integer Ring)577"""578if isinstance(v, dict):579# convert to a list580X = [0]*degree581for key, value in v.iteritems():582X[key] = value583v = X584# convert to a Sequence over common ring585# default to ZZ on an empty list586if R is None:587try:588if len(v) == 0:589R = ZZ590except TypeError:591pass592v = Sequence(v, universe=R, use_sage_types=True)593ring = v.universe()594if not is_Ring(ring):595raise TypeError("unable to find a common ring for all elements")596return v, ring597598def zero_vector(arg0, arg1=None):599r"""600Returns a vector or free module element with a specified number of zeros.601602CALL FORMATS:6036041. zero_vector(degree)6056062. zero_vector(ring, degree)607608INPUT:609610- ``degree`` - the number of zero entries in the vector or611free module element612613- ``ring`` - default ``ZZ`` - the base ring of the vector614space or module containing the constructed zero vector615616OUTPUT:617618A vector or free module element with ``degree`` entries,619all equal to zero and belonging to the ring if specified.620If no ring is given, a free module element over ``ZZ``621is returned.622623EXAMPLES:624625A zero vector over the field of rationals. ::626627sage: v = zero_vector(QQ, 5); v628(0, 0, 0, 0, 0)629sage: v.parent()630Vector space of dimension 5 over Rational Field631632A free module zero element. ::633634sage: w = zero_vector(Integers(6), 3); w635(0, 0, 0)636sage: w.parent()637Ambient free module of rank 3 over Ring of integers modulo 6638639If no ring is given, the integers are used. ::640641sage: u = zero_vector(9); u642(0, 0, 0, 0, 0, 0, 0, 0, 0)643sage: u.parent()644Ambient free module of rank 9 over the principal ideal domain Integer Ring645646Non-integer degrees produce an error. ::647648sage: zero_vector(5.6)649Traceback (most recent call last):650...651TypeError: Attempt to coerce non-integral RealNumber to Integer652653Negative degrees also give an error. ::654655sage: zero_vector(-3)656Traceback (most recent call last):657...658ValueError: rank (=-3) must be nonnegative659660Garbage instead of a ring will be recognized as such. ::661662sage: zero_vector(x^2, 5)663Traceback (most recent call last):664...665TypeError: first argument must be a ring666"""667if arg1 is None:668# default to a zero vector over the integers (ZZ) if no ring given669return (ZZ**arg0).zero_vector()670if is_Ring(arg0):671return (arg0**arg1).zero_vector()672raise TypeError("first argument must be a ring")673674def random_vector(ring, degree=None, *args, **kwds):675r"""676Returns a vector (or module element) with random entries.677678INPUT:679680- ring - default: ``ZZ`` - the base ring for the entries681- degree - a non-negative integer for the number of entries in the vector682- sparse - default: ``False`` - whether to use a sparse implementation683- args, kwds - additional arguments and keywords are passed684to the ``random_element()`` method of the ring685686OUTPUT:687688A vector, or free module element, with ``degree`` elements689from ``ring``, chosen randomly from the ring according to690the ring's ``random_element()`` method.691692.. note::693See below for examples of how random elements are694generated by some common base rings.695696EXAMPLES:697698First, module elements over the integers.699The default distribution is tightly clustered around -1, 0, 1.700Uniform distributions can be specified by giving bounds, though701the upper bound is never met. See702:meth:`sage.rings.integer_ring.IntegerRing_class.random_element`703for several other variants. ::704705sage: random_vector(10)706(-8, 2, 0, 0, 1, -1, 2, 1, -95, -1)707708sage: sorted(random_vector(20))709[-12, -6, -4, -4, -2, -2, -2, -1, -1, -1, 0, 0, 0, 0, 0, 1, 1, 1, 4, 5]710711sage: random_vector(ZZ, 20, x=4)712(2, 0, 3, 0, 1, 0, 2, 0, 2, 3, 0, 3, 1, 2, 2, 2, 1, 3, 2, 3)713714sage: random_vector(ZZ, 20, x=-20, y=100)715(43, 47, 89, 31, 56, -20, 23, 52, 13, 53, 49, -12, -2, 94, -1, 95, 60, 83, 28, 63)716717sage: random_vector(ZZ, 20, distribution="1/n")718(0, -1, -2, 0, -1, -2, 0, 0, 27, -1, 1, 1, 0, 2, -1, 1, -1, -2, -1, 3)719720If the ring is not specified, the default is the integers, and721parameters for the random distribution may be passed without using722keywords. This is a random vector with 20 entries uniformly distributed723between -20 and 100. ::724725sage: random_vector(20, -20, 100)726(70, 19, 98, 2, -18, 88, 36, 66, 76, 52, 82, 99, 55, -17, 82, -15, 36, 28, 79, 18)727728Now over the rationals. Note that bounds on the numerator and729denominator may be specified. See730:meth:`sage.rings.rational_field.RationalField.random_element`731for documentation. ::732733sage: random_vector(QQ, 10)734(0, -1, -4/3, 2, 0, -13, 2/3, 0, -4/5, -1)735736sage: random_vector(QQ, 10, num_bound = 15, den_bound = 5)737(-12/5, 9/4, -13/3, -1/3, 1, 5/4, 4, 1, -15, 10/3)738739Inexact rings may be used as well. The reals have740uniform distributions, with the range `(-1,1)` as741the default. More at:742:meth:`sage.rings.real_mpfr.RealField_class.random_element` ::743744sage: random_vector(RR, 5)745(0.248997268533725, -0.112200126330480, 0.776829203293064, -0.899146461031406, 0.534465018743125)746747sage: random_vector(RR, 5, min = 8, max = 14)748(8.43260944052606, 8.34129413391087, 8.92391495103829, 11.5784799413416, 11.0973561568002)749750Any ring with a ``random_element()`` method may be used. ::751752sage: F = FiniteField(23)753sage: hasattr(F, 'random_element')754True755sage: random_vector(F, 10)756(21, 6, 5, 2, 6, 2, 18, 9, 9, 7)757758The default implementation is a dense representation, equivalent to759setting ``sparse=False``. ::760761sage: v = random_vector(10)762sage: v.is_sparse()763False764765sage: w = random_vector(ZZ, 20, sparse=True)766sage: w.is_sparse()767True768769Inputs get checked before constructing the vector. ::770771sage: random_vector('junk')772Traceback (most recent call last):773...774TypeError: degree of a random vector must be an integer, not None775776sage: random_vector('stuff', 5)777Traceback (most recent call last):778...779TypeError: elements of a vector, or module element, must come from a ring, not stuff780781sage: random_vector(ZZ, -9)782Traceback (most recent call last):783...784ValueError: degree of a random vector must be non-negative, not -9785"""786if sage.rings.integer.is_Integer(ring) or isinstance(ring,(int,long)):787if not degree is None:788arglist = list(args)789arglist.insert(0, degree)790args = tuple(arglist)791degree = ring792ring = ZZ793if not (sage.rings.integer.is_Integer(degree) or isinstance(degree,(int,long))):794raise TypeError("degree of a random vector must be an integer, not %s" % degree)795if degree < 0:796raise ValueError("degree of a random vector must be non-negative, not %s" % degree)797if not is_Ring(ring):798raise TypeError("elements of a vector, or module element, must come from a ring, not %s" % ring)799if not hasattr(ring, "random_element"):800raise AttributeError("cannot create a random vector since there is no random_element() method for %s" % ring )801sparse = kwds.pop('sparse', False)802entries = [ring.random_element(*args, **kwds) for _ in range(degree)]803return vector(ring, degree, entries, sparse)804805cdef class FreeModuleElement(element_Vector): # abstract base class806"""807An element of a generic free module.808"""809def __init__(self, parent):810"""811EXAMPLES::812813sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)814sage: type(v)815<type 'sage.modules.free_module_element.FreeModuleElement'>816"""817self._parent = parent818self._degree = parent.degree()819self._is_mutable = 1820821def _giac_init_(self):822"""823EXAMPLES::824825sage: v = vector(ZZ, 4, range(4)) #optional - giac826sage: giac(v)+v #optional - giac827[0,2,4,6]828829::830831sage: v = vector(QQ, 3, [2/3, 0, 5/4]) #optional832sage: giac(v) #optional833[2/3,0,5/4]834835::836837sage: P.<x> = ZZ[] #optional838sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) #optional839sage: giac(v) #optional840[x^2+2,2*x+1,-2*x^2+4*x]841"""842return self.list()843844def _magma_init_(self, magma):845r"""846Convert self to Magma.847848EXAMPLES::849850sage: F = FreeModule(ZZ, 2, inner_product_matrix=matrix(ZZ, 2, 2, [1, 0, 0, -1]))851sage: v = F([1, 2])852sage: M = magma(v); M # optional - magma853(1 2)854sage: M.Type() # optional - magma855ModTupRngElt856sage: M.Parent() # optional - magma857Full RSpace of degree 2 over Integer Ring858Inner Product Matrix:859[ 1 0]860[ 0 -1]861sage: M.sage() # optional - magma862(1, 2)863sage: M.sage() == v # optional - magma864True865sage: M.sage().parent() is v.parent() # optional - magma866True867868::869870sage: v = vector(QQ, [1, 2, 5/6])871sage: M = magma(v); M # optional - magma872( 1 2 5/6)873sage: M.Type() # optional - magma874ModTupFldElt875sage: M.Parent() # optional - magma876Full Vector space of degree 3 over Rational Field877sage: M.sage() # optional - magma878(1, 2, 5/6)879sage: M.sage() == v # optional - magma880True881sage: M.sage().parent() is v.parent() # optional - magma882True883"""884# Get a reference to Magma version of parent.885R = magma(self.parent())886# Get list of coefficients.887v = ','.join([a._magma_init_(magma) for a in self.list()])888return '%s![%s]' % (R.name(), v)889890def __hash__(self):891"""892Return hash of this vector. Only mutable vectors are hashable.893894EXAMPLES::895sage: v = vector([1,2/3,pi])896sage: v.__hash__()897Traceback (most recent call last):898...899TypeError: mutable vectors are unhashable900sage: v.set_immutable()901sage: v.__hash__() # random output902"""903if self._is_mutable:904raise TypeError("mutable vectors are unhashable")905return hash(tuple(self))906907def _vector_(self, R=None):908r"""909Return self as a vector.910911EXAMPLES::912913sage: v = vector(ZZ, [2, 12, 22])914sage: vector(v)915(2, 12, 22)916sage: vector(GF(7), v)917(2, 5, 1)918sage: vector(v, ZZ['x', 'y'])919(2, 12, 22)920921sage: vector(vector((1, 6.8)))922(1.00000000000000, 6.80000000000000)923sage: vector(vector(SR, (1, sqrt(2)) ) )924(1, sqrt(2))925"""926if R is None:927R = self.base_ring()928return self.change_ring(R)929930def _matrix_(self, R=None):931r"""932Return self as a row matrix.933934EXAMPLES::935936sage: v = vector(ZZ, [2, 12, 22])937sage: vector(v)938(2, 12, 22)939sage: vector(GF(7), v)940(2, 5, 1)941sage: vector(v, ZZ['x', 'y'])942(2, 12, 22)943"""944if R is None:945R = self.base_ring()946sparse = self.is_sparse()947from sage.matrix.constructor import matrix948return matrix(R, [list(self)], sparse=sparse)949950def _sage_input_(self, sib, coerce):951r"""952Produce an expression which will reproduce this value when evaluated.953954EXAMPLES::955956sage: sage_input(vector(RR, [pi, e, 0.5]), verify=True)957# Verified958vector(RR, [3.1415926535897931, 2.7182818284590451, 0.5])959sage: sage_input(vector(GF(5), [1, 2, 3, 4, 5]), verify=True)960# Verified961vector(GF(5), [1, 2, 3, 4, 0])962sage: sage_input(vector([0, 0, 0, 1, 0, 0, 0], sparse=True), verify=True)963# Verified964vector(ZZ, {3:1, 6:0})965sage: sage_input(vector(ZZ, []), verify=True)966# Verified967vector(ZZ, [])968sage: sage_input(vector(RealField(27), [], sparse=True), verify=True)969# Verified970vector(RealField(27), {})971sage: from sage.misc.sage_input import SageInputBuilder972sage: vector(ZZ, [42, 389])._sage_input_(SageInputBuilder(), False)973{call: {atomic:vector}({atomic:ZZ}, {list: ({atomic:42}, {atomic:389})})}974sage: vector(RDF, {1:pi, 1000:e})._sage_input_(SageInputBuilder(), False)975{call: {atomic:vector}({atomic:RDF}, {dict: {{atomic:1}:{atomic:3.1415926535897931}, {atomic:1000}:{atomic:2.718281828459045...}}})}976"""977# Not a lot of room for prettiness here.978# We always specify the ring, because that lets us use coerced=2979# on the elements, which is sometimes much prettier than980# the coerced=False we would get otherwise.981if self.is_sparse_c():982items = [(n, sib(e, 2))983for n,e in self.dict().items()]984items.sort()985if len(self):986# we may need to add an extra element on the end to987# set the size. (There doesn't seem to be a better way988# to do it.)989if len(items) == 0 or len(self)-1 > items[-1][0]:990items.append((len(self)-1, sib.int(0)))991items_dict = sib.dict([(sib.int(n), e) for n,e in items])992993return sib.name('vector')(self.base_ring(), items_dict)994else:995return sib.name('vector')(self.base_ring(),996[sib(e, 2) for e in self])997998def _numerical_approx(self, prec=None, digits=None):999r"""1000Implements numerical approximation of a free module element1001by calling the ``n()`` method on all of its entries.10021003EXAMPLES::10041005sage: v = vector(RealField(212), [1,2,3])1006sage: v.N()1007(1.00000000000000, 2.00000000000000, 3.00000000000000)1008sage: _.parent()1009Vector space of dimension 3 over Real Field with 53 bits of precision1010sage: numerical_approx(v)1011(1.00000000000000, 2.00000000000000, 3.00000000000000)1012sage: _.parent()1013Vector space of dimension 3 over Real Field with 53 bits of precision1014sage: v.n(prec=75)1015(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1016sage: _.parent()1017Vector space of dimension 3 over Real Field with 75 bits of precision1018sage: numerical_approx(v, digits=3)1019(1.00, 2.00, 3.00)1020sage: _.parent()1021Vector space of dimension 3 over Real Field with 14 bits of precision10221023Both functional and object-oriented usage is possible. ::10241025sage: u = vector(QQ, [1/2, 1/3, 1/4])1026sage: u.n()1027(0.500000000000000, 0.333333333333333, 0.250000000000000)1028sage: u.N()1029(0.500000000000000, 0.333333333333333, 0.250000000000000)1030sage: u.numerical_approx()1031(0.500000000000000, 0.333333333333333, 0.250000000000000)1032sage: n(u)1033(0.500000000000000, 0.333333333333333, 0.250000000000000)1034sage: N(u)1035(0.500000000000000, 0.333333333333333, 0.250000000000000)1036sage: numerical_approx(u)1037(0.500000000000000, 0.333333333333333, 0.250000000000000)10381039Precision (bits) and digits (decimal) may be specified.1040When both are given, ``prec`` wins. ::10411042sage: u = vector(QQ, [1/2, 1/3, 1/4])1043sage: n(u, prec=15)1044(0.5000, 0.3333, 0.2500)1045sage: n(u, digits=5)1046(0.50000, 0.33333, 0.25000)1047sage: n(u, prec=30, digits=100)1048(0.50000000, 0.33333333, 0.25000000)10491050These are some legacy doctests that were part of various specialized1051versions of the numerical approximation routine that were removed as1052part of :trac:`12195`. ::10531054sage: v = vector(ZZ, [1,2,3])1055sage: v.n()1056(1.00000000000000, 2.00000000000000, 3.00000000000000)1057sage: _.parent()1058Vector space of dimension 3 over Real Field with 53 bits of precision1059sage: v.n(prec=75)1060(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1061sage: _.parent()1062Vector space of dimension 3 over Real Field with 75 bits of precision10631064sage: v = vector(RDF, [1,2,3])1065sage: v.n()1066(1.00000000000000, 2.00000000000000, 3.00000000000000)1067sage: _.parent()1068Vector space of dimension 3 over Real Field with 53 bits of precision1069sage: v.n(prec=75)1070(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1071sage: _.parent()1072Vector space of dimension 3 over Real Field with 75 bits of precision10731074sage: v = vector(CDF, [1,2,3])1075sage: v.n()1076(1.00000000000000, 2.00000000000000, 3.00000000000000)1077sage: _.parent()1078Vector space of dimension 3 over Complex Field with 53 bits of precision1079sage: v.n(prec=75)1080(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1081sage: _.parent()1082Vector space of dimension 3 over Complex Field with 75 bits of precision10831084sage: v = vector(Integers(8), [1,2,3])1085sage: v.n()1086(1.00000000000000, 2.00000000000000, 3.00000000000000)1087sage: _.parent()1088Vector space of dimension 3 over Real Field with 53 bits of precision1089sage: v.n(prec=75)1090(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1091sage: _.parent()1092Vector space of dimension 3 over Real Field with 75 bits of precision10931094sage: v = vector(QQ, [1,2,3])1095sage: v.n()1096(1.00000000000000, 2.00000000000000, 3.00000000000000)1097sage: _.parent()1098Vector space of dimension 3 over Real Field with 53 bits of precision1099sage: v.n(prec=75)1100(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1101sage: _.parent()1102Vector space of dimension 3 over Real Field with 75 bits of precision11031104TESTS:11051106Sparse vectors have a similar method that works efficiently for1107the sparse case. We test that it is working as it should. ::11081109sage: v = vector(QQ, [1/2, 0, 0, 1/3, 0, 0, 0, 1/4], sparse=True)1110sage: u = v.numerical_approx(digits=4)1111sage: u.is_sparse()1112True1113sage: u1114(0.5000, 0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000, 0.2500)1115"""1116return vector([e.n(prec, digits) for e in self])11171118def transpose(self):1119r"""1120Return self as a column matrix.11211122.. note::11231124The ``transpose()`` method has been deprecated as of Sage 4.6.2,1125in favor of the :meth:`column` method which is functionally identical.11261127EXAMPLES::11281129sage: v = vector(ZZ, [2, 12, 22])1130sage: transpose(vector(v))1131doctest:...: DeprecationWarning: The transpose() method for vectors has been deprecated, use column() instead1132(or check to see if you have a vector when you really want a matrix)1133See http://trac.sagemath.org/10541 for details.1134[ 2]1135[12]1136[22]11371138::11391140sage: transpose(vector(GF(7), v))1141[2]1142[5]1143[1]11441145::11461147sage: transpose(vector(v, ZZ['x', 'y']))1148[ 2]1149[12]1150[22]1151"""1152from sage.misc.superseded import deprecation1153deprecation(10541, 'The transpose() method for vectors has been deprecated, use column() instead\n(or check to see if you have a vector when you really want a matrix)')1154return self._matrix_().transpose()11551156def row(self):1157r"""1158Return a matrix with a single row and the same entries as the vector ``self``.11591160OUTPUT:11611162A matrix over the same ring as the vector (or free module element), with1163a single row. The entries of the row are identical to those of the vector,1164and in the same order.11651166EXAMPLES::11671168sage: v = vector(ZZ, [1,2,3])1169sage: w = v.row(); w1170[1 2 3]1171sage: w.parent()1172Full MatrixSpace of 1 by 3 dense matrices over Integer Ring11731174sage: x = vector(FiniteField(13), [2,4,8,16])1175sage: x.row()1176[2 4 8 3]11771178There is more than one way to get one-row matrix from a vector,1179but the ``row`` method is more efficient than making a column and1180then taking a transpose. Notice that supplying a vector to the1181matrix constructor demonstrates Sage's preference for rows. ::11821183sage: x = vector(RDF, [sin(i*pi/20) for i in range(10)])1184sage: x.row() == matrix(x)1185True1186sage: x.row() == x.column().transpose()1187True11881189Sparse or dense implementations are preserved. ::11901191sage: d = vector(RR, [1.0, 2.0, 3.0])1192sage: s = vector(CDF, {2:5.0+6.0*I})1193sage: dm = d.row()1194sage: sm = s.row()1195sage: all([d.is_dense(), dm.is_dense(), s.is_sparse(), sm.is_sparse()])1196True11971198TESTS:11991200The :meth:`~sage.matrix.matrix1.Matrix.row` method will return1201a specified row of a matrix as a vector. So here are a couple1202of round-trips. ::12031204sage: A = matrix(ZZ, [[1,2,3]])1205sage: A == A.row(0).row()1206True1207sage: v = vector(ZZ, [4,5,6])1208sage: v == v.row().row(0)1209True12101211And a very small corner case. ::12121213sage: v = vector(ZZ, [])1214sage: w = v.row()1215sage: w.parent()1216Full MatrixSpace of 1 by 0 dense matrices over Integer Ring1217"""1218return self._matrix_(R=None)12191220def column(self):1221r"""1222Return a matrix with a single column and the same entries as the vector ``self``.12231224OUTPUT:12251226A matrix over the same ring as the vector (or free module element), with1227a single column. The entries of the column are identical to those of the1228vector, and in the same order.12291230EXAMPLES::12311232sage: v = vector(ZZ, [1,2,3])1233sage: w = v.column(); w1234[1]1235[2]1236[3]1237sage: w.parent()1238Full MatrixSpace of 3 by 1 dense matrices over Integer Ring12391240sage: x = vector(FiniteField(13), [2,4,8,16])1241sage: x.column()1242[2]1243[4]1244[8]1245[3]12461247There is more than one way to get one-column matrix from a vector.1248The ``column`` method is about equally efficient to making a row and1249then taking a transpose. Notice that supplying a vector to the1250matrix constructor demonstrates Sage's preference for rows. ::12511252sage: x = vector(RDF, [sin(i*pi/20) for i in range(10)])1253sage: x.column() == matrix(x).transpose()1254True1255sage: x.column() == x.row().transpose()1256True12571258Sparse or dense implementations are preserved. ::12591260sage: d = vector(RR, [1.0, 2.0, 3.0])1261sage: s = vector(CDF, {2:5.0+6.0*I})1262sage: dm = d.column()1263sage: sm = s.column()1264sage: all([d.is_dense(), dm.is_dense(), s.is_sparse(), sm.is_sparse()])1265True12661267TESTS:12681269The :meth:`~sage.matrix.matrix1.Matrix.column` method will return1270a specified column of a matrix as a vector. So here are a couple1271of round-trips. ::12721273sage: A = matrix(ZZ, [[1],[2],[3]])1274sage: A == A.column(0).column()1275True1276sage: v = vector(ZZ, [4,5,6])1277sage: v == v.column().column(0)1278True12791280And a very small corner case. ::12811282sage: v = vector(ZZ, [])1283sage: w = v.column()1284sage: w.parent()1285Full MatrixSpace of 0 by 1 dense matrices over Integer Ring1286"""1287return self._matrix_(R=None).transpose()12881289def _hash(self):1290"""1291Return hash of an immutable form of self (works even if self1292is mutable).12931294EXAMPLES::1295sage: v = vector([1,2/3,pi])1296sage: v.__hash__()1297Traceback (most recent call last):1298...1299TypeError: mutable vectors are unhashable1300sage: v._hash() # random output1301"""1302return hash(tuple(list(self)))13031304def __copy__(self):1305"""1306Make a copy of this vector.13071308EXAMPLES::13091310sage: v = vector([1..5]); v1311(1, 2, 3, 4, 5)1312sage: w = copy(v)1313sage: v == w1314True1315sage: v is w1316False13171318::13191320sage: v = vector([1..5], sparse=True); v1321(1, 2, 3, 4, 5)1322sage: copy(v)1323(1, 2, 3, 4, 5)1324"""1325if self.is_sparse():1326return self.parent()(self.dict())1327else:1328return self.parent()(self.list())13291330def subs(self, in_dict=None, **kwds):1331"""1332EXAMPLES::13331334sage: var('a,b,d,e')1335(a, b, d, e)1336sage: v = vector([a, b, d, e])1337sage: v.substitute(a=1)1338(1, b, d, e)1339sage: v.subs(a=b, b=d)1340(b, d, d, e)1341"""1342return self.parent()([ a.subs(in_dict, **kwds) for a in self.list() ])13431344def set_immutable(self):1345"""1346Make this vector immutable. This operation can't be undone.13471348EXAMPLES::13491350sage: v = vector([1..5]); v1351(1, 2, 3, 4, 5)1352sage: v[1] = 101353sage: v.set_immutable()1354sage: v[1] = 101355Traceback (most recent call last):1356...1357ValueError: vector is immutable; please change a copy instead (use copy())1358"""1359self._is_mutable = 013601361def is_mutable(self):1362"""1363Return True if this vector is mutable, i.e., the entries can be1364changed.13651366EXAMPLES::13671368sage: v = vector(QQ['x,y'], [1..5]); v.is_mutable()1369True1370sage: v.set_immutable()1371sage: v.is_mutable()1372False1373"""1374return self._is_mutable13751376def is_immutable(self):1377"""1378Return True if this vector is immutable, i.e., the entries cannot1379be changed.13801381EXAMPLES::13821383sage: v = vector(QQ['x,y'], [1..5]); v.is_immutable()1384False1385sage: v.set_immutable()1386sage: v.is_immutable()1387True1388"""1389return not self._is_mutable13901391def change_ring(self, R):1392"""1393Change the base ring of this vector, by coercing each element of1394this vector into R.13951396EXAMPLES::13971398sage: v = vector(QQ['x,y'], [1..5]); v.change_ring(GF(3))1399(1, 2, 0, 1, 2)1400"""1401P = self.parent()1402if P.base_ring() is R:1403return self1404return P.change_ring(R)(self)14051406def additive_order(self):1407"""1408Return the additive order of self.14091410EXAMPLES::14111412sage: v = vector(Integers(4), [1,2])1413sage: v.additive_order()1414414151416::14171418sage: v = vector([1,2,3])1419sage: v.additive_order()1420+Infinity14211422::14231424sage: v = vector(Integers(30), [6, 15]); v1425(6, 15)1426sage: v.additive_order()1427101428sage: 10*v1429(0, 0)1430"""1431v = [None]*self.degree()1432cdef int i1433for i from 0 <= i < self.degree():1434v[i] = self[i].additive_order()1435if v[i] == +Infinity:1436return +Infinity1437return sage.rings.arith.LCM(v)14381439def iteritems(self):1440"""1441Return iterator over self.14421443EXAMPLES::14441445sage: v = vector([1,2/3,pi])1446sage: v.iteritems()1447<dictionary-itemiterator object at ...>1448sage: list(v.iteritems())1449[(0, 1), (1, 2/3), (2, pi)]1450"""1451return self.dict(copy=False).iteritems()14521453def __abs__(self):1454"""1455Return the square root of the sum of the squares of the entries of1456this vector.14571458EXAMPLES::14591460sage: v = vector([1..5]); abs(v)1461sqrt(55)1462sage: v = vector(RDF, [1..5]); abs(v)14637.41619848711464"""1465return sum([x**2 for x in self.list()]).sqrt()14661467def norm(self, p=sage.rings.integer.Integer(2)):1468r"""1469Return the `p`-norm of ``self``.14701471INPUT:14721473- ``p`` - default: 2 - ``p`` can be a real number greater than 1,1474infinity (``oo`` or ``Infinity``), or a symbolic expression.14751476- `p=1`: the taxicab (Manhattan) norm1477- `p=2`: the usual Euclidean norm (the default)1478- `p=\infty`: the maximum entry (in absolute value)14791480.. note::14811482See also :func:`sage.misc.functional.norm`14831484EXAMPLES::14851486sage: v = vector([1,2,-3])1487sage: v.norm(5)1488276^(1/5)14891490The default is the usual Euclidean norm. ::14911492sage: v.norm()1493sqrt(14)1494sage: v.norm(2)1495sqrt(14)14961497The infinity norm is the maximum size (in absolute value)1498of the entries. ::14991500sage: v.norm(Infinity)150131502sage: v.norm(oo)1503315041505Real or symbolic values may be used for ``p``. ::15061507sage: v=vector(RDF,[1,2,3])1508sage: v.norm(5)15093.077384885391510sage: v.norm(pi/2)15114.21659586471512sage: _=var('a b c d p'); v=vector([a, b, c, d])1513sage: v.norm(p)1514(abs(a)^p + abs(b)^p + abs(c)^p + abs(d)^p)^(1/p)15151516Notice that the result may be a symbolic expression, owing to1517the necessity of taking a square root (in the default case).1518These results can be converted to numerical values if needed. ::15191520sage: v = vector(ZZ, [3,4])1521sage: nrm = v.norm(); nrm152251523sage: nrm.parent()1524Rational Field15251526sage: v = vector(QQ, [3, 5])1527sage: nrm = v.norm(); nrm1528sqrt(34)1529sage: nrm.parent()1530Symbolic Ring1531sage: numeric = N(nrm); numeric15325.83095189484...1533sage: numeric.parent()1534Real Field with 53 bits of precision15351536TESTS:15371538The value of ``p`` must be greater than, or1539equal to, one. ::15401541sage: v = vector(QQ, [1,2])1542sage: v.norm(0.99)1543Traceback (most recent call last):1544...1545ValueError: 0.990000 is not greater than or equal to 115461547Norm works with python integers (see :trac:`13502`). ::15481549sage: v = vector(QQ, [1,2])1550sage: v.norm(int(2))1551sqrt(5)1552"""1553abs_self = [abs(x) for x in self]1554if p == Infinity:1555return max(abs_self)1556try:1557pr = RDF(p)1558if pr < 1:1559raise ValueError("%f is not greater than or equal to 1" %(pr))1560except TypeError:1561pass15621563s = sum([a**p for a in abs_self])1564return s**(__one__/p)15651566cdef int _cmp_c_impl(left, Element right) except -2:1567"""1568EXAMPLES::15691570sage: v = vector(SR, [0,0,0,0])1571sage: v == 01572True1573sage: v == 11574False1575sage: v == v1576True1577sage: w = vector(SR, [-1,x,pi,0])1578sage: w < v1579True1580sage: w > v1581False1582"""1583cdef Py_ssize_t i1584cdef int c1585for i from 0 <= i < left.degree():1586c = cmp(left[i], right[i])1587if c: return c1588return 015891590# see sage/structure/element.pyx1591def __richcmp__(left, right, int op):1592"""1593TESTS::15941595sage: F.<y> = PolynomialRing(QQ, 'y')1596sage: type(vector(F, [0]*4, sparse=True))1597<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>1598sage: vector(F, [0,0,0,y]) == vector(F, [0,0,0,y])1599True1600sage: vector(F, [0,0,0,0]) == vector(F, [0,2,0,y])1601False1602"""1603return (<Element>left)._richcmp(right, op)16041605def __getitem__(self, i):1606"""1607Return `i`-th entry or slice of self.16081609EXAMPLES::16101611This just raises NotImplementedError since this is an abstract1612base class, and __getitem__ has to be overloaded in the1613derived class::16141615sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)1616sage: v.__getitem__(0)1617Traceback (most recent call last):1618...1619NotImplementedError1620"""1621raise NotImplementedError16221623def __invert__(self):1624"""1625Invert v, which makes no sense, and is hence is not implemented.16261627EXAMPLES::16281629sage: vector([1,2/3,pi]).__invert__()1630Traceback (most recent call last):1631...1632NotImplementedError1633"""1634raise NotImplementedError16351636def __len__(self):1637"""1638EXAMPLES::16391640sage: len(sage.modules.free_module_element.FreeModuleElement(QQ^2010))164120101642"""1643return self.parent().degree()16441645def __mod__(self, p):1646"""1647EXAMPLES::16481649sage: V = vector(ZZ, [5, 9, 13, 15])1650sage: V % 71651(5, 2, 6, 1)1652sage: parent(V % 7)1653Ambient free module of rank 4 over the principal ideal domain Integer Ring1654"""1655return self.parent()([x % p for x in self.list()], copy=False, coerce=False, check=False)16561657def Mod(self, p):1658"""1659EXAMPLES::16601661sage: V = vector(ZZ, [5, 9, 13, 15])1662sage: V.Mod(7)1663(5, 2, 6, 1)1664sage: parent(V.Mod(7))1665Vector space of dimension 4 over Ring of integers modulo 71666"""1667return self.change_ring(self.base_ring().quotient_ring(p))16681669def list(self, copy=True):1670"""1671Return list of elements of self.16721673INPUT:16741675- copy -- bool, whether returned list is a copy that is1676safe to change, is ignored.16771678EXAMPLES::16791680sage: P.<x,y,z> = QQ[]1681sage: v = vector([x,y,z], sparse=True)1682sage: type(v)1683<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>1684sage: a = v.list(); a1685[x, y, z]1686sage: a[0] = x*y; v1687(x, y, z)16881689The optional argument ``copy`` is ignored::16901691sage: a = v.list(copy=False); a1692[x, y, z]1693sage: a[0] = x*y; v1694(x, y, z)1695"""1696cdef Py_ssize_t i1697return [self[i] for i in range(self.degree())]16981699def list_from_positions(self, positions):1700"""1701Return list of elements chosen from this vector using the1702given positions of this vector.17031704INPUT:17051706- positions -- iterable of ints170717081709EXAMPLES::17101711sage: v = vector([1,2/3,pi])1712sage: v.list_from_positions([0,0,0,2,1])1713[1, 1, 1, pi, 2/3]1714"""1715cdef Py_ssize_t i1716return [self[i] for i in positions]17171718def lift(self):1719"""1720EXAMPLES::17211722sage: V = vector(Integers(7), [5, 9, 13, 15]) ; V1723(5, 2, 6, 1)1724sage: V.lift()1725(5, 2, 6, 1)1726sage: parent(V.lift())1727Ambient free module of rank 4 over the principal ideal domain Integer Ring1728"""1729return self.change_ring(self.base_ring().cover_ring())17301731def __pos__(self):1732"""1733Always returns self, since +self == self.17341735EXAMPLES::17361737sage: v = vector([1,2/3,8])1738sage: v.__pos__()1739(1, 2/3, 8)1740sage: +v1741(1, 2/3, 8)1742"""1743return self17441745def __pow__(self, n, dummy):1746"""1747Raises a NotImplementedError, since powering doesn't make1748sense for vectors.17491750EXAMPLES::17511752sage: v = vector([1,2/3,8])1753sage: v^21754Traceback (most recent call last):1755...1756NotImplementedError1757"""1758raise NotImplementedError17591760def _repr_(self):1761"""1762String representation of a vector.17631764EXAMPLES::17651766sage: vector(QQ, [])._repr_()1767'()'1768sage: vector(QQ, range(5))._repr_()1769'(0, 1, 2, 3, 4)'17701771Symbolic are not displayed using ASCII art.17721773::17741775sage: x = var('x')1776sage: v = vector([x/(2*x)+sqrt(2)+var('theta')^3,x/(2*x)]); v1777(theta^3 + sqrt(2) + 1/2, 1/2)1778sage: v._repr_()1779'(theta^3 + sqrt(2) + 1/2, 1/2)'1780"""1781d = self.degree()1782if d == 0: return "()"1783# compute column widths1784S = [repr(x) for x in self.list(copy=False)]1785#width = max([len(x) for x in S])1786s = "("1787for i in xrange(d):1788if i == d-1:1789sep = ""1790else:1791sep=", "1792entry = S[i]1793#if i > 0:1794# entry = " "*(width-len(entry)) + entry1795s = s + entry + sep1796s = s + ")"1797return s17981799def _maple_init_(self):1800"""1801EXAMPLES::18021803sage: v = vector(ZZ, 4, range(4)) #optional1804sage: maple(v) #optional1805Vector[row](4, [0,1,2,3])18061807::18081809sage: v = vector(QQ, 3, [2/3, 0, 5/4]) #optional1810sage: maple(v) #optional1811Vector[row](3, [2/3,0,5/4])18121813::18141815sage: P.<x> = ZZ[] #optional1816sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) #optional1817sage: maple(v) #optional1818Vector[row](3, [x^2+2,2*x+1,-2*x^2+4*x])1819"""1820return "Vector[row](%s)"%(str(self.list()))18211822def __setitem__(self, i, x):1823"""1824Set the `i`-th entry or slice of self to x. This is not implemented,1825since self is an abstract base class.18261827EXAMPLES::18281829sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)1830sage: v[0] = 51831Traceback (most recent call last):1832...1833NotImplementedError18341835For derived classes, this works::18361837sage: v = vector([1,2/3,8])1838sage: v[0] = 51839sage: v1840(5, 2/3, 8)1841"""1842raise NotImplementedError18431844def __richcmp__(left, right, int op):1845"""1846EXAMPLES::18471848sage: v = vector([1,2/3,8]) # indirect test1849sage: v == v1850True1851"""1852cdef int ld, rd1853if not isinstance(left, FreeModuleElement) or not isinstance(right, FreeModuleElement):1854# use the generic compare1855return (<Element>left)._richcmp(right, op)1856ld = (<FreeModuleElement>left)._degree1857rd = (<FreeModuleElement>right)._degree1858if ld < rd:1859return (<Element>left)._rich_to_bool(op, -1)1860elif ld > rd:1861return (<Element>left)._rich_to_bool(op, 1)1862if (<FreeModuleElement>left)._parent.base_ring() is (<FreeModuleElement>right)._parent.base_ring():1863return (<Element>left)._rich_to_bool(op, (1864<FreeModuleElement>left)._cmp_same_ambient_c(right))1865return (<Element>left)._richcmp(right, op)186618671868cdef int _cmp_same_ambient_c(left, FreeModuleElement right) except -2:1869return cmp(left.list(copy=False), right.list(copy=False))18701871def degree(self):1872"""1873Return the degree of this vector, which is simply the number1874of entries.18751876EXAMPLES::18771878sage: sage.modules.free_module_element.FreeModuleElement(QQ^389).degree()18793891880sage: vector([1,2/3,8]).degree()188131882"""1883return self._degree18841885def denominator(self):1886"""1887Return the least common multiple of the denominators of the1888entries of self.18891890EXAMPLES::18911892sage: v = vector([1/2,2/5,3/14])1893sage: v.denominator()1894701895sage: 2*5*718967018971898TESTS:18991900The following was fixed in trac ticket #8800::19011902sage: M = GF(5)^31903sage: v = M((4,0,2))1904sage: v.denominator()1905119061907"""1908R = self.base_ring()1909if self.degree() == 0: return 11910x = self.list()1911# it may be that the marks do not have a denominator!1912d = x[0].denominator() if hasattr(x[0],'denominator') else 11913for y in x:1914d = d.lcm(y.denominator()) if hasattr(y,'denominator') else d1915return d19161917def dict(self, copy=True):1918"""1919Return dictionary of nonzero entries of self.19201921INPUT:19221923- ``copy`` -- bool (default: True)19241925OUTPUT:19261927- Python dictionary19281929EXAMPLES::19301931sage: v = vector([0,0,0,0,1/2,0,3/14])1932sage: v.dict()1933{4: 1/2, 6: 3/14}19341935In some cases when copy=False, we get back a dangerous reference::19361937sage: v = vector({0:5, 2:3/7}, sparse=True)1938sage: v.dict(copy=False)1939{0: 5, 2: 3/7}1940sage: v.dict(copy=False)[0] = 181941sage: v1942(18, 0, 3/7)1943"""1944e = {}1945for i in xrange(self.degree()):1946c = self[i]1947if c:1948e[i] = c1949return e19501951#############################1952# Plotting1953#############################1954def plot(self, plot_type=None, start=None, **kwds):1955"""1956INPUT:19571958- ``plot_type`` - (default: 'arrow' if v has 3 or fewer components,1959otherwise 'step') type of plot. Options are:19601961- 'arrow' to draw an arrow19621963- 'point' to draw a point at the coordinates specified by the1964vector19651966- 'step' to draw a step function representing the coordinates1967of the vector.19681969Both 'arrow' and 'point' raise exceptions if the vector has1970more than 3 dimensions.19711972- ``start`` - (default: origin in correct dimension) may be a tuple,1973list, or vector.19741975EXAMPLES:19761977The following both plot the given vector::19781979sage: v = vector(RDF, (1,2))1980sage: A = plot(v)1981sage: B = v.plot()1982sage: A+B # should just show one vector19831984Examples of the plot types::19851986sage: A = plot(v, plot_type='arrow')1987sage: B = plot(v, plot_type='point', color='green', size=20)1988sage: C = plot(v, plot_type='step') # calls v.plot_step()1989sage: A+B+C19901991You can use the optional arguments for :meth:`plot_step`::19921993sage: eps = 0.11994sage: plot(v, plot_type='step', eps=eps, xmax=5, hue=0)19951996Three-dimensional examples::19971998sage: v = vector(RDF, (1,2,1))1999sage: plot(v) # defaults to an arrow plot20002001::20022003sage: plot(v, plot_type='arrow')20042005::20062007sage: from sage.plot.plot3d.shapes2 import frame3d2008sage: plot(v, plot_type='point')+frame3d((0,0,0), v.list())20092010::20112012sage: plot(v, plot_type='step') # calls v.plot_step()20132014::20152016sage: plot(v, plot_type='step', eps=eps, xmax=5, hue=0)20172018With greater than three coordinates, it defaults to a step plot::20192020sage: v = vector(RDF, (1,2,3,4))2021sage: plot(v)20222023One dimensional vectors are plotted along the horizontal axis of2024the coordinate plane::20252026sage: plot(vector([1]))20272028An optional start argument may also be specified by a tuple, list, or vector::20292030sage: u = vector([1,2]); v = vector([2,5])2031sage: plot(u, start=v)20322033TESTS::20342035sage: u = vector([1,1]); v = vector([2,2,2]); z=(3,3,3)2036sage: plot(u) #test when start=None20372038::20392040sage: plot(u, start=v) #test when coordinate dimension mismatch exists2041Traceback (most recent call last):2042...2043ValueError: vector coordinates are not of the same dimension2044sage: P = plot(v, start=z) #test when start coordinates are passed as a tuple2045sage: P = plot(v, start=list(z)) #test when start coordinates are passed as a list2046"""2047# Give sensible defaults based on the vector length2048if plot_type is None:2049if len(self)<=3:2050plot_type='arrow'2051else:2052plot_type='step'20532054coords = self.list()20552056if start is None:2057start = [0]*len(coords)2058elif len(start)!=len(coords):2059raise ValueError("vector coordinates are not of the same dimension")2060else:2061start = list(start)206220632064if plot_type == 'arrow' or plot_type == 'point':2065dimension = len(coords)2066if dimension == 3:2067from sage.plot.plot3d.shapes2 import line3d, point3d20682069if plot_type == 'arrow':2070return line3d([start, [(u+v) for u,v in zip(coords, start)]], arrow_head=True, **kwds)2071else:2072return point3d(coords, **kwds)2073elif dimension < 3:2074if dimension < 2:2075# pad to make 2-dimensional2076coords.extend([0]*(2-dimension))2077start.extend([0]*(2-dimension))20782079from sage.plot.all import arrow, point2080if plot_type == 'arrow':2081return arrow(start, [(u+v) for u,v in zip(coords, start)], **kwds)2082else:2083return point(coords, **kwds)2084else:2085raise ValueError("arrow and point plots require vectors with 3 or fewer components")20862087elif plot_type == 'step':2088return self.plot_step(**kwds)2089else:2090raise NotImplementedError("plot_type was unrecognized")20912092def plot_step(self, xmin=0, xmax=1, eps=None, res=None,2093connect=True, **kwds):2094"""2095INPUT:20962097- ``xmin`` - (default: 0) start x position to start2098plotting20992100- ``xmax`` - (default: 1) stop x position to stop2101plotting21022103- ``eps`` - (default: determined by xmax) we view this2104vector as defining a function at the points xmin, xmin + eps, xmin2105+ 2\*eps, ...,21062107- ``res`` - (default: all points) total number of2108points to include in the graph21092110- ``connect`` - (default: True) if True draws a line;2111otherwise draw a list of points.211221132114EXAMPLES::21152116sage: eps=0.12117sage: v = vector(RDF, [sin(n*eps) for n in range(100)])2118sage: v.plot_step(eps=eps, xmax=5, hue=0)2119"""2120if res is None:2121res = self.degree()2122if eps is None:2123eps = float(xmax - xmin)/res2124v = []2125x = xmin2126for i in range(0, self.degree(), int(math.ceil(self.degree()/res))):2127y = float(self[i])2128if x > xmax:2129break2130v.append((x,y))2131x += eps2132v.append((x,y))2133from sage.plot.all import line, points2134if connect:2135return line(v, **kwds)2136else:2137return points(v, **kwds)21382139def dot_product(self, right):2140r"""2141Return the dot product of ``self`` and ``right``, which is the sum of the2142product of the corresponding entries.21432144INPUT:21452146- ``right`` - a vector of the same degree as ``self``.2147It does not need to belong to the same parent as ``self``,2148so long as the necessary products and sums are defined.21492150OUTPUT:21512152If ``self`` and ``right`` are the vectors `\vec{x}` and `\vec{y}`,2153of degree `n`, then this method returns21542155.. math::21562157\sum_{i=1}^{n}x_iy_i21582159.. note::21602161The :meth:`inner_product` is a more general version of2162this method, and the :meth:`hermitian_inner_product`2163method may be more appropriate if your vectors2164have complex entries.21652166EXAMPLES::21672168sage: V = FreeModule(ZZ, 3)2169sage: v = V([1,2,3])2170sage: w = V([4,5,6])2171sage: v.dot_product(w)21723221732174The vectors may be from different vector spaces,2175provided the necessary operations make sense.2176Notice that coercion will generate a result of2177the same type, even if the order of the2178arguments is reversed.::21792180sage: v = vector(ZZ, [1,2,3])2181sage: w = vector(FiniteField(3), [0,1,2])2182sage: ip = w.dot_product(v); ip218322184sage: ip.parent()2185Finite Field of size 321862187sage: ip = v.dot_product(w); ip218822189sage: ip.parent()2190Finite Field of size 321912192The dot product of a vector with itself is the 2-norm, squared. ::21932194sage: v = vector(QQ, [3, 4, 7])2195sage: v.dot_product(v) - v.norm()^22196021972198TESTS:21992200The second argument must be a free module element. ::22012202sage: v = vector(QQ, [1,2])2203sage: v.dot_product('junk')2204Traceback (most recent call last):2205...2206TypeError: right must be a free module element22072208The degrees of the arguments must match. ::22092210sage: v = vector(QQ, [1,2])2211sage: w = vector(QQ, [1,2,3])2212sage: v.dot_product(w)2213Traceback (most recent call last):2214...2215ArithmeticError: degrees (2 and 3) must be the same22162217Check that vectors with different base rings play out nicely (:trac:`3103`)::22182219sage: vector(CDF, [2, 2]) * vector(ZZ, [1, 3])22208.022212222"""2223if not PY_TYPE_CHECK(right, FreeModuleElement):2224raise TypeError("right must be a free module element")2225r = right.list(copy=False)2226l = self.list(copy=False)2227if len(r) != len(l):2228raise ArithmeticError("degrees (%s and %s) must be the same"%(len(l),len(r)))2229if len(r) == 0:2230return self._parent.base_ring()(0)2231sum = l[0] * r[0]2232cdef Py_ssize_t i2233for i from 1 <= i < len(l):2234sum += l[i] * r[i]2235return sum22362237def cross_product(self, right):2238"""2239Return the cross product of self and right, which is only defined2240for vectors of length 3 or 7.22412242INPUT:22432244- ``right`` - A vector of the same size as ``self``, either2245degree three or degree seven.22462247OUTPUT:22482249The cross product (vector product) of ``self`` and ``right``,2250a vector of the same size of ``self`` and ``right``.22512252This product is performed under the assumption that the basis2253vectors are orthonormal.22542255EXAMPLES::22562257sage: v = vector([1,2,3]); w = vector([0,5,-9])2258sage: v.cross_product(v)2259(0, 0, 0)2260sage: u = v.cross_product(w); u2261(-33, 9, 5)2262sage: u.dot_product(v)226302264sage: u.dot_product(w)2265022662267The cross product is defined for degree seven vectors as well.2268[WIKIPEDIA:CROSSPRODUCT]_2269The 3-D cross product is achieved using the quaternians,2270whereas the 7-D cross product is achieved using the octions. ::22712272sage: u = vector(QQ, [1, -1/3, 57, -9, 56/4, -4,1])2273sage: v = vector(QQ, [37, 55, -99/57, 9, -12, 11/3, 4/98])2274sage: u.cross_product(v)2275(1394815/2793, -2808401/2793, 39492/49, -48737/399, -9151880/2793, 62513/2793, -326603/171)22762277The degree seven cross product is anticommutative. ::22782279sage: u.cross_product(v) + v.cross_product(u)2280(0, 0, 0, 0, 0, 0, 0)22812282The degree seven cross product is distributive across addition. ::22832284sage: v = vector([-12, -8/9, 42, 89, -37, 60/99, 73])2285sage: u = vector([31, -42/7, 97, 80, 30/55, -32, 64])2286sage: w = vector([-25/4, 40, -89, -91, -72/7, 79, 58])2287sage: v.cross_product(u + w) - (v.cross_product(u) + v.cross_product(w))2288(0, 0, 0, 0, 0, 0, 0)22892290The degree seven cross product respects scalar multiplication. ::22912292sage: v = vector([2, 17, -11/5, 21, -6, 2/17, 16])2293sage: u = vector([-8, 9, -21, -6, -5/3, 12, 99])2294sage: (5*v).cross_product(u) - 5*(v.cross_product(u))2295(0, 0, 0, 0, 0, 0, 0)2296sage: v.cross_product(5*u) - 5*(v.cross_product(u))2297(0, 0, 0, 0, 0, 0, 0)2298sage: (5*v).cross_product(u) - (v.cross_product(5*u))2299(0, 0, 0, 0, 0, 0, 0)23002301The degree seven cross product respects the scalar triple product. ::23022303sage: v = vector([2,6,-7/4,-9/12,-7,12,9])2304sage: u = vector([22,-7,-9/11,12,15,15/7,11])2305sage: w = vector([-11,17,19,-12/5,44,21/56,-8])2306sage: v.dot_product(u.cross_product(w)) - w.dot_product(v.cross_product(u))2307023082309TESTS:23102311Both vectors need to be of length three or both vectors need to be of length seven. ::23122313sage: u = vector(range(7))2314sage: v = vector(range(3))2315sage: u.cross_product(v)2316Traceback (most recent call last):2317...2318ArithmeticError: Cross product only defined for vectors of length three or seven, not (7 and 3)23192320REFERENCES:23212322.. [WIKIPEDIA:CROSSPRODUCT] Algebraic Properties of the Cross Product2323http://en.wikipedia.org/wiki/Cross_product23242325AUTHOR:23262327Billy Wonderly (2010-05-11), Added 7-D Cross Product2328"""2329if not PY_TYPE_CHECK(right, FreeModuleElement):2330raise TypeError("right must be a free module element")2331r = right.list(copy=False)2332l = self.list(copy=False)2333if len(r) == 3 and len(l) == 3:2334return vector([l[1]*r[2] - l[2]*r[1],2335l[2]*r[0] - l[0]*r[2],2336l[0]*r[1] - l[1]*r[0]])23372338elif len(r) == 7 and len(l) == 7:2339return vector([l[1]*r[3] - l[3]*r[1] + l[2]*r[6] - l[6]*r[2] + l[4]*r[5] - l[5]*r[4],2340l[2]*r[4] - l[4]*r[2] + l[3]*r[0] - l[0]*r[3] + l[5]*r[6] - l[6]*r[5],2341l[3]*r[5] - l[5]*r[3] + l[4]*r[1] - l[1]*r[4] + l[6]*r[0] - l[0]*r[6],2342l[4]*r[6] - l[6]*r[4] + l[5]*r[2] - l[2]*r[5] + l[0]*r[1] - l[1]*r[0],2343l[5]*r[0] - l[0]*r[5] + l[6]*r[3] - l[3]*r[6] + l[1]*r[2] - l[2]*r[1],2344l[6]*r[1] - l[1]*r[6] + l[0]*r[4] - l[4]*r[0] + l[2]*r[3] - l[3]*r[2],2345l[0]*r[2] - l[2]*r[0] + l[1]*r[5] - l[5]*r[1] + l[3]*r[4] - l[4]*r[3]])23462347else:2348raise ArithmeticError("Cross product only defined for vectors of length three or seven, not (%s and %s)"%(len(l),len(r)))2349235023512352def pairwise_product(self, right):2353"""2354Return the pairwise product of self and right, which is a vector of2355the products of the corresponding entries.23562357INPUT:235823592360- ``right`` - vector of the same degree as self. It2361need not be in the same vector space as self, as long as the2362coefficients can be multiplied.236323642365EXAMPLES::23662367sage: V = FreeModule(ZZ, 3)2368sage: v = V([1,2,3])2369sage: w = V([4,5,6])2370sage: v.pairwise_product(w)2371(4, 10, 18)2372sage: sum(v.pairwise_product(w)) == v.dot_product(w)2373True23742375::23762377sage: W = VectorSpace(GF(3),3)2378sage: w = W([0,1,2])2379sage: w.pairwise_product(v)2380(0, 2, 0)2381sage: w.pairwise_product(v).parent()2382Vector space of dimension 3 over Finite Field of size 323832384Implicit coercion is well defined (regardless of order), so we2385get 2 even if we do the dot product in the other order.23862387::23882389sage: v.pairwise_product(w).parent()2390Vector space of dimension 3 over Finite Field of size 323912392TESTS::23932394sage: x, y = var('x, y')23952396::23972398sage: parent(vector(ZZ,[1,2]).pairwise_product(vector(ZZ,[1,2])))2399Ambient free module of rank 2 over the principal ideal domain Integer Ring2400sage: parent(vector(ZZ,[1,2]).pairwise_product(vector(QQ,[1,2])))2401Vector space of dimension 2 over Rational Field2402sage: parent(vector(QQ,[1,2]).pairwise_product(vector(ZZ,[1,2])))2403Vector space of dimension 2 over Rational Field2404sage: parent(vector(QQ,[1,2]).pairwise_product(vector(QQ,[1,2])))2405Vector space of dimension 2 over Rational Field24062407::24082409sage: parent(vector(QQ,[1,2,3,4]).pairwise_product(vector(ZZ[x],[1,2,3,4])))2410Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field2411sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(QQ,[1,2,3,4])))2412Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field24132414::24152416sage: parent(vector(QQ,[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))2417Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field2418sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ,[1,2,3,4])))2419Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field24202421::24222423sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))2424Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field2425sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ[x],[1,2,3,4])))2426Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field24272428::24292430sage: parent(vector(QQ[y],[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))2431Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field2432sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))2433Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field24342435::24362437sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(ZZ[y],[1,2,3,4])))2438Traceback (most recent call last):2439...2440TypeError: no common canonical parent for objects with parents: 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring'2441sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))2442Traceback (most recent call last):2443...2444TypeError: no common canonical parent for objects with parents: 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in x over Integer Ring' and 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'2445sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(ZZ[y],[1,2,3,4])))2446Traceback (most recent call last):2447...2448TypeError: no common canonical parent for objects with parents: 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Integer Ring'2449sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))2450Traceback (most recent call last):2451...2452TypeError: no common canonical parent for objects with parents: 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field' and 'Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in y over Rational Field'2453sage: v = vector({1: 1, 3: 2}) # test sparse vectors2454sage: w = vector({0: 6, 3: -4})2455sage: v.pairwise_product(w)2456(0, 0, 0, -8)2457sage: w.pairwise_product(v) == v.pairwise_product(w)2458True2459"""2460if not PY_TYPE_CHECK(right, FreeModuleElement):2461raise TypeError("right must be a free module element")2462if self._parent is not (<FreeModuleElement>right)._parent:2463self, right = canonical_coercion(self, right)2464return self._pairwise_product_(right)24652466def element(self):2467"""2468Simply returns self. This is useful, since for many objects,2469self.element() returns a vector corresponding to self.24702471EXAMPLES::24722473sage: v = vector([1/2,2/5,0]); v2474(1/2, 2/5, 0)2475sage: v.element()2476(1/2, 2/5, 0)2477"""2478return self24792480def get(self, Py_ssize_t i):2481"""2482The get method is in some cases more efficient (and more2483dangerous) than __getitem__, because it is not guaranteed to2484do any error checking.24852486EXAMPLES::24872488sage: vector([1/2,2/5,0]).get(0)24891/22490sage: vector([1/2,2/5,0]).get(3)2491Traceback (most recent call last):2492...2493IndexError: index out of range2494"""2495return self[i]24962497def set(self, Py_ssize_t i, x):2498"""2499The set method is meant to be more efficient than __setitem__,2500because it need not be guaranteed to do any error checking or2501coercion. Use with great, great care.25022503EXAMPLES::25042505sage: v = vector([1/2,2/5,0]); v2506(1/2, 2/5, 0)2507sage: v.set(2, -15/17); v2508(1/2, 2/5, -15/17)2509"""2510self[i] = x251125122513def monic(self):2514"""2515Return this vector divided through by the first nonzero entry of2516this vector.25172518EXAMPLES::25192520sage: v = vector(QQ, [0, 4/3, 5, 1, 2])2521sage: v.monic()2522(0, 1, 15/4, 3/4, 3/2)2523"""2524cdef Py_ssize_t i2525for i from 0 <= i < self._degree:2526if self[i] != 0:2527return (~self[i]) * self2528return self25292530def normalize(self):2531"""2532This function is deprecated. For division by the p-norm use2533'normalized', and for division by the first nonzero entry use2534'monic' (previously the purpose of this function).25352536EXAMPLES::25372538sage: v = vector(QQ, [0, 4/3, 5, 1, 2])2539sage: v.normalize()2540doctest:...: DeprecationWarning: 'normalize' is deprecated...2541(0, 1, 15/4, 3/4, 3/2)2542"""2543from sage.misc.superseded import deprecation2544deprecation(13393, "'normalize' is deprecated. For division by the \2545p-norm use 'normalized', and for division by the first nonzero entry use \2546'monic'.")2547return self.monic()25482549def normalized(self, p=sage.rings.integer.Integer(2)):2550"""2551Return the input vector divided by the p-norm.25522553INPUT:25542555* "p" - default: 2 - p value for the norm25562557EXAMPLES::25582559sage: v = vector(QQ, [4, 1, 3, 2])2560sage: v.normalized()2561(2/15*sqrt(30), 1/30*sqrt(30), 1/10*sqrt(30), 1/15*sqrt(30))2562sage: sum(v.normalized(1))2563125642565Note that normalizing the vector may change the base ring::25662567sage: v.base_ring() == v.normalized().base_ring()2568False2569sage: u = vector(RDF, [-3, 4, 6, 9])2570sage: u.base_ring() == u.normalized().base_ring()2571True2572"""2573return self / self.norm(p)25742575def conjugate(self):2576r"""2577Returns a vector where every entry has been replaced by its complex conjugate.25782579OUTPUT:25802581A vector of the same length, over the same ring,2582but with each entry replaced by the complex conjugate, as2583implemented by the ``conjugate()`` method for elements of2584the base ring, which is presently always complex conjugation.25852586EXAMPLES::25872588sage: v = vector(CDF, [2.3 - 5.4*I, -1.7 + 3.6*I])2589sage: w = v.conjugate(); w2590(2.3 + 5.4*I, -1.7 - 3.6*I)2591sage: w.parent()2592Vector space of dimension 2 over Complex Double Field25932594Even if conjugation seems nonsensical over a certain ring, this2595method for vectors cooperates silently. ::25962597sage: u = vector(ZZ, range(6))2598sage: u.conjugate()2599(0, 1, 2, 3, 4, 5)26002601Sage implements a few specialized subfields of the complex numbers,2602such as the cyclotomic fields. This example uses such a field2603containing a primitive 7-th root of unity named ``a``. ::26042605sage: F.<a> = CyclotomicField(7)2606sage: v = vector(F, [a^i for i in range(7)])2607sage: v2608(1, a, a^2, a^3, a^4, a^5, -a^5 - a^4 - a^3 - a^2 - a - 1)2609sage: v.conjugate()2610(1, -a^5 - a^4 - a^3 - a^2 - a - 1, a^5, a^4, a^3, a^2, a)26112612Sparse vectors are returned as such. ::26132614sage: v = vector(CC, {1: 5 - 6*I, 3: -7*I}); v2615(0.000000000000000, 5.00000000000000 - 6.00000000000000*I, 0.000000000000000, -7.00000000000000*I)2616sage: v.is_sparse()2617True2618sage: vc = v.conjugate(); vc2619(0.000000000000000, 5.00000000000000 + 6.00000000000000*I, 0.000000000000000, 7.00000000000000*I)2620sage: vc.conjugate()2621(0.000000000000000, 5.00000000000000 - 6.00000000000000*I, 0.000000000000000, -7.00000000000000*I)26222623TESTS::26242625sage: n = 152626sage: x = vector(CDF, [sin(i*pi/n)+cos(i*pi/n)*I for i in range(n)])2627sage: x + x.conjugate() in RDF^n2628True2629sage: I*(x - x.conjugate()) in RDF^n2630True26312632The parent of the conjugate is the same as that of the original vector.2633We test this by building a specialized vector space with a non-standard2634inner product, and constructing a test vector in this space. ::26352636sage: V = VectorSpace(CDF, 2, inner_product_matrix = [[2,1],[1,5]])2637sage: v = vector(CDF, [2-3*I, 4+5*I])2638sage: w = V(v)2639sage: w.parent()2640Ambient quadratic space of dimension 2 over Complex Double Field2641Inner product matrix:2642[2.0 1.0]2643[1.0 5.0]2644sage: w.conjugate().parent()2645Ambient quadratic space of dimension 2 over Complex Double Field2646Inner product matrix:2647[2.0 1.0]2648[1.0 5.0]2649"""2650V = self.parent()2651R = self.base_ring()2652degree = self.degree()2653if self.is_sparse():2654# this could be a dictionary comprehension in Python 32655entries = {}2656for index, entry in self.iteritems():2657entries[index] = entry.conjugate()2658else:2659entries = [entry.conjugate() for entry in self]2660return V(vector(R, degree, entries))26612662def inner_product(self, right):2663r"""2664Returns the inner product of ``self`` and ``right``,2665possibly using an inner product matrix from the parent of ``self``.26662667INPUT:26682669- ``right`` - a vector of the same degree as ``self``26702671OUTPUT:26722673If the parent vector space does not have an inner product2674matrix defined, then this is the usual dot product2675(:meth:`dot_product`). If ``self`` and ``right`` are2676considered as single column matrices, `\vec{x}` and `\vec{y}`,2677and `A` is the inner product matrix, then this method computes26782679.. math::26802681\left(\vec{x}\right)^tA\vec{y}26822683where `t` indicates the transpose.26842685.. note::26862687If your vectors have complex entries, the2688:meth:`hermitian_inner_product` may be more2689appropriate for your purposes.26902691EXAMPLES::26922693sage: v = vector(QQ, [1,2,3])2694sage: w = vector(QQ, [-1,2,-3])2695sage: v.inner_product(w)2696-62697sage: v.inner_product(w) == v.dot_product(w)2698True26992700The vector space or free module that is the parent to2701``self`` can have an inner product matrix defined, which2702will be used by this method. This matrix will be passed2703through to subspaces. ::27042705sage: ipm = matrix(ZZ,[[2,0,-1], [0,2,0], [-1,0,6]])2706sage: M = FreeModule(ZZ, 3, inner_product_matrix = ipm)2707sage: v = M([1,0,0])2708sage: v.inner_product(v)270922710sage: K = M.span_of_basis([[0/2,-1/2,-1/2], [0,1/2,-1/2],[2,0,0]])2711sage: (K.0).inner_product(K.0)271222713sage: w = M([1,3,-1])2714sage: v = M([2,-4,5])2715sage: w.row()*ipm*v.column() == w.inner_product(v)2716True27172718Note that the inner product matrix comes from the parent of ``self``.2719So if a vector is not an element of the correct parent, the result2720could be a source of confusion. ::27212722sage: V = VectorSpace(QQ, 2, inner_product_matrix=[[1,2],[2,1]])2723sage: v = V([12, -10])2724sage: w = vector(QQ, [10,12])2725sage: v.inner_product(w)2726882727sage: w.inner_product(v)272802729sage: w = V(w)2730sage: w.inner_product(v)27318827322733.. note::27342735The use of an inner product matrix makes no restrictions on2736the nature of the matrix. In particular, in this context it2737need not be Hermitian and positive-definite (as it is in the2738example above).27392740TESTS:27412742Most error handling occurs in the :meth:`dot_product` method.2743But with an inner product defined, this method will check2744that the input is a vector or free module element. ::27452746sage: W = VectorSpace(RDF, 2, inner_product_matrix = matrix(RDF, 2, [1.0,2.0,3.0,4.0]))2747sage: v = W([2.0, 4.0])2748sage: v.inner_product(5)2749Traceback (most recent call last):2750...2751TypeError: right must be a free module element2752"""2753if self.parent().is_ambient() and self.parent()._inner_product_is_dot_product():2754return self.dot_product(right)2755if not isinstance(right, FreeModuleElement):2756raise TypeError("right must be a free module element")2757M = self.parent()2758if M.is_ambient() or M.uses_ambient_inner_product():2759A = M.ambient_module().inner_product_matrix()2760return A.linear_combination_of_rows(self).dot_product(right)2761else:2762A = M.inner_product_matrix()2763v = M.coordinate_vector(self)2764w = M.coordinate_vector(right)2765return A.linear_combination_of_rows(v).dot_product(w)27662767def outer_product(self, right):2768r"""2769Returns a matrix, the outer product of two vectors ``self`` and ``right``.27702771INPUT:27722773- ``right`` - a vector (or free module element) of any size, whose2774elements are compatible (with regard to multiplication) with the2775elements of ``self``.27762777OUTPUT:27782779The outer product of two vectors `x` and `y` (respectively2780``self`` and ``right``) can be described several ways. If we2781interpret `x` as a `m\times 1` matrix and interpret `y` as a2782`1\times n` matrix, then the outer product is the `m\times n`2783matrix from the usual matrix product `xy`. Notice how this2784is the "opposite" in some ways from an inner product (which2785would require `m=n`).27862787If we just consider vectors, use each entry of `x` to create2788a scalar multiples of the vector `y` and use these vectors as2789the rows of a matrix. Or use each entry of `y` to create a2790scalar multiples of `x` and use these vectors as the columns2791of a matrix.27922793EXAMPLES::27942795sage: u = vector(QQ, [1/2, 1/3, 1/4, 1/5])2796sage: v = vector(ZZ, [60, 180, 600])2797sage: u.outer_product(v)2798[ 30 90 300]2799[ 20 60 200]2800[ 15 45 150]2801[ 12 36 120]2802sage: M = v.outer_product(u); M2803[ 30 20 15 12]2804[ 90 60 45 36]2805[300 200 150 120]2806sage: M.parent()2807Full MatrixSpace of 3 by 4 dense matrices over Rational Field28082809The more general :meth:`sage.matrix.matrix2.tensor_product` is an2810operation on a pair of matrices. If we construe a pair of vectors2811as a column vector and a row vector, then an outer product and a2812tensor product are identical. Thus `tensor_product` is a synonym2813for this method. ::28142815sage: u = vector(QQ, [1/2, 1/3, 1/4, 1/5])2816sage: v = vector(ZZ, [60, 180, 600])2817sage: u.tensor_product(v) == (u.column()).tensor_product(v.row())2818True28192820The result is always a dense matrix, no matter if the two2821vectors are, or are not, dense. ::28222823sage: d = vector(ZZ,[4,5], sparse=False)2824sage: s = vector(ZZ, [1,2,3], sparse=True)2825sage: dd = d.outer_product(d)2826sage: ds = d.outer_product(s)2827sage: sd = s.outer_product(d)2828sage: ss = s.outer_product(s)2829sage: all([dd.is_dense(), ds.is_dense(), sd.is_dense(), dd.is_dense()])2830True28312832Vectors with no entries do the right thing. ::28332834sage: v = vector(ZZ, [])2835sage: z = v.outer_product(v)2836sage: z.parent()2837Full MatrixSpace of 0 by 0 dense matrices over Integer Ring28382839There is a fair amount of latitude in the value of the ``right``2840vector, and the matrix that results can have entries from a new2841ring large enough to contain the result. If you know better,2842you can sometimes bring the result down to a less general ring. ::28432844sage: R.<t> = ZZ[]2845sage: v = vector(R, [12, 24*t])2846sage: w = vector(QQ, [1/2, 1/3, 1/4])2847sage: op = v.outer_product(w)2848sage: op2849[ 6 4 3]2850[12*t 8*t 6*t]2851sage: op.base_ring()2852Univariate Polynomial Ring in t over Rational Field2853sage: m = op.change_ring(R); m2854[ 6 4 3]2855[12*t 8*t 6*t]2856sage: m.base_ring()2857Univariate Polynomial Ring in t over Integer Ring28582859But some inputs are not compatible, even if vectors. ::28602861sage: w = vector(GF(5), [1,2])2862sage: v = vector(GF(7), [1,2,3,4])2863sage: z = w.outer_product(v)2864Traceback (most recent call last):2865...2866TypeError: unsupported operand parent(s) for '*': 'Full MatrixSpace of 2 by 1 dense matrices over Finite Field of size 5' and 'Full MatrixSpace of 1 by 4 dense matrices over Finite Field of size 7'28672868And some inputs don't make any sense at all. ::28692870sage: w=vector(QQ, [5,10])2871sage: z=w.outer_product(6)2872Traceback (most recent call last):2873...2874TypeError: right operand in an outer product must be a vector, not an element of Integer Ring2875"""2876if not PY_TYPE_CHECK(right, FreeModuleElement):2877raise TypeError('right operand in an outer product must be a vector, not an element of %s' % right.parent())2878return self.column()*right.row()28792880# tensor product is an alias in the special case of two vectors2881tensor_product = outer_product28822883def hermitian_inner_product(self, right):2884r"""2885Returns the dot product, but with the entries of the first vector2886conjugated beforehand.28872888INPUT:28892890- ``right`` - a vector of the same degree as ``self``28912892OUTPUT:28932894If ``self`` and ``right`` are the vectors `\vec{x}` and2895`\vec{y}` of degree `n` then this routine computes28962897.. math::28982899\sum_{i=1}^{n}\overline{x}_i{y}_i29002901where the bar indicates complex conjugation.29022903.. note::29042905If your vectors do not contain complex entries, then2906:meth:`dot_product` will return the same result without2907the overhead of conjugating elements of ``self``.29082909If you are not computing a weighted inner product, and2910your vectors do not have complex entries, then the2911:meth:`dot_product` will return the same result.29122913EXAMPLES::29142915sage: v = vector(CDF, [2+3*I, 5-4*I])2916sage: w = vector(CDF, [6-4*I, 2+3*I])2917sage: v.hermitian_inner_product(w)2918-2.0 - 3.0*I29192920Sage implements a few specialized fields over the complex numbers,2921such as cyclotomic fields and quadratic number fields. So long as2922the base rings have a conjugate method, then the Hermitian inner2923product will be available. ::29242925sage: Q.<a> = QuadraticField(-7)2926sage: a^22927-72928sage: v = vector(Q, [3+a, 5-2*a])2929sage: w = vector(Q, [6, 4+3*a])2930sage: v.hermitian_inner_product(w)293117*a - 429322933The Hermitian inner product should be additive in2934each argument (we only need to test one), linear2935in each argument (with conjugation on the first scalar),2936and anti-commutative. ::29372938sage: alpha = CDF(5.0 + 3.0*I)2939sage: u = vector(CDF, [2+4*I, -3+5*I, 2-7*I])2940sage: v = vector(CDF, [-1+3*I, 5+4*I, 9-2*I])2941sage: w = vector(CDF, [8+3*I, -4+7*I, 3-6*I])2942sage: (u+v).hermitian_inner_product(w) == u.hermitian_inner_product(w) + v.hermitian_inner_product(w)2943True2944sage: (alpha*u).hermitian_inner_product(w) == alpha.conjugate()*u.hermitian_inner_product(w)2945True2946sage: u.hermitian_inner_product(alpha*w) == alpha*u.hermitian_inner_product(w)2947True2948sage: u.hermitian_inner_product(v) == v.hermitian_inner_product(u).conjugate()2949True29502951For vectors with complex entries, the Hermitian inner product2952has a more natural relationship with the 2-norm (which is the2953default for the :meth:`norm` method). The norm squared equals2954the Hermitian inner product of the vector with itself. ::29552956sage: v = vector(CDF, [-0.66+0.47*I, -0.60+0.91*I, -0.62-0.87*I, 0.53+0.32*I])2957sage: abs(v.norm()^2 - v.hermitian_inner_product(v)) < 1.0e-102958True29592960TESTS:29612962This method is built on the :meth:`dot_product` method,2963which allows for a wide variety of inputs. Any error2964handling happens there. ::29652966sage: v = vector(CDF, [2+3*I])2967sage: w = vector(CDF, [5+2*I, 3+9*I])2968sage: v.hermitian_inner_product(w)2969Traceback (most recent call last):2970...2971ArithmeticError: degrees (1 and 2) must be the same2972"""2973return (self.conjugate()).dot_product(right)29742975def is_dense(self):2976"""2977Return True if this is a dense vector, which is just a2978statement about the data structure, not the number of nonzero2979entries.29802981EXAMPLES::29822983sage: vector([1/2,2/5,0]).is_dense()2984True2985sage: vector([1/2,2/5,0],sparse=True).is_dense()2986False2987"""2988return self.is_dense_c()29892990cdef bint is_dense_c(self):2991return self.parent().is_dense()29922993def is_sparse(self):2994"""2995Return True if this is a sparse vector, which is just a2996statement about the data structure, not the number of nonzero2997entries.29982999EXAMPLES::30003001sage: vector([1/2,2/5,0]).is_sparse()3002False3003sage: vector([1/2,2/5,0],sparse=True).is_sparse()3004True3005"""3006return self.is_sparse_c()30073008cdef bint is_sparse_c(self):3009return self.parent().is_sparse()30103011def is_vector(self):3012"""3013Return True, since this is a vector.30143015EXAMPLES::30163017sage: vector([1/2,2/5,0]).is_vector()3018True3019"""3020return True30213022def _mathematica_init_(self):3023"""3024Returns string representation of this vector as a Mathematica3025list.30263027EXAMPLES::30283029sage: vector((1,2,3), QQ)._mathematica_init_()3030'{1/1, 2/1, 3/1}'3031sage: mathematica(vector((1,2,3), QQ)) # optional - mathematica3032{1, 2, 3}3033sage: a = vector(SR, 5, [1, x, x^2, sin(x), pi]); a3034(1, x, x^2, sin(x), pi)3035sage: a._mathematica_init_()3036'{1, x, (x)^(2), Sin[x], Pi}'3037"""3038return '{' + ', '.join([x._mathematica_init_() for x in self.list()]) + '}'30393040## def zero_out_positions(self, P):3041## """3042## Set the positions of self in the list P equal to 0.3043## """3044## z = self.base_ring()(0)3045## d = self.degree()3046## for n in P:3047## self[n] = z30483049def nonzero_positions(self):3050"""3051Return the sorted list of integers ``i`` such that ``self[i] != 0``.30523053EXAMPLES::30543055sage: vector([-1,0,3,0,0,0,0.01]).nonzero_positions()3056[0, 2, 6]3057"""3058z = self.base_ring()(0)3059v = self.list()3060cdef Py_ssize_t i3061return [i for i from 0 <= i < self.degree() if v[i] != z]30623063def support(self): # do not override.3064"""3065Return the integers ``i`` such that ``self[i] != 0``.3066This is the same as the ``nonzero_positions`` function.30673068EXAMPLES::30693070sage: vector([-1,0,3,0,0,0,0.01]).support()3071[0, 2, 6]3072"""3073return self.nonzero_positions()30743075cpdef int hamming_weight(self):3076"""3077Return the number of positions ``i`` such that ``self[i] != 0``.30783079EXAMPLES::30803081sage: vector([-1,0,3,0,0,0,0.01]).hamming_weight()308233083"""3084cdef int res=03085for x in iter(self.list()):3086if not x.is_zero():3087res += 13088return res30893090def _latex_(self):3091r"""3092Return a latex representation of the vector ``self``.30933094OUTPUT:30953096If self is the free module element (1,2,3,4),3097then a string with the following latex is returned:3098"\left(1,\,2,\,3,\,4\right)" (without the quotes).3099The vector is enclosed in parentheses by default,3100but the delimiters can be changed using the command3101``latex.vector_delimiters(...)`` as in the example below.31023103EXAMPLES::31043105sage: v = vector(QQ, [1,2,3])3106sage: latex(v)3107\left(1,\,2,\,3\right)31083109This is an example of how to change the delimiters.3110You have the power to mix and match, though it is3111probably not advisable. For more detail see3112:meth:`~sage.misc.latex.Latex.vector_delimiters`.31133114sage: latex.vector_delimiters('[', '\\rangle')3115sage: w = vector(CDF, [1,2,3])3116sage: latex(w)3117\left[1.0,\,2.0,\,3.0\right\rangle3118"""3119latex = sage.misc.latex.latex3120vector_delimiters = latex.vector_delimiters()3121s = '\\left' + vector_delimiters[0]3122s += ',\,'.join([latex(a) for a in self.list()])3123return s + '\\right' + vector_delimiters[1]31243125def dense_vector(self):3126"""3127Return dense version of self. If self is dense, just return3128self; otherwise, create and return correspond dense vector.31293130EXAMPLES::31313132sage: vector([-1,0,3,0,0,0]).dense_vector().is_dense()3133True3134sage: vector([-1,0,3,0,0,0],sparse=True).dense_vector().is_dense()3135True3136sage: vector([-1,0,3,0,0,0],sparse=True).dense_vector()3137(-1, 0, 3, 0, 0, 0)3138"""3139if self.is_dense():3140return self3141else:3142return self.parent().ambient_module().dense_module()(self.list())31433144def sparse_vector(self):3145"""3146Return sparse version of self. If self is sparse, just return3147self; otherwise, create and return correspond sparse vector.31483149EXAMPLES::31503151sage: vector([-1,0,3,0,0,0]).sparse_vector().is_sparse()3152True3153sage: vector([-1,0,3,0,0,0]).sparse_vector().is_sparse()3154True3155sage: vector([-1,0,3,0,0,0]).sparse_vector()3156(-1, 0, 3, 0, 0, 0)3157"""3158if self.is_sparse():3159return self3160else:3161return self.parent().ambient_module().sparse_module()(self.list())316231633164def apply_map(self, phi, R=None, sparse=None):3165"""3166Apply the given map phi (an arbitrary Python function or callable3167object) to this free module element. If R is not given,3168automatically determine the base ring of the resulting element.31693170INPUT:3171sparse -- True or False will control whether the result3172is sparse. By default, the result is sparse iff self3173is sparse.317431753176- ``phi`` - arbitrary Python function or callable3177object31783179- ``R`` - (optional) ring318031813182OUTPUT: a free module element over R31833184EXAMPLES::31853186sage: m = vector([1,x,sin(x+1)])3187sage: m.apply_map(lambda x: x^2)3188(1, x^2, sin(x + 1)^2)3189sage: m.apply_map(sin)3190(sin(1), sin(x), sin(sin(x + 1)))31913192::31933194sage: m = vector(ZZ, 9, range(9))3195sage: k.<a> = GF(9)3196sage: m.apply_map(k)3197(0, 1, 2, 0, 1, 2, 0, 1, 2)31983199In this example, we explicitly specify the codomain.32003201::32023203sage: s = GF(3)3204sage: f = lambda x: s(x)3205sage: n = m.apply_map(f, k); n3206(0, 1, 2, 0, 1, 2, 0, 1, 2)3207sage: n.parent()3208Vector space of dimension 9 over Finite Field in a of size 3^232093210If your map sends 0 to a non-zero value, then your resulting3211vector is not mathematically sparse::32123213sage: v = vector([0] * 6 + [1], sparse=True); v3214(0, 0, 0, 0, 0, 0, 1)3215sage: v2 = v.apply_map(lambda x: x+1); v23216(1, 1, 1, 1, 1, 1, 2)32173218but it's still represented with a sparse data type::32193220sage: parent(v2)3221Ambient sparse free module of rank 7 over the principal ideal domain Integer Ring32223223This data type is inefficient for dense vectors, so you may3224want to specify sparse=False::32253226sage: v2 = v.apply_map(lambda x: x+1, sparse=False); v23227(1, 1, 1, 1, 1, 1, 2)3228sage: parent(v2)3229Ambient free module of rank 7 over the principal ideal domain Integer Ring32303231Or if you have a map that will result in mostly zeroes, you may3232want to specify sparse=True::32333234sage: v = vector(srange(10))3235sage: v2 = v.apply_map(lambda x: 0 if x else 1, sparse=True); v23236(1, 0, 0, 0, 0, 0, 0, 0, 0, 0)3237sage: parent(v2)3238Ambient sparse free module of rank 10 over the principal ideal domain Integer Ring32393240TESTS::32413242sage: m = vector(SR,[])3243sage: m.apply_map(lambda x: x*x) == m3244True32453246Check that we don't unnecessarily apply phi to 0 in the sparse case::32473248sage: m = vector(ZZ, range(1, 4), sparse=True)3249sage: m.apply_map(lambda x: 1/x)3250(1, 1/2, 1/3)32513252sage: parent(vector(RDF, (), sparse=True).apply_map(lambda x: x, sparse=True))3253Sparse vector space of dimension 0 over Real Double Field3254sage: parent(vector(RDF, (), sparse=True).apply_map(lambda x: x, sparse=False))3255Vector space of dimension 0 over Real Double Field3256sage: parent(vector(RDF, (), sparse=False).apply_map(lambda x: x, sparse=True))3257Sparse vector space of dimension 0 over Real Double Field3258sage: parent(vector(RDF, (), sparse=False).apply_map(lambda x: x, sparse=False))3259Vector space of dimension 0 over Real Double Field32603261Check that the bug in :trac:`14558` has been fixed::32623263sage: F.<a> = GF(9)3264sage: v = vector([a, 0,0,0], sparse=True)3265sage: f = F.hom([a**3])3266sage: v.apply_map(f)3267(2*a + 1, 0, 0, 0)3268"""3269if sparse is None:3270sparse = self.is_sparse()32713272if self._degree == 0:3273if sparse == self.is_sparse():3274from copy import copy3275return copy(self)3276elif sparse:3277return self.sparse_vector()3278else:3279return self.dense_vector()32803281v = None32823283if self.is_sparse():3284zero_res = 03285if len(self.dict(copy=False)) < self._degree:3286# OK, we have some zero entries.3287zero_res = phi(self.base_ring()(0))3288if not zero_res.is_zero():3289# And phi maps 0 to a non-zero value.3290v = [zero_res] * self._degree3291for i,z in self.dict(copy=False).items():3292v[i] = phi(z)32933294if v is None:3295# phi maps 0 to 0 (or else we don't have any zeroes at all)3296v = dict([(i,phi(z)) for i,z in self.dict(copy=False).items()])3297# add a zero at the last position, if it is not already set.3298# This will help the constructor to determine the right degree.3299v.setdefault(self._degree-1, zero_res)3300else:3301v = [phi(z) for z in self.list()]33023303if R is None:3304return vector(v, sparse=sparse)3305else:3306return vector(R, v, sparse=sparse)330733083309def _derivative(self, var=None):3310"""3311Differentiate with respect to var by differentiating each element3312with respect to var.33133314.. seealso:33153316:meth:`derivative`33173318EXAMPLES::33193320sage: v = vector([1,x,x^2])3321sage: v._derivative(x)3322(0, 1, 2*x)3323sage: type(v._derivative(x)) == type(v)3324True3325sage: v = vector([1,x,x^2], sparse=True)3326sage: v._derivative(x)3327(0, 1, 2*x)3328sage: type(v._derivative(x)) == type(v)3329True33303331If no variables are specified and the vector contains callable3332symbolic expressions, then calculate the matrix derivative3333(i.e., the Jacobian matrix)::33343335sage: T(r,theta)=[r*cos(theta),r*sin(theta)]3336sage: T3337(r, theta) |--> (r*cos(theta), r*sin(theta))3338sage: T.diff() # matrix derivative3339[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]3340[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]3341sage: diff(T) # matrix derivative again3342[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]3343[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]3344sage: T.diff().det() # Jacobian3345(r, theta) |--> r*cos(theta)^2 + r*sin(theta)^23346"""3347if var is None:3348if sage.symbolic.callable.is_CallableSymbolicExpressionRing(self.base_ring()):3349return sage.calculus.all.jacobian(self, self.base_ring().arguments())3350else:3351raise ValueError("No differentiation variable specified.")33523353# We would just use apply_map, except that Cython doesn't3354# allow lambda functions3355if self._degree == 0:3356from copy import copy3357return copy(self)33583359if self.is_sparse():3360v = dict([(i,z.derivative(var)) for i,z in self.dict().items()])3361else:3362v = [z.derivative(var) for z in self.list()]33633364return self.parent().ambient_module()(v)33653366def derivative(self, *args):3367"""3368Derivative with respect to variables supplied in args.33693370Multiple variables and iteration counts may be supplied; see3371documentation for the global derivative() function for more3372details.33733374:meth:`diff` is an alias of this function.33753376EXAMPLES::33773378sage: v = vector([1,x,x^2])3379sage: v.derivative(x)3380(0, 1, 2*x)3381sage: type(v.derivative(x)) == type(v)3382True3383sage: v = vector([1,x,x^2], sparse=True)3384sage: v.derivative(x)3385(0, 1, 2*x)3386sage: type(v.derivative(x)) == type(v)3387True3388sage: v.derivative(x,x)3389(0, 0, 2)3390"""3391return multi_derivative(self, args)33923393diff = derivative33943395def integral(self, *args, **kwds):3396"""3397Returns a symbolic integral of the vector, component-wise.33983399:meth:`integrate` is an alias of the function.34003401EXAMPLES::34023403sage: t=var('t')3404sage: r=vector([t,t^2,sin(t)])3405sage: r.integral(t)3406(1/2*t^2, 1/3*t^3, -cos(t))3407sage: integrate(r,t)3408(1/2*t^2, 1/3*t^3, -cos(t))3409sage: r.integrate(t,0,1)3410(1/2, 1/3, -cos(1) + 1)34113412"""3413from sage.misc.functional import integral34143415# If Cython supported lambda functions, we would just do3416# return self.apply_map(lambda x: integral(x,*args, **kwds) for x in self)34173418if self.is_sparse():3419v = dict([(i,integral(z,*args,**kwds)) for i,z in self.dict(copy=False).items()])3420else:3421v = [integral(z,*args,**kwds) for z in self.list()]34223423return vector(v,sparse=self.is_sparse())34243425integrate=integral342634273428def nintegral(self, *args, **kwds):3429"""3430Returns a numeric integral of the vector, component-wise, and3431the result of the nintegral command on each component of the3432input.34333434:meth:`nintegrate` is an alias of the function.34353436EXAMPLES::34373438sage: t=var('t')3439sage: r=vector([t,t^2,sin(t)])3440sage: vec,answers=r.nintegral(t,0,1)3441sage: vec3442(0.5, 0.333333333333, 0.459697694132)3443sage: type(vec)3444<type 'sage.modules.vector_real_double_dense.Vector_real_double_dense'>3445sage: answers3446[(0.5, 5.551115123125784e-15, 21, 0), (0.3333333333333..., 3.70074341541719e-15, 21, 0), (0.45969769413186..., 5.103669643922841e-15, 21, 0)]34473448sage: r=vector([t,0,1], sparse=True)3449sage: r.nintegral(t,0,1)3450((0.5, 0.0, 1.0), {0: (0.5, 5.551115123125784e-15, 21, 0), 2: (1.0, 1.11022302462515...e-14, 21, 0)})34513452"""3453# If Cython supported lambda functions, we would just do3454# return self.apply_map(lambda x: x.nintegral(*args, **kwds) for x in self)34553456if self.is_sparse():3457v = [(i,z.nintegral(*args,**kwds)) for i,z in self.dict(copy=False).items()]3458answers = dict([(i,a[0]) for i,a in v])3459v=dict(v)3460else:3461v = [z.nintegral(*args,**kwds) for z in self.list()]3462answers = [a[0] for a in v]34633464return (vector(answers,sparse=self.is_sparse()), v)34653466nintegrate=nintegral34673468#############################################3469# Generic dense element3470#############################################3471def make_FreeModuleElement_generic_dense(parent, entries, degree):3472"""3473EXAMPLES::34743475sage: sage.modules.free_module_element.make_FreeModuleElement_generic_dense(QQ^3, [1,2,-3/7], 3)3476(1, 2, -3/7)3477"""3478# If you think you want to change this function, don't.3479# Instead make a new version with a name like3480# make_FreeModuleElement_generic_dense_v13481# and changed the reduce method below.3482cdef FreeModuleElement_generic_dense v3483v = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)3484v._entries = entries3485v._parent = parent3486v._degree = degree3487return v34883489def make_FreeModuleElement_generic_dense_v1(parent, entries, degree, is_mutable):3490"""3491EXAMPLES::34923493sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_dense_v1(QQ^3, [1,2,-3/7], 3, True); v3494(1, 2, -3/7)3495sage: v[0] = 10; v3496(10, 2, -3/7)3497sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_dense_v1(QQ^3, [1,2,-3/7], 3, False); v3498(1, 2, -3/7)3499sage: v[0] = 103500Traceback (most recent call last):3501...3502ValueError: vector is immutable; please change a copy instead (use copy())3503"""3504# If you think you want to change this function, don't.3505# Instead make a new version with a name like3506# make_FreeModuleElement_generic_dense_v23507# and changed the reduce method below.3508cdef FreeModuleElement_generic_dense v3509v = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)3510v._entries = entries3511v._parent = parent3512v._degree = degree3513v._is_mutable = is_mutable3514return v35153516cdef class FreeModuleElement_generic_dense(FreeModuleElement):3517"""3518A generic dense element of a free module.3519"""3520## these work fine on the command line but fail in doctests :-(3521## TESTS:3522## sage: V = ZZ^33523## sage: loads(dumps(V)) == V3524## True3525## sage: v = V.03526## sage: loads(dumps(v)) == v3527## True3528## sage: v = (QQ['x']^3).03529## sage: loads(dumps(v)) == v3530## True3531cdef _new_c(self, object v):3532# Create a new dense free module element with minimal overhead and3533# no type checking.3534cdef FreeModuleElement_generic_dense x3535x = <FreeModuleElement_generic_dense>PY_NEW(<object>PY_TYPE(self))3536x._is_mutable = 13537x._parent = self._parent3538x._entries = v3539x._degree = self._degree3540return x35413542cdef bint is_dense_c(self):3543return 135443545cdef bint is_sparse_c(self):3546return 035473548def _hash(self):3549"""3550Return hash of an immutable form of self (works even if self3551is mutable).35523553sage: v = vector([-1,0,3,pi])3554sage: type(v)3555<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>3556sage: v._hash() # random output3557"""3558return hash(tuple(list(self)))35593560def __copy__(self):3561"""3562Return a copy of this generic dense vector.35633564EXAMPLES::35653566sage: v = vector([-1,0,3,pi])3567sage: type(v)3568<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>3569sage: v.__copy__()3570(-1, 0, 3, pi)3571sage: v.__copy__() is v3572False35733574sage: copy(v)3575(-1, 0, 3, pi)3576sage: copy(v) == v3577True3578sage: copy(v) is v3579False3580"""3581return self._new_c(list(self._entries))35823583def __init__(self, parent, entries, coerce=True, copy=True):3584"""3585EXAMPLES::35863587sage: type(vector([-1,0,3,pi])) # indirect doctest3588<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>35893590TESTS:35913592Check that #11751 is fixed::35933594sage: K.<x> = QQ[]3595sage: M = K^13596sage: N = M.span([[1/x]]); N3597Free module of degree 1 and rank 1 over Univariate Polynomial Ring in x over Rational Field3598Echelon basis matrix:3599[1/x]3600sage: N([1/x]) # this used to fail prior to #117513601(1/x)3602sage: N([1/x^2])3603Traceback (most recent call last):3604...3605TypeError: element (= [1/x^2]) is not in free module36063607::36083609sage: L=K^23610sage: R=L.span([[x,0],[0,1/x]], check=False, already_echelonized=True)3611sage: R.basis()[0][0].parent()3612Fraction Field of Univariate Polynomial Ring in x over Rational Field3613sage: R=L.span([[x,x^2]])3614sage: R.basis()[0][0].parent()3615Univariate Polynomial Ring in x over Rational Field3616"""3617FreeModuleElement.__init__(self, parent)3618R = self.parent().base_ring()3619if entries == 0:3620entries = [R(0)]*self.degree()3621else:3622if not isinstance(entries, (list, tuple)):3623raise TypeError("entries (=%s) must be a list"%(entries, ))36243625if len(entries) != self.degree():3626raise TypeError("entries must be a list of length %s"%\3627self.degree())3628if coerce:3629if len(entries) != 0:3630coefficient_ring = parent.basis()[0][0].parent()3631try:3632entries = [coefficient_ring(x) for x in entries]3633except TypeError:3634raise TypeError("Unable to coerce entries (=%s) to coefficients in %s"%(entries, coefficient_ring))3635elif copy:3636# Make a copy3637entries = list(entries)3638self._entries = entries36393640cpdef ModuleElement _add_(left, ModuleElement right):3641"""3642Add left and right.36433644EXAMPLES::36453646sage: v = vector([1,2/3,pi]); w = vector([-2/3,pi^2,1])3647sage: v._add_(w)3648(1/3, pi^2 + 2/3, pi + 1)3649"""3650cdef Py_ssize_t i, n3651n = PyList_Size(left._entries)3652v = [None]*n3653for i from 0 <= i < n:3654v[i] = (<RingElement>left._entries[i])._add_(<RingElement>3655((<FreeModuleElement_generic_dense>right)._entries[i]))3656return left._new_c(v)36573658cpdef ModuleElement _sub_(left, ModuleElement right):3659"""3660Subtract right from left.36613662EXAMPLES::36633664sage: V = QQ^53665sage: W = V.span([V.1, V.2])3666sage: W.0 - V.03667(-1, 1, 0, 0, 0)3668sage: V.0 - W.03669(1, -1, 0, 0, 0)3670"""3671cdef Py_ssize_t i, n3672n = PyList_Size(left._entries)3673v = [None]*n3674for i from 0 <= i < n:3675v[i] = (<RingElement>left._entries[i])._sub_(<RingElement>3676((<FreeModuleElement_generic_dense>right)._entries[i]))3677return left._new_c(v)36783679cpdef ModuleElement _rmul_(self, RingElement left):3680"""3681EXAMPLES::36823683sage: V = ZZ['x']^53684sage: 5 * V.03685(5, 0, 0, 0, 0)3686"""3687if left._parent is self._parent._base:3688v = [left._mul_(<RingElement>x) for x in self._entries]3689else:3690v = [left * x for x in self._entries]3691return self._new_c(v)36923693cpdef ModuleElement _lmul_(self, RingElement right):3694"""3695EXAMPLES::36963697sage: v = vector([-1,0,3,pi])3698sage: v._lmul_(2/3)3699(-2/3, 0, 2, 2/3*pi)3700sage: v * (2/3)3701(-2/3, 0, 2, 2/3*pi)3702"""3703if right._parent is self._parent._base:3704v = [(<RingElement>x)._mul_(right) for x in self._entries]3705else:3706v = [x * right for x in self._entries]3707return self._new_c(v)37083709cpdef Element _dot_product_(left, element_Vector right):3710"""3711Return the dot product of left and right.37123713EXAMPLES::37143715sage: R.<x> = QQ[]3716sage: v = vector([x,x^2,3*x]); w = vector([2*x,x,3+x])3717sage: v*w3718x^3 + 5*x^2 + 9*x3719sage: (x*2*x) + (x^2*x) + (3*x*(3+x))3720x^3 + 5*x^2 + 9*x3721sage: w*v3722x^3 + 5*x^2 + 9*x3723"""3724return left.dot_product(right)37253726cpdef element_Vector _pairwise_product_(left, element_Vector right):3727"""3728EXAMPLES::37293730sage: R.<x> = QQ[]3731sage: v = vector([x,x^2,3*x]); w = vector([2*x,x,3+x])3732sage: v.pairwise_product(w)3733(2*x^2, x^3, 3*x^2 + 9*x)3734sage: w.pairwise_product(v)3735(2*x^2, x^3, 3*x^2 + 9*x)3736"""3737if not right.parent() == left.parent():3738right = left.parent().ambient_module()(right)3739# Component wise vector * vector multiplication.3740cdef Py_ssize_t i, n3741n = PyList_Size(left._entries)3742v = [None]*n3743for i from 0 <= i < n:3744v[i] = (<RingElement>left._entries[i])._mul_((<FreeModuleElement_generic_dense>right)._entries[i])3745return left._new_c(v)37463747def __reduce__(self):3748"""3749EXAMPLES::37503751sage: v = vector([-1,0,3,pi])3752sage: v.__reduce__()3753(<built-in function make_FreeModuleElement_generic_dense_v1>, (Vector space of dimension 4 over Symbolic Ring, [-1, 0, 3, pi], 4, True))3754"""3755return (make_FreeModuleElement_generic_dense_v1, (self._parent, self._entries, self._degree, self._is_mutable))37563757def __getitem__(self, i):3758"""3759EXAMPLES::37603761sage: v = vector([RR(1), RR(2)]); v3762(1.00000000000000, 2.00000000000000)3763sage: v[0]37641.000000000000003765sage: v[-1]37662.000000000000003767sage: v[4]3768Traceback (most recent call last):3769...3770IndexError: index must be between -2 and 13771sage: v[-4]3772Traceback (most recent call last):3773...3774IndexError: index must be between -2 and 137753776sage: v = vector(QQ['x,y'], [1,2, 'x*y'])3777sage: v3778(1, 2, x*y)3779sage: v[1:]3780(2, x*y)3781"""3782if isinstance(i, slice):3783start, stop, step = i.indices(len(self))3784return vector(self.base_ring(), list(self)[start:stop:step])3785else:3786degree = self.degree()3787if i < 0:3788i += degree3789if i < 0 or i >= self.degree():3790raise IndexError("index must be between -%s and %s"%(degree, degree-1))3791return self._entries[i]37923793def __setitem__(self, i, value):3794"""3795Set entry i of self to value.37963797EXAMPLES::37983799sage: v = vector([1,2/3,pi])3800sage: v[1] = 19+pi3801sage: v3802(1, pi + 19, pi)3803sage: v = vector(QQ['x,y'], [1,2, 'x*y'])3804sage: v3805(1, 2, x*y)3806sage: v[1:]3807(2, x*y)3808sage: v[1:] = [4,5]; v3809(1, 4, 5)3810sage: v[:2] = [5,(6,2)]; v3811(5, 3, 5)3812sage: v[:2]3813(5, 3)3814"""3815if not self._is_mutable:3816raise ValueError("vector is immutable; please change a copy instead (use copy())")3817cdef Py_ssize_t k, n, d3818if isinstance(i, slice):3819start, stop, step = i.indices(len(self))3820d = self.degree()3821R = self.base_ring()3822n = 03823for k from start <= k < stop:3824if k >= d:3825return3826if k >= 0:3827self._entries[k] = R(value[n])3828n = n + 13829else:3830if i < 0 or i >= self.degree():3831raise IndexError("index (i=%s) must be between 0 and %s"%(i,3832self.degree()-1))3833self._entries[i] = self.base_ring()(value)38343835def list(self, copy=True):3836"""3837Return list of elements of self.38383839INPUT:38403841- copy -- bool, return list of underlying entries38423843EXAMPLES::38443845sage: P.<x,y,z> = QQ[]3846sage: v = vector([x,y,z])3847sage: type(v)3848<type 'sage.modules.free_module_element.FreeModuleElement_generic_dense'>3849sage: a = v.list(); a3850[x, y, z]3851sage: a[0] = x*y; v3852(x, y, z)3853sage: a = v.list(copy=False); a3854[x, y, z]3855sage: a[0] = x*y; v3856(x*y, y, z)3857"""3858if copy:3859return list(self._entries)3860else:3861return self._entries38623863def __call__(self, *args, **kwargs):3864"""3865Calling a free module element returns the result of calling each3866component.38673868EXAMPLES::38693870sage: x, y = var('x,y')3871sage: f = x^2 + y^23872sage: g = f.gradient()3873sage: g3874(2*x, 2*y)3875sage: type(g)3876<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>3877sage: g(y=2, x=3)3878(6, 4)3879sage: f(x,y) = x^2 + y^23880sage: g = f.gradient()3881sage: g(3,2)3882(6, 4)3883sage: g(x=3, y=2)3884(6, 4)3885"""3886return vector([e(*args, **kwargs) for e in self])38873888def function(self, *args):3889"""3890Returns a vector over a callable symbolic expression ring.38913892EXAMPLES::38933894sage: x,y=var('x,y')3895sage: v=vector([x,y,x*sin(y)])3896sage: w=v.function([x,y]); w3897(x, y) |--> (x, y, x*sin(y))3898sage: w.base_ring()3899Callable function ring with arguments (x, y)3900sage: w(1,2)3901(1, 2, sin(2))3902sage: w(2,1)3903(2, 1, 2*sin(1))3904sage: w(y=1,x=2)3905(2, 1, 2*sin(1))39063907::39083909sage: x,y=var('x,y')3910sage: v=vector([x,y,x*sin(y)])3911sage: w=v.function([x]); w3912x |--> (x, y, x*sin(y))3913sage: w.base_ring()3914Callable function ring with arguments (x,)3915sage: w(4)3916(4, y, 4*sin(y))3917"""3918from sage.symbolic.callable import CallableSymbolicExpressionRing3919return vector(CallableSymbolicExpressionRing(args), self.list())39203921#############################################3922# Generic sparse element3923#############################################3924def _sparse_dot_product(v, w):3925"""3926v and w are dictionaries with integer keys.39273928EXAMPLES::39293930sage: sage.modules.free_module_element._sparse_dot_product({0:5,1:7,2:3}, {0:-1, 2:2})393113932"""3933x = set(v.keys()).intersection(set(w.keys()))3934return sum([v[k]*w[k] for k in x])39353936def make_FreeModuleElement_generic_sparse(parent, entries, degree):3937"""3938EXAMPLES::39393940sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_sparse(QQ^3, {2:5/2}, 3); v3941(0, 0, 5/2)3942"""3943cdef FreeModuleElement_generic_sparse v3944v = FreeModuleElement_generic_sparse.__new__(FreeModuleElement_generic_sparse)3945v._entries = entries3946v._parent = parent3947v._degree = degree3948return v39493950def make_FreeModuleElement_generic_sparse_v1(parent, entries, degree, is_mutable):3951"""3952EXAMPLES::39533954sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_sparse_v1(QQ^3, {2:5/2}, 3, False); v3955(0, 0, 5/2)3956sage: v.is_mutable()3957False3958"""3959cdef FreeModuleElement_generic_sparse v3960v = FreeModuleElement_generic_sparse.__new__(FreeModuleElement_generic_sparse)3961v._entries = entries3962v._parent = parent3963v._degree = degree3964v._is_mutable = is_mutable3965return v39663967cdef class FreeModuleElement_generic_sparse(FreeModuleElement):3968"""3969A generic sparse free module element is a dictionary with keys ints3970i and entries in the base ring.39713972EXAMPLES:39733974Pickling works::39753976sage: v = FreeModule(ZZ, 3, sparse=True).03977sage: loads(dumps(v)) == v3978True3979sage: v = FreeModule(Integers(8)['x,y'], 5, sparse=True).13980sage: loads(dumps(v)) - v3981(0, 0, 0, 0, 0)39823983::39843985sage: a = vector([-1,0,1/1],sparse=True); b = vector([-1/1,0,0],sparse=True)3986sage: a.parent()3987Sparse vector space of dimension 3 over Rational Field3988sage: b - a3989(0, 0, -1)3990sage: (b-a).dict()3991{2: -1}3992"""3993cdef _new_c(self, object v):3994# Create a new sparse free module element with minimal overhead and3995# no type checking.3996cdef FreeModuleElement_generic_sparse x3997x = PY_NEW(FreeModuleElement_generic_sparse)3998x._is_mutable = 13999x._parent = self._parent4000x._entries = v4001x._degree = self._degree4002return x40034004cdef bint is_dense_c(self):4005return 040064007cdef bint is_sparse_c(self):4008return 140094010def __copy__(self):4011"""4012EXAMPLES::40134014sage: v = vector([1,2/3,pi], sparse=True)4015sage: v.__copy__()4016(1, 2/3, pi)4017"""4018return self._new_c(dict(self._entries))40194020def __init__(self, parent,4021entries=0,4022coerce=True,4023copy=True):4024"""4025EXAMPLES::40264027sage: v = sage.modules.free_module_element.FreeModuleElement_generic_sparse(VectorSpace(QQ,3,sparse=True), {1:5/4}); v4028(0, 5/4, 0)4029sage: v.is_sparse()4030True40314032TESTS:40334034Test that 11751 is fixed::40354036sage: K.<x> = QQ[]4037sage: M = FreeModule(K, 1, sparse=True)4038sage: N = M.span([{0:1/x}]); N4039Sparse free module of degree 1 and rank 1 over Univariate Polynomial Ring in x over Rational Field4040Echelon basis matrix:4041[1/x]4042sage: N({0:1/x}) # this used to fail prior to #117514043(1/x)4044sage: N({0:1/x^2})4045Traceback (most recent call last):4046...4047TypeError: element (= {0: 1/x^2}) is not in free module40484049::40504051sage: L = FreeModule(K, 2, sparse=True)4052sage: R = L.span([{0:x, 1:0}, {0:0, 1:1/x}], check=False, already_echelonized=True)4053sage: R.basis()[0][0].parent()4054Fraction Field of Univariate Polynomial Ring in x over Rational Field4055sage: R = L.span([{0:x, 1:x^2}])4056sage: R.basis()[0][0].parent()4057Univariate Polynomial Ring in x over Rational Field4058"""4059#WARNING: In creation, we do not check that the i pairs satisfy4060# 0 <= i < degree.4061FreeModuleElement.__init__(self, parent)4062R = self.base_ring()4063if entries == 0:4064entries = {}4065else:4066if isinstance(entries, list):4067if len(entries) != self.degree():4068raise TypeError("entries has the wrong length")4069x = entries4070entries = {}4071for i in xrange(self.degree()):4072if x[i] != 0:4073entries[i] = x[i]4074copy = False4075if not isinstance(entries, dict):4076raise TypeError, "entries must be a dict"4077if copy:4078# Make a copy4079entries = dict(entries)4080if coerce:4081if len(entries) != 0:4082coefficient_ring = parent.basis()[0][0].parent()4083try:4084for k, x in entries.iteritems():4085entries[k] = coefficient_ring(x)4086except TypeError:4087raise TypeError("Unable to coerce value (=%s) of entries dict (=%s) to %s"%(x, entries, coefficient_ring))4088self._entries = entries40894090cpdef ModuleElement _add_(left, ModuleElement right):4091"""4092Add left and right.40934094EXAMPLES::40954096sage: v = vector([1,2/3,pi], sparse=True)4097sage: v._add_(v)4098(2, 4/3, 2*pi)4099"""4100cdef object v, e4101e = dict((<FreeModuleElement_generic_sparse>right)._entries)4102for i, a in left._entries.iteritems():4103if e.has_key(i):4104sum = (<RingElement>a)._add_(<RingElement> e[i])4105if sum:4106e[i] = sum4107else:4108del e[i]4109elif a:4110e[i] = a4111return left._new_c(e)41124113cpdef ModuleElement _sub_(left, ModuleElement right):4114"""4115EXAMPLES::41164117sage: v = vector([1,2/3,pi], sparse=True)4118sage: v._sub_(v)4119(0, 0, 0)4120"""4121cdef object v, e4122e = dict(left._entries) # dict to make a copy4123for i, a in (<FreeModuleElement_generic_sparse>right)._entries.iteritems():4124if e.has_key(i):4125diff = (<RingElement> e[i])._sub_(<RingElement>a)4126if diff:4127e[i] = diff4128else:4129del e[i]4130elif a:4131e[i] = -a4132return left._new_c(e)41334134cpdef ModuleElement _lmul_(self, RingElement right):4135"""4136EXAMPLES::41374138sage: v = vector([1,2/3,pi], sparse=True)4139sage: v._lmul_(SR(3))4140(3, 2, 3*pi)4141"""4142cdef object v4143v = PyDict_New()4144if right:4145for i, a in self._entries.iteritems():4146prod = (<RingElement>a)._mul_(right)4147if prod:4148v[i] = prod4149return self._new_c(v)41504151cpdef ModuleElement _rmul_(self, RingElement left):4152"""4153EXAMPLES::41544155sage: v = vector([1,2/3,pi], sparse=True)4156sage: v._rmul_(SR(3))4157(3, 2, 3*pi)4158"""4159cdef object v4160v = PyDict_New()4161if left:4162for i, a in self._entries.iteritems():4163prod = left._mul_(a)4164if prod:4165v[i] = prod4166return self._new_c(v)41674168cpdef Element _dot_product_(left, element_Vector right):4169"""4170Return the dot product of left and right.41714172EXAMPLES::41734174sage: v = vector([1,2,0], sparse=True); w = vector([0,5,-9], sparse=True)4175sage: v * w4176104177sage: w * v4178104179"""4180cdef object v, e, z4181e = dict((<FreeModuleElement_generic_sparse>right)._entries)4182z = left.base_ring()(0)4183for i, a in left._entries.iteritems():4184if e.has_key(i):4185z += (<RingElement>a)._mul_(<RingElement> e[i])4186return z41874188cpdef element_Vector _pairwise_product_(left, element_Vector right):4189"""4190EXAMPLES::41914192sage: v = vector([1,2/3,pi], sparse=True); w = vector([-2/3,pi^2,1],sparse=True)4193sage: v._pairwise_product_(w)4194(-2/3, 2/3*pi^2, pi)4195"""4196# Component wise vector * vector multiplication.4197cdef object v, e4198e = dict((<FreeModuleElement_generic_sparse>right)._entries)4199v = PyDict_New()4200for i, a in left._entries.iteritems():4201if e.has_key(i):4202prod = (<RingElement>a)._mul_(<RingElement> e[i])4203if prod:4204v[i] = prod4205return left._new_c(v)42064207cdef int _cmp_c_impl(left, Element right) except -2:4208"""4209Compare two sparse free module elements.42104211Free module elements are compared in lexicographic order on4212the underlying list of coefficients. Two free module elements4213are equal if their coefficients are the same. (This is true4214even if one is sparse and one is dense.)42154216TESTS::42174218sage: v = vector([1,2/3,pi], sparse=True)4219sage: w = vector([1,2/3,pi], sparse=True)4220sage: w == v4221True42224223Check that the bug in :trac:`13929` has been fixed::42244225sage: V = FreeModule( GF(3), 2, sparse=True)4226sage: a = V([0,1])4227sage: b = V([1,0])4228sage: cmp(a, b)4229-14230"""42314232a = left._entries.items()4233a.sort()4234b = (< FreeModuleElement_generic_sparse > right)._entries.items()4235b.sort()42364237a = [(-x,y) for x, y in a]4238b = [(-x,y) for x, y in b]42394240return cmp(a, b)42414242# see sage/structure/element.pyx4243def __richcmp__(left, right, int op):4244"""4245TESTS::42464247sage: v = vector([1,2/3,pi], sparse=True)4248sage: v == v4249True4250"""4251return (<Element>left)._richcmp(right, op)42524253# __hash__ is not properly inherited if comparison is changed4254def __hash__(self):4255"""4256TESTS::42574258sage: v = vector([1,2/3,pi], sparse=True)4259sage: v.set_immutable()4260sage: isinstance(hash(v), int)4261True4262"""4263return FreeModuleElement.__hash__(self)42644265def iteritems(self):4266"""4267Return iterator over the entries of self.42684269EXAMPLES::42704271sage: v = vector([1,2/3,pi], sparse=True)4272sage: v.iteritems()4273<dictionary-itemiterator object at ...>4274sage: list(v.iteritems())4275[(0, 1), (1, 2/3), (2, pi)]4276"""4277return self._entries.iteritems()42784279def __reduce__(self):4280"""4281EXAMPLES::42824283sage: v = vector([1,2/3,pi], sparse=True)4284sage: v.__reduce__()4285(<built-in function make_FreeModuleElement_generic_sparse_v1>, (Sparse vector space of dimension 3 over Symbolic Ring, {0: 1, 1: 2/3, 2: pi}, 3, True))4286"""4287return (make_FreeModuleElement_generic_sparse_v1, (self._parent, self._entries, self._degree, self._is_mutable))42884289def __getitem__(self, i):4290"""4291EXAMPLES::42924293sage: v = vector([RR(1), RR(2)], sparse=True); v4294(1.00000000000000, 2.00000000000000)4295sage: v[0]42961.000000000000004297sage: v[-1]42982.000000000000004299sage: v[5]4300Traceback (most recent call last):4301...4302IndexError: index must be between -2 and 14303sage: v[-3]4304Traceback (most recent call last):4305...4306IndexError: index must be between -2 and 14307"""4308if isinstance(i, slice):4309start, stop, step = i.indices(len(self))4310return vector(self.base_ring(), self.list()[start:stop])4311else:4312i = int(i)4313degree = self.degree()4314if i < 0:4315i += degree4316if i < 0 or i >= degree:4317raise IndexError("index must be between %s and %s"%(-degree,4318degree-1))4319if self._entries.has_key(i):4320return self._entries[i]4321return self.base_ring()(0) # optimize this somehow43224323def get(self, i):4324"""4325Like __getitem__ but with no guaranteed type or bounds checking. Returns 04326if access is out of bounds.43274328EXAMPLES::43294330sage: v = vector([1,2/3,pi], sparse=True)4331sage: v.get(1)43322/34333sage: v.get(10)433404335"""4336i = int(i)4337if self._entries.has_key(i):4338return self._entries[i]4339return self.base_ring()(0) # optimize this somehow434043414342def set(self, i, x):4343"""4344Like __setitem__ but with no guaranteed type or bounds checking.43454346EXAMPLES::43474348sage: v = vector([1,2/3,pi], sparse=True)4349sage: v.set(1, pi^3)4350sage: v4351(1, pi^3, pi)43524353No bounds checking::43544355sage: v.set(10, pi)43564357This lack of bounds checking causes trouble later::43584359sage: v4360Traceback (most recent call last):4361...4362IndexError: list assignment index out of range4363"""4364if not self._is_mutable:4365raise ValueError("vector is immutable; please change a copy instead (use copy())")4366i = int(i)4367if x == 0:4368if self._entries.has_key(i):4369del self._entries[i]4370return4371self._entries[i] = x43724373def __setitem__(self, i, value):4374"""4375Set the `i`-th entry or slice of self to value.43764377EXAMPLES::43784379sage: V = VectorSpace(GF(17), 10000000, sparse=True)4380sage: w = V(0)4381sage: w[39893] = 204382sage: w[39893]438334384sage: w[39000:39003] = [4, 5, 6]; w[39000:39003]4385(4, 5, 6)4386sage: parent(w[39893])4387Finite Field of size 174388sage: w[39893] = sqrt(2)4389Traceback (most recent call last):4390...4391TypeError: unable to convert x (=sqrt(2)) to an integer4392"""4393if not self._is_mutable:4394raise ValueError("vector is immutable; please change a copy instead (use copy())")4395cdef Py_ssize_t k, d, n4396if isinstance(i, slice):4397start, stop = i.start, i.stop4398d = self.degree()4399R = self.base_ring()4400n = 04401for k from start <= k < stop:4402if k >= d:4403return4404if k >= 0:4405self[k] = R(value[n])4406n = n + 14407else:4408i = int(i)4409if i < 0 or i >= self.degree():4410raise IndexError("index (i=%s) must be between 0 and %s"%(i,4411self.degree()-1))4412self.set(i, self._parent.base_ring()(value))44134414def denominator(self):4415"""4416Return the least common multiple of the denominators of the4417entries of self.44184419EXAMPLES::44204421sage: v = vector([1/2,2/5,3/14], sparse=True)4422sage: v.denominator()4423704424"""4425R = self.base_ring()4426x = self._entries4427if len(x) == 0:4428return 14429Z = x.iteritems()4430d = Z.next()[1].denominator()4431for _, y in Z:4432d = d.lcm(y.denominator())4433return d44344435def dict(self, copy=True):4436"""4437Return dictionary of nonzero entries of self.44384439INPUT:44404441- ``copy`` -- bool (default: True)44424443OUTPUT:44444445- Python dictionary44464447EXAMPLES::44484449sage: v = vector([0,0,0,0,1/2,0,3/14], sparse=True)4450sage: v.dict()4451{4: 1/2, 6: 3/14}4452"""4453if copy:4454return dict(self._entries)4455else:4456return self._entries44574458def list(self, copy=True):4459"""4460Return list of elements of self.44614462INPUT:44634464- copy -- bool, return list of underlying entries44654466EXAMPLES::44674468sage: v = vector([1,2/3,pi], sparse=True)4469sage: type(v)4470<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>4471sage: a = v.list(); a4472[1, 2/3, pi]4473"""4474cdef Py_ssize_t n4475n = self._parent.degree()4476z = self._parent.base_ring()(0)4477v = [z]*n4478for i, a in self._entries.iteritems():4479v[i] = a4480return v44814482def nonzero_positions(self):4483"""4484Returns the list of numbers ``i`` such that ``self[i] != 0``.44854486EXAMPLES::44874488sage: v = vector({1: 1, 3: -2})4489sage: w = vector({1: 4, 3: 2})4490sage: v+w4491(0, 5, 0, 0)4492sage: (v+w).nonzero_positions()4493[1]4494"""4495K = self._entries.keys()4496K.sort()4497return K44984499cpdef int hamming_weight(self):4500"""4501Returns the number of positions ``i`` such that ``self[i] != 0``.45024503EXAMPLES::45044505sage: v = vector({1: 1, 3: -2})4506sage: w = vector({1: 4, 3: 2})4507sage: v+w4508(0, 5, 0, 0)4509sage: (v+w).hamming_weight()451014511"""4512return len(self._entries)45134514def _numerical_approx(self, prec=None, digits=None):4515"""4516Returns a numerical approximation of self by calling the n() method4517on all of its entries.45184519EXAMPLES::45204521sage: v = vector(RealField(200), [1,2,3], sparse=True)4522sage: v.n()4523(1.00000000000000, 2.00000000000000, 3.00000000000000)4524sage: _.parent()4525Sparse vector space of dimension 3 over Real Field with 53 bits of precision4526sage: v.n(prec=75)4527(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)4528sage: _.parent()4529Sparse vector space of dimension 3 over Real Field with 75 bits of precision4530"""4531return vector(dict([(e[0],e[1].n(prec, digits)) for e in self._entries.iteritems()]), sparse=True)4532453345344535