Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/modules/free_module_element.pyx
4045 views
1
r"""
2
Elements of free modules
3
4
AUTHORS:
5
6
- William Stein
7
8
- Josh Kantor
9
10
TODO: Change to use a get_unsafe / set_unsafe, etc., structure
11
exactly like with matrices, since we'll have to define a bunch of
12
special purpose implementations of vectors easily and
13
systematically.
14
15
EXAMPLES: We create a vector space over `\QQ` and a
16
subspace of this space.
17
18
::
19
20
sage: V = QQ^5
21
sage: W = V.span([V.1, V.2])
22
23
Arithmetic operations always return something in the ambient space,
24
since there is a canonical map from `W` to `V` but
25
not from `V` to `W`.
26
27
::
28
29
sage: parent(W.0 + V.1)
30
Vector space of dimension 5 over Rational Field
31
sage: parent(V.1 + W.0)
32
Vector space of dimension 5 over Rational Field
33
sage: W.0 + V.1
34
(0, 2, 0, 0, 0)
35
sage: W.0 - V.0
36
(-1, 1, 0, 0, 0)
37
38
Next we define modules over `\ZZ` and a finite
39
field.
40
41
::
42
43
sage: K = ZZ^5
44
sage: M = GF(7)^5
45
46
Arithmetic between the `\QQ` and
47
`\ZZ` modules is defined, and the result is always
48
over `\QQ`, since there is a canonical coercion map
49
to `\QQ`.
50
51
::
52
53
sage: K.0 + V.1
54
(1, 1, 0, 0, 0)
55
sage: parent(K.0 + V.1)
56
Vector space of dimension 5 over Rational Field
57
58
Since there is no canonical coercion map to the finite field from
59
`\QQ` the following arithmetic is not defined::
60
61
sage: V.0 + M.0
62
Traceback (most recent call last):
63
...
64
TypeError: 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'
65
66
However, there is a map from `\ZZ` to the finite
67
field, so the following is defined, and the result is in the finite
68
field.
69
70
::
71
72
sage: w = K.0 + M.0; w
73
(2, 0, 0, 0, 0)
74
sage: parent(w)
75
Vector space of dimension 5 over Finite Field of size 7
76
sage: parent(M.0 + K.0)
77
Vector space of dimension 5 over Finite Field of size 7
78
79
Matrix vector multiply::
80
81
sage: MS = MatrixSpace(QQ,3)
82
sage: A = MS([0,1,0,1,0,0,0,0,1])
83
sage: V = QQ^3
84
sage: v = V([1,2,3])
85
sage: v * A
86
(2, 1, 3)
87
88
TESTS::
89
90
sage: D = 46341
91
sage: u = 7
92
sage: R = Integers(D)
93
sage: p = matrix(R,[[84, 97, 55, 58, 51]])
94
sage: 2*p.row(0)
95
(168, 194, 110, 116, 102)
96
"""
97
98
import math
99
import operator
100
101
include '../ext/cdefs.pxi'
102
include '../ext/stdsage.pxi'
103
import sage.misc.misc as misc
104
import sage.misc.latex
105
106
from sage.structure.sequence import Sequence
107
108
from sage.structure.element cimport Element, ModuleElement, RingElement, Vector as element_Vector
109
from sage.structure.element import canonical_coercion
110
111
import sage.rings.arith
112
113
from sage.rings.infinity import Infinity
114
import sage.rings.integer
115
from sage.rings.integer_ring import ZZ
116
from sage.rings.real_double import RDF
117
from sage.rings.complex_double import CDF
118
from sage.misc.derivative import multi_derivative
119
120
121
# We use some cimports for very quick checking of Integer and Ring
122
# type to optimize vector(ring,n) for creating the zero vector.
123
from sage.rings.ring cimport Ring
124
from sage.rings.integer cimport Integer
125
126
# We define our own faster is_Ring since is_Ring in the
127
# sage.rings.ring module is slow due to it doing an import every time,
128
# and creating a category. We should rarely hit the second case
129
# (is_Ring_slow below). Note that this function will slightly slow
130
# down in the very rare case when R is not of type Ring, but it is in
131
# the category of rings. But it gives a big speedup for the most
132
# common case when R is a Ring.
133
from sage.rings.ring import is_Ring as is_Ring_slow
134
cdef is_Ring(R):
135
return isinstance(R, Ring) or is_Ring_slow(R)
136
137
def is_FreeModuleElement(x):
138
"""
139
EXAMPLES::
140
141
sage: sage.modules.free_module_element.is_FreeModuleElement(0)
142
False
143
sage: sage.modules.free_module_element.is_FreeModuleElement(vector([1,2,3]))
144
True
145
"""
146
return isinstance(x, FreeModuleElement)
147
148
def vector(arg0, arg1=None, arg2=None, sparse=None):
149
r"""
150
Return a vector or free module element with specified entries.
151
152
CALL FORMATS:
153
154
This constructor can be called in several different ways.
155
In each case, ``sparse=True`` or ``sparse=False`` can be
156
supplied as an option. ``free_module_element()`` is an
157
alias for ``vector()``.
158
159
1. vector(object)
160
161
2. vector(ring, object)
162
163
3. vector(object, ring)
164
165
4. vector(ring, degree, object)
166
167
5. vector(ring, degree)
168
169
6. vector(numpy_array)
170
171
INPUT:
172
173
- ``object`` - a list, dictionary, or other
174
iterable containing the entries of the vector, including
175
any object that is palatable to the ``Sequence`` constructor
176
177
- ``ring`` - a base ring (or field) for the vector
178
space or free module, which contains all of the elements
179
180
- ``degree`` - an integer specifying the number of
181
entries in the vector or free module element
182
183
- ``numpy_array`` - a NumPy array with the desired entries
184
185
- ``sparse`` - optional
186
187
In call format 4, an error is raised if the ``degree`` does not match
188
the length of ``object`` so this call can provide some safeguards.
189
Note however that using this format when ``object`` is a dictionary
190
is unlikely to work properly.
191
192
OUTPUT:
193
194
An element of the vector space or free module with the given
195
base ring and implied or specified dimension or rank,
196
containing the specified entries and with correct degree.
197
198
In call format 5, no entries are specified, so the element is
199
populated with all zeros.
200
201
If the ``sparse`` option is not supplied, the output will
202
generally have a dense representation. The exception is if
203
``object`` is a dictionary, then the representation will be sparse.
204
205
EXAMPLES::
206
207
sage: v = vector([1,2,3]); v
208
(1, 2, 3)
209
sage: v.parent()
210
Ambient free module of rank 3 over the principal ideal domain Integer Ring
211
sage: v = vector([1,2,3/5]); v
212
(1, 2, 3/5)
213
sage: v.parent()
214
Vector space of dimension 3 over Rational Field
215
216
All entries must *canonically* coerce to some common ring::
217
218
sage: v = vector([17, GF(11)(5), 19/3]); v
219
Traceback (most recent call last):
220
...
221
TypeError: unable to find a common ring for all elements
222
223
::
224
225
sage: v = vector([17, GF(11)(5), 19]); v
226
(6, 5, 8)
227
sage: v.parent()
228
Vector space of dimension 3 over Finite Field of size 11
229
sage: v = vector([17, GF(11)(5), 19], QQ); v
230
(17, 5, 19)
231
sage: v.parent()
232
Vector space of dimension 3 over Rational Field
233
sage: v = vector((1,2,3), QQ); v
234
(1, 2, 3)
235
sage: v.parent()
236
Vector space of dimension 3 over Rational Field
237
sage: v = vector(QQ, (1,2,3)); v
238
(1, 2, 3)
239
sage: v.parent()
240
Vector space of dimension 3 over Rational Field
241
sage: v = vector(vector([1,2,3])); v
242
(1, 2, 3)
243
sage: v.parent()
244
Ambient free module of rank 3 over the principal ideal domain Integer Ring
245
246
You can also use ``free_module_element``, which is
247
the same as ``vector``. ::
248
249
sage: free_module_element([1/3, -4/5])
250
(1/3, -4/5)
251
252
We make a vector mod 3 out of a vector over `\ZZ`. ::
253
254
sage: vector(vector([1,2,3]), GF(3))
255
(1, 2, 0)
256
257
The degree of a vector may be specified::
258
259
sage: vector(QQ, 4, [1,1/2,1/3,1/4])
260
(1, 1/2, 1/3, 1/4)
261
262
But it is an error if the degree and size of the list of entries
263
are mismatched::
264
265
sage: vector(QQ, 5, [1,1/2,1/3,1/4])
266
Traceback (most recent call last):
267
...
268
ValueError: incompatible degrees in vector constructor
269
270
Providing no entries populates the vector with zeros, but of course,
271
you must specify the degree since it is not implied. Here we use a
272
finite field as the base ring. ::
273
274
sage: w = vector(FiniteField(7), 4); w
275
(0, 0, 0, 0)
276
sage: w.parent()
277
Vector space of dimension 4 over Finite Field of size 7
278
279
The fastest method to construct a zero vector is to call the
280
:meth:`~sage.modules.free_module.FreeModule_generic.zero_vector`
281
method directly on a free module or vector space, since
282
vector(...) must do a small amount of type checking. Almost as
283
fast as the ``zero_vector()`` method is the
284
:func:`~sage.modules.free_module_element.zero_vector` constructor,
285
which defaults to the integers. ::
286
287
sage: vector(ZZ, 5) # works fine
288
(0, 0, 0, 0, 0)
289
sage: (ZZ^5).zero_vector() # very tiny bit faster
290
(0, 0, 0, 0, 0)
291
sage: zero_vector(ZZ, 5) # similar speed to vector(...)
292
(0, 0, 0, 0, 0)
293
sage: z = zero_vector(5); z
294
(0, 0, 0, 0, 0)
295
sage: z.parent()
296
Ambient free module of rank 5 over
297
the principal ideal domain Integer Ring
298
299
Here we illustrate the creation of sparse vectors by using a
300
dictionary. ::
301
302
sage: vector({1:1.1, 3:3.14})
303
(0.000000000000000, 1.10000000000000, 0.000000000000000, 3.14000000000000)
304
305
With no degree given, a dictionary of entries implicitly declares a
306
degree by the largest index (key) present. So you can provide a
307
terminal element (perhaps a zero?) to set the degree. But it is probably safer
308
to just include a degree in your construction. ::
309
310
sage: v = vector(QQ, {0:1/2, 4:-6, 7:0}); v
311
(1/2, 0, 0, 0, -6, 0, 0, 0)
312
sage: v.degree()
313
8
314
sage: v.is_sparse()
315
True
316
sage: w = vector(QQ, 8, {0:1/2, 4:-6})
317
sage: w == v
318
True
319
320
It is an error to specify a negative degree. ::
321
322
sage: vector(RR, -4, [1.0, 2.0, 3.0, 4.0])
323
Traceback (most recent call last):
324
...
325
ValueError: cannot specify the degree of a vector as a negative integer (-4)
326
327
It is an error to create a zero vector but not provide
328
a ring as the first argument. ::
329
330
sage: vector('junk', 20)
331
Traceback (most recent call last):
332
...
333
TypeError: first argument must be base ring of zero vector, not junk
334
335
And it is an error to specify an index in a dictionary
336
that is greater than or equal to a requested degree. ::
337
338
sage: vector(ZZ, 10, {3:4, 7:-2, 10:637})
339
Traceback (most recent call last):
340
...
341
ValueError: dictionary of entries has a key (index) exceeding the requested degree
342
343
Any 1 dimensional numpy array of type float or complex may be
344
passed to vector. The result will be a vector in the appropriate
345
dimensional vector space over the real double field or the complex
346
double field. The data in the array must be contiguous so
347
column-wise slices of numpy matrices will raise an exception. ::
348
349
sage: import numpy
350
sage: x=numpy.random.randn(10)
351
sage: y=vector(x)
352
sage: v=numpy.random.randn(10)*numpy.complex(0,1)
353
sage: w=vector(v)
354
355
If any of the arguments to vector have Python type int, long, real,
356
or complex, they will first be coerced to the appropriate Sage
357
objects. This fixes trac #3847. ::
358
359
sage: v = vector([int(0)]); v
360
(0)
361
sage: v[0].parent()
362
Integer Ring
363
sage: v = vector(range(10)); v
364
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
365
sage: v[3].parent()
366
Integer Ring
367
sage: v = vector([float(23.4), int(2), complex(2+7*I), long(1)]); v
368
(23.4, 2.0, 2.0 + 7.0*I, 1.0)
369
sage: v[1].parent()
370
Complex Double Field
371
372
If the argument is a vector, it doesn't change the base ring. This
373
fixes trac #6643. ::
374
375
sage: K.<sqrt3> = QuadraticField(3)
376
sage: u = vector(K, (1/2, sqrt3/2) )
377
sage: vector(u).base_ring()
378
Number Field in sqrt3 with defining polynomial x^2 - 3
379
sage: v = vector(K, (0, 1) )
380
sage: vector(v).base_ring()
381
Number Field in sqrt3 with defining polynomial x^2 - 3
382
383
Constructing a vector from a numpy array behaves as expected::
384
385
sage: import numpy
386
sage: a=numpy.array([1,2,3])
387
sage: v=vector(a); v
388
(1, 2, 3)
389
sage: parent(v)
390
Ambient free module of rank 3 over the principal ideal domain Integer Ring
391
392
Complex numbers can be converted naturally to a sequence of length 2. And
393
then to a vector. ::
394
395
sage: c = CDF(2 + 3*I)
396
sage: v = vector(c); v
397
(2.0, 3.0)
398
399
A generator, or other iterable, may also be supplied as input. Anything
400
that can be converted to a :class:`~sage.structure.sequence.Sequence` is
401
a possible input. ::
402
403
sage: type(i^2 for i in range(3))
404
<type 'generator'>
405
sage: v = vector(i^2 for i in range(3)); v
406
(0, 1, 4)
407
408
An empty list, without a ring given, will default to the integers. ::
409
410
sage: x = vector([]); x
411
()
412
sage: x.parent()
413
Ambient free module of rank 0 over the principal ideal domain Integer Ring
414
"""
415
# We first efficiently handle the important special case of the zero vector
416
# over a ring. See trac 11657.
417
# !! PLEASE DO NOT MOVE THIS CODE LOWER IN THIS FUNCTION !!
418
if arg2 is None and is_Ring(arg0) and (isinstance(arg1, (int, long, Integer))):
419
return (arg0**arg1).zero_vector()
420
421
# WARNING TO FUTURE OPTIMIZERS: The following two hasattr's take
422
# quite a significant amount of time.
423
if hasattr(arg0, '_vector_'):
424
return arg0._vector_(arg1)
425
426
if hasattr(arg1, '_vector_'):
427
return arg1._vector_(arg0)
428
429
# consider a possible degree specified in second argument
430
degree = None
431
maxindex = None
432
if sage.rings.integer.is_Integer(arg1) or isinstance(arg1,(int,long)):
433
if arg1 < 0:
434
raise ValueError("cannot specify the degree of a vector as a negative integer (%s)" % arg1)
435
if isinstance(arg2, dict):
436
maxindex = max([-1]+[index for index in arg2])
437
if not maxindex < arg1:
438
raise ValueError("dictionary of entries has a key (index) exceeding the requested degree")
439
# arg1 is now a legitimate degree
440
# With no arg2, we can try to return a zero vector
441
# else we size-check arg2 and slide it into arg1
442
degree = arg1
443
if arg2 is None:
444
if not is_Ring(arg0):
445
msg = "first argument must be base ring of zero vector, not {0}"
446
raise TypeError(msg.format(arg0))
447
else:
448
if not isinstance(arg2, dict) and len(arg2) != degree:
449
raise ValueError("incompatible degrees in vector constructor")
450
arg1 = arg2
451
452
# Analyze arg0 and arg1 to create a ring (R) and entries (v)
453
if is_Ring(arg0):
454
R = arg0
455
v = arg1
456
elif is_Ring(arg1):
457
R = arg1
458
v = arg0
459
else:
460
v = arg0
461
R = None
462
463
from numpy import ndarray
464
from free_module import VectorSpace
465
if isinstance(v,ndarray):
466
if len(v.shape)==1:
467
if str(v.dtype).count('float')==1:
468
V=VectorSpace(RDF,v.shape[0])
469
import vector_real_double_dense
470
_v=vector_real_double_dense.Vector_real_double_dense(V, v)
471
return _v
472
if str(v.dtype).count('complex')==1:
473
V=VectorSpace(CDF,v.shape[0])
474
import vector_complex_double_dense
475
_v=vector_complex_double_dense.Vector_complex_double_dense(V, v)
476
return _v
477
478
if isinstance(v, dict):
479
if degree is None:
480
degree = max([-1]+[index for index in v])+1
481
if sparse is None:
482
sparse = True
483
else:
484
degree = None
485
if sparse is None:
486
sparse = False
487
488
v, R = prepare(v, R, degree)
489
490
if sparse:
491
import free_module # slow -- can we improve
492
return free_module.FreeModule(R, len(v), sparse=True)(v)
493
else:
494
return (R**len(v))(v)
495
496
free_module_element = vector
497
498
def prepare(v, R, degree=None):
499
r"""
500
Converts an object describing elements of a vector into a list of entries in a common ring.
501
502
INPUT:
503
504
- ``v`` - a dictionary with non-negative integers as keys,
505
or a list or other object that can be converted by the ``Sequence``
506
constructor
507
- ``R`` - a ring containing all the entries, possibly given as ``None``
508
- ``degree`` - a requested size for the list when the input is a dictionary,
509
otherwise ignored
510
511
OUTPUT:
512
513
A pair.
514
515
The first item is a list of the values specified in the object ``v``.
516
If the object is a dictionary , entries are placed in the list
517
according to the indices that were their keys in the dictionary,
518
and the remainder of the entries are zero. The value of
519
``degree`` is assumed to be larger than any index provided
520
in the dictionary and will be used as the number of entries
521
in the returned list.
522
523
The second item returned is a ring that contains all of
524
the entries in the list. If ``R`` is given, the entries
525
are coerced in. Otherwise a common ring is found. For
526
more details, see the
527
:class:`~sage.structure.sequence.Sequence` object. When ``v``
528
has no elements and ``R`` is ``None``, the ring returned is
529
the integers.
530
531
532
EXAMPLES::
533
534
sage: from sage.modules.free_module_element import prepare
535
sage: prepare([1,2/3,5],None)
536
([1, 2/3, 5], Rational Field)
537
538
sage: prepare([1,2/3,5],RR)
539
([1.00000000000000, 0.666666666666667, 5.00000000000000], Real Field with 53 bits of precision)
540
541
sage: prepare({1:4, 3:-2}, ZZ, 6)
542
([0, 4, 0, -2, 0, 0], Integer Ring)
543
544
sage: prepare({3:1, 5:3}, QQ, 6)
545
([0, 0, 0, 1, 0, 3], Rational Field)
546
547
sage: prepare([1,2/3,'10',5],RR)
548
([1.00000000000000, 0.666666666666667, 10.0000000000000, 5.00000000000000], Real Field with 53 bits of precision)
549
550
sage: prepare({},QQ, 0)
551
([], Rational Field)
552
553
sage: prepare([1,2/3,'10',5],None)
554
Traceback (most recent call last):
555
...
556
TypeError: unable to find a common ring for all elements
557
558
Some objects can be converted to sequences even if they are not always
559
thought of as sequences. ::
560
561
sage: c = CDF(2+3*I)
562
sage: prepare(c, None)
563
([2.0, 3.0], Real Double Field)
564
565
This checks a bug listed at Trac #10595. Without good evidence for a ring, the default
566
is the integers. ::
567
568
sage: prepare([], None)
569
([], Integer Ring)
570
"""
571
if isinstance(v, dict):
572
# convert to a list
573
X = [0]*degree
574
for key, value in v.iteritems():
575
X[key] = value
576
v = X
577
# convert to a Sequence over common ring
578
# default to ZZ on an empty list
579
if R is None:
580
try:
581
if len(v) == 0:
582
R = ZZ
583
except TypeError:
584
pass
585
v = Sequence(v, universe=R, use_sage_types=True)
586
ring = v.universe()
587
if not is_Ring(ring):
588
raise TypeError("unable to find a common ring for all elements")
589
return v, ring
590
591
def zero_vector(arg0, arg1=None):
592
r"""
593
Returns a vector or free module element with a specified number of zeros.
594
595
CALL FORMATS:
596
597
1. zero_vector(degree)
598
599
2. zero_vector(ring, degree)
600
601
INPUT:
602
603
- ``degree`` - the number of zero entries in the vector or
604
free module element
605
606
- ``ring`` - default ``ZZ`` - the base ring of the vector
607
space or module containing the constructed zero vector
608
609
OUTPUT:
610
611
A vector or free module element with ``degree`` entries,
612
all equal to zero and belonging to the ring if specified.
613
If no ring is given, a free module element over ``ZZ``
614
is returned.
615
616
EXAMPLES:
617
618
A zero vector over the field of rationals. ::
619
620
sage: v = zero_vector(QQ, 5); v
621
(0, 0, 0, 0, 0)
622
sage: v.parent()
623
Vector space of dimension 5 over Rational Field
624
625
A free module zero element. ::
626
627
sage: w = zero_vector(Integers(6), 3); w
628
(0, 0, 0)
629
sage: w.parent()
630
Ambient free module of rank 3 over Ring of integers modulo 6
631
632
If no ring is given, the integers are used. ::
633
634
sage: u = zero_vector(9); u
635
(0, 0, 0, 0, 0, 0, 0, 0, 0)
636
sage: u.parent()
637
Ambient free module of rank 9 over the principal ideal domain Integer Ring
638
639
Non-integer degrees produce an error. ::
640
641
sage: zero_vector(5.6)
642
Traceback (most recent call last):
643
...
644
TypeError: Attempt to coerce non-integral RealNumber to Integer
645
646
Negative degrees also give an error. ::
647
648
sage: zero_vector(-3)
649
Traceback (most recent call last):
650
...
651
ValueError: rank (=-3) must be nonnegative
652
653
Garbage instead of a ring will be recognized as such. ::
654
655
sage: zero_vector(x^2, 5)
656
Traceback (most recent call last):
657
...
658
TypeError: first argument must be a ring
659
"""
660
if arg1 is None:
661
# default to a zero vector over the integers (ZZ) if no ring given
662
return (ZZ**arg0).zero_vector()
663
if is_Ring(arg0):
664
return (arg0**arg1).zero_vector()
665
raise TypeError("first argument must be a ring")
666
667
def random_vector(ring, degree=None, *args, **kwds):
668
r"""
669
Returns a vector (or module element) with random entries.
670
671
INPUT:
672
673
- ring - default: ``ZZ`` - the base ring for the entries
674
- degree - a non-negative integer for the number of entries in the vector
675
- sparse - default: ``False`` - whether to use a sparse implementation
676
- args, kwds - additional arguments and keywords are passed
677
to the ``random_element()`` method of the ring
678
679
OUTPUT:
680
681
A vector, or free module element, with ``degree`` elements
682
from ``ring``, chosen randomly from the ring according to
683
the ring's ``random_element()`` method.
684
685
.. note::
686
See below for examples of how random elements are
687
generated by some common base rings.
688
689
EXAMPLES:
690
691
First, module elements over the integers.
692
The default distribution is tightly clustered around -1, 0, 1.
693
Uniform distributions can be specified by giving bounds, though
694
the upper bound is never met. See
695
:meth:`sage.rings.integer_ring.IntegerRing_class.random_element`
696
for several other variants. ::
697
698
sage: random_vector(10)
699
(-8, 2, 0, 0, 1, -1, 2, 1, -95, -1)
700
701
sage: sorted(random_vector(20))
702
[-12, -6, -4, -4, -2, -2, -2, -1, -1, -1, 0, 0, 0, 0, 0, 1, 1, 1, 4, 5]
703
704
sage: random_vector(ZZ, 20, x=4)
705
(2, 0, 3, 0, 1, 0, 2, 0, 2, 3, 0, 3, 1, 2, 2, 2, 1, 3, 2, 3)
706
707
sage: random_vector(ZZ, 20, x=-20, y=100)
708
(43, 47, 89, 31, 56, -20, 23, 52, 13, 53, 49, -12, -2, 94, -1, 95, 60, 83, 28, 63)
709
710
sage: random_vector(ZZ, 20, distribution="1/n")
711
(0, -1, -2, 0, -1, -2, 0, 0, 27, -1, 1, 1, 0, 2, -1, 1, -1, -2, -1, 3)
712
713
If the ring is not specified, the default is the integers, and
714
parameters for the random distribution may be passed without using
715
keywords. This is a random vector with 20 entries uniformly distributed
716
between -20 and 100. ::
717
718
sage: random_vector(20, -20, 100)
719
(70, 19, 98, 2, -18, 88, 36, 66, 76, 52, 82, 99, 55, -17, 82, -15, 36, 28, 79, 18)
720
721
Now over the rationals. Note that bounds on the numerator and
722
denominator may be specified. See
723
:meth:`sage.rings.rational_field.RationalField.random_element`
724
for documentation. ::
725
726
sage: random_vector(QQ, 10)
727
(0, -1, -4/3, 2, 0, -13, 2/3, 0, -4/5, -1)
728
729
sage: random_vector(QQ, 10, num_bound = 15, den_bound = 5)
730
(-12/5, 9/4, -13/3, -1/3, 1, 5/4, 4, 1, -15, 10/3)
731
732
Inexact rings may be used as well. The reals have
733
uniform distributions, with the range `(-1,1)` as
734
the default. More at:
735
:meth:`sage.rings.real_mpfr.RealField_class.random_element` ::
736
737
sage: random_vector(RR, 5)
738
(0.248997268533725, -0.112200126330480, 0.776829203293064, -0.899146461031406, 0.534465018743125)
739
740
sage: random_vector(RR, 5, min = 8, max = 14)
741
(8.43260944052606, 8.34129413391087, 8.92391495103829, 11.5784799413416, 11.0973561568002)
742
743
Any ring with a ``random_element()`` method may be used. ::
744
745
sage: F = FiniteField(23)
746
sage: hasattr(F, 'random_element')
747
True
748
sage: random_vector(F, 10)
749
(21, 6, 5, 2, 6, 2, 18, 9, 9, 7)
750
751
The default implementation is a dense representation, equivalent to
752
setting ``sparse=False``. ::
753
754
sage: v = random_vector(10)
755
sage: v.is_sparse()
756
False
757
758
sage: w = random_vector(ZZ, 20, sparse=True)
759
sage: w.is_sparse()
760
True
761
762
Inputs get checked before constructing the vector. ::
763
764
sage: random_vector('junk')
765
Traceback (most recent call last):
766
...
767
TypeError: degree of a random vector must be an integer, not None
768
769
sage: random_vector('stuff', 5)
770
Traceback (most recent call last):
771
...
772
TypeError: elements of a vector, or module element, must come from a ring, not stuff
773
774
sage: random_vector(ZZ, -9)
775
Traceback (most recent call last):
776
...
777
ValueError: degree of a random vector must be non-negative, not -9
778
"""
779
if sage.rings.integer.is_Integer(ring) or isinstance(ring,(int,long)):
780
if not degree is None:
781
arglist = list(args)
782
arglist.insert(0, degree)
783
args = tuple(arglist)
784
degree = ring
785
ring = ZZ
786
if not (sage.rings.integer.is_Integer(degree) or isinstance(degree,(int,long))):
787
raise TypeError("degree of a random vector must be an integer, not %s" % degree)
788
if degree < 0:
789
raise ValueError("degree of a random vector must be non-negative, not %s" % degree)
790
if not is_Ring(ring):
791
raise TypeError("elements of a vector, or module element, must come from a ring, not %s" % ring)
792
if not hasattr(ring, "random_element"):
793
raise AttributeError("cannot create a random vector since there is no random_element() method for %s" % ring )
794
sparse = kwds.pop('sparse', False)
795
entries = [ring.random_element(*args, **kwds) for _ in range(degree)]
796
return vector(ring, degree, entries, sparse)
797
798
cdef class FreeModuleElement(element_Vector): # abstract base class
799
"""
800
An element of a generic free module.
801
"""
802
def __init__(self, parent):
803
"""
804
EXAMPLES::
805
806
sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)
807
sage: type(v)
808
<type 'sage.modules.free_module_element.FreeModuleElement'>
809
"""
810
self._parent = parent
811
self._degree = parent.degree()
812
self._is_mutable = 1
813
814
def _giac_init_(self):
815
"""
816
EXAMPLES::
817
818
sage: v = vector(ZZ, 4, range(4)) #optional - giac
819
sage: giac(v)+v #optional - giac
820
[0,2,4,6]
821
822
::
823
824
sage: v = vector(QQ, 3, [2/3, 0, 5/4]) #optional
825
sage: giac(v) #optional
826
[2/3,0,5/4]
827
828
::
829
830
sage: P.<x> = ZZ[] #optional
831
sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) #optional
832
sage: giac(v) #optional
833
[x^2+2,2*x+1,-2*x^2+4*x]
834
"""
835
return self.list()
836
837
def _magma_init_(self, magma):
838
r"""
839
Convert self to Magma.
840
841
EXAMPLES::
842
843
sage: F = FreeModule(ZZ, 2, inner_product_matrix=matrix(ZZ, 2, 2, [1, 0, 0, -1]))
844
sage: v = F([1, 2])
845
sage: M = magma(v); M # optional - magma
846
(1 2)
847
sage: M.Type() # optional - magma
848
ModTupRngElt
849
sage: M.Parent() # optional - magma
850
Full RSpace of degree 2 over Integer Ring
851
Inner Product Matrix:
852
[ 1 0]
853
[ 0 -1]
854
sage: M.sage() # optional - magma
855
(1, 2)
856
sage: M.sage() == v # optional - magma
857
True
858
sage: M.sage().parent() is v.parent() # optional - magma
859
True
860
861
::
862
863
sage: v = vector(QQ, [1, 2, 5/6])
864
sage: M = magma(v); M # optional - magma
865
( 1 2 5/6)
866
sage: M.Type() # optional - magma
867
ModTupFldElt
868
sage: M.Parent() # optional - magma
869
Full Vector space of degree 3 over Rational Field
870
sage: M.sage() # optional - magma
871
(1, 2, 5/6)
872
sage: M.sage() == v # optional - magma
873
True
874
sage: M.sage().parent() is v.parent() # optional - magma
875
True
876
"""
877
# Get a reference to Magma version of parent.
878
R = magma(self.parent())
879
# Get list of coefficients.
880
v = ','.join([a._magma_init_(magma) for a in self.list()])
881
return '%s![%s]' % (R.name(), v)
882
883
def __hash__(self):
884
"""
885
Return hash of this vector. Only mutable vectors are hashable.
886
887
EXAMPLES::
888
sage: v = vector([1,2/3,pi])
889
sage: v.__hash__()
890
Traceback (most recent call last):
891
...
892
TypeError: mutable vectors are unhashable
893
sage: v.set_immutable()
894
sage: v.__hash__() # random output
895
"""
896
if self._is_mutable:
897
raise TypeError("mutable vectors are unhashable")
898
return hash(tuple(self))
899
900
def _vector_(self, R=None):
901
r"""
902
Return self as a vector.
903
904
EXAMPLES::
905
906
sage: v = vector(ZZ, [2, 12, 22])
907
sage: vector(v)
908
(2, 12, 22)
909
sage: vector(GF(7), v)
910
(2, 5, 1)
911
sage: vector(v, ZZ['x', 'y'])
912
(2, 12, 22)
913
914
sage: vector(vector((1, 6.8)))
915
(1.00000000000000, 6.80000000000000)
916
sage: vector(vector(SR, (1, sqrt(2)) ) )
917
(1, sqrt(2))
918
"""
919
if R is None:
920
R = self.base_ring()
921
return self.change_ring(R)
922
923
def _matrix_(self, R=None):
924
r"""
925
Return self as a row matrix.
926
927
EXAMPLES::
928
929
sage: v = vector(ZZ, [2, 12, 22])
930
sage: vector(v)
931
(2, 12, 22)
932
sage: vector(GF(7), v)
933
(2, 5, 1)
934
sage: vector(v, ZZ['x', 'y'])
935
(2, 12, 22)
936
"""
937
if R is None:
938
R = self.base_ring()
939
sparse = self.is_sparse()
940
from sage.matrix.constructor import matrix
941
return matrix(R, [list(self)], sparse=sparse)
942
943
def _sage_input_(self, sib, coerce):
944
r"""
945
Produce an expression which will reproduce this value when evaluated.
946
947
EXAMPLES::
948
949
sage: sage_input(vector(RR, [pi, e, 0.5]), verify=True)
950
# Verified
951
vector(RR, [3.1415926535897931, 2.7182818284590451, 0.5])
952
sage: sage_input(vector(GF(5), [1, 2, 3, 4, 5]), verify=True)
953
# Verified
954
vector(GF(5), [1, 2, 3, 4, 0])
955
sage: sage_input(vector([0, 0, 0, 1, 0, 0, 0], sparse=True), verify=True)
956
# Verified
957
vector(ZZ, {3:1, 6:0})
958
sage: sage_input(vector(ZZ, []), verify=True)
959
# Verified
960
vector(ZZ, [])
961
sage: sage_input(vector(RealField(27), [], sparse=True), verify=True)
962
# Verified
963
vector(RealField(27), {})
964
sage: from sage.misc.sage_input import SageInputBuilder
965
sage: vector(ZZ, [42, 389])._sage_input_(SageInputBuilder(), False)
966
{call: {atomic:vector}({atomic:ZZ}, {list: ({atomic:42}, {atomic:389})})}
967
sage: vector(RDF, {1:pi, 1000:e})._sage_input_(SageInputBuilder(), False)
968
{call: {atomic:vector}({atomic:RDF}, {dict: {{atomic:1}:{atomic:3.1415926535897931}, {atomic:1000}:{atomic:2.718281828459045...}}})}
969
"""
970
# Not a lot of room for prettiness here.
971
# We always specify the ring, because that lets us use coerced=2
972
# on the elements, which is sometimes much prettier than
973
# the coerced=False we would get otherwise.
974
if self.is_sparse_c():
975
items = [(n, sib(e, 2))
976
for n,e in self.dict().items()]
977
items.sort()
978
if len(self):
979
# we may need to add an extra element on the end to
980
# set the size. (There doesn't seem to be a better way
981
# to do it.)
982
if len(items) == 0 or len(self)-1 > items[-1][0]:
983
items.append((len(self)-1, sib.int(0)))
984
items_dict = sib.dict([(sib.int(n), e) for n,e in items])
985
986
return sib.name('vector')(self.base_ring(), items_dict)
987
else:
988
return sib.name('vector')(self.base_ring(),
989
[sib(e, 2) for e in self])
990
991
def _numerical_approx(self, prec=None, digits=None):
992
r"""
993
Implements numerical approximation of a free module element
994
by calling the ``n()`` method on all of its entries.
995
996
EXAMPLES::
997
998
sage: v = vector(RealField(212), [1,2,3])
999
sage: v.N()
1000
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1001
sage: _.parent()
1002
Vector space of dimension 3 over Real Field with 53 bits of precision
1003
sage: numerical_approx(v)
1004
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1005
sage: _.parent()
1006
Vector space of dimension 3 over Real Field with 53 bits of precision
1007
sage: v.n(prec=75)
1008
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1009
sage: _.parent()
1010
Vector space of dimension 3 over Real Field with 75 bits of precision
1011
sage: numerical_approx(v, digits=3)
1012
(1.00, 2.00, 3.00)
1013
sage: _.parent()
1014
Vector space of dimension 3 over Real Field with 14 bits of precision
1015
1016
Both functional and object-oriented usage is possible. ::
1017
1018
sage: u = vector(QQ, [1/2, 1/3, 1/4])
1019
sage: u.n()
1020
(0.500000000000000, 0.333333333333333, 0.250000000000000)
1021
sage: u.N()
1022
(0.500000000000000, 0.333333333333333, 0.250000000000000)
1023
sage: u.numerical_approx()
1024
(0.500000000000000, 0.333333333333333, 0.250000000000000)
1025
sage: n(u)
1026
(0.500000000000000, 0.333333333333333, 0.250000000000000)
1027
sage: N(u)
1028
(0.500000000000000, 0.333333333333333, 0.250000000000000)
1029
sage: numerical_approx(u)
1030
(0.500000000000000, 0.333333333333333, 0.250000000000000)
1031
1032
Precision (bits) and digits (decimal) may be specified.
1033
When both are given, ``prec`` wins. ::
1034
1035
sage: u = vector(QQ, [1/2, 1/3, 1/4])
1036
sage: n(u, prec=15)
1037
(0.5000, 0.3333, 0.2500)
1038
sage: n(u, digits=5)
1039
(0.50000, 0.33333, 0.25000)
1040
sage: n(u, prec=30, digits=100)
1041
(0.50000000, 0.33333333, 0.25000000)
1042
1043
These are some legacy doctests that were part of various specialized
1044
versions of the numerical approximation routine that were removed as
1045
part of :trac:`12195`. ::
1046
1047
sage: v = vector(ZZ, [1,2,3])
1048
sage: v.n()
1049
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1050
sage: _.parent()
1051
Vector space of dimension 3 over Real Field with 53 bits of precision
1052
sage: v.n(prec=75)
1053
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1054
sage: _.parent()
1055
Vector space of dimension 3 over Real Field with 75 bits of precision
1056
1057
sage: v = vector(RDF, [1,2,3])
1058
sage: v.n()
1059
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1060
sage: _.parent()
1061
Vector space of dimension 3 over Real Field with 53 bits of precision
1062
sage: v.n(prec=75)
1063
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1064
sage: _.parent()
1065
Vector space of dimension 3 over Real Field with 75 bits of precision
1066
1067
sage: v = vector(CDF, [1,2,3])
1068
sage: v.n()
1069
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1070
sage: _.parent()
1071
Vector space of dimension 3 over Complex Field with 53 bits of precision
1072
sage: v.n(prec=75)
1073
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1074
sage: _.parent()
1075
Vector space of dimension 3 over Complex Field with 75 bits of precision
1076
1077
sage: v = vector(Integers(8), [1,2,3])
1078
sage: v.n()
1079
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1080
sage: _.parent()
1081
Vector space of dimension 3 over Real Field with 53 bits of precision
1082
sage: v.n(prec=75)
1083
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1084
sage: _.parent()
1085
Vector space of dimension 3 over Real Field with 75 bits of precision
1086
1087
sage: v = vector(QQ, [1,2,3])
1088
sage: v.n()
1089
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1090
sage: _.parent()
1091
Vector space of dimension 3 over Real Field with 53 bits of precision
1092
sage: v.n(prec=75)
1093
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1094
sage: _.parent()
1095
Vector space of dimension 3 over Real Field with 75 bits of precision
1096
1097
TESTS:
1098
1099
Sparse vectors have a similar method that works efficiently for
1100
the sparse case. We test that it is working as it should. ::
1101
1102
sage: v = vector(QQ, [1/2, 0, 0, 1/3, 0, 0, 0, 1/4], sparse=True)
1103
sage: u = v.numerical_approx(digits=4)
1104
sage: u.is_sparse()
1105
True
1106
sage: u
1107
(0.5000, 0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000, 0.2500)
1108
"""
1109
return vector([e.n(prec, digits) for e in self])
1110
1111
def transpose(self):
1112
r"""
1113
Return self as a column matrix.
1114
1115
.. note::
1116
1117
The ``transpose()`` method has been deprecated as of Sage 4.6.2,
1118
in favor of the :meth:`column` method which is functionally identical.
1119
1120
EXAMPLES::
1121
1122
sage: v = vector(ZZ, [2, 12, 22])
1123
sage: transpose(vector(v))
1124
doctest:...: DeprecationWarning: (Since Sage Version 4.6.2) The transpose() method for vectors has been deprecated, use column() instead
1125
(or check to see if you have a vector when you really want a matrix)
1126
[ 2]
1127
[12]
1128
[22]
1129
1130
::
1131
1132
sage: transpose(vector(GF(7), v))
1133
[2]
1134
[5]
1135
[1]
1136
1137
::
1138
1139
sage: transpose(vector(v, ZZ['x', 'y']))
1140
[ 2]
1141
[12]
1142
[22]
1143
"""
1144
from sage.misc.misc import deprecation
1145
deprecation('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')
1146
return self._matrix_().transpose()
1147
1148
def row(self):
1149
r"""
1150
Return a matrix with a single row and the same entries as the vector ``self``.
1151
1152
OUTPUT:
1153
1154
A matrix over the same ring as the vector (or free module element), with
1155
a single row. The entries of the row are identical to those of the vector,
1156
and in the same order.
1157
1158
EXAMPLES::
1159
1160
sage: v = vector(ZZ, [1,2,3])
1161
sage: w = v.row(); w
1162
[1 2 3]
1163
sage: w.parent()
1164
Full MatrixSpace of 1 by 3 dense matrices over Integer Ring
1165
1166
sage: x = vector(FiniteField(13), [2,4,8,16])
1167
sage: x.row()
1168
[2 4 8 3]
1169
1170
There is more than one way to get one-row matrix from a vector,
1171
but the ``row`` method is more efficient than making a column and
1172
then taking a transpose. Notice that supplying a vector to the
1173
matrix constructor demonstrates Sage's preference for rows. ::
1174
1175
sage: x = vector(RDF, [sin(i*pi/20) for i in range(10)])
1176
sage: x.row() == matrix(x)
1177
True
1178
sage: x.row() == x.column().transpose()
1179
True
1180
1181
Sparse or dense implementations are preserved. ::
1182
1183
sage: d = vector(RR, [1.0, 2.0, 3.0])
1184
sage: s = vector(CDF, {2:5.0+6.0*I})
1185
sage: dm = d.row()
1186
sage: sm = s.row()
1187
sage: all([d.is_dense(), dm.is_dense(), s.is_sparse(), sm.is_sparse()])
1188
True
1189
1190
TESTS:
1191
1192
The :meth:`~sage.matrix.matrix1.Matrix.row` method will return
1193
a specified row of a matrix as a vector. So here are a couple
1194
of round-trips. ::
1195
1196
sage: A = matrix(ZZ, [[1,2,3]])
1197
sage: A == A.row(0).row()
1198
True
1199
sage: v = vector(ZZ, [4,5,6])
1200
sage: v == v.row().row(0)
1201
True
1202
1203
And a very small corner case. ::
1204
1205
sage: v = vector(ZZ, [])
1206
sage: w = v.row()
1207
sage: w.parent()
1208
Full MatrixSpace of 1 by 0 dense matrices over Integer Ring
1209
"""
1210
return self._matrix_(R=None)
1211
1212
def column(self):
1213
r"""
1214
Return a matrix with a single column and the same entries as the vector ``self``.
1215
1216
OUTPUT:
1217
1218
A matrix over the same ring as the vector (or free module element), with
1219
a single column. The entries of the column are identical to those of the
1220
vector, and in the same order.
1221
1222
EXAMPLES::
1223
1224
sage: v = vector(ZZ, [1,2,3])
1225
sage: w = v.column(); w
1226
[1]
1227
[2]
1228
[3]
1229
sage: w.parent()
1230
Full MatrixSpace of 3 by 1 dense matrices over Integer Ring
1231
1232
sage: x = vector(FiniteField(13), [2,4,8,16])
1233
sage: x.column()
1234
[2]
1235
[4]
1236
[8]
1237
[3]
1238
1239
There is more than one way to get one-column matrix from a vector.
1240
The ``column`` method is about equally efficient to making a row and
1241
then taking a transpose. Notice that supplying a vector to the
1242
matrix constructor demonstrates Sage's preference for rows. ::
1243
1244
sage: x = vector(RDF, [sin(i*pi/20) for i in range(10)])
1245
sage: x.column() == matrix(x).transpose()
1246
True
1247
sage: x.column() == x.row().transpose()
1248
True
1249
1250
Sparse or dense implementations are preserved. ::
1251
1252
sage: d = vector(RR, [1.0, 2.0, 3.0])
1253
sage: s = vector(CDF, {2:5.0+6.0*I})
1254
sage: dm = d.column()
1255
sage: sm = s.column()
1256
sage: all([d.is_dense(), dm.is_dense(), s.is_sparse(), sm.is_sparse()])
1257
True
1258
1259
TESTS:
1260
1261
The :meth:`~sage.matrix.matrix1.Matrix.column` method will return
1262
a specified column of a matrix as a vector. So here are a couple
1263
of round-trips. ::
1264
1265
sage: A = matrix(ZZ, [[1],[2],[3]])
1266
sage: A == A.column(0).column()
1267
True
1268
sage: v = vector(ZZ, [4,5,6])
1269
sage: v == v.column().column(0)
1270
True
1271
1272
And a very small corner case. ::
1273
1274
sage: v = vector(ZZ, [])
1275
sage: w = v.column()
1276
sage: w.parent()
1277
Full MatrixSpace of 0 by 1 dense matrices over Integer Ring
1278
"""
1279
return self._matrix_(R=None).transpose()
1280
1281
def _hash(self):
1282
"""
1283
Return hash of an immutable form of self (works even if self
1284
is mutable).
1285
1286
EXAMPLES::
1287
sage: v = vector([1,2/3,pi])
1288
sage: v.__hash__()
1289
Traceback (most recent call last):
1290
...
1291
TypeError: mutable vectors are unhashable
1292
sage: v._hash() # random output
1293
"""
1294
return hash(tuple(list(self)))
1295
1296
def __copy__(self):
1297
"""
1298
Make a copy of this vector.
1299
1300
EXAMPLES::
1301
1302
sage: v = vector([1..5]); v
1303
(1, 2, 3, 4, 5)
1304
sage: w = copy(v)
1305
sage: v == w
1306
True
1307
sage: v is w
1308
False
1309
1310
::
1311
1312
sage: v = vector([1..5], sparse=True); v
1313
(1, 2, 3, 4, 5)
1314
sage: copy(v)
1315
(1, 2, 3, 4, 5)
1316
"""
1317
if self.is_sparse():
1318
return self.parent()(self.dict())
1319
else:
1320
return self.parent()(self.list())
1321
1322
def subs(self, in_dict=None, **kwds):
1323
"""
1324
EXAMPLES::
1325
1326
sage: var('a,b,d,e')
1327
(a, b, d, e)
1328
sage: v = vector([a, b, d, e])
1329
sage: v.substitute(a=1)
1330
(1, b, d, e)
1331
sage: v.subs(a=b, b=d)
1332
(b, d, d, e)
1333
"""
1334
return self.parent()([ a.subs(in_dict, **kwds) for a in self.list() ])
1335
1336
def set_immutable(self):
1337
"""
1338
Make this vector immutable. This operation can't be undone.
1339
1340
EXAMPLES::
1341
1342
sage: v = vector([1..5]); v
1343
(1, 2, 3, 4, 5)
1344
sage: v[1] = 10
1345
sage: v.set_immutable()
1346
sage: v[1] = 10
1347
Traceback (most recent call last):
1348
...
1349
ValueError: vector is immutable; please change a copy instead (use copy())
1350
"""
1351
self._is_mutable = 0
1352
1353
def is_mutable(self):
1354
"""
1355
Return True if this vector is mutable, i.e., the entries can be
1356
changed.
1357
1358
EXAMPLES::
1359
1360
sage: v = vector(QQ['x,y'], [1..5]); v.is_mutable()
1361
True
1362
sage: v.set_immutable()
1363
sage: v.is_mutable()
1364
False
1365
"""
1366
return self._is_mutable
1367
1368
def is_immutable(self):
1369
"""
1370
Return True if this vector is immutable, i.e., the entries cannot
1371
be changed.
1372
1373
EXAMPLES::
1374
1375
sage: v = vector(QQ['x,y'], [1..5]); v.is_immutable()
1376
False
1377
sage: v.set_immutable()
1378
sage: v.is_immutable()
1379
True
1380
"""
1381
return not self._is_mutable
1382
1383
def change_ring(self, R):
1384
"""
1385
Change the base ring of this vector, by coercing each element of
1386
this vector into R.
1387
1388
EXAMPLES::
1389
1390
sage: v = vector(QQ['x,y'], [1..5]); v.change_ring(GF(3))
1391
(1, 2, 0, 1, 2)
1392
"""
1393
P = self.parent()
1394
if P.base_ring() is R:
1395
return self
1396
return P.change_ring(R)(self)
1397
1398
def additive_order(self):
1399
"""
1400
Return the additive order of self.
1401
1402
EXAMPLES::
1403
1404
sage: v = vector(Integers(4), [1,2])
1405
sage: v.additive_order()
1406
4
1407
1408
::
1409
1410
sage: v = vector([1,2,3])
1411
sage: v.additive_order()
1412
+Infinity
1413
1414
::
1415
1416
sage: v = vector(Integers(30), [6, 15]); v
1417
(6, 15)
1418
sage: v.additive_order()
1419
10
1420
sage: 10*v
1421
(0, 0)
1422
"""
1423
v = [None]*self.degree()
1424
cdef int i
1425
for i from 0 <= i < self.degree():
1426
v[i] = self[i].additive_order()
1427
if v[i] == +Infinity:
1428
return +Infinity
1429
return sage.rings.arith.LCM(v)
1430
1431
def iteritems(self):
1432
"""
1433
Return iterator over self.
1434
1435
EXAMPLES::
1436
1437
sage: v = vector([1,2/3,pi])
1438
sage: v.iteritems()
1439
<dictionary-itemiterator object at ...>
1440
sage: list(v.iteritems())
1441
[(0, 1), (1, 2/3), (2, pi)]
1442
"""
1443
return self.dict(copy=False).iteritems()
1444
1445
def __abs__(self):
1446
"""
1447
Return the square root of the sum of the squares of the entries of
1448
this vector.
1449
1450
EXAMPLES::
1451
1452
sage: v = vector([1..5]); abs(v)
1453
sqrt(55)
1454
sage: v = vector(RDF, [1..5]); abs(v)
1455
7.4161984871
1456
"""
1457
return sum([x**2 for x in self.list()]).sqrt()
1458
1459
def norm(self, p=sage.rings.integer.Integer(2)):
1460
r"""
1461
Return the `p`-norm of ``self``.
1462
1463
INPUT:
1464
1465
- ``p`` - default: 2 - ``p`` can be a real number greater than 1,
1466
infinity (``oo`` or ``Infinity``), or a symbolic expression.
1467
1468
- `p=1`: the taxicab (Manhattan) norm
1469
- `p=2`: the usual Euclidean norm (the default)
1470
- `p=\infty`: the maximum entry (in absolute value)
1471
1472
.. note::
1473
1474
See also :func:`sage.misc.functional.norm`
1475
1476
EXAMPLES::
1477
1478
sage: v = vector([1,2,-3])
1479
sage: v.norm(5)
1480
276^(1/5)
1481
1482
The default is the usual Euclidean norm. ::
1483
1484
sage: v.norm()
1485
sqrt(14)
1486
sage: v.norm(2)
1487
sqrt(14)
1488
1489
The infinity norm is the maximum size (in absolute value)
1490
of the entries. ::
1491
1492
sage: v.norm(Infinity)
1493
3
1494
sage: v.norm(oo)
1495
3
1496
1497
Real or symbolic values may be used for ``p``. ::
1498
1499
sage: v=vector(RDF,[1,2,3])
1500
sage: v.norm(5)
1501
3.07738488539
1502
sage: v.norm(pi/2)
1503
4.2165958647
1504
sage: _=var('a b c d p'); v=vector([a, b, c, d])
1505
sage: v.norm(p)
1506
(abs(a)^p + abs(b)^p + abs(c)^p + abs(d)^p)^(1/p)
1507
1508
Notice that the result may be a symbolic expression, owing to
1509
the necessity of taking a square root (in the default case).
1510
These results can be converted to numerical values if needed. ::
1511
1512
sage: v = vector(ZZ, [3,4])
1513
sage: nrm = v.norm(); nrm
1514
5
1515
sage: nrm.parent()
1516
Rational Field
1517
1518
sage: v = vector(QQ, [3, 5])
1519
sage: nrm = v.norm(); nrm
1520
sqrt(34)
1521
sage: nrm.parent()
1522
Symbolic Ring
1523
sage: numeric = N(nrm); numeric
1524
5.83095189484...
1525
sage: numeric.parent()
1526
Real Field with 53 bits of precision
1527
1528
TESTS:
1529
1530
The value of ``p`` must be greater than, or
1531
equal to, one. ::
1532
1533
sage: v = vector(QQ, [1,2])
1534
sage: v.norm(0.99)
1535
Traceback (most recent call last):
1536
...
1537
ValueError: 0.990000 is not greater than or equal to 1
1538
"""
1539
abs_self = [abs(x) for x in self]
1540
if p == Infinity:
1541
return max(abs_self)
1542
try:
1543
pr = RDF(p)
1544
if pr < 1:
1545
raise ValueError("%f is not greater than or equal to 1" %(pr))
1546
except TypeError:
1547
pass
1548
1549
s = sum([a**p for a in abs_self])
1550
return s**(1/p)
1551
1552
cdef int _cmp_c_impl(left, Element right) except -2:
1553
"""
1554
EXAMPLES::
1555
1556
sage: v = vector(QQ, [0,0,0,0])
1557
sage: v == 0
1558
True
1559
sage: v == 1
1560
False
1561
sage: v == v
1562
True
1563
sage: w = vector(QQ, [-1,0,0,0])
1564
sage: w < v
1565
True
1566
sage: w > v
1567
False
1568
"""
1569
cdef Py_ssize_t i
1570
cdef int c
1571
for i from 0 <= i < left.degree():
1572
c = cmp(left[i], right[i])
1573
if c: return c
1574
return 0
1575
1576
def __getitem__(self, i):
1577
"""
1578
Return `i`-th entry or slice of self.
1579
1580
EXAMPLES::
1581
1582
This just raises NotImplementedError since this is an abstract
1583
base class, and __getitem__ has to be overloaded in the
1584
derived class::
1585
1586
sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)
1587
sage: v.__getitem__(0)
1588
Traceback (most recent call last):
1589
...
1590
NotImplementedError
1591
"""
1592
raise NotImplementedError
1593
1594
def __invert__(self):
1595
"""
1596
Invert v, which makes no sense, and is hence is not implemented.
1597
1598
EXAMPLES::
1599
1600
sage: vector([1,2/3,pi]).__invert__()
1601
Traceback (most recent call last):
1602
...
1603
NotImplementedError
1604
"""
1605
raise NotImplementedError
1606
1607
def __len__(self):
1608
"""
1609
EXAMPLES::
1610
1611
sage: len(sage.modules.free_module_element.FreeModuleElement(QQ^2010))
1612
2010
1613
"""
1614
return self.parent().degree()
1615
1616
def __mod__(self, p):
1617
"""
1618
EXAMPLES::
1619
1620
sage: V = vector(ZZ, [5, 9, 13, 15])
1621
sage: V % 7
1622
(5, 2, 6, 1)
1623
sage: parent(V % 7)
1624
Ambient free module of rank 4 over the principal ideal domain Integer Ring
1625
"""
1626
return self.parent()([x % p for x in self.list()], copy=False, coerce=False, check=False)
1627
1628
def Mod(self, p):
1629
"""
1630
EXAMPLES::
1631
1632
sage: V = vector(ZZ, [5, 9, 13, 15])
1633
sage: V.Mod(7)
1634
(5, 2, 6, 1)
1635
sage: parent(V.Mod(7))
1636
Vector space of dimension 4 over Ring of integers modulo 7
1637
"""
1638
return self.change_ring(self.base_ring().quotient_ring(p))
1639
1640
def list(self, copy=True):
1641
"""
1642
Return list of elements of self.
1643
1644
INPUT:
1645
1646
- copy -- bool, whether returned list is a copy that is
1647
safe to change, is ignored.
1648
1649
EXAMPLES::
1650
1651
sage: P.<x,y,z> = QQ[]
1652
sage: v = vector([x,y,z], sparse=True)
1653
sage: type(v)
1654
<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>
1655
sage: a = v.list(); a
1656
[x, y, z]
1657
sage: a[0] = x*y; v
1658
(x, y, z)
1659
1660
The optional argument ``copy`` is ignored::
1661
1662
sage: a = v.list(copy=False); a
1663
[x, y, z]
1664
sage: a[0] = x*y; v
1665
(x, y, z)
1666
"""
1667
cdef Py_ssize_t i
1668
return [self[i] for i in range(self.degree())]
1669
1670
def list_from_positions(self, positions):
1671
"""
1672
Return list of elements chosen from this vector using the
1673
given positions of this vector.
1674
1675
INPUT:
1676
1677
- positions -- iterable of ints
1678
1679
1680
EXAMPLES::
1681
1682
sage: v = vector([1,2/3,pi])
1683
sage: v.list_from_positions([0,0,0,2,1])
1684
[1, 1, 1, pi, 2/3]
1685
"""
1686
cdef Py_ssize_t i
1687
return [self[i] for i in positions]
1688
1689
def lift(self):
1690
"""
1691
EXAMPLES::
1692
1693
sage: V = vector(Integers(7), [5, 9, 13, 15]) ; V
1694
(5, 2, 6, 1)
1695
sage: V.lift()
1696
(5, 2, 6, 1)
1697
sage: parent(V.lift())
1698
Ambient free module of rank 4 over the principal ideal domain Integer Ring
1699
"""
1700
return self.change_ring(self.base_ring().cover_ring())
1701
1702
def __pos__(self):
1703
"""
1704
Always returns self, since +self == self.
1705
1706
EXAMPLES::
1707
1708
sage: v = vector([1,2/3,8])
1709
sage: v.__pos__()
1710
(1, 2/3, 8)
1711
sage: +v
1712
(1, 2/3, 8)
1713
"""
1714
return self
1715
1716
def __pow__(self, n, dummy):
1717
"""
1718
Raises a NotImplementedError, since powering doesn't make
1719
sense for vectors.
1720
1721
EXAMPLES::
1722
1723
sage: v = vector([1,2/3,8])
1724
sage: v^2
1725
Traceback (most recent call last):
1726
...
1727
NotImplementedError
1728
"""
1729
raise NotImplementedError
1730
1731
def _repr_(self):
1732
"""
1733
String representation of a vector.
1734
1735
EXAMPLES::
1736
1737
sage: vector(QQ, [])._repr_()
1738
'()'
1739
sage: vector(QQ, range(5))._repr_()
1740
'(0, 1, 2, 3, 4)'
1741
1742
Symbolic are not displayed using ASCII art.
1743
1744
::
1745
1746
sage: x = var('x')
1747
sage: v = vector([x/(2*x)+sqrt(2)+var('theta')^3,x/(2*x)]); v
1748
(sqrt(2) + theta^3 + 1/2, 1/2)
1749
sage: v._repr_()
1750
'(sqrt(2) + theta^3 + 1/2, 1/2)'
1751
"""
1752
d = self.degree()
1753
if d == 0: return "()"
1754
# compute column widths
1755
S = [repr(x) for x in self.list(copy=False)]
1756
#width = max([len(x) for x in S])
1757
s = "("
1758
for i in xrange(d):
1759
if i == d-1:
1760
sep = ""
1761
else:
1762
sep=", "
1763
entry = S[i]
1764
#if i > 0:
1765
# entry = " "*(width-len(entry)) + entry
1766
s = s + entry + sep
1767
s = s + ")"
1768
return s
1769
1770
def _maple_init_(self):
1771
"""
1772
EXAMPLES::
1773
1774
sage: v = vector(ZZ, 4, range(4)) #optional
1775
sage: maple(v) #optional
1776
Vector[row](4, [0,1,2,3])
1777
1778
::
1779
1780
sage: v = vector(QQ, 3, [2/3, 0, 5/4]) #optional
1781
sage: maple(v) #optional
1782
Vector[row](3, [2/3,0,5/4])
1783
1784
::
1785
1786
sage: P.<x> = ZZ[] #optional
1787
sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) #optional
1788
sage: maple(v) #optional
1789
Vector[row](3, [x^2+2,2*x+1,-2*x^2+4*x])
1790
"""
1791
return "Vector[row](%s)"%(str(self.list()))
1792
1793
def __setitem__(self, i, x):
1794
"""
1795
Set the `i`-th entry or slice of self to x. This is not implemented,
1796
since self is an abstract base class.
1797
1798
EXAMPLES::
1799
1800
sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)
1801
sage: v[0] = 5
1802
Traceback (most recent call last):
1803
...
1804
NotImplementedError
1805
1806
For derived classes, this works::
1807
1808
sage: v = vector([1,2/3,8])
1809
sage: v[0] = 5
1810
sage: v
1811
(5, 2/3, 8)
1812
"""
1813
raise NotImplementedError
1814
1815
def __richcmp__(left, right, int op):
1816
"""
1817
EXAMPLES::
1818
1819
sage: v = vector([1,2/3,8]) # indirect test
1820
sage: v == v
1821
True
1822
"""
1823
cdef int ld, rd
1824
if not isinstance(left, FreeModuleElement) or not isinstance(right, FreeModuleElement):
1825
# use the generic compare
1826
return (<Element>left)._richcmp(right, op)
1827
ld = (<FreeModuleElement>left)._degree
1828
rd = (<FreeModuleElement>right)._degree
1829
if ld < rd:
1830
return (<Element>left)._rich_to_bool(op, -1)
1831
elif ld > rd:
1832
return (<Element>left)._rich_to_bool(op, 1)
1833
if (<FreeModuleElement>left)._parent.base_ring() is (<FreeModuleElement>right)._parent.base_ring():
1834
return (<Element>left)._rich_to_bool(op, (
1835
<FreeModuleElement>left)._cmp_same_ambient_c(right))
1836
return (<Element>left)._richcmp(right, op)
1837
1838
1839
cdef int _cmp_same_ambient_c(left, FreeModuleElement right) except -2:
1840
return cmp(left.list(copy=False), right.list(copy=False))
1841
1842
def degree(self):
1843
"""
1844
Return the degree of this vector, which is simply the number
1845
of entries.
1846
1847
EXAMPLES::
1848
1849
sage: sage.modules.free_module_element.FreeModuleElement(QQ^389).degree()
1850
389
1851
sage: vector([1,2/3,8]).degree()
1852
3
1853
"""
1854
return self._degree
1855
1856
def denominator(self):
1857
"""
1858
Return the least common multiple of the denominators of the
1859
entries of self.
1860
1861
EXAMPLES::
1862
1863
sage: v = vector([1/2,2/5,3/14])
1864
sage: v.denominator()
1865
70
1866
sage: 2*5*7
1867
70
1868
1869
TESTS:
1870
1871
The following was fixed in trac ticket #8800::
1872
1873
sage: M = GF(5)^3
1874
sage: v = M((4,0,2))
1875
sage: v.denominator()
1876
1
1877
1878
"""
1879
R = self.base_ring()
1880
if self.degree() == 0: return 1
1881
x = self.list()
1882
# it may be that the marks do not have a denominator!
1883
d = x[0].denominator() if hasattr(x[0],'denominator') else 1
1884
for y in x:
1885
d = d.lcm(y.denominator()) if hasattr(y,'denominator') else d
1886
return d
1887
1888
def dict(self, copy=True):
1889
"""
1890
Return dictionary of nonzero entries of self.
1891
1892
INPUT:
1893
1894
- ``copy`` -- bool (default: True)
1895
1896
OUTPUT:
1897
1898
- Python dictionary
1899
1900
EXAMPLES::
1901
1902
sage: v = vector([0,0,0,0,1/2,0,3/14])
1903
sage: v.dict()
1904
{4: 1/2, 6: 3/14}
1905
1906
In some cases when copy=False, we get back a dangerous reference::
1907
1908
sage: v = vector({0:5, 2:3/7}, sparse=True)
1909
sage: v.dict(copy=False)
1910
{0: 5, 2: 3/7}
1911
sage: v.dict(copy=False)[0] = 18
1912
sage: v
1913
(18, 0, 3/7)
1914
"""
1915
e = {}
1916
for i in xrange(self.degree()):
1917
c = self[i]
1918
if c:
1919
e[i] = c
1920
return e
1921
1922
#############################
1923
# Plotting
1924
#############################
1925
def plot(self, plot_type=None, start=None, **kwds):
1926
"""
1927
INPUT:
1928
1929
- ``plot_type`` - (default: 'arrow' if v has 3 or fewer components,
1930
otherwise 'step') type of plot. Options are:
1931
1932
- 'arrow' to draw an arrow
1933
1934
- 'point' to draw a point at the coordinates specified by the
1935
vector
1936
1937
- 'step' to draw a step function representing the coordinates
1938
of the vector.
1939
1940
Both 'arrow' and 'point' raise exceptions if the vector has
1941
more than 3 dimensions.
1942
1943
- ``start`` - (default: origin in correct dimension) may be a tuple,
1944
list, or vector.
1945
1946
EXAMPLES:
1947
1948
The following both plot the given vector::
1949
1950
sage: v = vector(RDF, (1,2))
1951
sage: A = plot(v)
1952
sage: B = v.plot()
1953
sage: A+B # should just show one vector
1954
1955
Examples of the plot types::
1956
1957
sage: A = plot(v, plot_type='arrow')
1958
sage: B = plot(v, plot_type='point', color='green', size=20)
1959
sage: C = plot(v, plot_type='step') # calls v.plot_step()
1960
sage: A+B+C
1961
1962
You can use the optional arguments for :meth:`plot_step`::
1963
1964
sage: eps = 0.1
1965
sage: plot(v, plot_type='step', eps=eps, xmax=5, hue=0)
1966
1967
Three-dimensional examples::
1968
1969
sage: v = vector(RDF, (1,2,1))
1970
sage: plot(v) # defaults to an arrow plot
1971
1972
::
1973
1974
sage: plot(v, plot_type='arrow')
1975
1976
::
1977
1978
sage: from sage.plot.plot3d.shapes2 import frame3d
1979
sage: plot(v, plot_type='point')+frame3d((0,0,0), v.list())
1980
1981
::
1982
1983
sage: plot(v, plot_type='step') # calls v.plot_step()
1984
1985
::
1986
1987
sage: plot(v, plot_type='step', eps=eps, xmax=5, hue=0)
1988
1989
With greater than three coordinates, it defaults to a step plot::
1990
1991
sage: v = vector(RDF, (1,2,3,4))
1992
sage: plot(v)
1993
1994
One dimensional vectors are plotted along the horizontal axis of
1995
the coordinate plane::
1996
1997
sage: plot(vector([1]))
1998
1999
An optional start argument may also be specified by a tuple, list, or vector::
2000
2001
sage: u = vector([1,2]); v = vector([2,5])
2002
sage: plot(u, start=v)
2003
2004
TESTS::
2005
2006
sage: u = vector([1,1]); v = vector([2,2,2]); z=(3,3,3)
2007
sage: plot(u) #test when start=None
2008
2009
::
2010
2011
sage: plot(u, start=v) #test when coordinate dimension mismatch exists
2012
Traceback (most recent call last):
2013
...
2014
ValueError: vector coordinates are not of the same dimension
2015
sage: P = plot(v, start=z) #test when start coordinates are passed as a tuple
2016
sage: P = plot(v, start=list(z)) #test when start coordinates are passed as a list
2017
"""
2018
# Give sensible defaults based on the vector length
2019
if plot_type is None:
2020
if len(self)<=3:
2021
plot_type='arrow'
2022
else:
2023
plot_type='step'
2024
2025
coords = self.list()
2026
2027
if start is None:
2028
start = [0]*len(coords)
2029
elif len(start)!=len(coords):
2030
raise ValueError("vector coordinates are not of the same dimension")
2031
else:
2032
start = list(start)
2033
2034
2035
if plot_type == 'arrow' or plot_type == 'point':
2036
dimension = len(coords)
2037
if dimension == 3:
2038
from sage.plot.plot3d.shapes2 import line3d, point3d
2039
2040
if plot_type == 'arrow':
2041
return line3d([start, [(u+v) for u,v in zip(coords, start)]], arrow_head=True, **kwds)
2042
else:
2043
return point3d(coords, **kwds)
2044
elif dimension < 3:
2045
if dimension < 2:
2046
# pad to make 2-dimensional
2047
coords.extend([0]*(2-dimension))
2048
start.extend([0]*(2-dimension))
2049
2050
from sage.plot.all import arrow, point
2051
if plot_type == 'arrow':
2052
return arrow(start, [(u+v) for u,v in zip(coords, start)], **kwds)
2053
else:
2054
return point(coords, **kwds)
2055
else:
2056
raise ValueError("arrow and point plots require vectors with 3 or fewer components")
2057
2058
elif plot_type == 'step':
2059
return self.plot_step(**kwds)
2060
else:
2061
raise NotImplementedError("plot_type was unrecognized")
2062
2063
def plot_step(self, xmin=0, xmax=1, eps=None, res=None,
2064
connect=True, **kwds):
2065
"""
2066
INPUT:
2067
2068
- ``xmin`` - (default: 0) start x position to start
2069
plotting
2070
2071
- ``xmax`` - (default: 1) stop x position to stop
2072
plotting
2073
2074
- ``eps`` - (default: determined by xmax) we view this
2075
vector as defining a function at the points xmin, xmin + eps, xmin
2076
+ 2\*eps, ...,
2077
2078
- ``res`` - (default: all points) total number of
2079
points to include in the graph
2080
2081
- ``connect`` - (default: True) if True draws a line;
2082
otherwise draw a list of points.
2083
2084
2085
EXAMPLES::
2086
2087
sage: eps=0.1
2088
sage: v = vector(RDF, [sin(n*eps) for n in range(100)])
2089
sage: v.plot_step(eps=eps, xmax=5, hue=0)
2090
"""
2091
if res is None:
2092
res = self.degree()
2093
if eps is None:
2094
eps = float(xmax - xmin)/res
2095
v = []
2096
x = xmin
2097
for i in range(0, self.degree(), int(math.ceil(self.degree()/res))):
2098
y = float(self[i])
2099
if x > xmax:
2100
break
2101
v.append((x,y))
2102
x += eps
2103
v.append((x,y))
2104
from sage.plot.all import line, points
2105
if connect:
2106
return line(v, **kwds)
2107
else:
2108
return points(v, **kwds)
2109
2110
def dot_product(self, right):
2111
r"""
2112
Return the dot product of ``self`` and ``right``, which is the sum of the
2113
product of the corresponding entries.
2114
2115
INPUT:
2116
2117
- ``right`` - a vector of the same degree as ``self``.
2118
It does not need to belong to the same parent as ``self``,
2119
so long as the necessary products and sums are defined.
2120
2121
OUTPUT:
2122
2123
If ``self`` and ``right`` are the vectors `\vec{x}` and `\vec{y}`,
2124
of degree `n`, then this method returns
2125
2126
.. math::
2127
2128
\sum_{i=1}^{n}x_iy_i
2129
2130
.. note::
2131
2132
The :meth:`inner_product` is a more general version of
2133
this method, and the :meth:`hermitian_inner_product`
2134
method may be more appropriate if your vectors
2135
have complex entries.
2136
2137
EXAMPLES::
2138
2139
sage: V = FreeModule(ZZ, 3)
2140
sage: v = V([1,2,3])
2141
sage: w = V([4,5,6])
2142
sage: v.dot_product(w)
2143
32
2144
2145
The vectors may be from different vector spaces,
2146
provided the necessary operations make sense.
2147
Notice that coercion will generate a result of
2148
the same type, even if the order of the
2149
arguments is reversed.::
2150
2151
sage: v = vector(ZZ, [1,2,3])
2152
sage: w = vector(FiniteField(3), [0,1,2])
2153
sage: ip = w.dot_product(v); ip
2154
2
2155
sage: ip.parent()
2156
Finite Field of size 3
2157
2158
sage: ip = v.dot_product(w); ip
2159
2
2160
sage: ip.parent()
2161
Finite Field of size 3
2162
2163
The dot product of a vector with itself is the 2-norm, squared. ::
2164
2165
sage: v = vector(QQ, [3, 4, 7])
2166
sage: v.dot_product(v) - v.norm()^2
2167
0
2168
2169
TESTS:
2170
2171
The second argument must be a free module element. ::
2172
2173
sage: v = vector(QQ, [1,2])
2174
sage: v.dot_product('junk')
2175
Traceback (most recent call last):
2176
...
2177
TypeError: right must be a free module element
2178
2179
The degrees of the arguments must match. ::
2180
2181
sage: v = vector(QQ, [1,2])
2182
sage: w = vector(QQ, [1,2,3])
2183
sage: v.dot_product(w)
2184
Traceback (most recent call last):
2185
...
2186
ArithmeticError: degrees (2 and 3) must be the same
2187
"""
2188
if not PY_TYPE_CHECK(right, FreeModuleElement):
2189
raise TypeError("right must be a free module element")
2190
r = right.list(copy=False)
2191
l = self.list(copy=False)
2192
if len(r) != len(l):
2193
raise ArithmeticError("degrees (%s and %s) must be the same"%(len(l),len(r)))
2194
if len(r) == 0:
2195
return self._parent.base_ring()(0)
2196
sum = l[0] * r[0]
2197
cdef Py_ssize_t i
2198
for i from 1 <= i < len(l):
2199
sum += l[i] * r[i]
2200
return sum
2201
2202
def cross_product(self, right):
2203
"""
2204
Return the cross product of self and right, which is only defined
2205
for vectors of length 3 or 7.
2206
2207
INPUT:
2208
2209
- ``right`` - A vector of the same size as ``self``, either
2210
degree three or degree seven.
2211
2212
OUTPUT:
2213
2214
The cross product (vector product) of ``self`` and ``right``,
2215
a vector of the same size of ``self`` and ``right``.
2216
2217
This product is performed under the assumption that the basis
2218
vectors are orthonormal.
2219
2220
EXAMPLES::
2221
2222
sage: v = vector([1,2,3]); w = vector([0,5,-9])
2223
sage: v.cross_product(v)
2224
(0, 0, 0)
2225
sage: u = v.cross_product(w); u
2226
(-33, 9, 5)
2227
sage: u.dot_product(v)
2228
0
2229
sage: u.dot_product(w)
2230
0
2231
2232
The cross product is defined for degree seven vectors as well.
2233
[WIKIPEDIA:CROSSPRODUCT]_
2234
The 3-D cross product is achieved using the quaternians,
2235
whereas the 7-D cross product is achieved using the octions. ::
2236
2237
sage: u = vector(QQ, [1, -1/3, 57, -9, 56/4, -4,1])
2238
sage: v = vector(QQ, [37, 55, -99/57, 9, -12, 11/3, 4/98])
2239
sage: u.cross_product(v)
2240
(1394815/2793, -2808401/2793, 39492/49, -48737/399, -9151880/2793, 62513/2793, -326603/171)
2241
2242
The degree seven cross product is anticommutative. ::
2243
2244
sage: u.cross_product(v) + v.cross_product(u)
2245
(0, 0, 0, 0, 0, 0, 0)
2246
2247
The degree seven cross product is distributive across addition. ::
2248
2249
sage: v = vector([-12, -8/9, 42, 89, -37, 60/99, 73])
2250
sage: u = vector([31, -42/7, 97, 80, 30/55, -32, 64])
2251
sage: w = vector([-25/4, 40, -89, -91, -72/7, 79, 58])
2252
sage: v.cross_product(u + w) - (v.cross_product(u) + v.cross_product(w))
2253
(0, 0, 0, 0, 0, 0, 0)
2254
2255
The degree seven cross product respects scalar multiplication. ::
2256
2257
sage: v = vector([2, 17, -11/5, 21, -6, 2/17, 16])
2258
sage: u = vector([-8, 9, -21, -6, -5/3, 12, 99])
2259
sage: (5*v).cross_product(u) - 5*(v.cross_product(u))
2260
(0, 0, 0, 0, 0, 0, 0)
2261
sage: v.cross_product(5*u) - 5*(v.cross_product(u))
2262
(0, 0, 0, 0, 0, 0, 0)
2263
sage: (5*v).cross_product(u) - (v.cross_product(5*u))
2264
(0, 0, 0, 0, 0, 0, 0)
2265
2266
The degree seven cross product respects the scalar triple product. ::
2267
2268
sage: v = vector([2,6,-7/4,-9/12,-7,12,9])
2269
sage: u = vector([22,-7,-9/11,12,15,15/7,11])
2270
sage: w = vector([-11,17,19,-12/5,44,21/56,-8])
2271
sage: v.dot_product(u.cross_product(w)) - w.dot_product(v.cross_product(u))
2272
0
2273
2274
TESTS:
2275
2276
Both vectors need to be of length three or both vectors need to be of length seven. ::
2277
2278
sage: u = vector(range(7))
2279
sage: v = vector(range(3))
2280
sage: u.cross_product(v)
2281
Traceback (most recent call last):
2282
...
2283
ArithmeticError: Cross product only defined for vectors of length three or seven, not (7 and 3)
2284
2285
REFERENCES:
2286
2287
.. [WIKIPEDIA:CROSSPRODUCT] Algebraic Properties of the Cross Product
2288
http://en.wikipedia.org/wiki/Cross_product
2289
2290
AUTHOR:
2291
2292
Billy Wonderly (2010-05-11), Added 7-D Cross Product
2293
"""
2294
if not PY_TYPE_CHECK(right, FreeModuleElement):
2295
raise TypeError("right must be a free module element")
2296
r = right.list(copy=False)
2297
l = self.list(copy=False)
2298
if len(r) == 3 and len(l) == 3:
2299
return vector([l[1]*r[2] - l[2]*r[1],
2300
l[2]*r[0] - l[0]*r[2],
2301
l[0]*r[1] - l[1]*r[0]])
2302
2303
elif len(r) == 7 and len(l) == 7:
2304
return 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],
2305
l[2]*r[4] - l[4]*r[2] + l[3]*r[0] - l[0]*r[3] + l[5]*r[6] - l[6]*r[5],
2306
l[3]*r[5] - l[5]*r[3] + l[4]*r[1] - l[1]*r[4] + l[6]*r[0] - l[0]*r[6],
2307
l[4]*r[6] - l[6]*r[4] + l[5]*r[2] - l[2]*r[5] + l[0]*r[1] - l[1]*r[0],
2308
l[5]*r[0] - l[0]*r[5] + l[6]*r[3] - l[3]*r[6] + l[1]*r[2] - l[2]*r[1],
2309
l[6]*r[1] - l[1]*r[6] + l[0]*r[4] - l[4]*r[0] + l[2]*r[3] - l[3]*r[2],
2310
l[0]*r[2] - l[2]*r[0] + l[1]*r[5] - l[5]*r[1] + l[3]*r[4] - l[4]*r[3]])
2311
2312
else:
2313
raise ArithmeticError("Cross product only defined for vectors of length three or seven, not (%s and %s)"%(len(l),len(r)))
2314
2315
2316
2317
def pairwise_product(self, right):
2318
"""
2319
Return the pairwise product of self and right, which is a vector of
2320
the products of the corresponding entries.
2321
2322
INPUT:
2323
2324
2325
- ``right`` - vector of the same degree as self. It
2326
need not be in the same vector space as self, as long as the
2327
coefficients can be multiplied.
2328
2329
2330
EXAMPLES::
2331
2332
sage: V = FreeModule(ZZ, 3)
2333
sage: v = V([1,2,3])
2334
sage: w = V([4,5,6])
2335
sage: v.pairwise_product(w)
2336
(4, 10, 18)
2337
sage: sum(v.pairwise_product(w)) == v.dot_product(w)
2338
True
2339
2340
::
2341
2342
sage: W = VectorSpace(GF(3),3)
2343
sage: w = W([0,1,2])
2344
sage: w.pairwise_product(v)
2345
(0, 2, 0)
2346
sage: w.pairwise_product(v).parent()
2347
Vector space of dimension 3 over Finite Field of size 3
2348
2349
Implicit coercion is well defined (regardless of order), so we
2350
get 2 even if we do the dot product in the other order.
2351
2352
::
2353
2354
sage: v.pairwise_product(w).parent()
2355
Vector space of dimension 3 over Finite Field of size 3
2356
2357
TESTS::
2358
2359
sage: x, y = var('x, y')
2360
2361
::
2362
2363
sage: parent(vector(ZZ,[1,2]).pairwise_product(vector(ZZ,[1,2])))
2364
Ambient free module of rank 2 over the principal ideal domain Integer Ring
2365
sage: parent(vector(ZZ,[1,2]).pairwise_product(vector(QQ,[1,2])))
2366
Vector space of dimension 2 over Rational Field
2367
sage: parent(vector(QQ,[1,2]).pairwise_product(vector(ZZ,[1,2])))
2368
Vector space of dimension 2 over Rational Field
2369
sage: parent(vector(QQ,[1,2]).pairwise_product(vector(QQ,[1,2])))
2370
Vector space of dimension 2 over Rational Field
2371
2372
::
2373
2374
sage: parent(vector(QQ,[1,2,3,4]).pairwise_product(vector(ZZ[x],[1,2,3,4])))
2375
Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2376
sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(QQ,[1,2,3,4])))
2377
Ambient free module of rank 4 over the principal ideal domain Univariate Polynomial Ring in x over Rational Field
2378
2379
::
2380
2381
sage: parent(vector(QQ,[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))
2382
Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2383
sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ,[1,2,3,4])))
2384
Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2385
2386
::
2387
2388
sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))
2389
Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2390
sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ[x],[1,2,3,4])))
2391
Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2392
2393
::
2394
2395
sage: parent(vector(QQ[y],[1,2,3,4]).pairwise_product(vector(ZZ[x][y],[1,2,3,4])))
2396
Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2397
sage: parent(vector(ZZ[x][y],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))
2398
Ambient free module of rank 4 over the integral domain Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field
2399
2400
::
2401
2402
sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(ZZ[y],[1,2,3,4])))
2403
Traceback (most recent call last):
2404
...
2405
TypeError: 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'
2406
sage: parent(vector(ZZ[x],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))
2407
Traceback (most recent call last):
2408
...
2409
TypeError: 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'
2410
sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(ZZ[y],[1,2,3,4])))
2411
Traceback (most recent call last):
2412
...
2413
TypeError: 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'
2414
sage: parent(vector(QQ[x],[1,2,3,4]).pairwise_product(vector(QQ[y],[1,2,3,4])))
2415
Traceback (most recent call last):
2416
...
2417
TypeError: 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'
2418
sage: v = vector({1: 1, 3: 2}) # test sparse vectors
2419
sage: w = vector({0: 6, 3: -4})
2420
sage: v.pairwise_product(w)
2421
(0, 0, 0, -8)
2422
sage: w.pairwise_product(v) == v.pairwise_product(w)
2423
True
2424
"""
2425
if not PY_TYPE_CHECK(right, FreeModuleElement):
2426
raise TypeError("right must be a free module element")
2427
if self._parent is not (<FreeModuleElement>right)._parent:
2428
self, right = canonical_coercion(self, right)
2429
return self._pairwise_product_(right)
2430
2431
def element(self):
2432
"""
2433
Simply returns self. This is useful, since for many objects,
2434
self.element() returns a vector corresponding to self.
2435
2436
EXAMPLES::
2437
2438
sage: v = vector([1/2,2/5,0]); v
2439
(1/2, 2/5, 0)
2440
sage: v.element()
2441
(1/2, 2/5, 0)
2442
"""
2443
return self
2444
2445
def get(self, Py_ssize_t i):
2446
"""
2447
The get method is in some cases more efficient (and more
2448
dangerous) than __getitem__, because it is not guaranteed to
2449
do any error checking.
2450
2451
EXAMPLES::
2452
2453
sage: vector([1/2,2/5,0]).get(0)
2454
1/2
2455
sage: vector([1/2,2/5,0]).get(3)
2456
Traceback (most recent call last):
2457
...
2458
IndexError: index out of range
2459
"""
2460
return self[i]
2461
2462
def set(self, Py_ssize_t i, x):
2463
"""
2464
The set method is meant to be more efficient than __setitem__,
2465
because it need not be guaranteed to do any error checking or
2466
coercion. Use with great, great care.
2467
2468
EXAMPLES::
2469
2470
sage: v = vector([1/2,2/5,0]); v
2471
(1/2, 2/5, 0)
2472
sage: v.set(2, -15/17); v
2473
(1/2, 2/5, -15/17)
2474
"""
2475
self[i] = x
2476
2477
2478
def normalize(self):
2479
"""
2480
Return this vector divided through by the first nonzero entry of
2481
this vector.
2482
2483
EXAMPLES::
2484
2485
sage: v = vector(QQ,[0,4/3,5,1,2])
2486
sage: v.normalize()
2487
(0, 1, 15/4, 3/4, 3/2)
2488
"""
2489
cdef Py_ssize_t i
2490
for i from 0 <= i < self._degree:
2491
if self[i] != 0:
2492
return (~self[i]) * self
2493
return self
2494
2495
def conjugate(self):
2496
r"""
2497
Returns a vector where every entry has been replaced by its complex conjugate.
2498
2499
OUTPUT:
2500
2501
A vector of the same length, over the same ring,
2502
but with each entry replaced by the complex conjugate, as
2503
implemented by the ``conjugate()`` method for elements of
2504
the base ring, which is presently always complex conjugation.
2505
2506
EXAMPLES::
2507
2508
sage: v = vector(CDF, [2.3 - 5.4*I, -1.7 + 3.6*I])
2509
sage: w = v.conjugate(); w
2510
(2.3 + 5.4*I, -1.7 - 3.6*I)
2511
sage: w.parent()
2512
Vector space of dimension 2 over Complex Double Field
2513
2514
Even if conjugation seems nonsensical over a certain ring, this
2515
method for vectors cooperates silently. ::
2516
2517
sage: u = vector(ZZ, range(6))
2518
sage: u.conjugate()
2519
(0, 1, 2, 3, 4, 5)
2520
2521
Sage implements a few specialized subfields of the complex numbers,
2522
such as the cyclotomic fields. This example uses such a field
2523
containing a primitive 7-th root of unity named ``a``. ::
2524
2525
sage: F.<a> = CyclotomicField(7)
2526
sage: v = vector(F, [a^i for i in range(7)])
2527
sage: v
2528
(1, a, a^2, a^3, a^4, a^5, -a^5 - a^4 - a^3 - a^2 - a - 1)
2529
sage: v.conjugate()
2530
(1, -a^5 - a^4 - a^3 - a^2 - a - 1, a^5, a^4, a^3, a^2, a)
2531
2532
Sparse vectors are returned as such. ::
2533
2534
sage: v = vector(CC, {1: 5 - 6*I, 3: -7*I}); v
2535
(0.000000000000000, 5.00000000000000 - 6.00000000000000*I, 0.000000000000000, -7.00000000000000*I)
2536
sage: v.is_sparse()
2537
True
2538
sage: vc = v.conjugate(); vc
2539
(0.000000000000000, 5.00000000000000 + 6.00000000000000*I, 0.000000000000000, 7.00000000000000*I)
2540
sage: vc.conjugate()
2541
(0.000000000000000, 5.00000000000000 - 6.00000000000000*I, 0.000000000000000, -7.00000000000000*I)
2542
2543
TESTS::
2544
2545
sage: n = 15
2546
sage: x = vector(CDF, [sin(i*pi/n)+cos(i*pi/n)*I for i in range(n)])
2547
sage: x + x.conjugate() in RDF^n
2548
True
2549
sage: I*(x - x.conjugate()) in RDF^n
2550
True
2551
2552
The parent of the conjugate is the same as that of the orginal vector.
2553
We test this by building a specialized vector space with a non-standard
2554
inner product, and constructing a test vector in this space. ::
2555
2556
sage: V = VectorSpace(CDF, 2, inner_product_matrix = [[2,1],[1,5]])
2557
sage: v = vector(CDF, [2-3*I, 4+5*I])
2558
sage: w = V(v)
2559
sage: w.parent()
2560
Ambient quadratic space of dimension 2 over Complex Double Field
2561
Inner product matrix:
2562
[2.0 1.0]
2563
[1.0 5.0]
2564
sage: w.conjugate().parent()
2565
Ambient quadratic space of dimension 2 over Complex Double Field
2566
Inner product matrix:
2567
[2.0 1.0]
2568
[1.0 5.0]
2569
"""
2570
V = self.parent()
2571
R = self.base_ring()
2572
degree = self.degree()
2573
if self.is_sparse():
2574
# this could be a dictionary comprehension in Python 3
2575
entries = {}
2576
for index, entry in self.iteritems():
2577
entries[index] = entry.conjugate()
2578
else:
2579
entries = [entry.conjugate() for entry in self]
2580
return V(vector(R, degree, entries))
2581
2582
def inner_product(self, right):
2583
r"""
2584
Returns the inner product of ``self`` and ``right``,
2585
possibly using an inner product matrix from the parent of ``self``.
2586
2587
INPUT:
2588
2589
- ``right`` - a vector of the same degree as ``self``
2590
2591
OUTPUT:
2592
2593
If the parent vector space does not have an inner product
2594
matrix defined, then this is the usual dot product
2595
(:meth:`dot_product`). If ``self`` and ``right`` are
2596
considered as single column matrices, `\vec{x}` and `\vec{y}`,
2597
and `A` is the inner product matrix, then this method computes
2598
2599
.. math::
2600
2601
\left(\vec{x}\right)^tA\vec{y}
2602
2603
where `t` indicates the transpose.
2604
2605
.. note::
2606
2607
If your vectors have complex entries, the
2608
:meth:`hermitian_inner_product` may be more
2609
appropriate for your purposes.
2610
2611
EXAMPLES::
2612
2613
sage: v = vector(QQ, [1,2,3])
2614
sage: w = vector(QQ, [-1,2,-3])
2615
sage: v.inner_product(w)
2616
-6
2617
sage: v.inner_product(w) == v.dot_product(w)
2618
True
2619
2620
The vector space or free module that is the parent to
2621
``self`` can have an inner product matrix defined, which
2622
will be used by this method. This matrix will be passed
2623
through to subspaces. ::
2624
2625
sage: ipm = matrix(ZZ,[[2,0,-1], [0,2,0], [-1,0,6]])
2626
sage: M = FreeModule(ZZ, 3, inner_product_matrix = ipm)
2627
sage: v = M([1,0,0])
2628
sage: v.inner_product(v)
2629
2
2630
sage: K = M.span_of_basis([[0/2,-1/2,-1/2], [0,1/2,-1/2],[2,0,0]])
2631
sage: (K.0).inner_product(K.0)
2632
2
2633
sage: w = M([1,3,-1])
2634
sage: v = M([2,-4,5])
2635
sage: w.row()*ipm*v.column() == w.inner_product(v)
2636
True
2637
2638
Note that the inner product matrix comes from the parent of ``self``.
2639
So if a vector is not an element of the correct parent, the result
2640
could be a source of confusion. ::
2641
2642
sage: V = VectorSpace(QQ, 2, inner_product_matrix=[[1,2],[2,1]])
2643
sage: v = V([12, -10])
2644
sage: w = vector(QQ, [10,12])
2645
sage: v.inner_product(w)
2646
88
2647
sage: w.inner_product(v)
2648
0
2649
sage: w = V(w)
2650
sage: w.inner_product(v)
2651
88
2652
2653
.. note::
2654
2655
The use of an inner product matrix makes no restrictions on
2656
the nature of the matrix. In particular, in this context it
2657
need not be Hermitian and positive-definite (as it is in the
2658
example above).
2659
2660
TESTS:
2661
2662
Most error handling occurs in the :meth:`dot_product` method.
2663
But with an inner product defined, this method will check
2664
that the input is a vector or free module element. ::
2665
2666
sage: W = VectorSpace(RDF, 2, inner_product_matrix = matrix(RDF, 2, [1.0,2.0,3.0,4.0]))
2667
sage: v = W([2.0, 4.0])
2668
sage: v.inner_product(5)
2669
Traceback (most recent call last):
2670
...
2671
TypeError: right must be a free module element
2672
"""
2673
if self.parent().is_ambient() and self.parent()._inner_product_is_dot_product():
2674
return self.dot_product(right)
2675
if not isinstance(right, FreeModuleElement):
2676
raise TypeError("right must be a free module element")
2677
M = self.parent()
2678
if M.is_ambient() or M.uses_ambient_inner_product():
2679
A = M.ambient_module().inner_product_matrix()
2680
return A.linear_combination_of_rows(self).dot_product(right)
2681
else:
2682
A = M.inner_product_matrix()
2683
v = M.coordinate_vector(self)
2684
w = M.coordinate_vector(right)
2685
return A.linear_combination_of_rows(v).dot_product(w)
2686
2687
def outer_product(self, right):
2688
r"""
2689
Returns a matrix, the outer product of two vectors ``self`` and ``right``.
2690
2691
INPUT:
2692
2693
- ``right`` - a vector (or free module element) of any size, whose
2694
elements are compatible (with regard to multiplication) with the
2695
elements of ``self``.
2696
2697
OUTPUT:
2698
2699
The outer product of two vectors `x` and `y` (respectively
2700
``self`` and ``right``) can be described several ways. If we
2701
interpret `x` as a `m\times 1` matrix and interpret `y` as a
2702
`1\times n` matrix, then the outer product is the `m\times n`
2703
matrix from the usual matrix product `xy`. Notice how this
2704
is the "opposite" in some ways from an inner product (which
2705
would require `m=n`).
2706
2707
If we just consider vectors, use each entry of `x` to create
2708
a scalar multiples of the vector `y` and use these vectors as
2709
the rows of a matrix. Or use each entry of `y` to create a
2710
scalar multiples of `x` and use these vectors as the columns
2711
of a matrix.
2712
2713
EXAMPLES::
2714
2715
sage: u = vector(QQ, [1/2, 1/3, 1/4, 1/5])
2716
sage: v = vector(ZZ, [60, 180, 600])
2717
sage: u.outer_product(v)
2718
[ 30 90 300]
2719
[ 20 60 200]
2720
[ 15 45 150]
2721
[ 12 36 120]
2722
sage: M = v.outer_product(u); M
2723
[ 30 20 15 12]
2724
[ 90 60 45 36]
2725
[300 200 150 120]
2726
sage: M.parent()
2727
Full MatrixSpace of 3 by 4 dense matrices over Rational Field
2728
2729
The more general :meth:`sage.matrix.matrix2.tensor_product` is an
2730
operation on a pair of matrices. If we construe a pair of vectors
2731
as a column vector and a row vector, then an outer product and a
2732
tensor product are identical. Thus `tensor_product` is a synonym
2733
for this method. ::
2734
2735
sage: u = vector(QQ, [1/2, 1/3, 1/4, 1/5])
2736
sage: v = vector(ZZ, [60, 180, 600])
2737
sage: u.tensor_product(v) == (u.column()).tensor_product(v.row())
2738
True
2739
2740
The result is always a dense matrix, no matter if the two
2741
vectors are, or are not, dense. ::
2742
2743
sage: d = vector(ZZ,[4,5], sparse=False)
2744
sage: s = vector(ZZ, [1,2,3], sparse=True)
2745
sage: dd = d.outer_product(d)
2746
sage: ds = d.outer_product(s)
2747
sage: sd = s.outer_product(d)
2748
sage: ss = s.outer_product(s)
2749
sage: all([dd.is_dense(), ds.is_dense(), sd.is_dense(), dd.is_dense()])
2750
True
2751
2752
Vectors with no entries do the right thing. ::
2753
2754
sage: v = vector(ZZ, [])
2755
sage: z = v.outer_product(v)
2756
sage: z.parent()
2757
Full MatrixSpace of 0 by 0 dense matrices over Integer Ring
2758
2759
There is a fair amount of latitude in the value of the ``right``
2760
vector, and the matrix that results can have entries from a new
2761
ring large enough to contain the result. If you know better,
2762
you can sometimes bring the result down to a less general ring. ::
2763
2764
sage: R.<t> = ZZ[]
2765
sage: v = vector(R, [12, 24*t])
2766
sage: w = vector(QQ, [1/2, 1/3, 1/4])
2767
sage: op = v.outer_product(w)
2768
sage: op
2769
[ 6 4 3]
2770
[12*t 8*t 6*t]
2771
sage: op.base_ring()
2772
Univariate Polynomial Ring in t over Rational Field
2773
sage: m = op.change_ring(R); m
2774
[ 6 4 3]
2775
[12*t 8*t 6*t]
2776
sage: m.base_ring()
2777
Univariate Polynomial Ring in t over Integer Ring
2778
2779
But some inputs are not compatible, even if vectors. ::
2780
2781
sage: w = vector(GF(5), [1,2])
2782
sage: v = vector(GF(7), [1,2,3,4])
2783
sage: z = w.outer_product(v)
2784
Traceback (most recent call last):
2785
...
2786
TypeError: 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'
2787
2788
And some inputs don't make any sense at all. ::
2789
2790
sage: w=vector(QQ, [5,10])
2791
sage: z=w.outer_product(6)
2792
Traceback (most recent call last):
2793
...
2794
TypeError: right operand in an outer product must be a vector, not an element of Integer Ring
2795
"""
2796
if not PY_TYPE_CHECK(right, FreeModuleElement):
2797
raise TypeError('right operand in an outer product must be a vector, not an element of %s' % right.parent())
2798
return self.column()*right.row()
2799
2800
# tensor product is an alias in the special case of two vectors
2801
tensor_product = outer_product
2802
2803
def hermitian_inner_product(self, right):
2804
r"""
2805
Returns the dot product, but with the entries of the first vector
2806
conjugated beforehand.
2807
2808
INPUT:
2809
2810
- ``right`` - a vector of the same degree as ``self``
2811
2812
OUTPUT:
2813
2814
If ``self`` and ``right`` are the vectors `\vec{x}` and
2815
`\vec{y}` of degree `n` then this routine computes
2816
2817
.. math::
2818
2819
\sum_{i=1}^{n}\overline{x}_i{y}_i
2820
2821
where the bar indicates complex conjugation.
2822
2823
.. note::
2824
2825
If your vectors do not contain complex entries, then
2826
:meth:`dot_product` will return the same result without
2827
the overhead of conjugating elements of ``self``.
2828
2829
If you are not computing a weighted inner product, and
2830
your vectors do not have complex entries, then the
2831
:meth:`dot_product` will return the same result.
2832
2833
EXAMPLES::
2834
2835
sage: v = vector(CDF, [2+3*I, 5-4*I])
2836
sage: w = vector(CDF, [6-4*I, 2+3*I])
2837
sage: v.hermitian_inner_product(w)
2838
-2.0 - 3.0*I
2839
2840
Sage implements a few specialized fields over the complex numbers,
2841
such as cyclotomic fields and quadratic number fields. So long as
2842
the base rings have a conjugate method, then the Hermitian inner
2843
product will be available. ::
2844
2845
sage: Q.<a> = QuadraticField(-7)
2846
sage: a^2
2847
-7
2848
sage: v = vector(Q, [3+a, 5-2*a])
2849
sage: w = vector(Q, [6, 4+3*a])
2850
sage: v.hermitian_inner_product(w)
2851
17*a - 4
2852
2853
The Hermitian inner product should be additive in
2854
each argument (we only need to test one), linear
2855
in each argument (with conjugation on the first scalar),
2856
and anti-commutative. ::
2857
2858
sage: alpha = CDF(5.0 + 3.0*I)
2859
sage: u = vector(CDF, [2+4*I, -3+5*I, 2-7*I])
2860
sage: v = vector(CDF, [-1+3*I, 5+4*I, 9-2*I])
2861
sage: w = vector(CDF, [8+3*I, -4+7*I, 3-6*I])
2862
sage: (u+v).hermitian_inner_product(w) == u.hermitian_inner_product(w) + v.hermitian_inner_product(w)
2863
True
2864
sage: (alpha*u).hermitian_inner_product(w) == alpha.conjugate()*u.hermitian_inner_product(w)
2865
True
2866
sage: u.hermitian_inner_product(alpha*w) == alpha*u.hermitian_inner_product(w)
2867
True
2868
sage: u.hermitian_inner_product(v) == v.hermitian_inner_product(u).conjugate()
2869
True
2870
2871
For vectors with complex entries, the Hermitian inner product
2872
has a more natural relationship with the 2-norm (which is the
2873
default for the :meth:`norm` method). The norm squared equals
2874
the Hermitian inner product of the vector with itself. ::
2875
2876
sage: v = vector(CDF, [-0.66+0.47*I, -0.60+0.91*I, -0.62-0.87*I, 0.53+0.32*I])
2877
sage: abs(v.norm()^2 - v.hermitian_inner_product(v)) < 1.0e-10
2878
True
2879
2880
TESTS:
2881
2882
This method is built on the :meth:`dot_product` method,
2883
which allows for a wide variety of inputs. Any error
2884
handling happens there. ::
2885
2886
sage: v = vector(CDF, [2+3*I])
2887
sage: w = vector(CDF, [5+2*I, 3+9*I])
2888
sage: v.hermitian_inner_product(w)
2889
Traceback (most recent call last):
2890
...
2891
ArithmeticError: degrees (1 and 2) must be the same
2892
"""
2893
return (self.conjugate()).dot_product(right)
2894
2895
def is_dense(self):
2896
"""
2897
Return True if this is a dense vector, which is just a
2898
statement about the data structure, not the number of nonzero
2899
entries.
2900
2901
EXAMPLES::
2902
2903
sage: vector([1/2,2/5,0]).is_dense()
2904
True
2905
sage: vector([1/2,2/5,0],sparse=True).is_dense()
2906
False
2907
"""
2908
return self.is_dense_c()
2909
2910
cdef bint is_dense_c(self):
2911
return self.parent().is_dense()
2912
2913
def is_sparse(self):
2914
"""
2915
Return True if this is a sparse vector, which is just a
2916
statement about the data structure, not the number of nonzero
2917
entries.
2918
2919
EXAMPLES::
2920
2921
sage: vector([1/2,2/5,0]).is_sparse()
2922
False
2923
sage: vector([1/2,2/5,0],sparse=True).is_sparse()
2924
True
2925
"""
2926
return self.is_sparse_c()
2927
2928
cdef bint is_sparse_c(self):
2929
return self.parent().is_sparse()
2930
2931
def is_vector(self):
2932
"""
2933
Return True, since this is a vector.
2934
2935
EXAMPLES::
2936
2937
sage: vector([1/2,2/5,0]).is_vector()
2938
True
2939
"""
2940
return True
2941
2942
def _mathematica_init_(self):
2943
"""
2944
Returns string representation of this vector as a Mathematica
2945
list.
2946
2947
EXAMPLES::
2948
2949
sage: vector((1,2,3), QQ)._mathematica_init_()
2950
'{1/1, 2/1, 3/1}'
2951
sage: mathematica(vector((1,2,3), QQ)) #optional -- requires mathematica
2952
{1, 2, 3}
2953
sage: a = vector(SR, 5, [1, x, x^2, sin(x), pi]); a
2954
(1, x, x^2, sin(x), pi)
2955
sage: a._mathematica_init_()
2956
'{1, x, (x)^(2), Sin[x], Pi}'
2957
"""
2958
return '{' + ', '.join([x._mathematica_init_() for x in self.list()]) + '}'
2959
2960
## def zero_out_positions(self, P):
2961
## """
2962
## Set the positions of self in the list P equal to 0.
2963
## """
2964
## z = self.base_ring()(0)
2965
## d = self.degree()
2966
## for n in P:
2967
## self[n] = z
2968
2969
def nonzero_positions(self):
2970
"""
2971
Return the sorted list of integers i such that self[i] != 0.
2972
2973
EXAMPLES::
2974
2975
sage: vector([-1,0,3,0,0,0,0.01]).nonzero_positions()
2976
[0, 2, 6]
2977
"""
2978
z = self.base_ring()(0)
2979
v = self.list()
2980
cdef Py_ssize_t i
2981
return [i for i from 0 <= i < self.degree() if v[i] != z]
2982
2983
def support(self): # do not override.
2984
"""
2985
Return the integers i such that self[i] != 0.
2986
This is the same as the ``nonzero_positions`` function.
2987
2988
EXAMPLES::
2989
2990
sage: vector([-1,0,3,0,0,0,0.01]).support()
2991
[0, 2, 6]
2992
"""
2993
return self.nonzero_positions()
2994
2995
def _latex_(self):
2996
r"""
2997
Return a latex representation of the vector ``self``.
2998
2999
OUTPUT:
3000
3001
If self is the free module element (1,2,3,4),
3002
then a string with the following latex is returned:
3003
"\left(1,\,2,\,3,\,4\right)" (without the quotes).
3004
The vector is enclosed in parentheses by default,
3005
but the delimiters can be changed using the command
3006
``latex.vector_delimiters(...)`` as in the example below.
3007
3008
EXAMPLES::
3009
3010
sage: v = vector(QQ, [1,2,3])
3011
sage: latex(v)
3012
\left(1,\,2,\,3\right)
3013
3014
This is an example of how to change the delimiters.
3015
You have the power to mix and match, though it is
3016
probably not advisable. For more detail see
3017
:meth:`~sage.misc.latex.Latex.vector_delimiters`.
3018
3019
sage: latex.vector_delimiters('[', '\\rangle')
3020
sage: w = vector(CDF, [1,2,3])
3021
sage: latex(w)
3022
\left[1.0,\,2.0,\,3.0\right\rangle
3023
"""
3024
latex = sage.misc.latex.latex
3025
vector_delimiters = latex.vector_delimiters()
3026
s = '\\left' + vector_delimiters[0]
3027
s += ',\,'.join([latex(a) for a in self.list()])
3028
return s + '\\right' + vector_delimiters[1]
3029
3030
def dense_vector(self):
3031
"""
3032
Return dense version of self. If self is dense, just return
3033
self; otherwise, create and return correspond dense vector.
3034
3035
EXAMPLES::
3036
3037
sage: vector([-1,0,3,0,0,0]).dense_vector().is_dense()
3038
True
3039
sage: vector([-1,0,3,0,0,0],sparse=True).dense_vector().is_dense()
3040
True
3041
sage: vector([-1,0,3,0,0,0],sparse=True).dense_vector()
3042
(-1, 0, 3, 0, 0, 0)
3043
"""
3044
if self.is_dense():
3045
return self
3046
else:
3047
return self.parent().ambient_module().dense_module()(self.list())
3048
3049
def sparse_vector(self):
3050
"""
3051
Return sparse version of self. If self is sparse, just return
3052
self; otherwise, create and return correspond sparse vector.
3053
3054
EXAMPLES::
3055
3056
sage: vector([-1,0,3,0,0,0]).sparse_vector().is_sparse()
3057
True
3058
sage: vector([-1,0,3,0,0,0]).sparse_vector().is_sparse()
3059
True
3060
sage: vector([-1,0,3,0,0,0]).sparse_vector()
3061
(-1, 0, 3, 0, 0, 0)
3062
"""
3063
if self.is_sparse():
3064
return self
3065
else:
3066
return self.parent().ambient_module().sparse_module()(self.list())
3067
3068
3069
def apply_map(self, phi, R=None, sparse=None):
3070
"""
3071
Apply the given map phi (an arbitrary Python function or callable
3072
object) to this free module element. If R is not given,
3073
automatically determine the base ring of the resulting element.
3074
3075
INPUT:
3076
sparse -- True or False will control whether the result
3077
is sparse. By default, the result is sparse iff self
3078
is sparse.
3079
3080
3081
- ``phi`` - arbitrary Python function or callable
3082
object
3083
3084
- ``R`` - (optional) ring
3085
3086
3087
OUTPUT: a free module element over R
3088
3089
EXAMPLES::
3090
3091
sage: m = vector([1,x,sin(x+1)])
3092
sage: m.apply_map(lambda x: x^2)
3093
(1, x^2, sin(x + 1)^2)
3094
sage: m.apply_map(sin)
3095
(sin(1), sin(x), sin(sin(x + 1)))
3096
3097
::
3098
3099
sage: m = vector(ZZ, 9, range(9))
3100
sage: k.<a> = GF(9)
3101
sage: m.apply_map(k)
3102
(0, 1, 2, 0, 1, 2, 0, 1, 2)
3103
3104
In this example, we explicitly specify the codomain.
3105
3106
::
3107
3108
sage: s = GF(3)
3109
sage: f = lambda x: s(x)
3110
sage: n = m.apply_map(f, k); n
3111
(0, 1, 2, 0, 1, 2, 0, 1, 2)
3112
sage: n.parent()
3113
Vector space of dimension 9 over Finite Field in a of size 3^2
3114
3115
If your map sends 0 to a non-zero value, then your resulting
3116
vector is not mathematically sparse::
3117
3118
sage: v = vector([0] * 6 + [1], sparse=True); v
3119
(0, 0, 0, 0, 0, 0, 1)
3120
sage: v2 = v.apply_map(lambda x: x+1); v2
3121
(1, 1, 1, 1, 1, 1, 2)
3122
3123
but it's still represented with a sparse data type::
3124
3125
sage: parent(v2)
3126
Ambient sparse free module of rank 7 over the principal ideal domain Integer Ring
3127
3128
This data type is inefficient for dense vectors, so you may
3129
want to specify sparse=False::
3130
3131
sage: v2 = v.apply_map(lambda x: x+1, sparse=False); v2
3132
(1, 1, 1, 1, 1, 1, 2)
3133
sage: parent(v2)
3134
Ambient free module of rank 7 over the principal ideal domain Integer Ring
3135
3136
Or if you have a map that will result in mostly zeroes, you may
3137
want to specify sparse=True::
3138
3139
sage: v = vector(srange(10))
3140
sage: v2 = v.apply_map(lambda x: 0 if x else 1, sparse=True); v2
3141
(1, 0, 0, 0, 0, 0, 0, 0, 0, 0)
3142
sage: parent(v2)
3143
Ambient sparse free module of rank 10 over the principal ideal domain Integer Ring
3144
3145
TESTS::
3146
3147
sage: m = vector(SR,[])
3148
sage: m.apply_map(lambda x: x*x) == m
3149
True
3150
3151
Check that we don't unnecessarily apply phi to 0 in the sparse case::
3152
3153
sage: m = vector(ZZ, range(1, 4), sparse=True)
3154
sage: m.apply_map(lambda x: 1/x)
3155
(1, 1/2, 1/3)
3156
3157
sage: parent(vector(RDF, (), sparse=True).apply_map(lambda x: x, sparse=True))
3158
Sparse vector space of dimension 0 over Real Double Field
3159
sage: parent(vector(RDF, (), sparse=True).apply_map(lambda x: x, sparse=False))
3160
Vector space of dimension 0 over Real Double Field
3161
sage: parent(vector(RDF, (), sparse=False).apply_map(lambda x: x, sparse=True))
3162
Sparse vector space of dimension 0 over Real Double Field
3163
sage: parent(vector(RDF, (), sparse=False).apply_map(lambda x: x, sparse=False))
3164
Vector space of dimension 0 over Real Double Field
3165
"""
3166
if sparse is None:
3167
sparse = self.is_sparse()
3168
3169
if self._degree == 0:
3170
if sparse == self.is_sparse():
3171
from copy import copy
3172
return copy(self)
3173
elif sparse:
3174
return self.sparse_vector()
3175
else:
3176
return self.dense_vector()
3177
3178
v = None
3179
3180
if self.is_sparse():
3181
if len(self.dict(copy=False)) < self._degree:
3182
# OK, we have some zero entries.
3183
zero_res = phi(self.base_ring()(0))
3184
if not zero_res.is_zero():
3185
# And phi maps 0 to a non-zero value.
3186
v = [zero_res] * self._degree
3187
for i,z in self.dict(copy=False).items():
3188
v[i] = phi(z)
3189
3190
if v is None:
3191
# phi maps 0 to 0 (or else we don't have any zeroes at all)
3192
v = dict([(i,phi(z)) for i,z in self.dict(copy=False).items()])
3193
else:
3194
v = [phi(z) for z in self.list()]
3195
3196
if R is None:
3197
return vector(v, sparse=sparse)
3198
else:
3199
return vector(R, v, sparse=sparse)
3200
3201
3202
def _derivative(self, var=None):
3203
"""
3204
Differentiate with respect to var by differentiating each element
3205
with respect to var.
3206
3207
.. seealso:
3208
3209
:meth:`derivative`
3210
3211
EXAMPLES::
3212
3213
sage: v = vector([1,x,x^2])
3214
sage: v._derivative(x)
3215
(0, 1, 2*x)
3216
sage: type(v._derivative(x)) == type(v)
3217
True
3218
sage: v = vector([1,x,x^2], sparse=True)
3219
sage: v._derivative(x)
3220
(0, 1, 2*x)
3221
sage: type(v._derivative(x)) == type(v)
3222
True
3223
3224
If no variables are specified and the vector contains callable
3225
symbolic expressions, then calculate the matrix derivative
3226
(i.e., the Jacobian matrix)::
3227
3228
sage: T(r,theta)=[r*cos(theta),r*sin(theta)]
3229
sage: T
3230
(r, theta) |--> (r*cos(theta), r*sin(theta))
3231
sage: T.diff() # matrix derivative
3232
[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]
3233
[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]
3234
sage: diff(T) # matrix derivative again
3235
[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)]
3236
[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)]
3237
sage: T.diff().det() # Jacobian
3238
(r, theta) |--> r*sin(theta)^2 + r*cos(theta)^2
3239
"""
3240
if var is None:
3241
if sage.symbolic.callable.is_CallableSymbolicExpressionRing(self.base_ring()):
3242
return sage.calculus.all.jacobian(self, self.base_ring().arguments())
3243
else:
3244
raise ValueError("No differentiation variable specified.")
3245
3246
# We would just use apply_map, except that Cython doesn't
3247
# allow lambda functions
3248
if self._degree == 0:
3249
from copy import copy
3250
return copy(self)
3251
3252
if self.is_sparse():
3253
v = dict([(i,z.derivative(var)) for i,z in self.dict().items()])
3254
else:
3255
v = [z.derivative(var) for z in self.list()]
3256
3257
return self.parent().ambient_module()(v)
3258
3259
def derivative(self, *args):
3260
"""
3261
Derivative with respect to variables supplied in args.
3262
3263
Multiple variables and iteration counts may be supplied; see
3264
documentation for the global derivative() function for more
3265
details.
3266
3267
:meth:`diff` is an alias of this function.
3268
3269
EXAMPLES::
3270
3271
sage: v = vector([1,x,x^2])
3272
sage: v.derivative(x)
3273
(0, 1, 2*x)
3274
sage: type(v.derivative(x)) == type(v)
3275
True
3276
sage: v = vector([1,x,x^2], sparse=True)
3277
sage: v.derivative(x)
3278
(0, 1, 2*x)
3279
sage: type(v.derivative(x)) == type(v)
3280
True
3281
sage: v.derivative(x,x)
3282
(0, 0, 2)
3283
"""
3284
return multi_derivative(self, args)
3285
3286
diff = derivative
3287
3288
def integral(self, *args, **kwds):
3289
"""
3290
Returns a symbolic integral of the vector, component-wise.
3291
3292
:meth:`integrate` is an alias of the function.
3293
3294
EXAMPLES::
3295
3296
sage: t=var('t')
3297
sage: r=vector([t,t^2,sin(t)])
3298
sage: r.integral(t)
3299
(1/2*t^2, 1/3*t^3, -cos(t))
3300
sage: integrate(r,t)
3301
(1/2*t^2, 1/3*t^3, -cos(t))
3302
sage: r.integrate(t,0,1)
3303
(1/2, 1/3, -cos(1) + 1)
3304
3305
"""
3306
from sage.misc.functional import integral
3307
3308
# If Cython supported lambda functions, we would just do
3309
# return self.apply_map(lambda x: integral(x,*args, **kwds) for x in self)
3310
3311
if self.is_sparse():
3312
v = dict([(i,integral(z,*args,**kwds)) for i,z in self.dict(copy=False).items()])
3313
else:
3314
v = [integral(z,*args,**kwds) for z in self.list()]
3315
3316
return vector(v,sparse=self.is_sparse())
3317
3318
integrate=integral
3319
3320
3321
def nintegral(self, *args, **kwds):
3322
"""
3323
Returns a numeric integral of the vector, component-wise, and
3324
the result of the nintegral command on each component of the
3325
input.
3326
3327
:meth:`nintegrate` is an alias of the function.
3328
3329
EXAMPLES::
3330
3331
sage: t=var('t')
3332
sage: r=vector([t,t^2,sin(t)])
3333
sage: vec,answers=r.nintegral(t,0,1)
3334
sage: vec
3335
(0.5, 0.333333333333, 0.459697694132)
3336
sage: type(vec)
3337
<type 'sage.modules.vector_real_double_dense.Vector_real_double_dense'>
3338
sage: answers
3339
[(0.5, 5.551115123125784e-15, 21, 0), (0.3333333333333..., 3.70074341541719e-15, 21, 0), (0.45969769413186..., 5.103669643922841e-15, 21, 0)]
3340
3341
sage: r=vector([t,0,1], sparse=True)
3342
sage: r.nintegral(t,0,1)
3343
((0.5, 0.0, 1.0), {0: (0.5, 5.551115123125784e-15, 21, 0), 2: (1.0, 1.11022302462515...e-14, 21, 0)})
3344
3345
"""
3346
# If Cython supported lambda functions, we would just do
3347
# return self.apply_map(lambda x: x.nintegral(*args, **kwds) for x in self)
3348
3349
if self.is_sparse():
3350
v = [(i,z.nintegral(*args,**kwds)) for i,z in self.dict(copy=False).items()]
3351
answers = dict([(i,a[0]) for i,a in v])
3352
v=dict(v)
3353
else:
3354
v = [z.nintegral(*args,**kwds) for z in self.list()]
3355
answers = [a[0] for a in v]
3356
3357
return (vector(answers,sparse=self.is_sparse()), v)
3358
3359
nintegrate=nintegral
3360
3361
#############################################
3362
# Generic dense element
3363
#############################################
3364
def make_FreeModuleElement_generic_dense(parent, entries, degree):
3365
"""
3366
EXAMPLES::
3367
3368
sage: sage.modules.free_module_element.make_FreeModuleElement_generic_dense(QQ^3, [1,2,-3/7], 3)
3369
(1, 2, -3/7)
3370
"""
3371
# If you think you want to change this function, don't.
3372
# Instead make a new version with a name like
3373
# make_FreeModuleElement_generic_dense_v1
3374
# and changed the reduce method below.
3375
cdef FreeModuleElement_generic_dense v
3376
v = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)
3377
v._entries = entries
3378
v._parent = parent
3379
v._degree = degree
3380
return v
3381
3382
def make_FreeModuleElement_generic_dense_v1(parent, entries, degree, is_mutable):
3383
"""
3384
EXAMPLES::
3385
3386
sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_dense_v1(QQ^3, [1,2,-3/7], 3, True); v
3387
(1, 2, -3/7)
3388
sage: v[0] = 10; v
3389
(10, 2, -3/7)
3390
sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_dense_v1(QQ^3, [1,2,-3/7], 3, False); v
3391
(1, 2, -3/7)
3392
sage: v[0] = 10
3393
Traceback (most recent call last):
3394
...
3395
ValueError: vector is immutable; please change a copy instead (use copy())
3396
"""
3397
# If you think you want to change this function, don't.
3398
# Instead make a new version with a name like
3399
# make_FreeModuleElement_generic_dense_v2
3400
# and changed the reduce method below.
3401
cdef FreeModuleElement_generic_dense v
3402
v = FreeModuleElement_generic_dense.__new__(FreeModuleElement_generic_dense)
3403
v._entries = entries
3404
v._parent = parent
3405
v._degree = degree
3406
v._is_mutable = is_mutable
3407
return v
3408
3409
cdef class FreeModuleElement_generic_dense(FreeModuleElement):
3410
"""
3411
A generic dense element of a free module.
3412
"""
3413
## these work fine on the command line but fail in doctests :-(
3414
## TESTS:
3415
## sage: V = ZZ^3
3416
## sage: loads(dumps(V)) == V
3417
## True
3418
## sage: v = V.0
3419
## sage: loads(dumps(v)) == v
3420
## True
3421
## sage: v = (QQ['x']^3).0
3422
## sage: loads(dumps(v)) == v
3423
## True
3424
cdef _new_c(self, object v):
3425
# Create a new dense free module element with minimal overhead and
3426
# no type checking.
3427
cdef FreeModuleElement_generic_dense x
3428
x = <FreeModuleElement_generic_dense>PY_NEW(<object>PY_TYPE(self))
3429
x._is_mutable = 1
3430
x._parent = self._parent
3431
x._entries = v
3432
x._degree = self._degree
3433
return x
3434
3435
cdef bint is_dense_c(self):
3436
return 1
3437
3438
cdef bint is_sparse_c(self):
3439
return 0
3440
3441
def _hash(self):
3442
"""
3443
Return hash of an immutable form of self (works even if self
3444
is mutable).
3445
3446
sage: v = vector([-1,0,3,pi])
3447
sage: type(v)
3448
<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>
3449
sage: v._hash() # random output
3450
"""
3451
return hash(tuple(list(self)))
3452
3453
def __copy__(self):
3454
"""
3455
Return a copy of this generic dense vector.
3456
3457
EXAMPLES::
3458
3459
sage: v = vector([-1,0,3,pi])
3460
sage: type(v)
3461
<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>
3462
sage: v.__copy__()
3463
(-1, 0, 3, pi)
3464
sage: v.__copy__() is v
3465
False
3466
3467
sage: copy(v)
3468
(-1, 0, 3, pi)
3469
sage: copy(v) == v
3470
True
3471
sage: copy(v) is v
3472
False
3473
"""
3474
return self._new_c(list(self._entries))
3475
3476
def __init__(self, parent, entries, coerce=True, copy=True):
3477
"""
3478
EXAMPLES::
3479
3480
sage: type(vector([-1,0,3,pi])) # indirect doctest
3481
<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>
3482
3483
TESTS:
3484
3485
Check that #11751 is fixed::
3486
3487
sage: K.<x> = QQ[]
3488
sage: M = K^1
3489
sage: N = M.span([[1/x]]); N
3490
Free module of degree 1 and rank 1 over Univariate Polynomial Ring in x over Rational Field
3491
Echelon basis matrix:
3492
[1/x]
3493
sage: N([1/x]) # this used to fail prior to #11751
3494
(1/x)
3495
sage: N([1/x^2])
3496
Traceback (most recent call last):
3497
...
3498
TypeError: element (= [1/x^2]) is not in free module
3499
3500
::
3501
3502
sage: L=K^2
3503
sage: R=L.span([[x,0],[0,1/x]], check=False, already_echelonized=True)
3504
sage: R.basis()[0][0].parent()
3505
Fraction Field of Univariate Polynomial Ring in x over Rational Field
3506
sage: R=L.span([[x,x^2]])
3507
sage: R.basis()[0][0].parent()
3508
Univariate Polynomial Ring in x over Rational Field
3509
"""
3510
FreeModuleElement.__init__(self, parent)
3511
R = self.parent().base_ring()
3512
if entries == 0:
3513
entries = [R(0)]*self.degree()
3514
else:
3515
if not isinstance(entries, (list, tuple)):
3516
raise TypeError("entries (=%s) must be a list"%(entries, ))
3517
3518
if len(entries) != self.degree():
3519
raise TypeError("entries must be a list of length %s"%\
3520
self.degree())
3521
if coerce:
3522
if len(entries) != 0:
3523
coefficient_ring = parent.basis()[0][0].parent()
3524
try:
3525
entries = [coefficient_ring(x) for x in entries]
3526
except TypeError:
3527
raise TypeError("Unable to coerce entries (=%s) to coefficients in %s"%(entries, coefficient_ring))
3528
elif copy:
3529
# Make a copy
3530
entries = list(entries)
3531
self._entries = entries
3532
3533
cpdef ModuleElement _add_(left, ModuleElement right):
3534
"""
3535
Add left and right.
3536
3537
EXAMPLES::
3538
3539
sage: v = vector([1,2/3,pi]); w = vector([-2/3,pi^2,1])
3540
sage: v._add_(w)
3541
(1/3, pi^2 + 2/3, pi + 1)
3542
"""
3543
cdef Py_ssize_t i, n
3544
n = PyList_Size(left._entries)
3545
v = [None]*n
3546
for i from 0 <= i < n:
3547
v[i] = (<RingElement>left._entries[i])._add_(<RingElement>
3548
((<FreeModuleElement_generic_dense>right)._entries[i]))
3549
return left._new_c(v)
3550
3551
cpdef ModuleElement _sub_(left, ModuleElement right):
3552
"""
3553
Subtract right from left.
3554
3555
EXAMPLES::
3556
3557
sage: V = QQ^5
3558
sage: W = V.span([V.1, V.2])
3559
sage: W.0 - V.0
3560
(-1, 1, 0, 0, 0)
3561
sage: V.0 - W.0
3562
(1, -1, 0, 0, 0)
3563
"""
3564
cdef Py_ssize_t i, n
3565
n = PyList_Size(left._entries)
3566
v = [None]*n
3567
for i from 0 <= i < n:
3568
v[i] = (<RingElement>left._entries[i])._sub_(<RingElement>
3569
((<FreeModuleElement_generic_dense>right)._entries[i]))
3570
return left._new_c(v)
3571
3572
cpdef ModuleElement _rmul_(self, RingElement left):
3573
"""
3574
EXAMPLES::
3575
3576
sage: V = ZZ['x']^5
3577
sage: 5 * V.0
3578
(5, 0, 0, 0, 0)
3579
"""
3580
if left._parent is self._parent._base:
3581
v = [left._mul_(<RingElement>x) for x in self._entries]
3582
else:
3583
v = [left * x for x in self._entries]
3584
return self._new_c(v)
3585
3586
cpdef ModuleElement _lmul_(self, RingElement right):
3587
"""
3588
EXAMPLES::
3589
3590
sage: v = vector([-1,0,3,pi])
3591
sage: v._lmul_(2/3)
3592
(-2/3, 0, 2, 2/3*pi)
3593
sage: v * (2/3)
3594
(-2/3, 0, 2, 2/3*pi)
3595
"""
3596
if right._parent is self._parent._base:
3597
v = [(<RingElement>x)._mul_(right) for x in self._entries]
3598
else:
3599
v = [x * right for x in self._entries]
3600
return self._new_c(v)
3601
3602
cpdef Element _dot_product_(left, element_Vector right):
3603
"""
3604
Return the dot product of left and right.
3605
3606
EXAMPLES::
3607
3608
sage: R.<x> = QQ[]
3609
sage: v = vector([x,x^2,3*x]); w = vector([2*x,x,3+x])
3610
sage: v*w
3611
x^3 + 5*x^2 + 9*x
3612
sage: (x*2*x) + (x^2*x) + (3*x*(3+x))
3613
x^3 + 5*x^2 + 9*x
3614
sage: w*v
3615
x^3 + 5*x^2 + 9*x
3616
"""
3617
return left.dot_product(right)
3618
3619
cpdef element_Vector _pairwise_product_(left, element_Vector right):
3620
"""
3621
EXAMPLES::
3622
3623
sage: R.<x> = QQ[]
3624
sage: v = vector([x,x^2,3*x]); w = vector([2*x,x,3+x])
3625
sage: v.pairwise_product(w)
3626
(2*x^2, x^3, 3*x^2 + 9*x)
3627
sage: w.pairwise_product(v)
3628
(2*x^2, x^3, 3*x^2 + 9*x)
3629
"""
3630
if not right.parent() == left.parent():
3631
right = left.parent().ambient_module()(right)
3632
# Component wise vector * vector multiplication.
3633
cdef Py_ssize_t i, n
3634
n = PyList_Size(left._entries)
3635
v = [None]*n
3636
for i from 0 <= i < n:
3637
v[i] = (<RingElement>left._entries[i])._mul_((<FreeModuleElement_generic_dense>right)._entries[i])
3638
return left._new_c(v)
3639
3640
def __reduce__(self):
3641
"""
3642
EXAMPLES::
3643
3644
sage: v = vector([-1,0,3,pi])
3645
sage: v.__reduce__()
3646
(<built-in function make_FreeModuleElement_generic_dense_v1>, (Vector space of dimension 4 over Symbolic Ring, [-1, 0, 3, pi], 4, True))
3647
"""
3648
return (make_FreeModuleElement_generic_dense_v1, (self._parent, self._entries, self._degree, self._is_mutable))
3649
3650
def __getitem__(self, i):
3651
"""
3652
EXAMPLES::
3653
3654
sage: v = vector([RR(1), RR(2)]); v
3655
(1.00000000000000, 2.00000000000000)
3656
sage: v[0]
3657
1.00000000000000
3658
sage: v[-1]
3659
2.00000000000000
3660
sage: v[4]
3661
Traceback (most recent call last):
3662
...
3663
IndexError: index must be between -2 and 1
3664
sage: v[-4]
3665
Traceback (most recent call last):
3666
...
3667
IndexError: index must be between -2 and 1
3668
3669
sage: v = vector(QQ['x,y'], [1,2, 'x*y'])
3670
sage: v
3671
(1, 2, x*y)
3672
sage: v[1:]
3673
(2, x*y)
3674
"""
3675
if isinstance(i, slice):
3676
start, stop, step = i.indices(len(self))
3677
return vector(self.base_ring(), list(self)[start:stop:step])
3678
else:
3679
degree = self.degree()
3680
if i < 0:
3681
i += degree
3682
if i < 0 or i >= self.degree():
3683
raise IndexError("index must be between -%s and %s"%(degree, degree-1))
3684
return self._entries[i]
3685
3686
def __setitem__(self, i, value):
3687
"""
3688
Set entry i of self to value.
3689
3690
EXAMPLES::
3691
3692
sage: v = vector([1,2/3,pi])
3693
sage: v[1] = 19+pi
3694
sage: v
3695
(1, pi + 19, pi)
3696
sage: v = vector(QQ['x,y'], [1,2, 'x*y'])
3697
sage: v
3698
(1, 2, x*y)
3699
sage: v[1:]
3700
(2, x*y)
3701
sage: v[1:] = [4,5]; v
3702
(1, 4, 5)
3703
sage: v[:2] = [5,(6,2)]; v
3704
(5, 3, 5)
3705
sage: v[:2]
3706
(5, 3)
3707
"""
3708
if not self._is_mutable:
3709
raise ValueError("vector is immutable; please change a copy instead (use copy())")
3710
cdef Py_ssize_t k, n, d
3711
if isinstance(i, slice):
3712
start, stop, step = i.indices(len(self))
3713
d = self.degree()
3714
R = self.base_ring()
3715
n = 0
3716
for k from start <= k < stop:
3717
if k >= d:
3718
return
3719
if k >= 0:
3720
self._entries[k] = R(value[n])
3721
n = n + 1
3722
else:
3723
if i < 0 or i >= self.degree():
3724
raise IndexError("index (i=%s) must be between 0 and %s"%(i,
3725
self.degree()-1))
3726
self._entries[i] = self.base_ring()(value)
3727
3728
def list(self, copy=True):
3729
"""
3730
Return list of elements of self.
3731
3732
INPUT:
3733
3734
- copy -- bool, return list of underlying entries
3735
3736
EXAMPLES::
3737
3738
sage: P.<x,y,z> = QQ[]
3739
sage: v = vector([x,y,z])
3740
sage: type(v)
3741
<type 'sage.modules.free_module_element.FreeModuleElement_generic_dense'>
3742
sage: a = v.list(); a
3743
[x, y, z]
3744
sage: a[0] = x*y; v
3745
(x, y, z)
3746
sage: a = v.list(copy=False); a
3747
[x, y, z]
3748
sage: a[0] = x*y; v
3749
(x*y, y, z)
3750
"""
3751
if copy:
3752
return list(self._entries)
3753
else:
3754
return self._entries
3755
3756
cdef int _cmp_c_impl(left, Element right) except -2:
3757
"""
3758
Compare two free module elements with identical parents.
3759
3760
Free module elements are compared in lexicographic order on
3761
the underlying list of coefficients. Two free module elements
3762
are equal if their coefficients are the same. (This is true
3763
even if one is sparse and one is dense.)
3764
"""
3765
return cmp(left._entries, (<FreeModuleElement_generic_dense>right)._entries)
3766
3767
def __call__(self, *args, **kwargs):
3768
"""
3769
Calling a free module element returns the result of calling each
3770
component.
3771
3772
EXAMPLES::
3773
3774
sage: x, y = var('x,y')
3775
sage: f = x^2 + y^2
3776
sage: g = f.gradient()
3777
sage: g
3778
(2*x, 2*y)
3779
sage: type(g)
3780
<class 'sage.modules.vector_symbolic_dense.Vector_symbolic_dense'>
3781
sage: g(y=2, x=3)
3782
(6, 4)
3783
sage: f(x,y) = x^2 + y^2
3784
sage: g = f.gradient()
3785
sage: g(3,2)
3786
(6, 4)
3787
sage: g(x=3, y=2)
3788
(6, 4)
3789
"""
3790
return vector([e(*args, **kwargs) for e in self])
3791
3792
def function(self, *args):
3793
"""
3794
Returns a vector over a callable symbolic expression ring.
3795
3796
EXAMPLES::
3797
3798
sage: x,y=var('x,y')
3799
sage: v=vector([x,y,x*sin(y)])
3800
sage: w=v.function([x,y]); w
3801
(x, y) |--> (x, y, x*sin(y))
3802
sage: w.base_ring()
3803
Callable function ring with arguments (x, y)
3804
sage: w(1,2)
3805
(1, 2, sin(2))
3806
sage: w(2,1)
3807
(2, 1, 2*sin(1))
3808
sage: w(y=1,x=2)
3809
(2, 1, 2*sin(1))
3810
3811
::
3812
3813
sage: x,y=var('x,y')
3814
sage: v=vector([x,y,x*sin(y)])
3815
sage: w=v.function([x]); w
3816
x |--> (x, y, x*sin(y))
3817
sage: w.base_ring()
3818
Callable function ring with arguments (x,)
3819
sage: w(4)
3820
(4, y, 4*sin(y))
3821
"""
3822
from sage.symbolic.callable import CallableSymbolicExpressionRing
3823
return vector(CallableSymbolicExpressionRing(args), self.list())
3824
3825
#############################################
3826
# Generic sparse element
3827
#############################################
3828
def _sparse_dot_product(v, w):
3829
"""
3830
v and w are dictionaries with integer keys.
3831
3832
EXAMPLES::
3833
3834
sage: sage.modules.free_module_element._sparse_dot_product({0:5,1:7,2:3}, {0:-1, 2:2})
3835
1
3836
"""
3837
x = set(v.keys()).intersection(set(w.keys()))
3838
return sum([v[k]*w[k] for k in x])
3839
3840
def make_FreeModuleElement_generic_sparse(parent, entries, degree):
3841
"""
3842
EXAMPLES::
3843
3844
sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_sparse(QQ^3, {2:5/2}, 3); v
3845
(0, 0, 5/2)
3846
"""
3847
cdef FreeModuleElement_generic_sparse v
3848
v = FreeModuleElement_generic_sparse.__new__(FreeModuleElement_generic_sparse)
3849
v._entries = entries
3850
v._parent = parent
3851
v._degree = degree
3852
return v
3853
3854
def make_FreeModuleElement_generic_sparse_v1(parent, entries, degree, is_mutable):
3855
"""
3856
EXAMPLES::
3857
3858
sage: v = sage.modules.free_module_element.make_FreeModuleElement_generic_sparse_v1(QQ^3, {2:5/2}, 3, False); v
3859
(0, 0, 5/2)
3860
sage: v.is_mutable()
3861
False
3862
"""
3863
cdef FreeModuleElement_generic_sparse v
3864
v = FreeModuleElement_generic_sparse.__new__(FreeModuleElement_generic_sparse)
3865
v._entries = entries
3866
v._parent = parent
3867
v._degree = degree
3868
v._is_mutable = is_mutable
3869
return v
3870
3871
cdef class FreeModuleElement_generic_sparse(FreeModuleElement):
3872
"""
3873
A generic sparse free module element is a dictionary with keys ints
3874
i and entries in the base ring.
3875
3876
EXAMPLES:
3877
3878
Pickling works::
3879
3880
sage: v = FreeModule(ZZ, 3, sparse=True).0
3881
sage: loads(dumps(v)) == v
3882
True
3883
sage: v = FreeModule(Integers(8)['x,y'], 5, sparse=True).1
3884
sage: loads(dumps(v)) - v
3885
(0, 0, 0, 0, 0)
3886
3887
::
3888
3889
sage: a = vector([-1,0,1/1],sparse=True); b = vector([-1/1,0,0],sparse=True)
3890
sage: a.parent()
3891
Sparse vector space of dimension 3 over Rational Field
3892
sage: b - a
3893
(0, 0, -1)
3894
sage: (b-a).dict()
3895
{2: -1}
3896
"""
3897
cdef _new_c(self, object v):
3898
# Create a new sparse free module element with minimal overhead and
3899
# no type checking.
3900
cdef FreeModuleElement_generic_sparse x
3901
x = PY_NEW(FreeModuleElement_generic_sparse)
3902
x._is_mutable = 1
3903
x._parent = self._parent
3904
x._entries = v
3905
x._degree = self._degree
3906
return x
3907
3908
cdef bint is_dense_c(self):
3909
return 0
3910
3911
cdef bint is_sparse_c(self):
3912
return 1
3913
3914
def __copy__(self):
3915
"""
3916
EXAMPLES::
3917
3918
sage: v = vector([1,2/3,pi], sparse=True)
3919
sage: v.__copy__()
3920
(1, 2/3, pi)
3921
"""
3922
return self._new_c(dict(self._entries))
3923
3924
def __init__(self, parent,
3925
entries=0,
3926
coerce=True,
3927
copy=True):
3928
"""
3929
EXAMPLES::
3930
3931
sage: v = sage.modules.free_module_element.FreeModuleElement_generic_sparse(VectorSpace(QQ,3,sparse=True), {1:5/4}); v
3932
(0, 5/4, 0)
3933
sage: v.is_sparse()
3934
True
3935
3936
TESTS:
3937
3938
Test that 11751 is fixed::
3939
3940
sage: K.<x> = QQ[]
3941
sage: M = FreeModule(K, 1, sparse=True)
3942
sage: N = M.span([{0:1/x}]); N
3943
Sparse free module of degree 1 and rank 1 over Univariate Polynomial Ring in x over Rational Field
3944
Echelon basis matrix:
3945
[1/x]
3946
sage: N({0:1/x}) # this used to fail prior to #11751
3947
(1/x)
3948
sage: N({0:1/x^2})
3949
Traceback (most recent call last):
3950
...
3951
TypeError: element (= {0: 1/x^2}) is not in free module
3952
3953
::
3954
3955
sage: L = FreeModule(K, 2, sparse=True)
3956
sage: R = L.span([{0:x, 1:0}, {0:0, 1:1/x}], check=False, already_echelonized=True)
3957
sage: R.basis()[0][0].parent()
3958
Fraction Field of Univariate Polynomial Ring in x over Rational Field
3959
sage: R = L.span([{0:x, 1:x^2}])
3960
sage: R.basis()[0][0].parent()
3961
Univariate Polynomial Ring in x over Rational Field
3962
"""
3963
#WARNING: In creation, we do not check that the i pairs satisfy
3964
# 0 <= i < degree.
3965
FreeModuleElement.__init__(self, parent)
3966
R = self.base_ring()
3967
if entries == 0:
3968
entries = {}
3969
else:
3970
if isinstance(entries, list):
3971
if len(entries) != self.degree():
3972
raise TypeError("entries has the wrong length")
3973
x = entries
3974
entries = {}
3975
for i in xrange(self.degree()):
3976
if x[i] != 0:
3977
entries[i] = x[i]
3978
copy = False
3979
if not isinstance(entries, dict):
3980
raise TypeError, "entries must be a dict"
3981
if copy:
3982
# Make a copy
3983
entries = dict(entries)
3984
if coerce:
3985
if len(entries) != 0:
3986
coefficient_ring = parent.basis()[0][0].parent()
3987
try:
3988
for k, x in entries.iteritems():
3989
entries[k] = coefficient_ring(x)
3990
except TypeError:
3991
raise TypeError("Unable to coerce value (=%s) of entries dict (=%s) to %s"%(x, entries, coefficient_ring))
3992
self._entries = entries
3993
3994
cpdef ModuleElement _add_(left, ModuleElement right):
3995
"""
3996
Add left and right.
3997
3998
EXAMPLES::
3999
4000
sage: v = vector([1,2/3,pi], sparse=True)
4001
sage: v._add_(v)
4002
(2, 4/3, 2*pi)
4003
"""
4004
cdef object v, e
4005
e = dict((<FreeModuleElement_generic_sparse>right)._entries)
4006
for i, a in left._entries.iteritems():
4007
if e.has_key(i):
4008
sum = (<RingElement>a)._add_(<RingElement> e[i])
4009
if sum:
4010
e[i] = sum
4011
else:
4012
del e[i]
4013
elif a:
4014
e[i] = a
4015
return left._new_c(e)
4016
4017
cpdef ModuleElement _sub_(left, ModuleElement right):
4018
"""
4019
EXAMPLES::
4020
4021
sage: v = vector([1,2/3,pi], sparse=True)
4022
sage: v._sub_(v)
4023
(0, 0, 0)
4024
"""
4025
cdef object v, e
4026
e = dict(left._entries) # dict to make a copy
4027
for i, a in (<FreeModuleElement_generic_sparse>right)._entries.iteritems():
4028
if e.has_key(i):
4029
diff = (<RingElement> e[i])._sub_(<RingElement>a)
4030
if diff:
4031
e[i] = diff
4032
else:
4033
del e[i]
4034
elif a:
4035
e[i] = -a
4036
return left._new_c(e)
4037
4038
cpdef ModuleElement _lmul_(self, RingElement right):
4039
"""
4040
EXAMPLES::
4041
4042
sage: v = vector([1,2/3,pi], sparse=True)
4043
sage: v._lmul_(SR(3))
4044
(3, 2, 3*pi)
4045
"""
4046
cdef object v
4047
v = PyDict_New()
4048
if right:
4049
for i, a in self._entries.iteritems():
4050
prod = (<RingElement>a)._mul_(right)
4051
if prod:
4052
v[i] = prod
4053
return self._new_c(v)
4054
4055
cpdef ModuleElement _rmul_(self, RingElement left):
4056
"""
4057
EXAMPLES::
4058
4059
sage: v = vector([1,2/3,pi], sparse=True)
4060
sage: v._rmul_(SR(3))
4061
(3, 2, 3*pi)
4062
"""
4063
cdef object v
4064
v = PyDict_New()
4065
if left:
4066
for i, a in self._entries.iteritems():
4067
prod = left._mul_(a)
4068
if prod:
4069
v[i] = prod
4070
return self._new_c(v)
4071
4072
cpdef Element _dot_product_(left, element_Vector right):
4073
"""
4074
Return the dot product of left and right.
4075
4076
EXAMPLES::
4077
4078
sage: v = vector([1,2,0], sparse=True); w = vector([0,5,-9], sparse=True)
4079
sage: v * w
4080
10
4081
sage: w * v
4082
10
4083
"""
4084
cdef object v, e, z
4085
e = dict((<FreeModuleElement_generic_sparse>right)._entries)
4086
z = left.base_ring()(0)
4087
for i, a in left._entries.iteritems():
4088
if e.has_key(i):
4089
z += (<RingElement>a)._mul_(<RingElement> e[i])
4090
return z
4091
4092
cpdef element_Vector _pairwise_product_(left, element_Vector right):
4093
"""
4094
EXAMPLES::
4095
4096
sage: v = vector([1,2/3,pi], sparse=True); w = vector([-2/3,pi^2,1],sparse=True)
4097
sage: v._pairwise_product_(w)
4098
(-2/3, 2/3*pi^2, pi)
4099
"""
4100
# Component wise vector * vector multiplication.
4101
cdef object v, e
4102
e = dict((<FreeModuleElement_generic_sparse>right)._entries)
4103
v = PyDict_New()
4104
for i, a in left._entries.iteritems():
4105
if e.has_key(i):
4106
prod = (<RingElement>a)._mul_(<RingElement> e[i])
4107
if prod:
4108
v[i] = prod
4109
return left._new_c(v)
4110
4111
cdef int _cmp_c_impl(left, Element right) except -2:
4112
"""
4113
Compare two sparse free module elements.
4114
4115
Free module elements are compared in lexicographic order on
4116
the underlying list of coefficients. Two free module elements
4117
are equal if their coefficients are the same. (This is true
4118
even if one is sparse and one is dense.)
4119
"""
4120
a = left._entries.items()
4121
a.sort()
4122
b = (<FreeModuleElement_generic_dense>right)._entries.items()
4123
b.sort()
4124
return cmp(a,b)
4125
4126
def iteritems(self):
4127
"""
4128
Return iterator over the entries of self.
4129
4130
EXAMPLES::
4131
4132
sage: v = vector([1,2/3,pi], sparse=True)
4133
sage: v.iteritems()
4134
<dictionary-itemiterator object at ...>
4135
sage: list(v.iteritems())
4136
[(0, 1), (1, 2/3), (2, pi)]
4137
"""
4138
return self._entries.iteritems()
4139
4140
def __reduce__(self):
4141
"""
4142
EXAMPLES::
4143
4144
sage: v = vector([1,2/3,pi], sparse=True)
4145
sage: v.__reduce__()
4146
(<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))
4147
"""
4148
return (make_FreeModuleElement_generic_sparse_v1, (self._parent, self._entries, self._degree, self._is_mutable))
4149
4150
def __getitem__(self, i):
4151
"""
4152
EXAMPLES::
4153
4154
sage: v = vector([RR(1), RR(2)], sparse=True); v
4155
(1.00000000000000, 2.00000000000000)
4156
sage: v[0]
4157
1.00000000000000
4158
sage: v[-1]
4159
2.00000000000000
4160
sage: v[5]
4161
Traceback (most recent call last):
4162
...
4163
IndexError: index must be between -2 and 1
4164
sage: v[-3]
4165
Traceback (most recent call last):
4166
...
4167
IndexError: index must be between -2 and 1
4168
"""
4169
if isinstance(i, slice):
4170
start, stop, step = i.indices(len(self))
4171
return vector(self.base_ring(), self.list()[start:stop])
4172
else:
4173
i = int(i)
4174
degree = self.degree()
4175
if i < 0:
4176
i += degree
4177
if i < 0 or i >= degree:
4178
raise IndexError("index must be between %s and %s"%(-degree,
4179
degree-1))
4180
if self._entries.has_key(i):
4181
return self._entries[i]
4182
return self.base_ring()(0) # optimize this somehow
4183
4184
def get(self, i):
4185
"""
4186
Like __getitem__ but with no guaranteed type or bounds checking. Returns 0
4187
if access is out of bounds.
4188
4189
EXAMPLES::
4190
4191
sage: v = vector([1,2/3,pi], sparse=True)
4192
sage: v.get(1)
4193
2/3
4194
sage: v.get(10)
4195
0
4196
"""
4197
i = int(i)
4198
if self._entries.has_key(i):
4199
return self._entries[i]
4200
return self.base_ring()(0) # optimize this somehow
4201
4202
4203
def set(self, i, x):
4204
"""
4205
Like __setitem__ but with no guaranteed type or bounds checking.
4206
4207
EXAMPLES::
4208
4209
sage: v = vector([1,2/3,pi], sparse=True)
4210
sage: v.set(1, pi^3)
4211
sage: v
4212
(1, pi^3, pi)
4213
4214
No bounds checking::
4215
4216
sage: v.set(10, pi)
4217
4218
This lack of bounds checking causes trouble later::
4219
4220
sage: v
4221
Traceback (most recent call last):
4222
...
4223
IndexError: list assignment index out of range
4224
"""
4225
if not self._is_mutable:
4226
raise ValueError("vector is immutable; please change a copy instead (use copy())")
4227
i = int(i)
4228
if x == 0:
4229
if self._entries.has_key(i):
4230
del self._entries[i]
4231
return
4232
self._entries[i] = x
4233
4234
def __setitem__(self, i, value):
4235
"""
4236
Set the `i`-th entry or slice of self to value.
4237
4238
EXAMPLES::
4239
4240
sage: V = VectorSpace(GF(17), 10000000, sparse=True)
4241
sage: w = V(0)
4242
sage: w[39893] = 20
4243
sage: w[39893]
4244
3
4245
sage: w[39000:39003] = [4, 5, 6]; w[39000:39003]
4246
(4, 5, 6)
4247
sage: parent(w[39893])
4248
Finite Field of size 17
4249
sage: w[39893] = sqrt(2)
4250
Traceback (most recent call last):
4251
...
4252
TypeError: unable to convert x (=sqrt(2)) to an integer
4253
"""
4254
if not self._is_mutable:
4255
raise ValueError("vector is immutable; please change a copy instead (use copy())")
4256
cdef Py_ssize_t k, d, n
4257
if isinstance(i, slice):
4258
start, stop = i.start, i.stop
4259
d = self.degree()
4260
R = self.base_ring()
4261
n = 0
4262
for k from start <= k < stop:
4263
if k >= d:
4264
return
4265
if k >= 0:
4266
self[k] = R(value[n])
4267
n = n + 1
4268
else:
4269
i = int(i)
4270
if i < 0 or i >= self.degree():
4271
raise IndexError("index (i=%s) must be between 0 and %s"%(i,
4272
self.degree()-1))
4273
self.set(i, self._parent.base_ring()(value))
4274
4275
def denominator(self):
4276
"""
4277
Return the least common multiple of the denominators of the
4278
entries of self.
4279
4280
EXAMPLES::
4281
4282
sage: v = vector([1/2,2/5,3/14], sparse=True)
4283
sage: v.denominator()
4284
70
4285
"""
4286
R = self.base_ring()
4287
x = self._entries
4288
if len(x) == 0:
4289
return 1
4290
Z = x.iteritems()
4291
d = Z.next()[1].denominator()
4292
for _, y in Z:
4293
d = d.lcm(y.denominator())
4294
return d
4295
4296
def dict(self, copy=True):
4297
"""
4298
Return dictionary of nonzero entries of self.
4299
4300
INPUT:
4301
4302
- ``copy`` -- bool (default: True)
4303
4304
OUTPUT:
4305
4306
- Python dictionary
4307
4308
EXAMPLES::
4309
4310
sage: v = vector([0,0,0,0,1/2,0,3/14], sparse=True)
4311
sage: v.dict()
4312
{4: 1/2, 6: 3/14}
4313
"""
4314
if copy:
4315
return dict(self._entries)
4316
else:
4317
return self._entries
4318
4319
def list(self, copy=True):
4320
"""
4321
Return list of elements of self.
4322
4323
INPUT:
4324
4325
- copy -- bool, return list of underlying entries
4326
4327
EXAMPLES::
4328
4329
sage: v = vector([1,2/3,pi], sparse=True)
4330
sage: type(v)
4331
<type 'sage.modules.free_module_element.FreeModuleElement_generic_sparse'>
4332
sage: a = v.list(); a
4333
[1, 2/3, pi]
4334
"""
4335
cdef Py_ssize_t n
4336
n = self._parent.degree()
4337
z = self._parent.base_ring()(0)
4338
v = [z]*n
4339
for i, a in self._entries.iteritems():
4340
v[i] = a
4341
return v
4342
4343
def nonzero_positions(self):
4344
"""
4345
Returns the list of numbers i such that self[i] != 0.
4346
4347
EXAMPLES::
4348
4349
sage: v = vector({1: 1, 3: -2})
4350
sage: w = vector({1: 4, 3: 2})
4351
sage: v+w
4352
(0, 5, 0, 0)
4353
sage: (v+w).nonzero_positions()
4354
[1]
4355
"""
4356
K = self._entries.keys()
4357
K.sort()
4358
return K
4359
4360
4361
def _numerical_approx(self, prec=None, digits=None):
4362
"""
4363
Returns a numerical approximation of self by calling the n() method
4364
on all of its entries.
4365
4366
EXAMPLES::
4367
4368
sage: v = vector(RealField(200), [1,2,3], sparse=True)
4369
sage: v.n()
4370
(1.00000000000000, 2.00000000000000, 3.00000000000000)
4371
sage: _.parent()
4372
Sparse vector space of dimension 3 over Real Field with 53 bits of precision
4373
sage: v.n(prec=75)
4374
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
4375
sage: _.parent()
4376
Sparse vector space of dimension 3 over Real Field with 75 bits of precision
4377
"""
4378
return vector(dict([(e[0],e[1].n(prec, digits)) for e in self._entries.iteritems()]), sparse=True)
4379
4380
4381