Path: blob/master/sage/modules/free_module_element.pyx
4045 views
r"""1Elements of free modules23AUTHORS:45- William Stein67- Josh Kantor89TODO: Change to use a get_unsafe / set_unsafe, etc., structure10exactly like with matrices, since we'll have to define a bunch of11special purpose implementations of vectors easily and12systematically.1314EXAMPLES: We create a vector space over `\QQ` and a15subspace of this space.1617::1819sage: V = QQ^520sage: W = V.span([V.1, V.2])2122Arithmetic operations always return something in the ambient space,23since there is a canonical map from `W` to `V` but24not from `V` to `W`.2526::2728sage: parent(W.0 + V.1)29Vector space of dimension 5 over Rational Field30sage: parent(V.1 + W.0)31Vector space of dimension 5 over Rational Field32sage: W.0 + V.133(0, 2, 0, 0, 0)34sage: W.0 - V.035(-1, 1, 0, 0, 0)3637Next we define modules over `\ZZ` and a finite38field.3940::4142sage: K = ZZ^543sage: M = GF(7)^54445Arithmetic between the `\QQ` and46`\ZZ` modules is defined, and the result is always47over `\QQ`, since there is a canonical coercion map48to `\QQ`.4950::5152sage: K.0 + V.153(1, 1, 0, 0, 0)54sage: parent(K.0 + V.1)55Vector space of dimension 5 over Rational Field5657Since there is no canonical coercion map to the finite field from58`\QQ` the following arithmetic is not defined::5960sage: V.0 + M.061Traceback (most recent call last):62...63TypeError: 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'6465However, there is a map from `\ZZ` to the finite66field, so the following is defined, and the result is in the finite67field.6869::7071sage: w = K.0 + M.0; w72(2, 0, 0, 0, 0)73sage: parent(w)74Vector space of dimension 5 over Finite Field of size 775sage: parent(M.0 + K.0)76Vector space of dimension 5 over Finite Field of size 77778Matrix vector multiply::7980sage: MS = MatrixSpace(QQ,3)81sage: A = MS([0,1,0,1,0,0,0,0,1])82sage: V = QQ^383sage: v = V([1,2,3])84sage: v * A85(2, 1, 3)8687TESTS::8889sage: D = 4634190sage: u = 791sage: R = Integers(D)92sage: p = matrix(R,[[84, 97, 55, 58, 51]])93sage: 2*p.row(0)94(168, 194, 110, 116, 102)95"""9697import math98import operator99100include '../ext/cdefs.pxi'101include '../ext/stdsage.pxi'102import sage.misc.misc as misc103import sage.misc.latex104105from sage.structure.sequence import Sequence106107from sage.structure.element cimport Element, ModuleElement, RingElement, Vector as element_Vector108from sage.structure.element import canonical_coercion109110import sage.rings.arith111112from sage.rings.infinity import Infinity113import sage.rings.integer114from sage.rings.integer_ring import ZZ115from sage.rings.real_double import RDF116from sage.rings.complex_double import CDF117from sage.misc.derivative import multi_derivative118119120# We use some cimports for very quick checking of Integer and Ring121# type to optimize vector(ring,n) for creating the zero vector.122from sage.rings.ring cimport Ring123from sage.rings.integer cimport Integer124125# We define our own faster is_Ring since is_Ring in the126# sage.rings.ring module is slow due to it doing an import every time,127# and creating a category. We should rarely hit the second case128# (is_Ring_slow below). Note that this function will slightly slow129# down in the very rare case when R is not of type Ring, but it is in130# the category of rings. But it gives a big speedup for the most131# common case when R is a Ring.132from sage.rings.ring import is_Ring as is_Ring_slow133cdef is_Ring(R):134return isinstance(R, Ring) or is_Ring_slow(R)135136def is_FreeModuleElement(x):137"""138EXAMPLES::139140sage: sage.modules.free_module_element.is_FreeModuleElement(0)141False142sage: sage.modules.free_module_element.is_FreeModuleElement(vector([1,2,3]))143True144"""145return isinstance(x, FreeModuleElement)146147def vector(arg0, arg1=None, arg2=None, sparse=None):148r"""149Return a vector or free module element with specified entries.150151CALL FORMATS:152153This constructor can be called in several different ways.154In each case, ``sparse=True`` or ``sparse=False`` can be155supplied as an option. ``free_module_element()`` is an156alias for ``vector()``.1571581. vector(object)1591602. vector(ring, object)1611623. vector(object, ring)1631644. vector(ring, degree, object)1651665. vector(ring, degree)1671686. vector(numpy_array)169170INPUT:171172- ``object`` - a list, dictionary, or other173iterable containing the entries of the vector, including174any object that is palatable to the ``Sequence`` constructor175176- ``ring`` - a base ring (or field) for the vector177space or free module, which contains all of the elements178179- ``degree`` - an integer specifying the number of180entries in the vector or free module element181182- ``numpy_array`` - a NumPy array with the desired entries183184- ``sparse`` - optional185186In call format 4, an error is raised if the ``degree`` does not match187the length of ``object`` so this call can provide some safeguards.188Note however that using this format when ``object`` is a dictionary189is unlikely to work properly.190191OUTPUT:192193An element of the vector space or free module with the given194base ring and implied or specified dimension or rank,195containing the specified entries and with correct degree.196197In call format 5, no entries are specified, so the element is198populated with all zeros.199200If the ``sparse`` option is not supplied, the output will201generally have a dense representation. The exception is if202``object`` is a dictionary, then the representation will be sparse.203204EXAMPLES::205206sage: v = vector([1,2,3]); v207(1, 2, 3)208sage: v.parent()209Ambient free module of rank 3 over the principal ideal domain Integer Ring210sage: v = vector([1,2,3/5]); v211(1, 2, 3/5)212sage: v.parent()213Vector space of dimension 3 over Rational Field214215All entries must *canonically* coerce to some common ring::216217sage: v = vector([17, GF(11)(5), 19/3]); v218Traceback (most recent call last):219...220TypeError: unable to find a common ring for all elements221222::223224sage: v = vector([17, GF(11)(5), 19]); v225(6, 5, 8)226sage: v.parent()227Vector space of dimension 3 over Finite Field of size 11228sage: v = vector([17, GF(11)(5), 19], QQ); v229(17, 5, 19)230sage: v.parent()231Vector space of dimension 3 over Rational Field232sage: v = vector((1,2,3), QQ); v233(1, 2, 3)234sage: v.parent()235Vector space of dimension 3 over Rational Field236sage: v = vector(QQ, (1,2,3)); v237(1, 2, 3)238sage: v.parent()239Vector space of dimension 3 over Rational Field240sage: v = vector(vector([1,2,3])); v241(1, 2, 3)242sage: v.parent()243Ambient free module of rank 3 over the principal ideal domain Integer Ring244245You can also use ``free_module_element``, which is246the same as ``vector``. ::247248sage: free_module_element([1/3, -4/5])249(1/3, -4/5)250251We make a vector mod 3 out of a vector over `\ZZ`. ::252253sage: vector(vector([1,2,3]), GF(3))254(1, 2, 0)255256The degree of a vector may be specified::257258sage: vector(QQ, 4, [1,1/2,1/3,1/4])259(1, 1/2, 1/3, 1/4)260261But it is an error if the degree and size of the list of entries262are mismatched::263264sage: vector(QQ, 5, [1,1/2,1/3,1/4])265Traceback (most recent call last):266...267ValueError: incompatible degrees in vector constructor268269Providing no entries populates the vector with zeros, but of course,270you must specify the degree since it is not implied. Here we use a271finite field as the base ring. ::272273sage: w = vector(FiniteField(7), 4); w274(0, 0, 0, 0)275sage: w.parent()276Vector space of dimension 4 over Finite Field of size 7277278The fastest method to construct a zero vector is to call the279:meth:`~sage.modules.free_module.FreeModule_generic.zero_vector`280method directly on a free module or vector space, since281vector(...) must do a small amount of type checking. Almost as282fast as the ``zero_vector()`` method is the283:func:`~sage.modules.free_module_element.zero_vector` constructor,284which defaults to the integers. ::285286sage: vector(ZZ, 5) # works fine287(0, 0, 0, 0, 0)288sage: (ZZ^5).zero_vector() # very tiny bit faster289(0, 0, 0, 0, 0)290sage: zero_vector(ZZ, 5) # similar speed to vector(...)291(0, 0, 0, 0, 0)292sage: z = zero_vector(5); z293(0, 0, 0, 0, 0)294sage: z.parent()295Ambient free module of rank 5 over296the principal ideal domain Integer Ring297298Here we illustrate the creation of sparse vectors by using a299dictionary. ::300301sage: vector({1:1.1, 3:3.14})302(0.000000000000000, 1.10000000000000, 0.000000000000000, 3.14000000000000)303304With no degree given, a dictionary of entries implicitly declares a305degree by the largest index (key) present. So you can provide a306terminal element (perhaps a zero?) to set the degree. But it is probably safer307to just include a degree in your construction. ::308309sage: v = vector(QQ, {0:1/2, 4:-6, 7:0}); v310(1/2, 0, 0, 0, -6, 0, 0, 0)311sage: v.degree()3128313sage: v.is_sparse()314True315sage: w = vector(QQ, 8, {0:1/2, 4:-6})316sage: w == v317True318319It is an error to specify a negative degree. ::320321sage: vector(RR, -4, [1.0, 2.0, 3.0, 4.0])322Traceback (most recent call last):323...324ValueError: cannot specify the degree of a vector as a negative integer (-4)325326It is an error to create a zero vector but not provide327a ring as the first argument. ::328329sage: vector('junk', 20)330Traceback (most recent call last):331...332TypeError: first argument must be base ring of zero vector, not junk333334And it is an error to specify an index in a dictionary335that is greater than or equal to a requested degree. ::336337sage: vector(ZZ, 10, {3:4, 7:-2, 10:637})338Traceback (most recent call last):339...340ValueError: dictionary of entries has a key (index) exceeding the requested degree341342Any 1 dimensional numpy array of type float or complex may be343passed to vector. The result will be a vector in the appropriate344dimensional vector space over the real double field or the complex345double field. The data in the array must be contiguous so346column-wise slices of numpy matrices will raise an exception. ::347348sage: import numpy349sage: x=numpy.random.randn(10)350sage: y=vector(x)351sage: v=numpy.random.randn(10)*numpy.complex(0,1)352sage: w=vector(v)353354If any of the arguments to vector have Python type int, long, real,355or complex, they will first be coerced to the appropriate Sage356objects. This fixes trac #3847. ::357358sage: v = vector([int(0)]); v359(0)360sage: v[0].parent()361Integer Ring362sage: v = vector(range(10)); v363(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)364sage: v[3].parent()365Integer Ring366sage: v = vector([float(23.4), int(2), complex(2+7*I), long(1)]); v367(23.4, 2.0, 2.0 + 7.0*I, 1.0)368sage: v[1].parent()369Complex Double Field370371If the argument is a vector, it doesn't change the base ring. This372fixes trac #6643. ::373374sage: K.<sqrt3> = QuadraticField(3)375sage: u = vector(K, (1/2, sqrt3/2) )376sage: vector(u).base_ring()377Number Field in sqrt3 with defining polynomial x^2 - 3378sage: v = vector(K, (0, 1) )379sage: vector(v).base_ring()380Number Field in sqrt3 with defining polynomial x^2 - 3381382Constructing a vector from a numpy array behaves as expected::383384sage: import numpy385sage: a=numpy.array([1,2,3])386sage: v=vector(a); v387(1, 2, 3)388sage: parent(v)389Ambient free module of rank 3 over the principal ideal domain Integer Ring390391Complex numbers can be converted naturally to a sequence of length 2. And392then to a vector. ::393394sage: c = CDF(2 + 3*I)395sage: v = vector(c); v396(2.0, 3.0)397398A generator, or other iterable, may also be supplied as input. Anything399that can be converted to a :class:`~sage.structure.sequence.Sequence` is400a possible input. ::401402sage: type(i^2 for i in range(3))403<type 'generator'>404sage: v = vector(i^2 for i in range(3)); v405(0, 1, 4)406407An empty list, without a ring given, will default to the integers. ::408409sage: x = vector([]); x410()411sage: x.parent()412Ambient free module of rank 0 over the principal ideal domain Integer Ring413"""414# We first efficiently handle the important special case of the zero vector415# over a ring. See trac 11657.416# !! PLEASE DO NOT MOVE THIS CODE LOWER IN THIS FUNCTION !!417if arg2 is None and is_Ring(arg0) and (isinstance(arg1, (int, long, Integer))):418return (arg0**arg1).zero_vector()419420# WARNING TO FUTURE OPTIMIZERS: The following two hasattr's take421# quite a significant amount of time.422if hasattr(arg0, '_vector_'):423return arg0._vector_(arg1)424425if hasattr(arg1, '_vector_'):426return arg1._vector_(arg0)427428# consider a possible degree specified in second argument429degree = None430maxindex = None431if sage.rings.integer.is_Integer(arg1) or isinstance(arg1,(int,long)):432if arg1 < 0:433raise ValueError("cannot specify the degree of a vector as a negative integer (%s)" % arg1)434if isinstance(arg2, dict):435maxindex = max([-1]+[index for index in arg2])436if not maxindex < arg1:437raise ValueError("dictionary of entries has a key (index) exceeding the requested degree")438# arg1 is now a legitimate degree439# With no arg2, we can try to return a zero vector440# else we size-check arg2 and slide it into arg1441degree = arg1442if arg2 is None:443if not is_Ring(arg0):444msg = "first argument must be base ring of zero vector, not {0}"445raise TypeError(msg.format(arg0))446else:447if not isinstance(arg2, dict) and len(arg2) != degree:448raise ValueError("incompatible degrees in vector constructor")449arg1 = arg2450451# Analyze arg0 and arg1 to create a ring (R) and entries (v)452if is_Ring(arg0):453R = arg0454v = arg1455elif is_Ring(arg1):456R = arg1457v = arg0458else:459v = arg0460R = None461462from numpy import ndarray463from free_module import VectorSpace464if isinstance(v,ndarray):465if len(v.shape)==1:466if str(v.dtype).count('float')==1:467V=VectorSpace(RDF,v.shape[0])468import vector_real_double_dense469_v=vector_real_double_dense.Vector_real_double_dense(V, v)470return _v471if str(v.dtype).count('complex')==1:472V=VectorSpace(CDF,v.shape[0])473import vector_complex_double_dense474_v=vector_complex_double_dense.Vector_complex_double_dense(V, v)475return _v476477if isinstance(v, dict):478if degree is None:479degree = max([-1]+[index for index in v])+1480if sparse is None:481sparse = True482else:483degree = None484if sparse is None:485sparse = False486487v, R = prepare(v, R, degree)488489if sparse:490import free_module # slow -- can we improve491return free_module.FreeModule(R, len(v), sparse=True)(v)492else:493return (R**len(v))(v)494495free_module_element = vector496497def prepare(v, R, degree=None):498r"""499Converts an object describing elements of a vector into a list of entries in a common ring.500501INPUT:502503- ``v`` - a dictionary with non-negative integers as keys,504or a list or other object that can be converted by the ``Sequence``505constructor506- ``R`` - a ring containing all the entries, possibly given as ``None``507- ``degree`` - a requested size for the list when the input is a dictionary,508otherwise ignored509510OUTPUT:511512A pair.513514The first item is a list of the values specified in the object ``v``.515If the object is a dictionary , entries are placed in the list516according to the indices that were their keys in the dictionary,517and the remainder of the entries are zero. The value of518``degree`` is assumed to be larger than any index provided519in the dictionary and will be used as the number of entries520in the returned list.521522The second item returned is a ring that contains all of523the entries in the list. If ``R`` is given, the entries524are coerced in. Otherwise a common ring is found. For525more details, see the526:class:`~sage.structure.sequence.Sequence` object. When ``v``527has no elements and ``R`` is ``None``, the ring returned is528the integers.529530531EXAMPLES::532533sage: from sage.modules.free_module_element import prepare534sage: prepare([1,2/3,5],None)535([1, 2/3, 5], Rational Field)536537sage: prepare([1,2/3,5],RR)538([1.00000000000000, 0.666666666666667, 5.00000000000000], Real Field with 53 bits of precision)539540sage: prepare({1:4, 3:-2}, ZZ, 6)541([0, 4, 0, -2, 0, 0], Integer Ring)542543sage: prepare({3:1, 5:3}, QQ, 6)544([0, 0, 0, 1, 0, 3], Rational Field)545546sage: prepare([1,2/3,'10',5],RR)547([1.00000000000000, 0.666666666666667, 10.0000000000000, 5.00000000000000], Real Field with 53 bits of precision)548549sage: prepare({},QQ, 0)550([], Rational Field)551552sage: prepare([1,2/3,'10',5],None)553Traceback (most recent call last):554...555TypeError: unable to find a common ring for all elements556557Some objects can be converted to sequences even if they are not always558thought of as sequences. ::559560sage: c = CDF(2+3*I)561sage: prepare(c, None)562([2.0, 3.0], Real Double Field)563564This checks a bug listed at Trac #10595. Without good evidence for a ring, the default565is the integers. ::566567sage: prepare([], None)568([], Integer Ring)569"""570if isinstance(v, dict):571# convert to a list572X = [0]*degree573for key, value in v.iteritems():574X[key] = value575v = X576# convert to a Sequence over common ring577# default to ZZ on an empty list578if R is None:579try:580if len(v) == 0:581R = ZZ582except TypeError:583pass584v = Sequence(v, universe=R, use_sage_types=True)585ring = v.universe()586if not is_Ring(ring):587raise TypeError("unable to find a common ring for all elements")588return v, ring589590def zero_vector(arg0, arg1=None):591r"""592Returns a vector or free module element with a specified number of zeros.593594CALL FORMATS:5955961. zero_vector(degree)5975982. zero_vector(ring, degree)599600INPUT:601602- ``degree`` - the number of zero entries in the vector or603free module element604605- ``ring`` - default ``ZZ`` - the base ring of the vector606space or module containing the constructed zero vector607608OUTPUT:609610A vector or free module element with ``degree`` entries,611all equal to zero and belonging to the ring if specified.612If no ring is given, a free module element over ``ZZ``613is returned.614615EXAMPLES:616617A zero vector over the field of rationals. ::618619sage: v = zero_vector(QQ, 5); v620(0, 0, 0, 0, 0)621sage: v.parent()622Vector space of dimension 5 over Rational Field623624A free module zero element. ::625626sage: w = zero_vector(Integers(6), 3); w627(0, 0, 0)628sage: w.parent()629Ambient free module of rank 3 over Ring of integers modulo 6630631If no ring is given, the integers are used. ::632633sage: u = zero_vector(9); u634(0, 0, 0, 0, 0, 0, 0, 0, 0)635sage: u.parent()636Ambient free module of rank 9 over the principal ideal domain Integer Ring637638Non-integer degrees produce an error. ::639640sage: zero_vector(5.6)641Traceback (most recent call last):642...643TypeError: Attempt to coerce non-integral RealNumber to Integer644645Negative degrees also give an error. ::646647sage: zero_vector(-3)648Traceback (most recent call last):649...650ValueError: rank (=-3) must be nonnegative651652Garbage instead of a ring will be recognized as such. ::653654sage: zero_vector(x^2, 5)655Traceback (most recent call last):656...657TypeError: first argument must be a ring658"""659if arg1 is None:660# default to a zero vector over the integers (ZZ) if no ring given661return (ZZ**arg0).zero_vector()662if is_Ring(arg0):663return (arg0**arg1).zero_vector()664raise TypeError("first argument must be a ring")665666def random_vector(ring, degree=None, *args, **kwds):667r"""668Returns a vector (or module element) with random entries.669670INPUT:671672- ring - default: ``ZZ`` - the base ring for the entries673- degree - a non-negative integer for the number of entries in the vector674- sparse - default: ``False`` - whether to use a sparse implementation675- args, kwds - additional arguments and keywords are passed676to the ``random_element()`` method of the ring677678OUTPUT:679680A vector, or free module element, with ``degree`` elements681from ``ring``, chosen randomly from the ring according to682the ring's ``random_element()`` method.683684.. note::685See below for examples of how random elements are686generated by some common base rings.687688EXAMPLES:689690First, module elements over the integers.691The default distribution is tightly clustered around -1, 0, 1.692Uniform distributions can be specified by giving bounds, though693the upper bound is never met. See694:meth:`sage.rings.integer_ring.IntegerRing_class.random_element`695for several other variants. ::696697sage: random_vector(10)698(-8, 2, 0, 0, 1, -1, 2, 1, -95, -1)699700sage: sorted(random_vector(20))701[-12, -6, -4, -4, -2, -2, -2, -1, -1, -1, 0, 0, 0, 0, 0, 1, 1, 1, 4, 5]702703sage: random_vector(ZZ, 20, x=4)704(2, 0, 3, 0, 1, 0, 2, 0, 2, 3, 0, 3, 1, 2, 2, 2, 1, 3, 2, 3)705706sage: random_vector(ZZ, 20, x=-20, y=100)707(43, 47, 89, 31, 56, -20, 23, 52, 13, 53, 49, -12, -2, 94, -1, 95, 60, 83, 28, 63)708709sage: random_vector(ZZ, 20, distribution="1/n")710(0, -1, -2, 0, -1, -2, 0, 0, 27, -1, 1, 1, 0, 2, -1, 1, -1, -2, -1, 3)711712If the ring is not specified, the default is the integers, and713parameters for the random distribution may be passed without using714keywords. This is a random vector with 20 entries uniformly distributed715between -20 and 100. ::716717sage: random_vector(20, -20, 100)718(70, 19, 98, 2, -18, 88, 36, 66, 76, 52, 82, 99, 55, -17, 82, -15, 36, 28, 79, 18)719720Now over the rationals. Note that bounds on the numerator and721denominator may be specified. See722:meth:`sage.rings.rational_field.RationalField.random_element`723for documentation. ::724725sage: random_vector(QQ, 10)726(0, -1, -4/3, 2, 0, -13, 2/3, 0, -4/5, -1)727728sage: random_vector(QQ, 10, num_bound = 15, den_bound = 5)729(-12/5, 9/4, -13/3, -1/3, 1, 5/4, 4, 1, -15, 10/3)730731Inexact rings may be used as well. The reals have732uniform distributions, with the range `(-1,1)` as733the default. More at:734:meth:`sage.rings.real_mpfr.RealField_class.random_element` ::735736sage: random_vector(RR, 5)737(0.248997268533725, -0.112200126330480, 0.776829203293064, -0.899146461031406, 0.534465018743125)738739sage: random_vector(RR, 5, min = 8, max = 14)740(8.43260944052606, 8.34129413391087, 8.92391495103829, 11.5784799413416, 11.0973561568002)741742Any ring with a ``random_element()`` method may be used. ::743744sage: F = FiniteField(23)745sage: hasattr(F, 'random_element')746True747sage: random_vector(F, 10)748(21, 6, 5, 2, 6, 2, 18, 9, 9, 7)749750The default implementation is a dense representation, equivalent to751setting ``sparse=False``. ::752753sage: v = random_vector(10)754sage: v.is_sparse()755False756757sage: w = random_vector(ZZ, 20, sparse=True)758sage: w.is_sparse()759True760761Inputs get checked before constructing the vector. ::762763sage: random_vector('junk')764Traceback (most recent call last):765...766TypeError: degree of a random vector must be an integer, not None767768sage: random_vector('stuff', 5)769Traceback (most recent call last):770...771TypeError: elements of a vector, or module element, must come from a ring, not stuff772773sage: random_vector(ZZ, -9)774Traceback (most recent call last):775...776ValueError: degree of a random vector must be non-negative, not -9777"""778if sage.rings.integer.is_Integer(ring) or isinstance(ring,(int,long)):779if not degree is None:780arglist = list(args)781arglist.insert(0, degree)782args = tuple(arglist)783degree = ring784ring = ZZ785if not (sage.rings.integer.is_Integer(degree) or isinstance(degree,(int,long))):786raise TypeError("degree of a random vector must be an integer, not %s" % degree)787if degree < 0:788raise ValueError("degree of a random vector must be non-negative, not %s" % degree)789if not is_Ring(ring):790raise TypeError("elements of a vector, or module element, must come from a ring, not %s" % ring)791if not hasattr(ring, "random_element"):792raise AttributeError("cannot create a random vector since there is no random_element() method for %s" % ring )793sparse = kwds.pop('sparse', False)794entries = [ring.random_element(*args, **kwds) for _ in range(degree)]795return vector(ring, degree, entries, sparse)796797cdef class FreeModuleElement(element_Vector): # abstract base class798"""799An element of a generic free module.800"""801def __init__(self, parent):802"""803EXAMPLES::804805sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)806sage: type(v)807<type 'sage.modules.free_module_element.FreeModuleElement'>808"""809self._parent = parent810self._degree = parent.degree()811self._is_mutable = 1812813def _giac_init_(self):814"""815EXAMPLES::816817sage: v = vector(ZZ, 4, range(4)) #optional - giac818sage: giac(v)+v #optional - giac819[0,2,4,6]820821::822823sage: v = vector(QQ, 3, [2/3, 0, 5/4]) #optional824sage: giac(v) #optional825[2/3,0,5/4]826827::828829sage: P.<x> = ZZ[] #optional830sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) #optional831sage: giac(v) #optional832[x^2+2,2*x+1,-2*x^2+4*x]833"""834return self.list()835836def _magma_init_(self, magma):837r"""838Convert self to Magma.839840EXAMPLES::841842sage: F = FreeModule(ZZ, 2, inner_product_matrix=matrix(ZZ, 2, 2, [1, 0, 0, -1]))843sage: v = F([1, 2])844sage: M = magma(v); M # optional - magma845(1 2)846sage: M.Type() # optional - magma847ModTupRngElt848sage: M.Parent() # optional - magma849Full RSpace of degree 2 over Integer Ring850Inner Product Matrix:851[ 1 0]852[ 0 -1]853sage: M.sage() # optional - magma854(1, 2)855sage: M.sage() == v # optional - magma856True857sage: M.sage().parent() is v.parent() # optional - magma858True859860::861862sage: v = vector(QQ, [1, 2, 5/6])863sage: M = magma(v); M # optional - magma864( 1 2 5/6)865sage: M.Type() # optional - magma866ModTupFldElt867sage: M.Parent() # optional - magma868Full Vector space of degree 3 over Rational Field869sage: M.sage() # optional - magma870(1, 2, 5/6)871sage: M.sage() == v # optional - magma872True873sage: M.sage().parent() is v.parent() # optional - magma874True875"""876# Get a reference to Magma version of parent.877R = magma(self.parent())878# Get list of coefficients.879v = ','.join([a._magma_init_(magma) for a in self.list()])880return '%s![%s]' % (R.name(), v)881882def __hash__(self):883"""884Return hash of this vector. Only mutable vectors are hashable.885886EXAMPLES::887sage: v = vector([1,2/3,pi])888sage: v.__hash__()889Traceback (most recent call last):890...891TypeError: mutable vectors are unhashable892sage: v.set_immutable()893sage: v.__hash__() # random output894"""895if self._is_mutable:896raise TypeError("mutable vectors are unhashable")897return hash(tuple(self))898899def _vector_(self, R=None):900r"""901Return self as a vector.902903EXAMPLES::904905sage: v = vector(ZZ, [2, 12, 22])906sage: vector(v)907(2, 12, 22)908sage: vector(GF(7), v)909(2, 5, 1)910sage: vector(v, ZZ['x', 'y'])911(2, 12, 22)912913sage: vector(vector((1, 6.8)))914(1.00000000000000, 6.80000000000000)915sage: vector(vector(SR, (1, sqrt(2)) ) )916(1, sqrt(2))917"""918if R is None:919R = self.base_ring()920return self.change_ring(R)921922def _matrix_(self, R=None):923r"""924Return self as a row matrix.925926EXAMPLES::927928sage: v = vector(ZZ, [2, 12, 22])929sage: vector(v)930(2, 12, 22)931sage: vector(GF(7), v)932(2, 5, 1)933sage: vector(v, ZZ['x', 'y'])934(2, 12, 22)935"""936if R is None:937R = self.base_ring()938sparse = self.is_sparse()939from sage.matrix.constructor import matrix940return matrix(R, [list(self)], sparse=sparse)941942def _sage_input_(self, sib, coerce):943r"""944Produce an expression which will reproduce this value when evaluated.945946EXAMPLES::947948sage: sage_input(vector(RR, [pi, e, 0.5]), verify=True)949# Verified950vector(RR, [3.1415926535897931, 2.7182818284590451, 0.5])951sage: sage_input(vector(GF(5), [1, 2, 3, 4, 5]), verify=True)952# Verified953vector(GF(5), [1, 2, 3, 4, 0])954sage: sage_input(vector([0, 0, 0, 1, 0, 0, 0], sparse=True), verify=True)955# Verified956vector(ZZ, {3:1, 6:0})957sage: sage_input(vector(ZZ, []), verify=True)958# Verified959vector(ZZ, [])960sage: sage_input(vector(RealField(27), [], sparse=True), verify=True)961# Verified962vector(RealField(27), {})963sage: from sage.misc.sage_input import SageInputBuilder964sage: vector(ZZ, [42, 389])._sage_input_(SageInputBuilder(), False)965{call: {atomic:vector}({atomic:ZZ}, {list: ({atomic:42}, {atomic:389})})}966sage: vector(RDF, {1:pi, 1000:e})._sage_input_(SageInputBuilder(), False)967{call: {atomic:vector}({atomic:RDF}, {dict: {{atomic:1}:{atomic:3.1415926535897931}, {atomic:1000}:{atomic:2.718281828459045...}}})}968"""969# Not a lot of room for prettiness here.970# We always specify the ring, because that lets us use coerced=2971# on the elements, which is sometimes much prettier than972# the coerced=False we would get otherwise.973if self.is_sparse_c():974items = [(n, sib(e, 2))975for n,e in self.dict().items()]976items.sort()977if len(self):978# we may need to add an extra element on the end to979# set the size. (There doesn't seem to be a better way980# to do it.)981if len(items) == 0 or len(self)-1 > items[-1][0]:982items.append((len(self)-1, sib.int(0)))983items_dict = sib.dict([(sib.int(n), e) for n,e in items])984985return sib.name('vector')(self.base_ring(), items_dict)986else:987return sib.name('vector')(self.base_ring(),988[sib(e, 2) for e in self])989990def _numerical_approx(self, prec=None, digits=None):991r"""992Implements numerical approximation of a free module element993by calling the ``n()`` method on all of its entries.994995EXAMPLES::996997sage: v = vector(RealField(212), [1,2,3])998sage: v.N()999(1.00000000000000, 2.00000000000000, 3.00000000000000)1000sage: _.parent()1001Vector space of dimension 3 over Real Field with 53 bits of precision1002sage: numerical_approx(v)1003(1.00000000000000, 2.00000000000000, 3.00000000000000)1004sage: _.parent()1005Vector space of dimension 3 over Real Field with 53 bits of precision1006sage: v.n(prec=75)1007(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1008sage: _.parent()1009Vector space of dimension 3 over Real Field with 75 bits of precision1010sage: numerical_approx(v, digits=3)1011(1.00, 2.00, 3.00)1012sage: _.parent()1013Vector space of dimension 3 over Real Field with 14 bits of precision10141015Both functional and object-oriented usage is possible. ::10161017sage: u = vector(QQ, [1/2, 1/3, 1/4])1018sage: u.n()1019(0.500000000000000, 0.333333333333333, 0.250000000000000)1020sage: u.N()1021(0.500000000000000, 0.333333333333333, 0.250000000000000)1022sage: u.numerical_approx()1023(0.500000000000000, 0.333333333333333, 0.250000000000000)1024sage: n(u)1025(0.500000000000000, 0.333333333333333, 0.250000000000000)1026sage: N(u)1027(0.500000000000000, 0.333333333333333, 0.250000000000000)1028sage: numerical_approx(u)1029(0.500000000000000, 0.333333333333333, 0.250000000000000)10301031Precision (bits) and digits (decimal) may be specified.1032When both are given, ``prec`` wins. ::10331034sage: u = vector(QQ, [1/2, 1/3, 1/4])1035sage: n(u, prec=15)1036(0.5000, 0.3333, 0.2500)1037sage: n(u, digits=5)1038(0.50000, 0.33333, 0.25000)1039sage: n(u, prec=30, digits=100)1040(0.50000000, 0.33333333, 0.25000000)10411042These are some legacy doctests that were part of various specialized1043versions of the numerical approximation routine that were removed as1044part of :trac:`12195`. ::10451046sage: v = vector(ZZ, [1,2,3])1047sage: v.n()1048(1.00000000000000, 2.00000000000000, 3.00000000000000)1049sage: _.parent()1050Vector space of dimension 3 over Real Field with 53 bits of precision1051sage: v.n(prec=75)1052(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1053sage: _.parent()1054Vector space of dimension 3 over Real Field with 75 bits of precision10551056sage: v = vector(RDF, [1,2,3])1057sage: v.n()1058(1.00000000000000, 2.00000000000000, 3.00000000000000)1059sage: _.parent()1060Vector space of dimension 3 over Real Field with 53 bits of precision1061sage: v.n(prec=75)1062(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1063sage: _.parent()1064Vector space of dimension 3 over Real Field with 75 bits of precision10651066sage: v = vector(CDF, [1,2,3])1067sage: v.n()1068(1.00000000000000, 2.00000000000000, 3.00000000000000)1069sage: _.parent()1070Vector space of dimension 3 over Complex Field with 53 bits of precision1071sage: v.n(prec=75)1072(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1073sage: _.parent()1074Vector space of dimension 3 over Complex Field with 75 bits of precision10751076sage: v = vector(Integers(8), [1,2,3])1077sage: v.n()1078(1.00000000000000, 2.00000000000000, 3.00000000000000)1079sage: _.parent()1080Vector space of dimension 3 over Real Field with 53 bits of precision1081sage: v.n(prec=75)1082(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1083sage: _.parent()1084Vector space of dimension 3 over Real Field with 75 bits of precision10851086sage: v = vector(QQ, [1,2,3])1087sage: v.n()1088(1.00000000000000, 2.00000000000000, 3.00000000000000)1089sage: _.parent()1090Vector space of dimension 3 over Real Field with 53 bits of precision1091sage: v.n(prec=75)1092(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)1093sage: _.parent()1094Vector space of dimension 3 over Real Field with 75 bits of precision10951096TESTS:10971098Sparse vectors have a similar method that works efficiently for1099the sparse case. We test that it is working as it should. ::11001101sage: v = vector(QQ, [1/2, 0, 0, 1/3, 0, 0, 0, 1/4], sparse=True)1102sage: u = v.numerical_approx(digits=4)1103sage: u.is_sparse()1104True1105sage: u1106(0.5000, 0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000, 0.2500)1107"""1108return vector([e.n(prec, digits) for e in self])11091110def transpose(self):1111r"""1112Return self as a column matrix.11131114.. note::11151116The ``transpose()`` method has been deprecated as of Sage 4.6.2,1117in favor of the :meth:`column` method which is functionally identical.11181119EXAMPLES::11201121sage: v = vector(ZZ, [2, 12, 22])1122sage: transpose(vector(v))1123doctest:...: DeprecationWarning: (Since Sage Version 4.6.2) The transpose() method for vectors has been deprecated, use column() instead1124(or check to see if you have a vector when you really want a matrix)1125[ 2]1126[12]1127[22]11281129::11301131sage: transpose(vector(GF(7), v))1132[2]1133[5]1134[1]11351136::11371138sage: transpose(vector(v, ZZ['x', 'y']))1139[ 2]1140[12]1141[22]1142"""1143from sage.misc.misc import deprecation1144deprecation('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)', 'Sage Version 4.6.2')1145return self._matrix_().transpose()11461147def row(self):1148r"""1149Return a matrix with a single row and the same entries as the vector ``self``.11501151OUTPUT:11521153A matrix over the same ring as the vector (or free module element), with1154a single row. The entries of the row are identical to those of the vector,1155and in the same order.11561157EXAMPLES::11581159sage: v = vector(ZZ, [1,2,3])1160sage: w = v.row(); w1161[1 2 3]1162sage: w.parent()1163Full MatrixSpace of 1 by 3 dense matrices over Integer Ring11641165sage: x = vector(FiniteField(13), [2,4,8,16])1166sage: x.row()1167[2 4 8 3]11681169There is more than one way to get one-row matrix from a vector,1170but the ``row`` method is more efficient than making a column and1171then taking a transpose. Notice that supplying a vector to the1172matrix constructor demonstrates Sage's preference for rows. ::11731174sage: x = vector(RDF, [sin(i*pi/20) for i in range(10)])1175sage: x.row() == matrix(x)1176True1177sage: x.row() == x.column().transpose()1178True11791180Sparse or dense implementations are preserved. ::11811182sage: d = vector(RR, [1.0, 2.0, 3.0])1183sage: s = vector(CDF, {2:5.0+6.0*I})1184sage: dm = d.row()1185sage: sm = s.row()1186sage: all([d.is_dense(), dm.is_dense(), s.is_sparse(), sm.is_sparse()])1187True11881189TESTS:11901191The :meth:`~sage.matrix.matrix1.Matrix.row` method will return1192a specified row of a matrix as a vector. So here are a couple1193of round-trips. ::11941195sage: A = matrix(ZZ, [[1,2,3]])1196sage: A == A.row(0).row()1197True1198sage: v = vector(ZZ, [4,5,6])1199sage: v == v.row().row(0)1200True12011202And a very small corner case. ::12031204sage: v = vector(ZZ, [])1205sage: w = v.row()1206sage: w.parent()1207Full MatrixSpace of 1 by 0 dense matrices over Integer Ring1208"""1209return self._matrix_(R=None)12101211def column(self):1212r"""1213Return a matrix with a single column and the same entries as the vector ``self``.12141215OUTPUT:12161217A matrix over the same ring as the vector (or free module element), with1218a single column. The entries of the column are identical to those of the1219vector, and in the same order.12201221EXAMPLES::12221223sage: v = vector(ZZ, [1,2,3])1224sage: w = v.column(); w1225[1]1226[2]1227[3]1228sage: w.parent()1229Full MatrixSpace of 3 by 1 dense matrices over Integer Ring12301231sage: x = vector(FiniteField(13), [2,4,8,16])1232sage: x.column()1233[2]1234[4]1235[8]1236[3]12371238There is more than one way to get one-column matrix from a vector.1239The ``column`` method is about equally efficient to making a row and1240then taking a transpose. Notice that supplying a vector to the1241matrix constructor demonstrates Sage's preference for rows. ::12421243sage: x = vector(RDF, [sin(i*pi/20) for i in range(10)])1244sage: x.column() == matrix(x).transpose()1245True1246sage: x.column() == x.row().transpose()1247True12481249Sparse or dense implementations are preserved. ::12501251sage: d = vector(RR, [1.0, 2.0, 3.0])1252sage: s = vector(CDF, {2:5.0+6.0*I})1253sage: dm = d.column()1254sage: sm = s.column()1255sage: all([d.is_dense(), dm.is_dense(), s.is_sparse(), sm.is_sparse()])1256True12571258TESTS:12591260The :meth:`~sage.matrix.matrix1.Matrix.column` method will return1261a specified column of a matrix as a vector. So here are a couple1262of round-trips. ::12631264sage: A = matrix(ZZ, [[1],[2],[3]])1265sage: A == A.column(0).column()1266True1267sage: v = vector(ZZ, [4,5,6])1268sage: v == v.column().column(0)1269True12701271And a very small corner case. ::12721273sage: v = vector(ZZ, [])1274sage: w = v.column()1275sage: w.parent()1276Full MatrixSpace of 0 by 1 dense matrices over Integer Ring1277"""1278return self._matrix_(R=None).transpose()12791280def _hash(self):1281"""1282Return hash of an immutable form of self (works even if self1283is mutable).12841285EXAMPLES::1286sage: v = vector([1,2/3,pi])1287sage: v.__hash__()1288Traceback (most recent call last):1289...1290TypeError: mutable vectors are unhashable1291sage: v._hash() # random output1292"""1293return hash(tuple(list(self)))12941295def __copy__(self):1296"""1297Make a copy of this vector.12981299EXAMPLES::13001301sage: v = vector([1..5]); v1302(1, 2, 3, 4, 5)1303sage: w = copy(v)1304sage: v == w1305True1306sage: v is w1307False13081309::13101311sage: v = vector([1..5], sparse=True); v1312(1, 2, 3, 4, 5)1313sage: copy(v)1314(1, 2, 3, 4, 5)1315"""1316if self.is_sparse():1317return self.parent()(self.dict())1318else:1319return self.parent()(self.list())13201321def subs(self, in_dict=None, **kwds):1322"""1323EXAMPLES::13241325sage: var('a,b,d,e')1326(a, b, d, e)1327sage: v = vector([a, b, d, e])1328sage: v.substitute(a=1)1329(1, b, d, e)1330sage: v.subs(a=b, b=d)1331(b, d, d, e)1332"""1333return self.parent()([ a.subs(in_dict, **kwds) for a in self.list() ])13341335def set_immutable(self):1336"""1337Make this vector immutable. This operation can't be undone.13381339EXAMPLES::13401341sage: v = vector([1..5]); v1342(1, 2, 3, 4, 5)1343sage: v[1] = 101344sage: v.set_immutable()1345sage: v[1] = 101346Traceback (most recent call last):1347...1348ValueError: vector is immutable; please change a copy instead (use copy())1349"""1350self._is_mutable = 013511352def is_mutable(self):1353"""1354Return True if this vector is mutable, i.e., the entries can be1355changed.13561357EXAMPLES::13581359sage: v = vector(QQ['x,y'], [1..5]); v.is_mutable()1360True1361sage: v.set_immutable()1362sage: v.is_mutable()1363False1364"""1365return self._is_mutable13661367def is_immutable(self):1368"""1369Return True if this vector is immutable, i.e., the entries cannot1370be changed.13711372EXAMPLES::13731374sage: v = vector(QQ['x,y'], [1..5]); v.is_immutable()1375False1376sage: v.set_immutable()1377sage: v.is_immutable()1378True1379"""1380return not self._is_mutable13811382def change_ring(self, R):1383"""1384Change the base ring of this vector, by coercing each element of1385this vector into R.13861387EXAMPLES::13881389sage: v = vector(QQ['x,y'], [1..5]); v.change_ring(GF(3))1390(1, 2, 0, 1, 2)1391"""1392P = self.parent()1393if P.base_ring() is R:1394return self1395return P.change_ring(R)(self)13961397def additive_order(self):1398"""1399Return the additive order of self.14001401EXAMPLES::14021403sage: v = vector(Integers(4), [1,2])1404sage: v.additive_order()1405414061407::14081409sage: v = vector([1,2,3])1410sage: v.additive_order()1411+Infinity14121413::14141415sage: v = vector(Integers(30), [6, 15]); v1416(6, 15)1417sage: v.additive_order()1418101419sage: 10*v1420(0, 0)1421"""1422v = [None]*self.degree()1423cdef int i1424for i from 0 <= i < self.degree():1425v[i] = self[i].additive_order()1426if v[i] == +Infinity:1427return +Infinity1428return sage.rings.arith.LCM(v)14291430def iteritems(self):1431"""1432Return iterator over self.14331434EXAMPLES::14351436sage: v = vector([1,2/3,pi])1437sage: v.iteritems()1438<dictionary-itemiterator object at ...>1439sage: list(v.iteritems())1440[(0, 1), (1, 2/3), (2, pi)]1441"""1442return self.dict(copy=False).iteritems()14431444def __abs__(self):1445"""1446Return the square root of the sum of the squares of the entries of1447this vector.14481449EXAMPLES::14501451sage: v = vector([1..5]); abs(v)1452sqrt(55)1453sage: v = vector(RDF, [1..5]); abs(v)14547.41619848711455"""1456return sum([x**2 for x in self.list()]).sqrt()14571458def norm(self, p=sage.rings.integer.Integer(2)):1459r"""1460Return the `p`-norm of ``self``.14611462INPUT:14631464- ``p`` - default: 2 - ``p`` can be a real number greater than 1,1465infinity (``oo`` or ``Infinity``), or a symbolic expression.14661467- `p=1`: the taxicab (Manhattan) norm1468- `p=2`: the usual Euclidean norm (the default)1469- `p=\infty`: the maximum entry (in absolute value)14701471.. note::14721473See also :func:`sage.misc.functional.norm`14741475EXAMPLES::14761477sage: v = vector([1,2,-3])1478sage: v.norm(5)1479276^(1/5)14801481The default is the usual Euclidean norm. ::14821483sage: v.norm()1484sqrt(14)1485sage: v.norm(2)1486sqrt(14)14871488The infinity norm is the maximum size (in absolute value)1489of the entries. ::14901491sage: v.norm(Infinity)149231493sage: v.norm(oo)1494314951496Real or symbolic values may be used for ``p``. ::14971498sage: v=vector(RDF,[1,2,3])1499sage: v.norm(5)15003.077384885391501sage: v.norm(pi/2)15024.21659586471503sage: _=var('a b c d p'); v=vector([a, b, c, d])1504sage: v.norm(p)1505(abs(a)^p + abs(b)^p + abs(c)^p + abs(d)^p)^(1/p)15061507Notice that the result may be a symbolic expression, owing to1508the necessity of taking a square root (in the default case).1509These results can be converted to numerical values if needed. ::15101511sage: v = vector(ZZ, [3,4])1512sage: nrm = v.norm(); nrm151351514sage: nrm.parent()1515Rational Field15161517sage: v = vector(QQ, [3, 5])1518sage: nrm = v.norm(); nrm1519sqrt(34)1520sage: nrm.parent()1521Symbolic Ring1522sage: numeric = N(nrm); numeric15235.83095189484...1524sage: numeric.parent()1525Real Field with 53 bits of precision15261527TESTS:15281529The value of ``p`` must be greater than, or1530equal to, one. ::15311532sage: v = vector(QQ, [1,2])1533sage: v.norm(0.99)1534Traceback (most recent call last):1535...1536ValueError: 0.990000 is not greater than or equal to 11537"""1538abs_self = [abs(x) for x in self]1539if p == Infinity:1540return max(abs_self)1541try:1542pr = RDF(p)1543if pr < 1:1544raise ValueError("%f is not greater than or equal to 1" %(pr))1545except TypeError:1546pass15471548s = sum([a**p for a in abs_self])1549return s**(1/p)15501551cdef int _cmp_c_impl(left, Element right) except -2:1552"""1553EXAMPLES::15541555sage: v = vector(QQ, [0,0,0,0])1556sage: v == 01557True1558sage: v == 11559False1560sage: v == v1561True1562sage: w = vector(QQ, [-1,0,0,0])1563sage: w < v1564True1565sage: w > v1566False1567"""1568cdef Py_ssize_t i1569cdef int c1570for i from 0 <= i < left.degree():1571c = cmp(left[i], right[i])1572if c: return c1573return 015741575def __getitem__(self, i):1576"""1577Return `i`-th entry or slice of self.15781579EXAMPLES::15801581This just raises NotImplementedError since this is an abstract1582base class, and __getitem__ has to be overloaded in the1583derived class::15841585sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)1586sage: v.__getitem__(0)1587Traceback (most recent call last):1588...1589NotImplementedError1590"""1591raise NotImplementedError15921593def __invert__(self):1594"""1595Invert v, which makes no sense, and is hence is not implemented.15961597EXAMPLES::15981599sage: vector([1,2/3,pi]).__invert__()1600Traceback (most recent call last):1601...1602NotImplementedError1603"""1604raise NotImplementedError16051606def __len__(self):1607"""1608EXAMPLES::16091610sage: len(sage.modules.free_module_element.FreeModuleElement(QQ^2010))161120101612"""1613return self.parent().degree()16141615def __mod__(self, p):1616"""1617EXAMPLES::16181619sage: V = vector(ZZ, [5, 9, 13, 15])1620sage: V % 71621(5, 2, 6, 1)1622sage: parent(V % 7)1623Ambient free module of rank 4 over the principal ideal domain Integer Ring1624"""1625return self.parent()([x % p for x in self.list()], copy=False, coerce=False, check=False)16261627def Mod(self, p):1628"""1629EXAMPLES::16301631sage: V = vector(ZZ, [5, 9, 13, 15])1632sage: V.Mod(7)1633(5, 2, 6, 1)1634sage: parent(V.Mod(7))1635Vector space of dimension 4 over Ring of integers modulo 71636"""1637return self.change_ring(self.base_ring().quotient_ring(p))16381639def list(self, copy=True):1640"""1641Return list of elements of self.16421643INPUT:16441645- copy -- bool, whether returned list is a copy that is1646safe to change, is ignored.16471648EXAMPLES::16491650sage: P.<x,y,z> = QQ[]1651sage: v = vector([x,y,z], sparse=True)1652sage: type(v)1653<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>1654sage: a = v.list(); a1655[x, y, z]1656sage: a[0] = x*y; v1657(x, y, z)16581659The optional argument ``copy`` is ignored::16601661sage: a = v.list(copy=False); a1662[x, y, z]1663sage: a[0] = x*y; v1664(x, y, z)1665"""1666cdef Py_ssize_t i1667return [self[i] for i in range(self.degree())]16681669def list_from_positions(self, positions):1670"""1671Return list of elements chosen from this vector using the1672given positions of this vector.16731674INPUT:16751676- positions -- iterable of ints167716781679EXAMPLES::16801681sage: v = vector([1,2/3,pi])1682sage: v.list_from_positions([0,0,0,2,1])1683[1, 1, 1, pi, 2/3]1684"""1685cdef Py_ssize_t i1686return [self[i] for i in positions]16871688def lift(self):1689"""1690EXAMPLES::16911692sage: V = vector(Integers(7), [5, 9, 13, 15]) ; V1693(5, 2, 6, 1)1694sage: V.lift()1695(5, 2, 6, 1)1696sage: parent(V.lift())1697Ambient free module of rank 4 over the principal ideal domain Integer Ring1698"""1699return self.change_ring(self.base_ring().cover_ring())17001701def __pos__(self):1702"""1703Always returns self, since +self == self.17041705EXAMPLES::17061707sage: v = vector([1,2/3,8])1708sage: v.__pos__()1709(1, 2/3, 8)1710sage: +v1711(1, 2/3, 8)1712"""1713return self17141715def __pow__(self, n, dummy):1716"""1717Raises a NotImplementedError, since powering doesn't make1718sense for vectors.17191720EXAMPLES::17211722sage: v = vector([1,2/3,8])1723sage: v^21724Traceback (most recent call last):1725...1726NotImplementedError1727"""1728raise NotImplementedError17291730def _repr_(self):1731"""1732String representation of a vector.17331734EXAMPLES::17351736sage: vector(QQ, [])._repr_()1737'()'1738sage: vector(QQ, range(5))._repr_()1739'(0, 1, 2, 3, 4)'17401741Symbolic are not displayed using ASCII art.17421743::17441745sage: x = var('x')1746sage: v = vector([x/(2*x)+sqrt(2)+var('theta')^3,x/(2*x)]); v1747(sqrt(2) + theta^3 + 1/2, 1/2)1748sage: v._repr_()1749'(sqrt(2) + theta^3 + 1/2, 1/2)'1750"""1751d = self.degree()1752if d == 0: return "()"1753# compute column widths1754S = [repr(x) for x in self.list(copy=False)]1755#width = max([len(x) for x in S])1756s = "("1757for i in xrange(d):1758if i == d-1:1759sep = ""1760else:1761sep=", "1762entry = S[i]1763#if i > 0:1764# entry = " "*(width-len(entry)) + entry1765s = s + entry + sep1766s = s + ")"1767return s17681769def _maple_init_(self):1770"""1771EXAMPLES::17721773sage: v = vector(ZZ, 4, range(4)) #optional1774sage: maple(v) #optional1775Vector[row](4, [0,1,2,3])17761777::17781779sage: v = vector(QQ, 3, [2/3, 0, 5/4]) #optional1780sage: maple(v) #optional1781Vector[row](3, [2/3,0,5/4])17821783::17841785sage: P.<x> = ZZ[] #optional1786sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) #optional1787sage: maple(v) #optional1788Vector[row](3, [x^2+2,2*x+1,-2*x^2+4*x])1789"""1790return "Vector[row](%s)"%(str(self.list()))17911792def __setitem__(self, i, x):1793"""1794Set the `i`-th entry or slice of self to x. This is not implemented,1795since self is an abstract base class.17961797EXAMPLES::17981799sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)1800sage: v[0] = 51801Traceback (most recent call last):1802...1803NotImplementedError18041805For derived classes, this works::18061807sage: v = vector([1,2/3,8])1808sage: v[0] = 51809sage: v1810(5, 2/3, 8)1811"""1812raise NotImplementedError18131814def __richcmp__(left, right, int op):1815"""1816EXAMPLES::18171818sage: v = vector([1,2/3,8]) # indirect test1819sage: v == v1820True1821"""1822cdef int ld, rd1823if not isinstance(left, FreeModuleElement) or not isinstance(right, FreeModuleElement):1824# use the generic compare1825return (<Element>left)._richcmp(right, op)1826ld = (<FreeModuleElement>left)._degree1827rd = (<FreeModuleElement>right)._degree1828if ld < rd:1829return (<Element>left)._rich_to_bool(op, -1)1830elif ld > rd:1831return (<Element>left)._rich_to_bool(op, 1)1832if (<FreeModuleElement>left)._parent.base_ring() is (<FreeModuleElement>right)._parent.base_ring():1833return (<Element>left)._rich_to_bool(op, (1834<FreeModuleElement>left)._cmp_same_ambient_c(right))1835return (<Element>left)._richcmp(right, op)183618371838cdef int _cmp_same_ambient_c(left, FreeModuleElement right) except -2:1839return cmp(left.list(copy=False), right.list(copy=False))18401841def degree(self):1842"""1843Return the degree of this vector, which is simply the number1844of entries.18451846EXAMPLES::18471848sage: sage.modules.free_module_element.FreeModuleElement(QQ^389).degree()18493891850sage: vector([1,2/3,8]).degree()185131852"""1853return self._degree18541855def denominator(self):1856"""1857Return the least common multiple of the denominators of the1858entries of self.18591860EXAMPLES::18611862sage: v = vector([1/2,2/5,3/14])1863sage: v.denominator()1864701865sage: 2*5*718667018671868TESTS:18691870The following was fixed in trac ticket #8800::18711872sage: M = GF(5)^31873sage: v = M((4,0,2))1874sage: v.denominator()1875118761877"""1878R = self.base_ring()1879if self.degree() == 0: return 11880x = self.list()1881# it may be that the marks do not have a denominator!1882d = x[0].denominator() if hasattr(x[0],'denominator') else 11883for y in x:1884d = d.lcm(y.denominator()) if hasattr(y,'denominator') else d1885return d18861887def dict(self, copy=True):1888"""1889Return dictionary of nonzero entries of self.18901891INPUT:18921893- ``copy`` -- bool (default: True)18941895OUTPUT:18961897- Python dictionary18981899EXAMPLES::19001901sage: v = vector([0,0,0,0,1/2,0,3/14])1902sage: v.dict()1903{4: 1/2, 6: 3/14}19041905In some cases when copy=False, we get back a dangerous reference::19061907sage: v = vector({0:5, 2:3/7}, sparse=True)1908sage: v.dict(copy=False)1909{0: 5, 2: 3/7}1910sage: v.dict(copy=False)[0] = 181911sage: v1912(18, 0, 3/7)1913"""1914e = {}1915for i in xrange(self.degree()):1916c = self[i]1917if c:1918e[i] = c1919return e19201921#############################1922# Plotting1923#############################1924def plot(self, plot_type=None, start=None, **kwds):1925"""1926INPUT:19271928- ``plot_type`` - (default: 'arrow' if v has 3 or fewer components,1929otherwise 'step') type of plot. Options are:19301931- 'arrow' to draw an arrow19321933- 'point' to draw a point at the coordinates specified by the1934vector19351936- 'step' to draw a step function representing the coordinates1937of the vector.19381939Both 'arrow' and 'point' raise exceptions if the vector has1940more than 3 dimensions.19411942- ``start`` - (default: origin in correct dimension) may be a tuple,1943list, or vector.19441945EXAMPLES:19461947The following both plot the given vector::19481949sage: v = vector(RDF, (1,2))1950sage: A = plot(v)1951sage: B = v.plot()1952sage: A+B # should just show one vector19531954Examples of the plot types::19551956sage: A = plot(v, plot_type='arrow')1957sage: B = plot(v, plot_type='point', color='green', size=20)1958sage: C = plot(v, plot_type='step') # calls v.plot_step()1959sage: A+B+C19601961You can use the optional arguments for :meth:`plot_step`::19621963sage: eps = 0.11964sage: plot(v, plot_type='step', eps=eps, xmax=5, hue=0)19651966Three-dimensional examples::19671968sage: v = vector(RDF, (1,2,1))1969sage: plot(v) # defaults to an arrow plot19701971::19721973sage: plot(v, plot_type='arrow')19741975::19761977sage: from sage.plot.plot3d.shapes2 import frame3d1978sage: plot(v, plot_type='point')+frame3d((0,0,0), v.list())19791980::19811982sage: plot(v, plot_type='step') # calls v.plot_step()19831984::19851986sage: plot(v, plot_type='step', eps=eps, xmax=5, hue=0)19871988With greater than three coordinates, it defaults to a step plot::19891990sage: v = vector(RDF, (1,2,3,4))1991sage: plot(v)19921993One dimensional vectors are plotted along the horizontal axis of1994the coordinate plane::19951996sage: plot(vector([1]))19971998An optional start argument may also be specified by a tuple, list, or vector::19992000sage: u = vector([1,2]); v = vector([2,5])2001sage: plot(u, start=v)20022003TESTS::20042005sage: u = vector([1,1]); v = vector([2,2,2]); z=(3,3,3)2006sage: plot(u) #test when start=None20072008::20092010sage: plot(u, start=v) #test when coordinate dimension mismatch exists2011Traceback (most recent call last):2012...2013ValueError: vector coordinates are not of the same dimension2014sage: P = plot(v, start=z) #test when start coordinates are passed as a tuple2015sage: P = plot(v, start=list(z)) #test when start coordinates are passed as a list2016"""2017# Give sensible defaults based on the vector length2018if plot_type is None:2019if len(self)<=3:2020plot_type='arrow'2021else:2022plot_type='step'20232024coords = self.list()20252026if start is None:2027start = [0]*len(coords)2028elif len(start)!=len(coords):2029raise ValueError("vector coordinates are not of the same dimension")2030else:2031start = list(start)203220332034if plot_type == 'arrow' or plot_type == 'point':2035dimension = len(coords)2036if dimension == 3:2037from sage.plot.plot3d.shapes2 import line3d, point3d20382039if plot_type == 'arrow':2040return line3d([start, [(u+v) for u,v in zip(coords, start)]], arrow_head=True, **kwds)2041else:2042return point3d(coords, **kwds)2043elif dimension < 3:2044if dimension < 2:2045# pad to make 2-dimensional2046coords.extend([0]*(2-dimension))2047start.extend([0]*(2-dimension))20482049from sage.plot.all import arrow, point2050if plot_type == 'arrow':2051return arrow(start, [(u+v) for u,v in zip(coords, start)], **kwds)2052else:2053return point(coords, **kwds)2054else:2055raise ValueError("arrow and point plots require vectors with 3 or fewer components")20562057elif plot_type == 'step':2058return self.plot_step(**kwds)2059else:2060raise NotImplementedError("plot_type was unrecognized")20612062def plot_step(self, xmin=0, xmax=1, eps=None, res=None,2063connect=True, **kwds):2064"""2065INPUT:20662067- ``xmin`` - (default: 0) start x position to start2068plotting20692070- ``xmax`` - (default: 1) stop x position to stop2071plotting20722073- ``eps`` - (default: determined by xmax) we view this2074vector as defining a function at the points xmin, xmin + eps, xmin2075+ 2\*eps, ...,20762077- ``res`` - (default: all points) total number of2078points to include in the graph20792080- ``connect`` - (default: True) if True draws a line;2081otherwise draw a list of points.208220832084EXAMPLES::20852086sage: eps=0.12087sage: v = vector(RDF, [sin(n*eps) for n in range(100)])2088sage: v.plot_step(eps=eps, xmax=5, hue=0)2089"""2090if res is None:2091res = self.degree()2092if eps is None:2093eps = float(xmax - xmin)/res2094v = []2095x = xmin2096for i in range(0, self.degree(), int(math.ceil(self.degree()/res))):2097y = float(self[i])2098if x > xmax:2099break2100v.append((x,y))2101x += eps2102v.append((x,y))2103from sage.plot.all import line, points2104if connect:2105return line(v, **kwds)2106else:2107return points(v, **kwds)21082109def dot_product(self, right):2110r"""2111Return the dot product of ``self`` and ``right``, which is the sum of the2112product of the corresponding entries.21132114INPUT:21152116- ``right`` - a vector of the same degree as ``self``.2117It does not need to belong to the same parent as ``self``,2118so long as the necessary products and sums are defined.21192120OUTPUT:21212122If ``self`` and ``right`` are the vectors `\vec{x}` and `\vec{y}`,2123of degree `n`, then this method returns21242125.. math::21262127\sum_{i=1}^{n}x_iy_i21282129.. note::21302131The :meth:`inner_product` is a more general version of2132this method, and the :meth:`hermitian_inner_product`2133method may be more appropriate if your vectors2134have complex entries.21352136EXAMPLES::21372138sage: V = FreeModule(ZZ, 3)2139sage: v = V([1,2,3])2140sage: w = V([4,5,6])2141sage: v.dot_product(w)21423221432144The vectors may be from different vector spaces,2145provided the necessary operations make sense.2146Notice that coercion will generate a result of2147the same type, even if the order of the2148arguments is reversed.::21492150sage: v = vector(ZZ, [1,2,3])2151sage: w = vector(FiniteField(3), [0,1,2])2152sage: ip = w.dot_product(v); ip215322154sage: ip.parent()2155Finite Field of size 321562157sage: ip = v.dot_product(w); ip215822159sage: ip.parent()2160Finite Field of size 321612162The dot product of a vector with itself is the 2-norm, squared. ::21632164sage: v = vector(QQ, [3, 4, 7])2165sage: v.dot_product(v) - v.norm()^22166021672168TESTS:21692170The second argument must be a free module element. ::21712172sage: v = vector(QQ, [1,2])2173sage: v.dot_product('junk')2174Traceback (most recent call last):2175...2176TypeError: right must be a free module element21772178The degrees of the arguments must match. ::21792180sage: v = vector(QQ, [1,2])2181sage: w = vector(QQ, [1,2,3])2182sage: v.dot_product(w)2183Traceback (most recent call last):2184...2185ArithmeticError: degrees (2 and 3) must be the same2186"""2187if not PY_TYPE_CHECK(right, FreeModuleElement):2188raise TypeError("right must be a free module element")2189r = right.list(copy=False)2190l = self.list(copy=False)2191if len(r) != len(l):2192raise ArithmeticError("degrees (%s and %s) must be the same"%(len(l),len(r)))2193if len(r) == 0:2194return self._parent.base_ring()(0)2195sum = l[0] * r[0]2196cdef Py_ssize_t i2197for i from 1 <= i < len(l):2198sum += l[i] * r[i]2199return sum22002201def cross_product(self, right):2202"""2203Return the cross product of self and right, which is only defined2204for vectors of length 3 or 7.22052206INPUT:22072208- ``right`` - A vector of the same size as ``self``, either2209degree three or degree seven.22102211OUTPUT:22122213The cross product (vector product) of ``self`` and ``right``,2214a vector of the same size of ``self`` and ``right``.22152216This product is performed under the assumption that the basis2217vectors are orthonormal.22182219EXAMPLES::22202221sage: v = vector([1,2,3]); w = vector([0,5,-9])2222sage: v.cross_product(v)2223(0, 0, 0)2224sage: u = v.cross_product(w); u2225(-33, 9, 5)2226sage: u.dot_product(v)222702228sage: u.dot_product(w)2229022302231The cross product is defined for degree seven vectors as well.2232[WIKIPEDIA:CROSSPRODUCT]_2233The 3-D cross product is achieved using the quaternians,2234whereas the 7-D cross product is achieved using the octions. ::22352236sage: u = vector(QQ, [1, -1/3, 57, -9, 56/4, -4,1])2237sage: v = vector(QQ, [37, 55, -99/57, 9, -12, 11/3, 4/98])2238sage: u.cross_product(v)2239(1394815/2793, -2808401/2793, 39492/49, -48737/399, -9151880/2793, 62513/2793, -326603/171)22402241The degree seven cross product is anticommutative. ::22422243sage: u.cross_product(v) + v.cross_product(u)2244(0, 0, 0, 0, 0, 0, 0)22452246The degree seven cross product is distributive across addition. ::22472248sage: v = vector([-12, -8/9, 42, 89, -37, 60/99, 73])2249sage: u = vector([31, -42/7, 97, 80, 30/55, -32, 64])2250sage: w = vector([-25/4, 40, -89, -91, -72/7, 79, 58])2251sage: v.cross_product(u + w) - (v.cross_product(u) + v.cross_product(w))2252(0, 0, 0, 0, 0, 0, 0)22532254The degree seven cross product respects scalar multiplication. ::22552256sage: v = vector([2, 17, -11/5, 21, -6, 2/17, 16])2257sage: u = vector([-8, 9, -21, -6, -5/3, 12, 99])2258sage: (5*v).cross_product(u) - 5*(v.cross_product(u))2259(0, 0, 0, 0, 0, 0, 0)2260sage: v.cross_product(5*u) - 5*(v.cross_product(u))2261(0, 0, 0, 0, 0, 0, 0)2262sage: (5*v).cross_product(u) - (v.cross_product(5*u))2263(0, 0, 0, 0, 0, 0, 0)22642265The degree seven cross product respects the scalar triple product. ::22662267sage: v = vector([2,6,-7/4,-9/12,-7,12,9])2268sage: u = vector([22,-7,-9/11,12,15,15/7,11])2269sage: w = vector([-11,17,19,-12/5,44,21/56,-8])2270sage: v.dot_product(u.cross_product(w)) - w.dot_product(v.cross_product(u))2271022722273TESTS:22742275Both vectors need to be of length three or both vectors need to be of length seven. ::22762277sage: u = vector(range(7))2278sage: v = vector(range(3))2279sage: u.cross_product(v)2280Traceback (most recent call last):2281...2282ArithmeticError: Cross product only defined for vectors of length three or seven, not (7 and 3)22832284REFERENCES:22852286.. [WIKIPEDIA:CROSSPRODUCT] Algebraic Properties of the Cross Product2287http://en.wikipedia.org/wiki/Cross_product22882289AUTHOR:22902291Billy Wonderly (2010-05-11), Added 7-D Cross Product2292"""2293if not PY_TYPE_CHECK(right, FreeModuleElement):2294raise TypeError("right must be a free module element")2295r = right.list(copy=False)2296l = self.list(copy=False)2297if len(r) == 3 and len(l) == 3:2298return vector([l[1]*r[2] - l[2]*r[1],2299l[2]*r[0] - l[0]*r[2],2300l[0]*r[1] - l[1]*r[0]])23012302elif len(r) == 7 and len(l) == 7:2303return 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],2304l[2]*r[4] - l[4]*r[2] + l[3]*r[0] - l[0]*r[3] + l[5]*r[6] - l[6]*r[5],2305l[3]*r[5] - l[5]*r[3] + l[4]*r[1] - l[1]*r[4] + l[6]*r[0] - l[0]*r[6],2306l[4]*r[6] - l[6]*r[4] + l[5]*r[2] - l[2]*r[5] + l[0]*r[1] - l[1]*r[0],2307l[5]*r[0] - l[0]*r[5] + l[6]*r[3] - l[3]*r[6] + l[1]*r[2] - l[2]*r[1],2308l[6]*r[1] - l[1]*r[6] + l[0]*r[4] - l[4]*r[0] + l[2]*r[3] - l[3]*r[2],2309l[0]*r[2] - l[2]*r[0] + l[1]*r[5] - l[5]*r[1] + l[3]*r[4] - l[4]*r[3]])23102311else:2312raise ArithmeticError("Cross product only defined for vectors of length three or seven, not (%s and %s)"%(len(l),len(r)))2313231423152316def pairwise_product(self, right):2317"""2318Return the pairwise product of self and right, which is a vector of2319the products of the corresponding entries.23202321INPUT:232223232324- ``right`` - vector of the same degree as self. It2325need not be in the same vector space as self, as long as the2326coefficients can be multiplied.232723282329EXAMPLES::23302331sage: V = FreeModule(ZZ, 3)2332sage: v = V([1,2,3])2333sage: w = V([4,5,6])2334sage: v.pairwise_product(w)2335(4, 10, 18)2336sage: sum(v.pairwise_product(w)) == v.dot_product(w)2337True23382339::23402341sage: W = VectorSpace(GF(3),3)2342sage: w = W([0,1,2])2343sage: w.pairwise_product(v)2344(0, 2, 0)2345sage: w.pairwise_product(v).parent()2346Vector space of dimension 3 over Finite Field of size 323472348Implicit coercion is well defined (regardless of order), so we2349get 2 even if we do the dot product in the other order.23502351::23522353sage: v.pairwise_product(w).parent()2354Vector space of dimension 3 over Finite Field of size 323552356TESTS::23572358sage: x, y = var('x, y')23592360::23612362sage: parent(vector(ZZ,[1,2]).pairwise_product(vector(ZZ,[1,2])))2363Ambient free module of rank 2 over the principal ideal domain Integer Ring2364sage: parent(vector(ZZ,[1,2]).pairwise_product(vector(QQ,[1,2])))2365Vector space of dimension 2 over Rational Field2366sage: parent(vector(QQ,[1,2]).pairwise_product(vector(ZZ,[1,2])))2367Vector space of dimension 2 over Rational Field2368sage: parent(vector(QQ,[1,2]).pairwise_product(vector(QQ,[1,2])))2369Vector space of dimension 2 over Rational Field23702371::23722373sage: parent(vector(QQ,[1,2,3,4]).pairwise_product(vector(ZZ[x],[1,2,3,4])))2374Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field2375sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(QQ,[1,2,3,4])))2376Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field23772378::23792380sage: parent(vector(QQ,[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))2381Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field2382sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ,[1,2,3,4])))2383Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field23842385::23862387sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))2388Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field2389sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ[x],[1,2,3,4])))2390Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field23912392::23932394sage: parent(vector(QQ[y],[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))2395Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field2396sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))2397Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field23982399::24002401sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(ZZ[y],[1,2,3,4])))2402Traceback (most recent call last):2403...2404TypeError: 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'2405sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))2406Traceback (most recent call last):2407...2408TypeError: 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'2409sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(ZZ[y],[1,2,3,4])))2410Traceback (most recent call last):2411...2412TypeError: 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'2413sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))2414Traceback (most recent call last):2415...2416TypeError: 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'2417sage: v = vector({1: 1, 3: 2}) # test sparse vectors2418sage: w = vector({0: 6, 3: -4})2419sage: v.pairwise_product(w)2420(0, 0, 0, -8)2421sage: w.pairwise_product(v) == v.pairwise_product(w)2422True2423"""2424if not PY_TYPE_CHECK(right, FreeModuleElement):2425raise TypeError("right must be a free module element")2426if self._parent is not (<FreeModuleElement>right)._parent:2427self, right = canonical_coercion(self, right)2428return self._pairwise_product_(right)24292430def element(self):2431"""2432Simply returns self. This is useful, since for many objects,2433self.element() returns a vector corresponding to self.24342435EXAMPLES::24362437sage: v = vector([1/2,2/5,0]); v2438(1/2, 2/5, 0)2439sage: v.element()2440(1/2, 2/5, 0)2441"""2442return self24432444def get(self, Py_ssize_t i):2445"""2446The get method is in some cases more efficient (and more2447dangerous) than __getitem__, because it is not guaranteed to2448do any error checking.24492450EXAMPLES::24512452sage: vector([1/2,2/5,0]).get(0)24531/22454sage: vector([1/2,2/5,0]).get(3)2455Traceback (most recent call last):2456...2457IndexError: index out of range2458"""2459return self[i]24602461def set(self, Py_ssize_t i, x):2462"""2463The set method is meant to be more efficient than __setitem__,2464because it need not be guaranteed to do any error checking or2465coercion. Use with great, great care.24662467EXAMPLES::24682469sage: v = vector([1/2,2/5,0]); v2470(1/2, 2/5, 0)2471sage: v.set(2, -15/17); v2472(1/2, 2/5, -15/17)2473"""2474self[i] = x247524762477def normalize(self):2478"""2479Return this vector divided through by the first nonzero entry of2480this vector.24812482EXAMPLES::24832484sage: v = vector(QQ,[0,4/3,5,1,2])2485sage: v.normalize()2486(0, 1, 15/4, 3/4, 3/2)2487"""2488cdef Py_ssize_t i2489for i from 0 <= i < self._degree:2490if self[i] != 0:2491return (~self[i]) * self2492return self24932494def conjugate(self):2495r"""2496Returns a vector where every entry has been replaced by its complex conjugate.24972498OUTPUT:24992500A vector of the same length, over the same ring,2501but with each entry replaced by the complex conjugate, as2502implemented by the ``conjugate()`` method for elements of2503the base ring, which is presently always complex conjugation.25042505EXAMPLES::25062507sage: v = vector(CDF, [2.3 - 5.4*I, -1.7 + 3.6*I])2508sage: w = v.conjugate(); w2509(2.3 + 5.4*I, -1.7 - 3.6*I)2510sage: w.parent()2511Vector space of dimension 2 over Complex Double Field25122513Even if conjugation seems nonsensical over a certain ring, this2514method for vectors cooperates silently. ::25152516sage: u = vector(ZZ, range(6))2517sage: u.conjugate()2518(0, 1, 2, 3, 4, 5)25192520Sage implements a few specialized subfields of the complex numbers,2521such as the cyclotomic fields. This example uses such a field2522containing a primitive 7-th root of unity named ``a``. ::25232524sage: F.<a> = CyclotomicField(7)2525sage: v = vector(F, [a^i for i in range(7)])2526sage: v2527(1, a, a^2, a^3, a^4, a^5, -a^5 - a^4 - a^3 - a^2 - a - 1)2528sage: v.conjugate()2529(1, -a^5 - a^4 - a^3 - a^2 - a - 1, a^5, a^4, a^3, a^2, a)25302531Sparse vectors are returned as such. ::25322533sage: v = vector(CC, {1: 5 - 6*I, 3: -7*I}); v2534(0.000000000000000, 5.00000000000000 - 6.00000000000000*I, 0.000000000000000, -7.00000000000000*I)2535sage: v.is_sparse()2536True2537sage: vc = v.conjugate(); vc2538(0.000000000000000, 5.00000000000000 + 6.00000000000000*I, 0.000000000000000, 7.00000000000000*I)2539sage: vc.conjugate()2540(0.000000000000000, 5.00000000000000 - 6.00000000000000*I, 0.000000000000000, -7.00000000000000*I)25412542TESTS::25432544sage: n = 152545sage: x = vector(CDF, [sin(i*pi/n)+cos(i*pi/n)*I for i in range(n)])2546sage: x + x.conjugate() in RDF^n2547True2548sage: I*(x - x.conjugate()) in RDF^n2549True25502551The parent of the conjugate is the same as that of the orginal vector.2552We test this by building a specialized vector space with a non-standard2553inner product, and constructing a test vector in this space. ::25542555sage: V = VectorSpace(CDF, 2, inner_product_matrix = [[2,1],[1,5]])2556sage: v = vector(CDF, [2-3*I, 4+5*I])2557sage: w = V(v)2558sage: w.parent()2559Ambient quadratic space of dimension 2 over Complex Double Field2560Inner product matrix:2561[2.0 1.0]2562[1.0 5.0]2563sage: w.conjugate().parent()2564Ambient quadratic space of dimension 2 over Complex Double Field2565Inner product matrix:2566[2.0 1.0]2567[1.0 5.0]2568"""2569V = self.parent()2570R = self.base_ring()2571degree = self.degree()2572if self.is_sparse():2573# this could be a dictionary comprehension in Python 32574entries = {}2575for index, entry in self.iteritems():2576entries[index] = entry.conjugate()2577else:2578entries = [entry.conjugate() for entry in self]2579return V(vector(R, degree, entries))25802581def inner_product(self, right):2582r"""2583Returns the inner product of ``self`` and ``right``,2584possibly using an inner product matrix from the parent of ``self``.25852586INPUT:25872588- ``right`` - a vector of the same degree as ``self``25892590OUTPUT:25912592If the parent vector space does not have an inner product2593matrix defined, then this is the usual dot product2594(:meth:`dot_product`). If ``self`` and ``right`` are2595considered as single column matrices, `\vec{x}` and `\vec{y}`,2596and `A` is the inner product matrix, then this method computes25972598.. math::25992600\left(\vec{x}\right)^tA\vec{y}26012602where `t` indicates the transpose.26032604.. note::26052606If your vectors have complex entries, the2607:meth:`hermitian_inner_product` may be more2608appropriate for your purposes.26092610EXAMPLES::26112612sage: v = vector(QQ, [1,2,3])2613sage: w = vector(QQ, [-1,2,-3])2614sage: v.inner_product(w)2615-62616sage: v.inner_product(w) == v.dot_product(w)2617True26182619The vector space or free module that is the parent to2620``self`` can have an inner product matrix defined, which2621will be used by this method. This matrix will be passed2622through to subspaces. ::26232624sage: ipm = matrix(ZZ,[[2,0,-1], [0,2,0], [-1,0,6]])2625sage: M = FreeModule(ZZ, 3, inner_product_matrix = ipm)2626sage: v = M([1,0,0])2627sage: v.inner_product(v)262822629sage: K = M.span_of_basis([[0/2,-1/2,-1/2], [0,1/2,-1/2],[2,0,0]])2630sage: (K.0).inner_product(K.0)263122632sage: w = M([1,3,-1])2633sage: v = M([2,-4,5])2634sage: w.row()*ipm*v.column() == w.inner_product(v)2635True26362637Note that the inner product matrix comes from the parent of ``self``.2638So if a vector is not an element of the correct parent, the result2639could be a source of confusion. ::26402641sage: V = VectorSpace(QQ, 2, inner_product_matrix=[[1,2],[2,1]])2642sage: v = V([12, -10])2643sage: w = vector(QQ, [10,12])2644sage: v.inner_product(w)2645882646sage: w.inner_product(v)264702648sage: w = V(w)2649sage: w.inner_product(v)26508826512652.. note::26532654The use of an inner product matrix makes no restrictions on2655the nature of the matrix. In particular, in this context it2656need not be Hermitian and positive-definite (as it is in the2657example above).26582659TESTS:26602661Most error handling occurs in the :meth:`dot_product` method.2662But with an inner product defined, this method will check2663that the input is a vector or free module element. ::26642665sage: W = VectorSpace(RDF, 2, inner_product_matrix = matrix(RDF, 2, [1.0,2.0,3.0,4.0]))2666sage: v = W([2.0, 4.0])2667sage: v.inner_product(5)2668Traceback (most recent call last):2669...2670TypeError: right must be a free module element2671"""2672if self.parent().is_ambient() and self.parent()._inner_product_is_dot_product():2673return self.dot_product(right)2674if not isinstance(right, FreeModuleElement):2675raise TypeError("right must be a free module element")2676M = self.parent()2677if M.is_ambient() or M.uses_ambient_inner_product():2678A = M.ambient_module().inner_product_matrix()2679return A.linear_combination_of_rows(self).dot_product(right)2680else:2681A = M.inner_product_matrix()2682v = M.coordinate_vector(self)2683w = M.coordinate_vector(right)2684return A.linear_combination_of_rows(v).dot_product(w)26852686def outer_product(self, right):2687r"""2688Returns a matrix, the outer product of two vectors ``self`` and ``right``.26892690INPUT:26912692- ``right`` - a vector (or free module element) of any size, whose2693elements are compatible (with regard to multiplication) with the2694elements of ``self``.26952696OUTPUT:26972698The outer product of two vectors `x` and `y` (respectively2699``self`` and ``right``) can be described several ways. If we2700interpret `x` as a `m\times 1` matrix and interpret `y` as a2701`1\times n` matrix, then the outer product is the `m\times n`2702matrix from the usual matrix product `xy`. Notice how this2703is the "opposite" in some ways from an inner product (which2704would require `m=n`).27052706If we just consider vectors, use each entry of `x` to create2707a scalar multiples of the vector `y` and use these vectors as2708the rows of a matrix. Or use each entry of `y` to create a2709scalar multiples of `x` and use these vectors as the columns2710of a matrix.27112712EXAMPLES::27132714sage: u = vector(QQ, [1/2, 1/3, 1/4, 1/5])2715sage: v = vector(ZZ, [60, 180, 600])2716sage: u.outer_product(v)2717[ 30 90 300]2718[ 20 60 200]2719[ 15 45 150]2720[ 12 36 120]2721sage: M = v.outer_product(u); M2722[ 30 20 15 12]2723[ 90 60 45 36]2724[300 200 150 120]2725sage: M.parent()2726Full MatrixSpace of 3 by 4 dense matrices over Rational Field27272728The more general :meth:`sage.matrix.matrix2.tensor_product` is an2729operation on a pair of matrices. If we construe a pair of vectors2730as a column vector and a row vector, then an outer product and a2731tensor product are identical. Thus `tensor_product` is a synonym2732for this method. ::27332734sage: u = vector(QQ, [1/2, 1/3, 1/4, 1/5])2735sage: v = vector(ZZ, [60, 180, 600])2736sage: u.tensor_product(v) == (u.column()).tensor_product(v.row())2737True27382739The result is always a dense matrix, no matter if the two2740vectors are, or are not, dense. ::27412742sage: d = vector(ZZ,[4,5], sparse=False)2743sage: s = vector(ZZ, [1,2,3], sparse=True)2744sage: dd = d.outer_product(d)2745sage: ds = d.outer_product(s)2746sage: sd = s.outer_product(d)2747sage: ss = s.outer_product(s)2748sage: all([dd.is_dense(), ds.is_dense(), sd.is_dense(), dd.is_dense()])2749True27502751Vectors with no entries do the right thing. ::27522753sage: v = vector(ZZ, [])2754sage: z = v.outer_product(v)2755sage: z.parent()2756Full MatrixSpace of 0 by 0 dense matrices over Integer Ring27572758There is a fair amount of latitude in the value of the ``right``2759vector, and the matrix that results can have entries from a new2760ring large enough to contain the result. If you know better,2761you can sometimes bring the result down to a less general ring. ::27622763sage: R.<t> = ZZ[]2764sage: v = vector(R, [12, 24*t])2765sage: w = vector(QQ, [1/2, 1/3, 1/4])2766sage: op = v.outer_product(w)2767sage: op2768[ 6 4 3]2769[12*t 8*t 6*t]2770sage: op.base_ring()2771Univariate Polynomial Ring in t over Rational Field2772sage: m = op.change_ring(R); m2773[ 6 4 3]2774[12*t 8*t 6*t]2775sage: m.base_ring()2776Univariate Polynomial Ring in t over Integer Ring27772778But some inputs are not compatible, even if vectors. ::27792780sage: w = vector(GF(5), [1,2])2781sage: v = vector(GF(7), [1,2,3,4])2782sage: z = w.outer_product(v)2783Traceback (most recent call last):2784...2785TypeError: 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'27862787And some inputs don't make any sense at all. ::27882789sage: w=vector(QQ, [5,10])2790sage: z=w.outer_product(6)2791Traceback (most recent call last):2792...2793TypeError: right operand in an outer product must be a vector, not an element of Integer Ring2794"""2795if not PY_TYPE_CHECK(right, FreeModuleElement):2796raise TypeError('right operand in an outer product must be a vector, not an element of %s' % right.parent())2797return self.column()*right.row()27982799# tensor product is an alias in the special case of two vectors2800tensor_product = outer_product28012802def hermitian_inner_product(self, right):2803r"""2804Returns the dot product, but with the entries of the first vector2805conjugated beforehand.28062807INPUT:28082809- ``right`` - a vector of the same degree as ``self``28102811OUTPUT:28122813If ``self`` and ``right`` are the vectors `\vec{x}` and2814`\vec{y}` of degree `n` then this routine computes28152816.. math::28172818\sum_{i=1}^{n}\overline{x}_i{y}_i28192820where the bar indicates complex conjugation.28212822.. note::28232824If your vectors do not contain complex entries, then2825:meth:`dot_product` will return the same result without2826the overhead of conjugating elements of ``self``.28272828If you are not computing a weighted inner product, and2829your vectors do not have complex entries, then the2830:meth:`dot_product` will return the same result.28312832EXAMPLES::28332834sage: v = vector(CDF, [2+3*I, 5-4*I])2835sage: w = vector(CDF, [6-4*I, 2+3*I])2836sage: v.hermitian_inner_product(w)2837-2.0 - 3.0*I28382839Sage implements a few specialized fields over the complex numbers,2840such as cyclotomic fields and quadratic number fields. So long as2841the base rings have a conjugate method, then the Hermitian inner2842product will be available. ::28432844sage: Q.<a> = QuadraticField(-7)2845sage: a^22846-72847sage: v = vector(Q, [3+a, 5-2*a])2848sage: w = vector(Q, [6, 4+3*a])2849sage: v.hermitian_inner_product(w)285017*a - 428512852The Hermitian inner product should be additive in2853each argument (we only need to test one), linear2854in each argument (with conjugation on the first scalar),2855and anti-commutative. ::28562857sage: alpha = CDF(5.0 + 3.0*I)2858sage: u = vector(CDF, [2+4*I, -3+5*I, 2-7*I])2859sage: v = vector(CDF, [-1+3*I, 5+4*I, 9-2*I])2860sage: w = vector(CDF, [8+3*I, -4+7*I, 3-6*I])2861sage: (u+v).hermitian_inner_product(w) == u.hermitian_inner_product(w) + v.hermitian_inner_product(w)2862True2863sage: (alpha*u).hermitian_inner_product(w) == alpha.conjugate()*u.hermitian_inner_product(w)2864True2865sage: u.hermitian_inner_product(alpha*w) == alpha*u.hermitian_inner_product(w)2866True2867sage: u.hermitian_inner_product(v) == v.hermitian_inner_product(u).conjugate()2868True28692870For vectors with complex entries, the Hermitian inner product2871has a more natural relationship with the 2-norm (which is the2872default for the :meth:`norm` method). The norm squared equals2873the Hermitian inner product of the vector with itself. ::28742875sage: v = vector(CDF, [-0.66+0.47*I, -0.60+0.91*I, -0.62-0.87*I, 0.53+0.32*I])2876sage: abs(v.norm()^2 - v.hermitian_inner_product(v)) < 1.0e-102877True28782879TESTS:28802881This method is built on the :meth:`dot_product` method,2882which allows for a wide variety of inputs. Any error2883handling happens there. ::28842885sage: v = vector(CDF, [2+3*I])2886sage: w = vector(CDF, [5+2*I, 3+9*I])2887sage: v.hermitian_inner_product(w)2888Traceback (most recent call last):2889...2890ArithmeticError: degrees (1 and 2) must be the same2891"""2892return (self.conjugate()).dot_product(right)28932894def is_dense(self):2895"""2896Return True if this is a dense vector, which is just a2897statement about the data structure, not the number of nonzero2898entries.28992900EXAMPLES::29012902sage: vector([1/2,2/5,0]).is_dense()2903True2904sage: vector([1/2,2/5,0],sparse=True).is_dense()2905False2906"""2907return self.is_dense_c()29082909cdef bint is_dense_c(self):2910return self.parent().is_dense()29112912def is_sparse(self):2913"""2914Return True if this is a sparse vector, which is just a2915statement about the data structure, not the number of nonzero2916entries.29172918EXAMPLES::29192920sage: vector([1/2,2/5,0]).is_sparse()2921False2922sage: vector([1/2,2/5,0],sparse=True).is_sparse()2923True2924"""2925return self.is_sparse_c()29262927cdef bint is_sparse_c(self):2928return self.parent().is_sparse()29292930def is_vector(self):2931"""2932Return True, since this is a vector.29332934EXAMPLES::29352936sage: vector([1/2,2/5,0]).is_vector()2937True2938"""2939return True29402941def _mathematica_init_(self):2942"""2943Returns string representation of this vector as a Mathematica2944list.29452946EXAMPLES::29472948sage: vector((1,2,3), QQ)._mathematica_init_()2949'{1/1, 2/1, 3/1}'2950sage: mathematica(vector((1,2,3), QQ)) #optional -- requires mathematica2951{1, 2, 3}2952sage: a = vector(SR, 5, [1, x, x^2, sin(x), pi]); a2953(1, x, x^2, sin(x), pi)2954sage: a._mathematica_init_()2955'{1, x, (x)^(2), Sin[x], Pi}'2956"""2957return '{' + ', '.join([x._mathematica_init_() for x in self.list()]) + '}'29582959## def zero_out_positions(self, P):2960## """2961## Set the positions of self in the list P equal to 0.2962## """2963## z = self.base_ring()(0)2964## d = self.degree()2965## for n in P:2966## self[n] = z29672968def nonzero_positions(self):2969"""2970Return the sorted list of integers i such that self[i] != 0.29712972EXAMPLES::29732974sage: vector([-1,0,3,0,0,0,0.01]).nonzero_positions()2975[0, 2, 6]2976"""2977z = self.base_ring()(0)2978v = self.list()2979cdef Py_ssize_t i2980return [i for i from 0 <= i < self.degree() if v[i] != z]29812982def support(self): # do not override.2983"""2984Return the integers i such that self[i] != 0.2985This is the same as the ``nonzero_positions`` function.29862987EXAMPLES::29882989sage: vector([-1,0,3,0,0,0,0.01]).support()2990[0, 2, 6]2991"""2992return self.nonzero_positions()29932994def _latex_(self):2995r"""2996Return a latex representation of the vector ``self``.29972998OUTPUT:29993000If self is the free module element (1,2,3,4),3001then a string with the following latex is returned:3002"\left(1,\,2,\,3,\,4\right)" (without the quotes).3003The vector is enclosed in parentheses by default,3004but the delimiters can be changed using the command3005``latex.vector_delimiters(...)`` as in the example below.30063007EXAMPLES::30083009sage: v = vector(QQ, [1,2,3])3010sage: latex(v)3011\left(1,\,2,\,3\right)30123013This is an example of how to change the delimiters.3014You have the power to mix and match, though it is3015probably not advisable. For more detail see3016:meth:`~sage.misc.latex.Latex.vector_delimiters`.30173018sage: latex.vector_delimiters('[', '\\rangle')3019sage: w = vector(CDF, [1,2,3])3020sage: latex(w)3021\left[1.0,\,2.0,\,3.0\right\rangle3022"""3023latex = sage.misc.latex.latex3024vector_delimiters = latex.vector_delimiters()3025s = '\\left' + vector_delimiters[0]3026s += ',\,'.join([latex(a) for a in self.list()])3027return s + '\\right' + vector_delimiters[1]30283029def dense_vector(self):3030"""3031Return dense version of self. If self is dense, just return3032self; otherwise, create and return correspond dense vector.30333034EXAMPLES::30353036sage: vector([-1,0,3,0,0,0]).dense_vector().is_dense()3037True3038sage: vector([-1,0,3,0,0,0],sparse=True).dense_vector().is_dense()3039True3040sage: vector([-1,0,3,0,0,0],sparse=True).dense_vector()3041(-1, 0, 3, 0, 0, 0)3042"""3043if self.is_dense():3044return self3045else:3046return self.parent().ambient_module().dense_module()(self.list())30473048def sparse_vector(self):3049"""3050Return sparse version of self. If self is sparse, just return3051self; otherwise, create and return correspond sparse vector.30523053EXAMPLES::30543055sage: vector([-1,0,3,0,0,0]).sparse_vector().is_sparse()3056True3057sage: vector([-1,0,3,0,0,0]).sparse_vector().is_sparse()3058True3059sage: vector([-1,0,3,0,0,0]).sparse_vector()3060(-1, 0, 3, 0, 0, 0)3061"""3062if self.is_sparse():3063return self3064else:3065return self.parent().ambient_module().sparse_module()(self.list())306630673068def apply_map(self, phi, R=None, sparse=None):3069"""3070Apply the given map phi (an arbitrary Python function or callable3071object) to this free module element. If R is not given,3072automatically determine the base ring of the resulting element.30733074INPUT:3075sparse -- True or False will control whether the result3076is sparse. By default, the result is sparse iff self3077is sparse.307830793080- ``phi`` - arbitrary Python function or callable3081object30823083- ``R`` - (optional) ring308430853086OUTPUT: a free module element over R30873088EXAMPLES::30893090sage: m = vector([1,x,sin(x+1)])3091sage: m.apply_map(lambda x: x^2)3092(1, x^2, sin(x + 1)^2)3093sage: m.apply_map(sin)3094(sin(1), sin(x), sin(sin(x + 1)))30953096::30973098sage: m = vector(ZZ, 9, range(9))3099sage: k.<a> = GF(9)3100sage: m.apply_map(k)3101(0, 1, 2, 0, 1, 2, 0, 1, 2)31023103In this example, we explicitly specify the codomain.31043105::31063107sage: s = GF(3)3108sage: f = lambda x: s(x)3109sage: n = m.apply_map(f, k); n3110(0, 1, 2, 0, 1, 2, 0, 1, 2)3111sage: n.parent()3112Vector space of dimension 9 over Finite Field in a of size 3^231133114If your map sends 0 to a non-zero value, then your resulting3115vector is not mathematically sparse::31163117sage: v = vector([0] * 6 + [1], sparse=True); v3118(0, 0, 0, 0, 0, 0, 1)3119sage: v2 = v.apply_map(lambda x: x+1); v23120(1, 1, 1, 1, 1, 1, 2)31213122but it's still represented with a sparse data type::31233124sage: parent(v2)3125Ambient sparse free module of rank 7 over the principal ideal domain Integer Ring31263127This data type is inefficient for dense vectors, so you may3128want to specify sparse=False::31293130sage: v2 = v.apply_map(lambda x: x+1, sparse=False); v23131(1, 1, 1, 1, 1, 1, 2)3132sage: parent(v2)3133Ambient free module of rank 7 over the principal ideal domain Integer Ring31343135Or if you have a map that will result in mostly zeroes, you may3136want to specify sparse=True::31373138sage: v = vector(srange(10))3139sage: v2 = v.apply_map(lambda x: 0 if x else 1, sparse=True); v23140(1, 0, 0, 0, 0, 0, 0, 0, 0, 0)3141sage: parent(v2)3142Ambient sparse free module of rank 10 over the principal ideal domain Integer Ring31433144TESTS::31453146sage: m = vector(SR,[])3147sage: m.apply_map(lambda x: x*x) == m3148True31493150Check that we don't unnecessarily apply phi to 0 in the sparse case::31513152sage: m = vector(ZZ, range(1, 4), sparse=True)3153sage: m.apply_map(lambda x: 1/x)3154(1, 1/2, 1/3)31553156sage: parent(vector(RDF, (), sparse=True).apply_map(lambda x: x, sparse=True))3157Sparse vector space of dimension 0 over Real Double Field3158sage: parent(vector(RDF, (), sparse=True).apply_map(lambda x: x, sparse=False))3159Vector space of dimension 0 over Real Double Field3160sage: parent(vector(RDF, (), sparse=False).apply_map(lambda x: x, sparse=True))3161Sparse vector space of dimension 0 over Real Double Field3162sage: parent(vector(RDF, (), sparse=False).apply_map(lambda x: x, sparse=False))3163Vector space of dimension 0 over Real Double Field3164"""3165if sparse is None:3166sparse = self.is_sparse()31673168if self._degree == 0:3169if sparse == self.is_sparse():3170from copy import copy3171return copy(self)3172elif sparse:3173return self.sparse_vector()3174else:3175return self.dense_vector()31763177v = None31783179if self.is_sparse():3180if len(self.dict(copy=False)) < self._degree:3181# OK, we have some zero entries.3182zero_res = phi(self.base_ring()(0))3183if not zero_res.is_zero():3184# And phi maps 0 to a non-zero value.3185v = [zero_res] * self._degree3186for i,z in self.dict(copy=False).items():3187v[i] = phi(z)31883189if v is None:3190# phi maps 0 to 0 (or else we don't have any zeroes at all)3191v = dict([(i,phi(z)) for i,z in self.dict(copy=False).items()])3192else:3193v = [phi(z) for z in self.list()]31943195if R is None:3196return vector(v, sparse=sparse)3197else:3198return vector(R, v, sparse=sparse)319932003201def _derivative(self, var=None):3202"""3203Differentiate with respect to var by differentiating each element3204with respect to var.32053206.. seealso:32073208:meth:`derivative`32093210EXAMPLES::32113212sage: v = vector([1,x,x^2])3213sage: v._derivative(x)3214(0, 1, 2*x)3215sage: type(v._derivative(x)) == type(v)3216True3217sage: v = vector([1,x,x^2], sparse=True)3218sage: v._derivative(x)3219(0, 1, 2*x)3220sage: type(v._derivative(x)) == type(v)3221True32223223If no variables are specified and the vector contains callable3224symbolic expressions, then calculate the matrix derivative3225(i.e., the Jacobian matrix)::32263227sage: T(r,theta)=[r*cos(theta),r*sin(theta)]3228sage: T3229(r, theta) |--> (r*cos(theta), r*sin(theta))3230sage: T.diff() # matrix derivative3231[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]3232[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]3233sage: diff(T) # matrix derivative again3234[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]3235[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]3236sage: T.diff().det() # Jacobian3237(r, theta) |--> r*sin(theta)^2 + r*cos(theta)^23238"""3239if var is None:3240if sage.symbolic.callable.is_CallableSymbolicExpressionRing(self.base_ring()):3241return sage.calculus.all.jacobian(self, self.base_ring().arguments())3242else:3243raise ValueError("No differentiation variable specified.")32443245# We would just use apply_map, except that Cython doesn't3246# allow lambda functions3247if self._degree == 0:3248from copy import copy3249return copy(self)32503251if self.is_sparse():3252v = dict([(i,z.derivative(var)) for i,z in self.dict().items()])3253else:3254v = [z.derivative(var) for z in self.list()]32553256return self.parent().ambient_module()(v)32573258def derivative(self, *args):3259"""3260Derivative with respect to variables supplied in args.32613262Multiple variables and iteration counts may be supplied; see3263documentation for the global derivative() function for more3264details.32653266:meth:`diff` is an alias of this function.32673268EXAMPLES::32693270sage: v = vector([1,x,x^2])3271sage: v.derivative(x)3272(0, 1, 2*x)3273sage: type(v.derivative(x)) == type(v)3274True3275sage: v = vector([1,x,x^2], sparse=True)3276sage: v.derivative(x)3277(0, 1, 2*x)3278sage: type(v.derivative(x)) == type(v)3279True3280sage: v.derivative(x,x)3281(0, 0, 2)3282"""3283return multi_derivative(self, args)32843285diff = derivative32863287def integral(self, *args, **kwds):3288"""3289Returns a symbolic integral of the vector, component-wise.32903291:meth:`integrate` is an alias of the function.32923293EXAMPLES::32943295sage: t=var('t')3296sage: r=vector([t,t^2,sin(t)])3297sage: r.integral(t)3298(1/2*t^2, 1/3*t^3, -cos(t))3299sage: integrate(r,t)3300(1/2*t^2, 1/3*t^3, -cos(t))3301sage: r.integrate(t,0,1)3302(1/2, 1/3, -cos(1) + 1)33033304"""3305from sage.misc.functional import integral33063307# If Cython supported lambda functions, we would just do3308# return self.apply_map(lambda x: integral(x,*args, **kwds) for x in self)33093310if self.is_sparse():3311v = dict([(i,integral(z,*args,**kwds)) for i,z in self.dict(copy=False).items()])3312else:3313v = [integral(z,*args,**kwds) for z in self.list()]33143315return vector(v,sparse=self.is_sparse())33163317integrate=integral331833193320def nintegral(self, *args, **kwds):3321"""3322Returns a numeric integral of the vector, component-wise, and3323the result of the nintegral command on each component of the3324input.33253326:meth:`nintegrate` is an alias of the function.33273328EXAMPLES::33293330sage: t=var('t')3331sage: r=vector([t,t^2,sin(t)])3332sage: vec,answers=r.nintegral(t,0,1)3333sage: vec3334(0.5, 0.333333333333, 0.459697694132)3335sage: type(vec)3336<type 'sage.modules.vector_real_double_dense.Vector_real_double_dense'>3337sage: answers3338[(0.5, 5.551115123125784e-15, 21, 0), (0.3333333333333..., 3.70074341541719e-15, 21, 0), (0.45969769413186..., 5.103669643922841e-15, 21, 0)]33393340sage: r=vector([t,0,1], sparse=True)3341sage: r.nintegral(t,0,1)3342((0.5, 0.0, 1.0), {0: (0.5, 5.551115123125784e-15, 21, 0), 2: (1.0, 1.11022302462515...e-14, 21, 0)})33433344"""3345# If Cython supported lambda functions, we would just do3346# return self.apply_map(lambda x: x.nintegral(*args, **kwds) for x in self)33473348if self.is_sparse():3349v = [(i,z.nintegral(*args,**kwds)) for i,z in self.dict(copy=False).items()]3350answers = dict([(i,a[0]) for i,a in v])3351v=dict(v)3352else:3353v = [z.nintegral(*args,**kwds) for z in self.list()]3354answers = [a[0] for a in v]33553356return (vector(answers,sparse=self.is_sparse()), v)33573358nintegrate=nintegral33593360#############################################3361# Generic dense element3362#############################################3363def make_FreeModuleElement_generic_dense(parent, entries, degree):3364"""3365EXAMPLES::33663367sage: sage.modules.free_module_element.make_FreeModuleElement_generic_dense(QQ^3, [1,2,-3/7], 3)3368(1, 2, -3/7)3369"""3370# If you think you want to change this function, don't.3371# Instead make a new version with a name like3372# make_FreeModuleElement_generic_dense_v13373# and changed the reduce method below.3374cdef FreeModuleElement_generic_dense v3375v = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)3376v._entries = entries3377v._parent = parent3378v._degree = degree3379return v33803381def make_FreeModuleElement_generic_dense_v1(parent, entries, degree, is_mutable):3382"""3383EXAMPLES::33843385sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_dense_v1(QQ^3, [1,2,-3/7], 3, True); v3386(1, 2, -3/7)3387sage: v[0] = 10; v3388(10, 2, -3/7)3389sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_dense_v1(QQ^3, [1,2,-3/7], 3, False); v3390(1, 2, -3/7)3391sage: v[0] = 103392Traceback (most recent call last):3393...3394ValueError: vector is immutable; please change a copy instead (use copy())3395"""3396# If you think you want to change this function, don't.3397# Instead make a new version with a name like3398# make_FreeModuleElement_generic_dense_v23399# and changed the reduce method below.3400cdef FreeModuleElement_generic_dense v3401v = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)3402v._entries = entries3403v._parent = parent3404v._degree = degree3405v._is_mutable = is_mutable3406return v34073408cdef class FreeModuleElement_generic_dense(FreeModuleElement):3409"""3410A generic dense element of a free module.3411"""3412## these work fine on the command line but fail in doctests :-(3413## TESTS:3414## sage: V = ZZ^33415## sage: loads(dumps(V)) == V3416## True3417## sage: v = V.03418## sage: loads(dumps(v)) == v3419## True3420## sage: v = (QQ['x']^3).03421## sage: loads(dumps(v)) == v3422## True3423cdef _new_c(self, object v):3424# Create a new dense free module element with minimal overhead and3425# no type checking.3426cdef FreeModuleElement_generic_dense x3427x = <FreeModuleElement_generic_dense>PY_NEW(<object>PY_TYPE(self))3428x._is_mutable = 13429x._parent = self._parent3430x._entries = v3431x._degree = self._degree3432return x34333434cdef bint is_dense_c(self):3435return 134363437cdef bint is_sparse_c(self):3438return 034393440def _hash(self):3441"""3442Return hash of an immutable form of self (works even if self3443is mutable).34443445sage: v = vector([-1,0,3,pi])3446sage: type(v)3447<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>3448sage: v._hash() # random output3449"""3450return hash(tuple(list(self)))34513452def __copy__(self):3453"""3454Return a copy of this generic dense vector.34553456EXAMPLES::34573458sage: v = vector([-1,0,3,pi])3459sage: type(v)3460<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>3461sage: v.__copy__()3462(-1, 0, 3, pi)3463sage: v.__copy__() is v3464False34653466sage: copy(v)3467(-1, 0, 3, pi)3468sage: copy(v) == v3469True3470sage: copy(v) is v3471False3472"""3473return self._new_c(list(self._entries))34743475def __init__(self, parent, entries, coerce=True, copy=True):3476"""3477EXAMPLES::34783479sage: type(vector([-1,0,3,pi])) # indirect doctest3480<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>34813482TESTS:34833484Check that #11751 is fixed::34853486sage: K.<x> = QQ[]3487sage: M = K^13488sage: N = M.span([[1/x]]); N3489Free module of degree 1 and rank 1 over Univariate Polynomial Ring in x over Rational Field3490Echelon basis matrix:3491[1/x]3492sage: N([1/x]) # this used to fail prior to #117513493(1/x)3494sage: N([1/x^2])3495Traceback (most recent call last):3496...3497TypeError: element (= [1/x^2]) is not in free module34983499::35003501sage: L=K^23502sage: R=L.span([[x,0],[0,1/x]], check=False, already_echelonized=True)3503sage: R.basis()[0][0].parent()3504Fraction Field of Univariate Polynomial Ring in x over Rational Field3505sage: R=L.span([[x,x^2]])3506sage: R.basis()[0][0].parent()3507Univariate Polynomial Ring in x over Rational Field3508"""3509FreeModuleElement.__init__(self, parent)3510R = self.parent().base_ring()3511if entries == 0:3512entries = [R(0)]*self.degree()3513else:3514if not isinstance(entries, (list, tuple)):3515raise TypeError("entries (=%s) must be a list"%(entries, ))35163517if len(entries) != self.degree():3518raise TypeError("entries must be a list of length %s"%\3519self.degree())3520if coerce:3521if len(entries) != 0:3522coefficient_ring = parent.basis()[0][0].parent()3523try:3524entries = [coefficient_ring(x) for x in entries]3525except TypeError:3526raise TypeError("Unable to coerce entries (=%s) to coefficients in %s"%(entries, coefficient_ring))3527elif copy:3528# Make a copy3529entries = list(entries)3530self._entries = entries35313532cpdef ModuleElement _add_(left, ModuleElement right):3533"""3534Add left and right.35353536EXAMPLES::35373538sage: v = vector([1,2/3,pi]); w = vector([-2/3,pi^2,1])3539sage: v._add_(w)3540(1/3, pi^2 + 2/3, pi + 1)3541"""3542cdef Py_ssize_t i, n3543n = PyList_Size(left._entries)3544v = [None]*n3545for i from 0 <= i < n:3546v[i] = (<RingElement>left._entries[i])._add_(<RingElement>3547((<FreeModuleElement_generic_dense>right)._entries[i]))3548return left._new_c(v)35493550cpdef ModuleElement _sub_(left, ModuleElement right):3551"""3552Subtract right from left.35533554EXAMPLES::35553556sage: V = QQ^53557sage: W = V.span([V.1, V.2])3558sage: W.0 - V.03559(-1, 1, 0, 0, 0)3560sage: V.0 - W.03561(1, -1, 0, 0, 0)3562"""3563cdef Py_ssize_t i, n3564n = PyList_Size(left._entries)3565v = [None]*n3566for i from 0 <= i < n:3567v[i] = (<RingElement>left._entries[i])._sub_(<RingElement>3568((<FreeModuleElement_generic_dense>right)._entries[i]))3569return left._new_c(v)35703571cpdef ModuleElement _rmul_(self, RingElement left):3572"""3573EXAMPLES::35743575sage: V = ZZ['x']^53576sage: 5 * V.03577(5, 0, 0, 0, 0)3578"""3579if left._parent is self._parent._base:3580v = [left._mul_(<RingElement>x) for x in self._entries]3581else:3582v = [left * x for x in self._entries]3583return self._new_c(v)35843585cpdef ModuleElement _lmul_(self, RingElement right):3586"""3587EXAMPLES::35883589sage: v = vector([-1,0,3,pi])3590sage: v._lmul_(2/3)3591(-2/3, 0, 2, 2/3*pi)3592sage: v * (2/3)3593(-2/3, 0, 2, 2/3*pi)3594"""3595if right._parent is self._parent._base:3596v = [(<RingElement>x)._mul_(right) for x in self._entries]3597else:3598v = [x * right for x in self._entries]3599return self._new_c(v)36003601cpdef Element _dot_product_(left, element_Vector right):3602"""3603Return the dot product of left and right.36043605EXAMPLES::36063607sage: R.<x> = QQ[]3608sage: v = vector([x,x^2,3*x]); w = vector([2*x,x,3+x])3609sage: v*w3610x^3 + 5*x^2 + 9*x3611sage: (x*2*x) + (x^2*x) + (3*x*(3+x))3612x^3 + 5*x^2 + 9*x3613sage: w*v3614x^3 + 5*x^2 + 9*x3615"""3616return left.dot_product(right)36173618cpdef element_Vector _pairwise_product_(left, element_Vector right):3619"""3620EXAMPLES::36213622sage: R.<x> = QQ[]3623sage: v = vector([x,x^2,3*x]); w = vector([2*x,x,3+x])3624sage: v.pairwise_product(w)3625(2*x^2, x^3, 3*x^2 + 9*x)3626sage: w.pairwise_product(v)3627(2*x^2, x^3, 3*x^2 + 9*x)3628"""3629if not right.parent() == left.parent():3630right = left.parent().ambient_module()(right)3631# Component wise vector * vector multiplication.3632cdef Py_ssize_t i, n3633n = PyList_Size(left._entries)3634v = [None]*n3635for i from 0 <= i < n:3636v[i] = (<RingElement>left._entries[i])._mul_((<FreeModuleElement_generic_dense>right)._entries[i])3637return left._new_c(v)36383639def __reduce__(self):3640"""3641EXAMPLES::36423643sage: v = vector([-1,0,3,pi])3644sage: v.__reduce__()3645(<built-in function make_FreeModuleElement_generic_dense_v1>, (Vector space of dimension 4 over Symbolic Ring, [-1, 0, 3, pi], 4, True))3646"""3647return (make_FreeModuleElement_generic_dense_v1, (self._parent, self._entries, self._degree, self._is_mutable))36483649def __getitem__(self, i):3650"""3651EXAMPLES::36523653sage: v = vector([RR(1), RR(2)]); v3654(1.00000000000000, 2.00000000000000)3655sage: v[0]36561.000000000000003657sage: v[-1]36582.000000000000003659sage: v[4]3660Traceback (most recent call last):3661...3662IndexError: index must be between -2 and 13663sage: v[-4]3664Traceback (most recent call last):3665...3666IndexError: index must be between -2 and 136673668sage: v = vector(QQ['x,y'], [1,2, 'x*y'])3669sage: v3670(1, 2, x*y)3671sage: v[1:]3672(2, x*y)3673"""3674if isinstance(i, slice):3675start, stop, step = i.indices(len(self))3676return vector(self.base_ring(), list(self)[start:stop:step])3677else:3678degree = self.degree()3679if i < 0:3680i += degree3681if i < 0 or i >= self.degree():3682raise IndexError("index must be between -%s and %s"%(degree, degree-1))3683return self._entries[i]36843685def __setitem__(self, i, value):3686"""3687Set entry i of self to value.36883689EXAMPLES::36903691sage: v = vector([1,2/3,pi])3692sage: v[1] = 19+pi3693sage: v3694(1, pi + 19, pi)3695sage: v = vector(QQ['x,y'], [1,2, 'x*y'])3696sage: v3697(1, 2, x*y)3698sage: v[1:]3699(2, x*y)3700sage: v[1:] = [4,5]; v3701(1, 4, 5)3702sage: v[:2] = [5,(6,2)]; v3703(5, 3, 5)3704sage: v[:2]3705(5, 3)3706"""3707if not self._is_mutable:3708raise ValueError("vector is immutable; please change a copy instead (use copy())")3709cdef Py_ssize_t k, n, d3710if isinstance(i, slice):3711start, stop, step = i.indices(len(self))3712d = self.degree()3713R = self.base_ring()3714n = 03715for k from start <= k < stop:3716if k >= d:3717return3718if k >= 0:3719self._entries[k] = R(value[n])3720n = n + 13721else:3722if i < 0 or i >= self.degree():3723raise IndexError("index (i=%s) must be between 0 and %s"%(i,3724self.degree()-1))3725self._entries[i] = self.base_ring()(value)37263727def list(self, copy=True):3728"""3729Return list of elements of self.37303731INPUT:37323733- copy -- bool, return list of underlying entries37343735EXAMPLES::37363737sage: P.<x,y,z> = QQ[]3738sage: v = vector([x,y,z])3739sage: type(v)3740<type 'sage.modules.free_module_element.FreeModuleElement_generic_dense'>3741sage: a = v.list(); a3742[x, y, z]3743sage: a[0] = x*y; v3744(x, y, z)3745sage: a = v.list(copy=False); a3746[x, y, z]3747sage: a[0] = x*y; v3748(x*y, y, z)3749"""3750if copy:3751return list(self._entries)3752else:3753return self._entries37543755cdef int _cmp_c_impl(left, Element right) except -2:3756"""3757Compare two free module elements with identical parents.37583759Free module elements are compared in lexicographic order on3760the underlying list of coefficients. Two free module elements3761are equal if their coefficients are the same. (This is true3762even if one is sparse and one is dense.)3763"""3764return cmp(left._entries, (<FreeModuleElement_generic_dense>right)._entries)37653766def __call__(self, *args, **kwargs):3767"""3768Calling a free module element returns the result of calling each3769component.37703771EXAMPLES::37723773sage: x, y = var('x,y')3774sage: f = x^2 + y^23775sage: g = f.gradient()3776sage: g3777(2*x, 2*y)3778sage: type(g)3779<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>3780sage: g(y=2, x=3)3781(6, 4)3782sage: f(x,y) = x^2 + y^23783sage: g = f.gradient()3784sage: g(3,2)3785(6, 4)3786sage: g(x=3, y=2)3787(6, 4)3788"""3789return vector([e(*args, **kwargs) for e in self])37903791def function(self, *args):3792"""3793Returns a vector over a callable symbolic expression ring.37943795EXAMPLES::37963797sage: x,y=var('x,y')3798sage: v=vector([x,y,x*sin(y)])3799sage: w=v.function([x,y]); w3800(x, y) |--> (x, y, x*sin(y))3801sage: w.base_ring()3802Callable function ring with arguments (x, y)3803sage: w(1,2)3804(1, 2, sin(2))3805sage: w(2,1)3806(2, 1, 2*sin(1))3807sage: w(y=1,x=2)3808(2, 1, 2*sin(1))38093810::38113812sage: x,y=var('x,y')3813sage: v=vector([x,y,x*sin(y)])3814sage: w=v.function([x]); w3815x |--> (x, y, x*sin(y))3816sage: w.base_ring()3817Callable function ring with arguments (x,)3818sage: w(4)3819(4, y, 4*sin(y))3820"""3821from sage.symbolic.callable import CallableSymbolicExpressionRing3822return vector(CallableSymbolicExpressionRing(args), self.list())38233824#############################################3825# Generic sparse element3826#############################################3827def _sparse_dot_product(v, w):3828"""3829v and w are dictionaries with integer keys.38303831EXAMPLES::38323833sage: sage.modules.free_module_element._sparse_dot_product({0:5,1:7,2:3}, {0:-1, 2:2})383413835"""3836x = set(v.keys()).intersection(set(w.keys()))3837return sum([v[k]*w[k] for k in x])38383839def make_FreeModuleElement_generic_sparse(parent, entries, degree):3840"""3841EXAMPLES::38423843sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_sparse(QQ^3, {2:5/2}, 3); v3844(0, 0, 5/2)3845"""3846cdef FreeModuleElement_generic_sparse v3847v = FreeModuleElement_generic_sparse.__new__(FreeModuleElement_generic_sparse)3848v._entries = entries3849v._parent = parent3850v._degree = degree3851return v38523853def make_FreeModuleElement_generic_sparse_v1(parent, entries, degree, is_mutable):3854"""3855EXAMPLES::38563857sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_sparse_v1(QQ^3, {2:5/2}, 3, False); v3858(0, 0, 5/2)3859sage: v.is_mutable()3860False3861"""3862cdef FreeModuleElement_generic_sparse v3863v = FreeModuleElement_generic_sparse.__new__(FreeModuleElement_generic_sparse)3864v._entries = entries3865v._parent = parent3866v._degree = degree3867v._is_mutable = is_mutable3868return v38693870cdef class FreeModuleElement_generic_sparse(FreeModuleElement):3871"""3872A generic sparse free module element is a dictionary with keys ints3873i and entries in the base ring.38743875EXAMPLES:38763877Pickling works::38783879sage: v = FreeModule(ZZ, 3, sparse=True).03880sage: loads(dumps(v)) == v3881True3882sage: v = FreeModule(Integers(8)['x,y'], 5, sparse=True).13883sage: loads(dumps(v)) - v3884(0, 0, 0, 0, 0)38853886::38873888sage: a = vector([-1,0,1/1],sparse=True); b = vector([-1/1,0,0],sparse=True)3889sage: a.parent()3890Sparse vector space of dimension 3 over Rational Field3891sage: b - a3892(0, 0, -1)3893sage: (b-a).dict()3894{2: -1}3895"""3896cdef _new_c(self, object v):3897# Create a new sparse free module element with minimal overhead and3898# no type checking.3899cdef FreeModuleElement_generic_sparse x3900x = PY_NEW(FreeModuleElement_generic_sparse)3901x._is_mutable = 13902x._parent = self._parent3903x._entries = v3904x._degree = self._degree3905return x39063907cdef bint is_dense_c(self):3908return 039093910cdef bint is_sparse_c(self):3911return 139123913def __copy__(self):3914"""3915EXAMPLES::39163917sage: v = vector([1,2/3,pi], sparse=True)3918sage: v.__copy__()3919(1, 2/3, pi)3920"""3921return self._new_c(dict(self._entries))39223923def __init__(self, parent,3924entries=0,3925coerce=True,3926copy=True):3927"""3928EXAMPLES::39293930sage: v = sage.modules.free_module_element.FreeModuleElement_generic_sparse(VectorSpace(QQ,3,sparse=True), {1:5/4}); v3931(0, 5/4, 0)3932sage: v.is_sparse()3933True39343935TESTS:39363937Test that 11751 is fixed::39383939sage: K.<x> = QQ[]3940sage: M = FreeModule(K, 1, sparse=True)3941sage: N = M.span([{0:1/x}]); N3942Sparse free module of degree 1 and rank 1 over Univariate Polynomial Ring in x over Rational Field3943Echelon basis matrix:3944[1/x]3945sage: N({0:1/x}) # this used to fail prior to #117513946(1/x)3947sage: N({0:1/x^2})3948Traceback (most recent call last):3949...3950TypeError: element (= {0: 1/x^2}) is not in free module39513952::39533954sage: L = FreeModule(K, 2, sparse=True)3955sage: R = L.span([{0:x, 1:0}, {0:0, 1:1/x}], check=False, already_echelonized=True)3956sage: R.basis()[0][0].parent()3957Fraction Field of Univariate Polynomial Ring in x over Rational Field3958sage: R = L.span([{0:x, 1:x^2}])3959sage: R.basis()[0][0].parent()3960Univariate Polynomial Ring in x over Rational Field3961"""3962#WARNING: In creation, we do not check that the i pairs satisfy3963# 0 <= i < degree.3964FreeModuleElement.__init__(self, parent)3965R = self.base_ring()3966if entries == 0:3967entries = {}3968else:3969if isinstance(entries, list):3970if len(entries) != self.degree():3971raise TypeError("entries has the wrong length")3972x = entries3973entries = {}3974for i in xrange(self.degree()):3975if x[i] != 0:3976entries[i] = x[i]3977copy = False3978if not isinstance(entries, dict):3979raise TypeError, "entries must be a dict"3980if copy:3981# Make a copy3982entries = dict(entries)3983if coerce:3984if len(entries) != 0:3985coefficient_ring = parent.basis()[0][0].parent()3986try:3987for k, x in entries.iteritems():3988entries[k] = coefficient_ring(x)3989except TypeError:3990raise TypeError("Unable to coerce value (=%s) of entries dict (=%s) to %s"%(x, entries, coefficient_ring))3991self._entries = entries39923993cpdef ModuleElement _add_(left, ModuleElement right):3994"""3995Add left and right.39963997EXAMPLES::39983999sage: v = vector([1,2/3,pi], sparse=True)4000sage: v._add_(v)4001(2, 4/3, 2*pi)4002"""4003cdef object v, e4004e = dict((<FreeModuleElement_generic_sparse>right)._entries)4005for i, a in left._entries.iteritems():4006if e.has_key(i):4007sum = (<RingElement>a)._add_(<RingElement> e[i])4008if sum:4009e[i] = sum4010else:4011del e[i]4012elif a:4013e[i] = a4014return left._new_c(e)40154016cpdef ModuleElement _sub_(left, ModuleElement right):4017"""4018EXAMPLES::40194020sage: v = vector([1,2/3,pi], sparse=True)4021sage: v._sub_(v)4022(0, 0, 0)4023"""4024cdef object v, e4025e = dict(left._entries) # dict to make a copy4026for i, a in (<FreeModuleElement_generic_sparse>right)._entries.iteritems():4027if e.has_key(i):4028diff = (<RingElement> e[i])._sub_(<RingElement>a)4029if diff:4030e[i] = diff4031else:4032del e[i]4033elif a:4034e[i] = -a4035return left._new_c(e)40364037cpdef ModuleElement _lmul_(self, RingElement right):4038"""4039EXAMPLES::40404041sage: v = vector([1,2/3,pi], sparse=True)4042sage: v._lmul_(SR(3))4043(3, 2, 3*pi)4044"""4045cdef object v4046v = PyDict_New()4047if right:4048for i, a in self._entries.iteritems():4049prod = (<RingElement>a)._mul_(right)4050if prod:4051v[i] = prod4052return self._new_c(v)40534054cpdef ModuleElement _rmul_(self, RingElement left):4055"""4056EXAMPLES::40574058sage: v = vector([1,2/3,pi], sparse=True)4059sage: v._rmul_(SR(3))4060(3, 2, 3*pi)4061"""4062cdef object v4063v = PyDict_New()4064if left:4065for i, a in self._entries.iteritems():4066prod = left._mul_(a)4067if prod:4068v[i] = prod4069return self._new_c(v)40704071cpdef Element _dot_product_(left, element_Vector right):4072"""4073Return the dot product of left and right.40744075EXAMPLES::40764077sage: v = vector([1,2,0], sparse=True); w = vector([0,5,-9], sparse=True)4078sage: v * w4079104080sage: w * v4081104082"""4083cdef object v, e, z4084e = dict((<FreeModuleElement_generic_sparse>right)._entries)4085z = left.base_ring()(0)4086for i, a in left._entries.iteritems():4087if e.has_key(i):4088z += (<RingElement>a)._mul_(<RingElement> e[i])4089return z40904091cpdef element_Vector _pairwise_product_(left, element_Vector right):4092"""4093EXAMPLES::40944095sage: v = vector([1,2/3,pi], sparse=True); w = vector([-2/3,pi^2,1],sparse=True)4096sage: v._pairwise_product_(w)4097(-2/3, 2/3*pi^2, pi)4098"""4099# Component wise vector * vector multiplication.4100cdef object v, e4101e = dict((<FreeModuleElement_generic_sparse>right)._entries)4102v = PyDict_New()4103for i, a in left._entries.iteritems():4104if e.has_key(i):4105prod = (<RingElement>a)._mul_(<RingElement> e[i])4106if prod:4107v[i] = prod4108return left._new_c(v)41094110cdef int _cmp_c_impl(left, Element right) except -2:4111"""4112Compare two sparse free module elements.41134114Free module elements are compared in lexicographic order on4115the underlying list of coefficients. Two free module elements4116are equal if their coefficients are the same. (This is true4117even if one is sparse and one is dense.)4118"""4119a = left._entries.items()4120a.sort()4121b = (<FreeModuleElement_generic_dense>right)._entries.items()4122b.sort()4123return cmp(a,b)41244125def iteritems(self):4126"""4127Return iterator over the entries of self.41284129EXAMPLES::41304131sage: v = vector([1,2/3,pi], sparse=True)4132sage: v.iteritems()4133<dictionary-itemiterator object at ...>4134sage: list(v.iteritems())4135[(0, 1), (1, 2/3), (2, pi)]4136"""4137return self._entries.iteritems()41384139def __reduce__(self):4140"""4141EXAMPLES::41424143sage: v = vector([1,2/3,pi], sparse=True)4144sage: v.__reduce__()4145(<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))4146"""4147return (make_FreeModuleElement_generic_sparse_v1, (self._parent, self._entries, self._degree, self._is_mutable))41484149def __getitem__(self, i):4150"""4151EXAMPLES::41524153sage: v = vector([RR(1), RR(2)], sparse=True); v4154(1.00000000000000, 2.00000000000000)4155sage: v[0]41561.000000000000004157sage: v[-1]41582.000000000000004159sage: v[5]4160Traceback (most recent call last):4161...4162IndexError: index must be between -2 and 14163sage: v[-3]4164Traceback (most recent call last):4165...4166IndexError: index must be between -2 and 14167"""4168if isinstance(i, slice):4169start, stop, step = i.indices(len(self))4170return vector(self.base_ring(), self.list()[start:stop])4171else:4172i = int(i)4173degree = self.degree()4174if i < 0:4175i += degree4176if i < 0 or i >= degree:4177raise IndexError("index must be between %s and %s"%(-degree,4178degree-1))4179if self._entries.has_key(i):4180return self._entries[i]4181return self.base_ring()(0) # optimize this somehow41824183def get(self, i):4184"""4185Like __getitem__ but with no guaranteed type or bounds checking. Returns 04186if access is out of bounds.41874188EXAMPLES::41894190sage: v = vector([1,2/3,pi], sparse=True)4191sage: v.get(1)41922/34193sage: v.get(10)419404195"""4196i = int(i)4197if self._entries.has_key(i):4198return self._entries[i]4199return self.base_ring()(0) # optimize this somehow420042014202def set(self, i, x):4203"""4204Like __setitem__ but with no guaranteed type or bounds checking.42054206EXAMPLES::42074208sage: v = vector([1,2/3,pi], sparse=True)4209sage: v.set(1, pi^3)4210sage: v4211(1, pi^3, pi)42124213No bounds checking::42144215sage: v.set(10, pi)42164217This lack of bounds checking causes trouble later::42184219sage: v4220Traceback (most recent call last):4221...4222IndexError: list assignment index out of range4223"""4224if not self._is_mutable:4225raise ValueError("vector is immutable; please change a copy instead (use copy())")4226i = int(i)4227if x == 0:4228if self._entries.has_key(i):4229del self._entries[i]4230return4231self._entries[i] = x42324233def __setitem__(self, i, value):4234"""4235Set the `i`-th entry or slice of self to value.42364237EXAMPLES::42384239sage: V = VectorSpace(GF(17), 10000000, sparse=True)4240sage: w = V(0)4241sage: w[39893] = 204242sage: w[39893]424334244sage: w[39000:39003] = [4, 5, 6]; w[39000:39003]4245(4, 5, 6)4246sage: parent(w[39893])4247Finite Field of size 174248sage: w[39893] = sqrt(2)4249Traceback (most recent call last):4250...4251TypeError: unable to convert x (=sqrt(2)) to an integer4252"""4253if not self._is_mutable:4254raise ValueError("vector is immutable; please change a copy instead (use copy())")4255cdef Py_ssize_t k, d, n4256if isinstance(i, slice):4257start, stop = i.start, i.stop4258d = self.degree()4259R = self.base_ring()4260n = 04261for k from start <= k < stop:4262if k >= d:4263return4264if k >= 0:4265self[k] = R(value[n])4266n = n + 14267else:4268i = int(i)4269if i < 0 or i >= self.degree():4270raise IndexError("index (i=%s) must be between 0 and %s"%(i,4271self.degree()-1))4272self.set(i, self._parent.base_ring()(value))42734274def denominator(self):4275"""4276Return the least common multiple of the denominators of the4277entries of self.42784279EXAMPLES::42804281sage: v = vector([1/2,2/5,3/14], sparse=True)4282sage: v.denominator()4283704284"""4285R = self.base_ring()4286x = self._entries4287if len(x) == 0:4288return 14289Z = x.iteritems()4290d = Z.next()[1].denominator()4291for _, y in Z:4292d = d.lcm(y.denominator())4293return d42944295def dict(self, copy=True):4296"""4297Return dictionary of nonzero entries of self.42984299INPUT:43004301- ``copy`` -- bool (default: True)43024303OUTPUT:43044305- Python dictionary43064307EXAMPLES::43084309sage: v = vector([0,0,0,0,1/2,0,3/14], sparse=True)4310sage: v.dict()4311{4: 1/2, 6: 3/14}4312"""4313if copy:4314return dict(self._entries)4315else:4316return self._entries43174318def list(self, copy=True):4319"""4320Return list of elements of self.43214322INPUT:43234324- copy -- bool, return list of underlying entries43254326EXAMPLES::43274328sage: v = vector([1,2/3,pi], sparse=True)4329sage: type(v)4330<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>4331sage: a = v.list(); a4332[1, 2/3, pi]4333"""4334cdef Py_ssize_t n4335n = self._parent.degree()4336z = self._parent.base_ring()(0)4337v = [z]*n4338for i, a in self._entries.iteritems():4339v[i] = a4340return v43414342def nonzero_positions(self):4343"""4344Returns the list of numbers i such that self[i] != 0.43454346EXAMPLES::43474348sage: v = vector({1: 1, 3: -2})4349sage: w = vector({1: 4, 3: 2})4350sage: v+w4351(0, 5, 0, 0)4352sage: (v+w).nonzero_positions()4353[1]4354"""4355K = self._entries.keys()4356K.sort()4357return K435843594360def _numerical_approx(self, prec=None, digits=None):4361"""4362Returns a numerical approximation of self by calling the n() method4363on all of its entries.43644365EXAMPLES::43664367sage: v = vector(RealField(200), [1,2,3], sparse=True)4368sage: v.n()4369(1.00000000000000, 2.00000000000000, 3.00000000000000)4370sage: _.parent()4371Sparse vector space of dimension 3 over Real Field with 53 bits of precision4372sage: v.n(prec=75)4373(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)4374sage: _.parent()4375Sparse vector space of dimension 3 over Real Field with 75 bits of precision4376"""4377return vector(dict([(e[0],e[1].n(prec, digits)) for e in self._entries.iteritems()]), sparse=True)4378437943804381