/
free_module_element.pyx
5012 lines (4033 loc) · 164 KB
/
free_module_element.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Elements of free modules
AUTHORS:
- William Stein
- Josh Kantor
- Thomas Feulner (2012-11): Added :meth:`FreeModuleElement.hamming_weight` and
:meth:`FreeModuleElement_generic_sparse.hamming_weight`
- Jeroen Demeyer (2015-02-24): Implement fast Cython methods
``get_unsafe`` and ``set_unsafe`` similar to other places in Sage
(:trac:`17562`)
EXAMPLES: We create a vector space over `\QQ` and a
subspace of this space.
::
sage: V = QQ^5
sage: W = V.span([V.1, V.2])
Arithmetic operations always return something in the ambient space,
since there is a canonical map from `W` to `V` but
not from `V` to `W`.
::
sage: parent(W.0 + V.1)
Vector space of dimension 5 over Rational Field
sage: parent(V.1 + W.0)
Vector space of dimension 5 over Rational Field
sage: W.0 + V.1
(0, 2, 0, 0, 0)
sage: W.0 - V.0
(-1, 1, 0, 0, 0)
Next we define modules over `\ZZ` and a finite
field.
::
sage: K = ZZ^5
sage: M = GF(7)^5
Arithmetic between the `\QQ` and
`\ZZ` modules is defined, and the result is always
over `\QQ`, since there is a canonical coercion map
to `\QQ`.
::
sage: K.0 + V.1
(1, 1, 0, 0, 0)
sage: parent(K.0 + V.1)
Vector space of dimension 5 over Rational Field
Since there is no canonical coercion map to the finite field from
`\QQ` the following arithmetic is not defined::
sage: V.0 + M.0
Traceback (most recent call last):
...
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'
However, there is a map from `\ZZ` to the finite
field, so the following is defined, and the result is in the finite
field.
::
sage: w = K.0 + M.0; w
(2, 0, 0, 0, 0)
sage: parent(w)
Vector space of dimension 5 over Finite Field of size 7
sage: parent(M.0 + K.0)
Vector space of dimension 5 over Finite Field of size 7
Matrix vector multiply::
sage: MS = MatrixSpace(QQ,3)
sage: A = MS([0,1,0,1,0,0,0,0,1])
sage: V = QQ^3
sage: v = V([1,2,3])
sage: v * A
(2, 1, 3)
TESTS::
sage: D = 46341
sage: u = 7
sage: R = Integers(D)
sage: p = matrix(R,[[84, 97, 55, 58, 51]])
sage: 2*p.row(0)
(168, 194, 110, 116, 102)
"""
#*****************************************************************************
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
cimport cython
from cpython.slice cimport PySlice_GetIndicesEx
from sage.structure.sequence import Sequence
from sage.structure.element cimport Element, ModuleElement, RingElement, Vector
from sage.structure.element import canonical_coercion
from sage.rings.ring import is_Ring
from sage.rings.infinity import Infinity, AnInfinity
from sage.rings.integer_ring import ZZ
from sage.rings.real_double import RDF
from sage.rings.complex_double import CDF
from sage.misc.derivative import multi_derivative
from sage.rings.ring cimport Ring
from sage.rings.integer cimport Integer, smallInteger
# For the norm function, we cache Sage integers 1 and 2
__one__ = smallInteger(1)
__two__ = smallInteger(2)
def is_FreeModuleElement(x):
"""
EXAMPLES::
sage: sage.modules.free_module_element.is_FreeModuleElement(0)
False
sage: sage.modules.free_module_element.is_FreeModuleElement(vector([1,2,3]))
True
"""
return isinstance(x, FreeModuleElement)
def vector(arg0, arg1=None, arg2=None, sparse=None):
r"""
Return a vector or free module element with specified entries.
CALL FORMATS:
This constructor can be called in several different ways.
In each case, ``sparse=True`` or ``sparse=False`` can be
supplied as an option. ``free_module_element()`` is an
alias for ``vector()``.
1. vector(object)
2. vector(ring, object)
3. vector(object, ring)
4. vector(ring, degree, object)
5. vector(ring, degree)
INPUT:
- ``object`` -- a list, dictionary, or other
iterable containing the entries of the vector, including
any object that is palatable to the ``Sequence`` constructor
- ``ring`` -- a base ring (or field) for the vector space or free module,
which contains all of the elements
- ``degree`` -- an integer specifying the number of
entries in the vector or free module element
- ``sparse`` -- boolean, whether the result should be a sparse
vector
In call format 4, an error is raised if the ``degree`` does not match
the length of ``object`` so this call can provide some safeguards.
Note however that using this format when ``object`` is a dictionary
is unlikely to work properly.
OUTPUT:
An element of the ambient vector space or free module with the
given base ring and implied or specified dimension or rank,
containing the specified entries and with correct degree.
In call format 5, no entries are specified, so the element is
populated with all zeros.
If the ``sparse`` option is not supplied, the output will
generally have a dense representation. The exception is if
``object`` is a dictionary, then the representation will be sparse.
EXAMPLES::
sage: v = vector([1,2,3]); v
(1, 2, 3)
sage: v.parent()
Ambient free module of rank 3 over the principal ideal domain Integer Ring
sage: v = vector([1,2,3/5]); v
(1, 2, 3/5)
sage: v.parent()
Vector space of dimension 3 over Rational Field
All entries must *canonically* coerce to some common ring::
sage: v = vector([17, GF(11)(5), 19/3]); v
Traceback (most recent call last):
...
TypeError: unable to find a common ring for all elements
::
sage: v = vector([17, GF(11)(5), 19]); v
(6, 5, 8)
sage: v.parent()
Vector space of dimension 3 over Finite Field of size 11
sage: v = vector([17, GF(11)(5), 19], QQ); v
(17, 5, 19)
sage: v.parent()
Vector space of dimension 3 over Rational Field
sage: v = vector((1,2,3), QQ); v
(1, 2, 3)
sage: v.parent()
Vector space of dimension 3 over Rational Field
sage: v = vector(QQ, (1,2,3)); v
(1, 2, 3)
sage: v.parent()
Vector space of dimension 3 over Rational Field
sage: v = vector(vector([1,2,3])); v
(1, 2, 3)
sage: v.parent()
Ambient free module of rank 3 over the principal ideal domain Integer Ring
You can also use ``free_module_element``, which is
the same as ``vector``. ::
sage: free_module_element([1/3, -4/5])
(1/3, -4/5)
We make a vector mod 3 out of a vector over `\ZZ`. ::
sage: vector(vector([1,2,3]), GF(3))
(1, 2, 0)
The degree of a vector may be specified::
sage: vector(QQ, 4, [1,1/2,1/3,1/4])
(1, 1/2, 1/3, 1/4)
But it is an error if the degree and size of the list of entries
are mismatched::
sage: vector(QQ, 5, [1,1/2,1/3,1/4])
Traceback (most recent call last):
...
ValueError: incompatible degrees in vector constructor
Providing no entries populates the vector with zeros, but of course,
you must specify the degree since it is not implied. Here we use a
finite field as the base ring. ::
sage: w = vector(FiniteField(7), 4); w
(0, 0, 0, 0)
sage: w.parent()
Vector space of dimension 4 over Finite Field of size 7
The fastest method to construct a zero vector is to call the
:meth:`~sage.modules.free_module.FreeModule_generic.zero_vector`
method directly on a free module or vector space, since
vector(...) must do a small amount of type checking. Almost as
fast as the ``zero_vector()`` method is the
:func:`~sage.modules.free_module_element.zero_vector` constructor,
which defaults to the integers. ::
sage: vector(ZZ, 5) # works fine
(0, 0, 0, 0, 0)
sage: (ZZ^5).zero_vector() # very tiny bit faster
(0, 0, 0, 0, 0)
sage: zero_vector(ZZ, 5) # similar speed to vector(...)
(0, 0, 0, 0, 0)
sage: z = zero_vector(5); z
(0, 0, 0, 0, 0)
sage: z.parent()
Ambient free module of rank 5 over
the principal ideal domain Integer Ring
Here we illustrate the creation of sparse vectors by using a
dictionary. ::
sage: vector({1:1.1, 3:3.14})
(0.000000000000000, 1.10000000000000, 0.000000000000000, 3.14000000000000)
With no degree given, a dictionary of entries implicitly declares a
degree by the largest index (key) present. So you can provide a
terminal element (perhaps a zero?) to set the degree. But it is probably safer
to just include a degree in your construction. ::
sage: v = vector(QQ, {0:1/2, 4:-6, 7:0}); v
(1/2, 0, 0, 0, -6, 0, 0, 0)
sage: v.degree()
8
sage: v.is_sparse()
True
sage: w = vector(QQ, 8, {0:1/2, 4:-6})
sage: w == v
True
It is an error to specify a negative degree. ::
sage: vector(RR, -4, [1.0, 2.0, 3.0, 4.0])
Traceback (most recent call last):
...
ValueError: cannot specify the degree of a vector as a negative integer (-4)
It is an error to create a zero vector but not provide
a ring as the first argument. ::
sage: vector('junk', 20)
Traceback (most recent call last):
...
TypeError: first argument must be base ring of zero vector, not junk
And it is an error to specify an index in a dictionary
that is greater than or equal to a requested degree. ::
sage: vector(ZZ, 10, {3:4, 7:-2, 10:637})
Traceback (most recent call last):
...
ValueError: dictionary of entries has a key (index) exceeding the requested degree
A 1-dimensional numpy array of type float or complex may be
passed to vector. Unless an explicit ring is given, the result will
be a vector in the appropriate dimensional vector space over the
real double field or the complex double field. The data in the array
must be contiguous, so column-wise slices of numpy matrices will
raise an exception. ::
sage: import numpy
sage: x = numpy.random.randn(10)
sage: y = vector(x)
sage: parent(y)
Vector space of dimension 10 over Real Double Field
sage: parent(vector(RDF, x))
Vector space of dimension 10 over Real Double Field
sage: parent(vector(CDF, x))
Vector space of dimension 10 over Complex Double Field
sage: parent(vector(RR, x))
Vector space of dimension 10 over Real Field with 53 bits of precision
sage: v = numpy.random.randn(10) * numpy.complex(0,1)
sage: w = vector(v)
sage: parent(w)
Vector space of dimension 10 over Complex Double Field
Multi-dimensional arrays are not supported::
sage: import numpy as np
sage: a = np.array([[1, 2, 3], [4, 5, 6]], np.float64)
sage: vector(a)
Traceback (most recent call last):
...
TypeError: cannot convert 2-dimensional array to a vector
If any of the arguments to vector have Python type int, long, real,
or complex, they will first be coerced to the appropriate Sage
objects. This fixes :trac:`3847`. ::
sage: v = vector([int(0)]); v
(0)
sage: v[0].parent()
Integer Ring
sage: v = vector(range(10)); v
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sage: v[3].parent()
Integer Ring
sage: v = vector([float(23.4), int(2), complex(2+7*I), long(1)]); v
(23.4, 2.0, 2.0 + 7.0*I, 1.0)
sage: v[1].parent()
Complex Double Field
If the argument is a vector, it doesn't change the base ring. This
fixes :trac:`6643`::
sage: K.<sqrt3> = QuadraticField(3)
sage: u = vector(K, (1/2, sqrt3/2) )
sage: vector(u).base_ring()
Number Field in sqrt3 with defining polynomial x^2 - 3
sage: v = vector(K, (0, 1) )
sage: vector(v).base_ring()
Number Field in sqrt3 with defining polynomial x^2 - 3
Constructing a vector from a numpy array behaves as expected::
sage: import numpy
sage: a=numpy.array([1,2,3])
sage: v=vector(a); v
(1, 2, 3)
sage: parent(v)
Ambient free module of rank 3 over the principal ideal domain Integer Ring
Complex numbers can be converted naturally to a sequence of length 2. And
then to a vector. ::
sage: c = CDF(2 + 3*I)
sage: v = vector(c); v
(2.0, 3.0)
A generator, or other iterable, may also be supplied as input. Anything
that can be converted to a :class:`~sage.structure.sequence.Sequence` is
a possible input. ::
sage: type(i^2 for i in range(3))
<type 'generator'>
sage: v = vector(i^2 for i in range(3)); v
(0, 1, 4)
An empty list, without a ring given, will default to the integers. ::
sage: x = vector([]); x
()
sage: x.parent()
Ambient free module of rank 0 over the principal ideal domain Integer Ring
"""
# We first efficiently handle the important special case of the zero vector
# over a ring. See trac 11657.
# !! PLEASE DO NOT MOVE THIS CODE LOWER IN THIS FUNCTION !!
if arg2 is None and is_Ring(arg0) and (isinstance(arg1, (int, long, Integer))):
if sparse:
from free_module import FreeModule
M = FreeModule(arg0, arg1, sparse=True)
else:
M = arg0 ** arg1
return M.zero_vector()
# WARNING TO FUTURE OPTIMIZERS: The following two hasattr's take
# quite a significant amount of time.
if hasattr(arg0, '_vector_'):
return arg0._vector_(arg1)
if hasattr(arg1, '_vector_'):
return arg1._vector_(arg0)
# consider a possible degree specified in second argument
degree = None
maxindex = None
if isinstance(arg1, (Integer, int, long)):
if arg1 < 0:
raise ValueError("cannot specify the degree of a vector as a negative integer (%s)" % arg1)
if isinstance(arg2, dict):
maxindex = max([-1]+[index for index in arg2])
if not maxindex < arg1:
raise ValueError("dictionary of entries has a key (index) exceeding the requested degree")
# arg1 is now a legitimate degree
# With no arg2, we can try to return a zero vector
# else we size-check arg2 and slide it into arg1
degree = arg1
if arg2 is None:
if not is_Ring(arg0):
msg = "first argument must be base ring of zero vector, not {0}"
raise TypeError(msg.format(arg0))
else:
if not isinstance(arg2, dict) and len(arg2) != degree:
raise ValueError("incompatible degrees in vector constructor")
arg1 = arg2
# Analyze arg0 and arg1 to create a ring (R) and entries (v)
if is_Ring(arg0):
R = arg0
v = arg1
elif is_Ring(arg1):
R = arg1
v = arg0
else:
v = arg0
R = None
from numpy import ndarray
if isinstance(v, ndarray):
if len(v.shape) != 1:
raise TypeError("cannot convert %r-dimensional array to a vector" % len(v.shape))
from free_module import VectorSpace
if (R is None or R is RDF) and v.dtype.kind == 'f':
V = VectorSpace(RDF, v.shape[0])
from vector_real_double_dense import Vector_real_double_dense
return Vector_real_double_dense(V, v)
if (R is None or R is CDF) and v.dtype.kind == 'c':
V = VectorSpace(CDF, v.shape[0])
from vector_complex_double_dense import Vector_complex_double_dense
return Vector_complex_double_dense(V, v)
# Use slower conversion via list
v = list(v)
if isinstance(v, dict):
if degree is None:
degree = max([-1]+[index for index in v])+1
if sparse is None:
sparse = True
else:
degree = None
if sparse is None:
sparse = False
v, R = prepare(v, R, degree)
if sparse:
from free_module import FreeModule
M = FreeModule(R, len(v), sparse=True)
else:
M = R ** len(v)
return M(v)
free_module_element = vector
def prepare(v, R, degree=None):
r"""
Converts an object describing elements of a vector into a list of entries in a common ring.
INPUT:
- ``v`` - a dictionary with non-negative integers as keys,
or a list or other object that can be converted by the ``Sequence``
constructor
- ``R`` - a ring containing all the entries, possibly given as ``None``
- ``degree`` - a requested size for the list when the input is a dictionary,
otherwise ignored
OUTPUT:
A pair.
The first item is a list of the values specified in the object ``v``.
If the object is a dictionary , entries are placed in the list
according to the indices that were their keys in the dictionary,
and the remainder of the entries are zero. The value of
``degree`` is assumed to be larger than any index provided
in the dictionary and will be used as the number of entries
in the returned list.
The second item returned is a ring that contains all of
the entries in the list. If ``R`` is given, the entries
are coerced in. Otherwise a common ring is found. For
more details, see the
:class:`~sage.structure.sequence.Sequence` object. When ``v``
has no elements and ``R`` is ``None``, the ring returned is
the integers.
EXAMPLES::
sage: from sage.modules.free_module_element import prepare
sage: prepare([1,2/3,5],None)
([1, 2/3, 5], Rational Field)
sage: prepare([1,2/3,5],RR)
([1.00000000000000, 0.666666666666667, 5.00000000000000], Real Field with 53 bits of precision)
sage: prepare({1:4, 3:-2}, ZZ, 6)
([0, 4, 0, -2, 0, 0], Integer Ring)
sage: prepare({3:1, 5:3}, QQ, 6)
([0, 0, 0, 1, 0, 3], Rational Field)
sage: prepare([1,2/3,'10',5],RR)
([1.00000000000000, 0.666666666666667, 10.0000000000000, 5.00000000000000], Real Field with 53 bits of precision)
sage: prepare({},QQ, 0)
([], Rational Field)
sage: prepare([1,2/3,'10',5],None)
Traceback (most recent call last):
...
TypeError: unable to find a common ring for all elements
Some objects can be converted to sequences even if they are not always
thought of as sequences. ::
sage: c = CDF(2+3*I)
sage: prepare(c, None)
([2.0, 3.0], Real Double Field)
This checks a bug listed at :trac:`10595`. Without good evidence
for a ring, the default is the integers. ::
sage: prepare([], None)
([], Integer Ring)
"""
if isinstance(v, dict):
# convert to a list
X = [0]*degree
for key, value in v.iteritems():
X[key] = value
v = X
# convert to a Sequence over common ring
# default to ZZ on an empty list
if R is None:
try:
if len(v) == 0:
R = ZZ
except TypeError:
pass
v = Sequence(v, universe=R, use_sage_types=True)
ring = v.universe()
if not is_Ring(ring):
raise TypeError("unable to find a common ring for all elements")
return v, ring
def zero_vector(arg0, arg1=None):
r"""
Returns a vector or free module element with a specified number of zeros.
CALL FORMATS:
1. zero_vector(degree)
2. zero_vector(ring, degree)
INPUT:
- ``degree`` - the number of zero entries in the vector or
free module element
- ``ring`` - default ``ZZ`` - the base ring of the vector
space or module containing the constructed zero vector
OUTPUT:
A vector or free module element with ``degree`` entries,
all equal to zero and belonging to the ring if specified.
If no ring is given, a free module element over ``ZZ``
is returned.
EXAMPLES:
A zero vector over the field of rationals. ::
sage: v = zero_vector(QQ, 5); v
(0, 0, 0, 0, 0)
sage: v.parent()
Vector space of dimension 5 over Rational Field
A free module zero element. ::
sage: w = zero_vector(Integers(6), 3); w
(0, 0, 0)
sage: w.parent()
Ambient free module of rank 3 over Ring of integers modulo 6
If no ring is given, the integers are used. ::
sage: u = zero_vector(9); u
(0, 0, 0, 0, 0, 0, 0, 0, 0)
sage: u.parent()
Ambient free module of rank 9 over the principal ideal domain Integer Ring
Non-integer degrees produce an error. ::
sage: zero_vector(5.6)
Traceback (most recent call last):
...
TypeError: Attempt to coerce non-integral RealNumber to Integer
Negative degrees also give an error. ::
sage: zero_vector(-3)
Traceback (most recent call last):
...
ValueError: rank (=-3) must be nonnegative
Garbage instead of a ring will be recognized as such. ::
sage: zero_vector(x^2, 5)
Traceback (most recent call last):
...
TypeError: first argument must be a ring
"""
if arg1 is None:
# default to a zero vector over the integers (ZZ) if no ring given
return (ZZ**arg0).zero_vector()
if is_Ring(arg0):
return (arg0**arg1).zero_vector()
raise TypeError("first argument must be a ring")
def random_vector(ring, degree=None, *args, **kwds):
r"""
Returns a vector (or module element) with random entries.
INPUT:
- ring - default: ``ZZ`` - the base ring for the entries
- degree - a non-negative integer for the number of entries in the vector
- sparse - default: ``False`` - whether to use a sparse implementation
- args, kwds - additional arguments and keywords are passed
to the ``random_element()`` method of the ring
OUTPUT:
A vector, or free module element, with ``degree`` elements
from ``ring``, chosen randomly from the ring according to
the ring's ``random_element()`` method.
.. note::
See below for examples of how random elements are
generated by some common base rings.
EXAMPLES:
First, module elements over the integers.
The default distribution is tightly clustered around -1, 0, 1.
Uniform distributions can be specified by giving bounds, though
the upper bound is never met. See
:meth:`sage.rings.integer_ring.IntegerRing_class.random_element`
for several other variants. ::
sage: random_vector(10)
(-8, 2, 0, 0, 1, -1, 2, 1, -95, -1)
sage: sorted(random_vector(20))
[-12, -6, -4, -4, -2, -2, -2, -1, -1, -1, 0, 0, 0, 0, 0, 1, 1, 1, 4, 5]
sage: random_vector(ZZ, 20, x=4)
(2, 0, 3, 0, 1, 0, 2, 0, 2, 3, 0, 3, 1, 2, 2, 2, 1, 3, 2, 3)
sage: random_vector(ZZ, 20, x=-20, y=100)
(43, 47, 89, 31, 56, -20, 23, 52, 13, 53, 49, -12, -2, 94, -1, 95, 60, 83, 28, 63)
sage: random_vector(ZZ, 20, distribution="1/n")
(0, -1, -2, 0, -1, -2, 0, 0, 27, -1, 1, 1, 0, 2, -1, 1, -1, -2, -1, 3)
If the ring is not specified, the default is the integers, and
parameters for the random distribution may be passed without using
keywords. This is a random vector with 20 entries uniformly distributed
between -20 and 100. ::
sage: random_vector(20, -20, 100)
(70, 19, 98, 2, -18, 88, 36, 66, 76, 52, 82, 99, 55, -17, 82, -15, 36, 28, 79, 18)
Now over the rationals. Note that bounds on the numerator and
denominator may be specified. See
:meth:`sage.rings.rational_field.RationalField.random_element`
for documentation. ::
sage: random_vector(QQ, 10)
(0, -1, -4/3, 2, 0, -13, 2/3, 0, -4/5, -1)
sage: random_vector(QQ, 10, num_bound = 15, den_bound = 5)
(-12/5, 9/4, -13/3, -1/3, 1, 5/4, 4, 1, -15, 10/3)
Inexact rings may be used as well. The reals have
uniform distributions, with the range `(-1,1)` as
the default. More at:
:meth:`sage.rings.real_mpfr.RealField_class.random_element` ::
sage: random_vector(RR, 5)
(0.248997268533725, -0.112200126330480, 0.776829203293064, -0.899146461031406, 0.534465018743125)
sage: random_vector(RR, 5, min = 8, max = 14)
(8.43260944052606, 8.34129413391087, 8.92391495103829, 11.5784799413416, 11.0973561568002)
Any ring with a ``random_element()`` method may be used. ::
sage: F = FiniteField(23)
sage: hasattr(F, 'random_element')
True
sage: random_vector(F, 10)
(21, 6, 5, 2, 6, 2, 18, 9, 9, 7)
The default implementation is a dense representation, equivalent to
setting ``sparse=False``. ::
sage: v = random_vector(10)
sage: v.is_sparse()
False
sage: w = random_vector(ZZ, 20, sparse=True)
sage: w.is_sparse()
True
Inputs get checked before constructing the vector. ::
sage: random_vector('junk')
Traceback (most recent call last):
...
TypeError: degree of a random vector must be an integer, not None
sage: random_vector('stuff', 5)
Traceback (most recent call last):
...
TypeError: elements of a vector, or module element, must come from a ring, not stuff
sage: random_vector(ZZ, -9)
Traceback (most recent call last):
...
ValueError: degree of a random vector must be non-negative, not -9
"""
if isinstance(ring, (Integer, int, long)):
if not degree is None:
arglist = list(args)
arglist.insert(0, degree)
args = tuple(arglist)
degree = ring
ring = ZZ
if not isinstance(degree,(Integer, int, long)):
raise TypeError("degree of a random vector must be an integer, not %s" % degree)
if degree < 0:
raise ValueError("degree of a random vector must be non-negative, not %s" % degree)
if not is_Ring(ring):
raise TypeError("elements of a vector, or module element, must come from a ring, not %s" % ring)
if not hasattr(ring, "random_element"):
raise AttributeError("cannot create a random vector since there is no random_element() method for %s" % ring )
sparse = kwds.pop('sparse', False)
entries = [ring.random_element(*args, **kwds) for _ in range(degree)]
return vector(ring, degree, entries, sparse)
cdef class FreeModuleElement(Vector): # abstract base class
"""
An element of a generic free module.
"""
def __init__(self, parent):
"""
EXAMPLES::
sage: v = sage.modules.free_module_element.FreeModuleElement(QQ^3)
sage: type(v)
<type 'sage.modules.free_module_element.FreeModuleElement'>
"""
self._parent = parent
self._degree = parent.degree()
self._is_mutable = 1
def _giac_init_(self):
"""
EXAMPLES::
sage: v = vector(ZZ, 4, range(4)) # optional - giac
sage: giac(v)+v # optional - giac
[0,2,4,6]
::
sage: v = vector(QQ, 3, [2/3, 0, 5/4]) # optional - giac
sage: giac(v) # optional - giac
[2/3,0,5/4]
::
sage: P.<x> = ZZ[] # optional - giac
sage: v = vector(P, 3, [x^2 + 2, 2*x + 1, -2*x^2 + 4*x]) # optional - giac
sage: giac(v) # optional - giac
[x^2+2,2*x+1,-2*x^2+4*x]
"""
return self.list()
def _pari_(self):
"""
Convert ``self`` to a PARI vector.
OUTPUT:
A PARI ``gen`` of type ``t_VEC``.
EXAMPLES::
sage: v = vector(range(4))
sage: v._pari_()
[0, 1, 2, 3]
sage: v._pari_().type()
't_VEC'
A list of vectors::
sage: L = [vector(i^n for i in range(4)) for n in [1,3,5]]
sage: pari(L)
[[0, 1, 2, 3], [0, 1, 8, 27], [0, 1, 32, 243]]
"""
from sage.libs.pari.all import pari
return pari(self.list())
def _pari_init_(self):
"""
Give a string which, when evaluated in GP, gives a PARI
representation of ``self``.
OUTPUT:
A string.
EXAMPLES::
sage: v = vector(range(4))
sage: v._pari_init_()
'[0,1,2,3]'
Create the multiplication table of `GF(4)` using GP::
sage: k.<a> = GF(4, impl="pari_ffelt")
sage: v = gp(vector(list(k)))
sage: v
[0, 1, a, a + 1]
sage: v.mattranspose() * v
[0, 0, 0, 0; 0, 1, a, a + 1; 0, a, a + 1, 1; 0, a + 1, 1, a]
"""
# Elements in vectors are always Sage Elements, so they should
# have a _pari_init_() method.
L = [x._pari_init_() for x in self.list()]
return "[" + ",".join(L) + "]"
def _magma_init_(self, magma):
r"""
Convert self to Magma.
EXAMPLES::
sage: F = FreeModule(ZZ, 2, inner_product_matrix=matrix(ZZ, 2, 2, [1, 0, 0, -1]))
sage: v = F([1, 2])
sage: M = magma(v); M # optional - magma
(1 2)
sage: M.Type() # optional - magma
ModTupRngElt
sage: M.Parent() # optional - magma
Full RSpace of degree 2 over Integer Ring
Inner Product Matrix:
[ 1 0]
[ 0 -1]
sage: M.sage() # optional - magma
(1, 2)
sage: M.sage() == v # optional - magma
True
sage: M.sage().parent() is v.parent() # optional - magma
True
::
sage: v = vector(QQ, [1, 2, 5/6])
sage: M = magma(v); M # optional - magma
( 1 2 5/6)
sage: M.Type() # optional - magma
ModTupFldElt
sage: M.Parent() # optional - magma
Full Vector space of degree 3 over Rational Field
sage: M.sage() # optional - magma
(1, 2, 5/6)
sage: M.sage() == v # optional - magma
True
sage: M.sage().parent() is v.parent() # optional - magma
True
"""
# Get a reference to Magma version of parent.
R = magma(self.parent())
# Get list of coefficients.
v = ','.join([a._magma_init_(magma) for a in self.list()])
return '%s![%s]' % (R.name(), v)
def numpy(self, dtype=object):
"""
Converts self to a numpy array.
INPUT:
- ``dtype`` -- the `numpy dtype <http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html>`_
of the returned array
EXAMPLES::
sage: v = vector([1,2,3])
sage: v.numpy()
array([1, 2, 3], dtype=object)
sage: v.numpy() * v.numpy()
array([1, 4, 9], dtype=object)
sage: vector(QQ, [1, 2, 5/6]).numpy()
array([1, 2, 5/6], dtype=object)
By default the ``object`` `dtype <http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html>`_ is used.
Alternatively, the desired dtype can be passed in as a parameter::
sage: v = vector(QQ, [1, 2, 5/6])
sage: v.numpy()
array([1, 2, 5/6], dtype=object)
sage: v.numpy(dtype=float)
array([ 1. , 2. , 0.83333333])
sage: v.numpy(dtype=int)
array([1, 2, 0])
sage: import numpy
sage: v.numpy(dtype=numpy.uint8)
array([1, 2, 0], dtype=uint8)
Passing a dtype of None will let numpy choose a native type, which can
be more efficient but may have unintended consequences::
sage: v.numpy(dtype=None)
array([ 1. , 2. , 0.83333333])
sage: w = vector(ZZ, [0, 1, 2^63 -1]); w
(0, 1, 9223372036854775807)
sage: wn = w.numpy(dtype=None); wn
array([ 0, 1, 9223372036854775807]...)
sage: wn.dtype
dtype('int64')