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