-
-
Notifications
You must be signed in to change notification settings - Fork 401
/
matrix0.pyx
5772 lines (4710 loc) · 183 KB
/
matrix0.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
# -*- coding: utf-8 -*-
"""
Base class for matrices, part 0
.. NOTE::
For design documentation see matrix/docs.py.
EXAMPLES::
sage: matrix(2,[1,2,3,4])
[1 2]
[3 4]
"""
# ****************************************************************************
# Copyright (C) 2005, 2006 William Stein <wstein@gmail.com>
#
# 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.
# https://www.gnu.org/licenses/
# ****************************************************************************
from __future__ import print_function, absolute_import
from cpython cimport *
from cysignals.signals cimport sig_check
import sage.modules.free_module
import sage.misc.latex
import sage.rings.integer
from sage.arith.power cimport generic_power
from sage.misc.misc import verbose, get_verbose
from sage.structure.sequence import Sequence
from sage.structure.parent cimport Parent
cimport sage.structure.element
from sage.structure.element cimport ModuleElement, Element, RingElement, Vector
from sage.structure.mutability cimport Mutability
from sage.misc.misc_c cimport normalize_index
from sage.rings.ring cimport CommutativeRing
from sage.rings.ring import is_Ring
from sage.rings.finite_rings.integer_mod_ring import is_IntegerModRing
import sage.modules.free_module
from .matrix_misc import row_iterator
cdef class Matrix(sage.structure.element.Matrix):
r"""
A generic matrix.
The ``Matrix`` class is the base class for all matrix
classes. To create a ``Matrix``, first create a
``MatrixSpace``, then coerce a list of elements into
the ``MatrixSpace``. See the documentation of
``MatrixSpace`` for more details.
EXAMPLES:
We illustrate matrices and matrix spaces. Note that no actual
matrix that you make should have class Matrix; the class should
always be derived from Matrix.
::
sage: M = MatrixSpace(CDF,2,3); M
Full MatrixSpace of 2 by 3 dense matrices over Complex Double Field
sage: a = M([1,2,3, 4,5,6]); a
[1.0 2.0 3.0]
[4.0 5.0 6.0]
sage: type(a)
<type 'sage.matrix.matrix_complex_double_dense.Matrix_complex_double_dense'>
sage: parent(a)
Full MatrixSpace of 2 by 3 dense matrices over Complex Double Field
::
sage: matrix(CDF, 2,3, [1,2,3, 4,5,6])
[1.0 2.0 3.0]
[4.0 5.0 6.0]
sage: Mat(CDF,2,3)(range(1,7))
[1.0 2.0 3.0]
[4.0 5.0 6.0]
::
sage: Q.<i,j,k> = QuaternionAlgebra(QQ, -1,-1)
sage: matrix(Q,2,1,[1,2])
[1]
[2]
"""
def __cinit__(self, parent, *args, **kwds):
"""
The initialization routine of the ``Matrix`` base class ensures
that it sets the attributes ``self._parent``, ``self._base_ring``,
``self._nrows``, ``self._ncols``.
The private attributes ``self._is_immutable`` and ``self._cache``
are implicitly initialized to valid values upon memory allocation.
EXAMPLES::
sage: import sage.matrix.matrix0
sage: A = sage.matrix.matrix0.Matrix(MatrixSpace(QQ,2))
sage: type(A)
<type 'sage.matrix.matrix0.Matrix'>
"""
P = <Parent?>parent
self._parent = P
self._base_ring = P._base
self._nrows = P.nrows()
self._ncols = P.ncols()
self.hash = -1
def list(self):
"""
List of the elements of ``self`` ordered by elements in each
row. It is safe to change the returned list.
.. warning::
This function returns a list of the entries in the matrix
``self``. It does not return a list of the rows of ``self``,
so it is different than the output of ``list(self)``, which
returns ``[self[0],self[1],...]``.
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: a = matrix(R,2,[x,y,x*y, y,x,2*x+y]); a
[ x y x*y]
[ y x 2*x + y]
sage: v = a.list(); v
[x, y, x*y, y, x, 2*x + y]
Note that list(a) is different than a.list()::
sage: a.list()
[x, y, x*y, y, x, 2*x + y]
sage: list(a)
[(x, y, x*y), (y, x, 2*x + y)]
Notice that changing the returned list does not change a (the list
is a copy)::
sage: v[0] = 25
sage: a
[ x y x*y]
[ y x 2*x + y]
"""
return list(self._list())
def _list(self):
"""
Unsafe version of the ``list`` method, mainly for internal use.
This may return the list of elements, but as an *unsafe* reference
to the underlying list of the object. It is dangerous to change
entries of the returned list.
EXAMPLES:
Using ``_list`` is potentially fast and memory efficient,
but very dangerous (at least for generic dense matrices).
::
sage: a = matrix(QQ['x,y'],2,range(6)); a
[0 1 2]
[3 4 5]
sage: v = a._list(); v
[0, 1, 2, 3, 4, 5]
If you change an entry of the list, the corresponding entry of the
matrix will be changed (but without clearing any caches of
computing information about the matrix)::
sage: v[0] = -2/3; v
[-2/3, 1, 2, 3, 4, 5]
sage: a._list()
[-2/3, 1, 2, 3, 4, 5]
Now the 0,0 entry of the matrix is `-2/3`, which is weird.
::
sage: a[0,0]
-2/3
See::
sage: a
[-2/3 1 2]
[ 3 4 5]
"""
cdef Py_ssize_t i, j
x = self.fetch('list')
if not x is None:
return x
x = []
for i from 0 <= i < self._nrows:
for j from 0 <= j < self._ncols:
x.append(self.get_unsafe(i, j))
return x
def dict(self, copy=True):
r"""
Dictionary of the elements of ``self`` with keys pairs ``(i,j)``
and values the nonzero entries of ``self``.
INPUT:
- ``copy`` -- (default: ``True``) make a copy of the ``dict``
corresponding to ``self``
If ``copy=True``, then is safe to change the returned dictionary.
Otherwise, this can cause undesired behavior by mutating the ``dict``.
EXAMPLES::
sage: R.<x,y> = QQ[]
sage: a = matrix(R,2,[x,y,0, 0,0,2*x+y]); a
[ x y 0]
[ 0 0 2*x + y]
sage: d = a.dict(); d
{(0, 0): x, (0, 1): y, (1, 2): 2*x + y}
Notice that changing the returned list does not change a (the list
is a copy)::
sage: d[0,0] = 25
sage: a
[ x y 0]
[ 0 0 2*x + y]
"""
if copy:
return dict(self._dict())
return self._dict()
monomial_coefficients = dict
def _dict(self):
"""
Unsafe version of the dict method, mainly for internal use.
This may return the dict of elements, but as an *unsafe*
reference to the underlying dict of the object. It might
dangerous if you change entries of the returned dict.
EXAMPLES: Using _dict is potentially fast and memory efficient,
but very dangerous (at least for generic sparse matrices).
::
sage: a = matrix(QQ['x,y'],2,range(6), sparse=True); a
[0 1 2]
[3 4 5]
sage: v = a._dict(); v
{(0, 1): 1, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5}
If you change a key of the dictionary, the corresponding entry of
the matrix will be changed (but without clearing any caches of
computing information about the matrix)::
sage: v[0,1] = -2/3; v
{(0, 1): -2/3, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5}
sage: a._dict()
{(0, 1): -2/3, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5}
sage: a[0,1]
-2/3
But the matrix doesn't know the entry changed, so it returns the
cached version of its print representation::
sage: a
[0 1 2]
[3 4 5]
If we change an entry, the cache is cleared, and the correct print
representation appears::
sage: a[1,2]=10
sage: a
[ 0 -2/3 2]
[ 3 4 10]
"""
d = self.fetch('dict')
if not d is None:
return d
cdef Py_ssize_t i, j
d = {}
for i from 0 <= i < self._nrows:
for j from 0 <= j < self._ncols:
x = self.get_unsafe(i, j)
if x != 0:
d[(int(i),int(j))] = x
self.cache('dict', d)
return d
###########################################################
# Cache
###########################################################
def _clear_cache(self):
"""
Clear anything cached about this matrix.
EXAMPLES::
sage: m = Matrix(QQ, 2, range(4))
sage: m._clear_cache()
"""
self.clear_cache()
cdef void clear_cache(self):
"""
Clear the properties cache.
"""
self._cache = None
self.hash = -1
cdef fetch(self, key):
"""
Try to get an element from the cache; if there isn't anything
there, return None.
"""
if self._cache is None:
return None
try:
return self._cache[key]
except KeyError:
return None
cdef cache(self, key, x):
"""
Record x in the cache with given key.
"""
if self._cache is None:
self._cache = {}
self._cache[key] = x
def _get_cache(self):
"""
Return the cache.
EXAMPLES::
sage: m=Matrix(QQ,2,range(0,4))
sage: m._get_cache()
{}
"""
if self._cache is None:
self._cache = {}
return self._cache
###########################################################
# Mutability and bounds checking
###########################################################
cdef check_bounds(self, Py_ssize_t i, Py_ssize_t j):
"""
This function gets called when you're about to access the i,j entry
of this matrix. If i, j are out of range, an IndexError is
raised.
"""
if i<0 or i >= self._nrows or j<0 or j >= self._ncols:
raise IndexError("matrix index out of range")
cdef check_mutability(self):
"""
This function gets called when you're about to change this matrix.
If self is immutable, a ValueError is raised, since you should
never change a mutable matrix.
If self is mutable, the cache of results about self is deleted.
"""
if self._is_immutable:
raise ValueError("matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).")
else:
self._cache = None
cdef check_bounds_and_mutability(self, Py_ssize_t i, Py_ssize_t j):
"""
This function gets called when you're about to set the i,j entry of
this matrix. If i or j is out of range, an IndexError exception is
raised.
If self is immutable, a ValueError is raised, since you should
never change a mutable matrix.
If self is mutable, the cache of results about self is deleted.
"""
if self._is_immutable:
raise ValueError("matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).")
else:
self._cache = None
if i<0 or i >= self._nrows or j<0 or j >= self._ncols:
raise IndexError("matrix index out of range")
def set_immutable(self):
r"""
Call this function to set the matrix as immutable.
Matrices are always mutable by default, i.e., you can change their
entries using ``A[i,j] = x``. However, mutable matrices
aren't hashable, so can't be used as keys in dictionaries, etc.
Also, often when implementing a class, you might compute a matrix
associated to it, e.g., the matrix of a Hecke operator. If you
return this matrix to the user you're really returning a reference
and the user could then change an entry; this could be confusing.
Thus you should set such a matrix immutable.
EXAMPLES::
sage: A = Matrix(QQ, 2, 2, range(4))
sage: A.is_mutable()
True
sage: A[0,0] = 10
sage: A
[10 1]
[ 2 3]
Mutable matrices are not hashable, so can't be used as keys for
dictionaries::
sage: hash(A)
Traceback (most recent call last):
...
TypeError: mutable matrices are unhashable
sage: v = {A:1}
Traceback (most recent call last):
...
TypeError: mutable matrices are unhashable
If we make A immutable it suddenly is hashable.
::
sage: A.set_immutable()
sage: A.is_mutable()
False
sage: A[0,0] = 10
Traceback (most recent call last):
...
ValueError: matrix is immutable; please change a copy instead (i.e., use copy(M) to change a copy of M).
sage: hash(A) #random
12
sage: v = {A:1}; v
{[10 1]
[ 2 3]: 1}
"""
self._is_immutable = True
def is_immutable(self):
"""
Return True if this matrix is immutable.
See the documentation for self.set_immutable for more details
about mutability.
EXAMPLES::
sage: A = Matrix(QQ['t','s'], 2, 2, range(4))
sage: A.is_immutable()
False
sage: A.set_immutable()
sage: A.is_immutable()
True
"""
return self._is_immutable
def is_mutable(self):
"""
Return True if this matrix is mutable.
See the documentation for self.set_immutable for more details
about mutability.
EXAMPLES::
sage: A = Matrix(QQ['t','s'], 2, 2, range(4))
sage: A.is_mutable()
True
sage: A.set_immutable()
sage: A.is_mutable()
False
"""
return not(self._is_immutable)
###########################################################
# Entry access
# The first two must be overloaded in the derived class
###########################################################
cdef set_unsafe(self, Py_ssize_t i, Py_ssize_t j, object x):
"""
Set entry quickly without doing any bounds checking. Calling this
with invalid arguments is allowed to produce a segmentation fault.
This is fast since it is a cdef function and there is no bounds
checking.
"""
raise NotImplementedError("this must be defined in the derived class (type=%s)"%type(self))
cdef get_unsafe(self, Py_ssize_t i, Py_ssize_t j):
"""
Entry access, but fast since it might be without bounds checking.
This is fast since it is a cdef function and there is no bounds
checking.
"""
raise NotImplementedError("this must be defined in the derived type.")
def add_to_entry(self, Py_ssize_t i, Py_ssize_t j, elt):
r"""
Add ``elt`` to the entry at position ``(i, j)``.
EXAMPLES::
sage: m = matrix(QQ['x,y'], 2, 2)
sage: m.add_to_entry(0, 1, 2)
sage: m
[0 2]
[0 0]
"""
elt = self.base_ring()(elt)
if i < 0:
i += self._nrows
if i < 0 or i >= self._nrows:
raise IndexError("row index out of range")
if j < 0:
j += self._ncols
if j < 0 or j >= self._ncols:
raise IndexError("column index out of range")
self.set_unsafe(i, j, elt + self.get_unsafe(i, j))
## def _get_very_unsafe(self, i, j):
## r"""
## Entry access, but potentially fast since it might be without
## bounds checking. (I know of no cases where this is actually
## faster.)
## This function it can very easily !! SEG FAULT !! if you call
## it with invalid input. Use with *extreme* caution.
## EXAMPLES:
## sage: a = matrix(ZZ,2,range(4))
## sage: a._get_very_unsafe(0,1)
## 1
## If you do \code{a.\_get\_very\_unsafe(0,10)} you'll very likely crash Sage
## completely.
## """
## return self.get_unsafe(i, j)
def __iter__(self):
"""
Return an iterator for the rows of self.
EXAMPLES::
sage: m = matrix(2,[1,2,3,4])
sage: next(m.__iter__())
(1, 2)
"""
return row_iterator(self)
def __getitem__(self, key):
"""
Return element, row, or slice of self.
INPUT:
- ``key``- tuple (i,j) where i, j can be integers, slices or lists
USAGE:
- ``A[i, j]`` - the i,j element (or elements, if i or j are
slices or lists) of A, or
- ``A[i:j]`` - rows of A, according to slice notation
EXAMPLES::
sage: A = Matrix(Integers(2006),2,2,[-1,2,3,4])
sage: A[0,0]
2005
sage: A[0]
(2005, 2)
The returned row is immutable (mainly to avoid confusion)::
sage: A[0][0] = 123
Traceback (most recent call last):
...
ValueError: vector is immutable; please change a copy instead (use copy())
sage: A[0].is_immutable()
True
sage: a = matrix(ZZ,3,range(9)); a
[0 1 2]
[3 4 5]
[6 7 8]
sage: a[1,2]
5
sage: a[0]
(0, 1, 2)
sage: a[4,7]
Traceback (most recent call last):
...
IndexError: matrix index out of range
sage: a[-1,0]
6
::
sage: a[2.7]
Traceback (most recent call last):
...
TypeError: index must be an integer
sage: a[1, 2.7]
Traceback (most recent call last):
...
TypeError: index must be an integer
sage: a[2.7, 1]
Traceback (most recent call last):
...
TypeError: index must be an integer
sage: m=[(1, -2, -1, -1,9), (1, 8, 6, 2,2), (1, 1, -1, 1,4), (-1, 2, -2, -1,4)];M= matrix(m)
sage: M
[ 1 -2 -1 -1 9]
[ 1 8 6 2 2]
[ 1 1 -1 1 4]
[-1 2 -2 -1 4]
Get the 2 x 2 submatrix of M, starting at row index and column
index 1
::
sage: M[1:3,1:3]
[ 8 6]
[ 1 -1]
Get the 2 x 3 submatrix of M starting at row index and column index
1::
sage: M[1:3,[1..3]]
[ 8 6 2]
[ 1 -1 1]
Get the second column of M::
sage: M[:,1]
[-2]
[ 8]
[ 1]
[ 2]
Get the first row of M::
sage: M[0,:]
[ 1 -2 -1 -1 9]
More examples::
sage: M[range(2),:]
[ 1 -2 -1 -1 9]
[ 1 8 6 2 2]
sage: M[range(2),4]
[9]
[2]
sage: M[range(3),range(5)]
[ 1 -2 -1 -1 9]
[ 1 8 6 2 2]
[ 1 1 -1 1 4]
::
sage: M[3,range(5)]
[-1 2 -2 -1 4]
sage: M[3,:]
[-1 2 -2 -1 4]
sage: M[3,4]
4
sage: M[-1,:]
[-1 2 -2 -1 4]
sage: A = matrix(ZZ,3,4, [3, 2, -5, 0, 1, -1, 1, -4, 1, 0, 1, -3]); A
[ 3 2 -5 0]
[ 1 -1 1 -4]
[ 1 0 1 -3]
::
sage: A[:,0:4:2]
[ 3 -5]
[ 1 1]
[ 1 1]
::
sage: A[1:,0:4:2]
[1 1]
[1 1]
sage: A[2::-1,:]
[ 1 0 1 -3]
[ 1 -1 1 -4]
[ 3 2 -5 0]
sage: A[1:,3::-1]
[-4 1 -1 1]
[-3 1 0 1]
sage: A[1:,3::-2]
[-4 -1]
[-3 0]
sage: A[2::-1,3:1:-1]
[-3 1]
[-4 1]
[ 0 -5]
::
sage: A= matrix(3,4,[1, 0, -3, -1, 3, 0, -2, 1, -3, -5, -1, -5])
sage: A[range(2,-1,-1),:]
[-3 -5 -1 -5]
[ 3 0 -2 1]
[ 1 0 -3 -1]
::
sage: A[range(2,-1,-1),range(3,-1,-1)]
[-5 -1 -5 -3]
[ 1 -2 0 3]
[-1 -3 0 1]
::
sage: A = matrix(2, [1, 2, 3, 4])
sage: A[[0,0],[0,0]]
[1 1]
[1 1]
::
sage: M = matrix(3, 4, range(12))
sage: M[0:0, 0:0]
[]
sage: M[0:0, 1:4]
[]
sage: M[2:3, 3:3]
[]
sage: M[range(2,2), :3]
[]
sage: M[(1,2), 3]
[ 7]
[11]
sage: M[(1,2),(0,1,1)]
[4 5 5]
[8 9 9]
sage: m=[(1, -2, -1, -1), (1, 8, 6, 2), (1, 1, -1, 1), (-1, 2, -2, -1)]
sage: M= matrix(m);M
[ 1 -2 -1 -1]
[ 1 8 6 2]
[ 1 1 -1 1]
[-1 2 -2 -1]
sage: M[:2]
[ 1 -2 -1 -1]
[ 1 8 6 2]
sage: M[:]
[ 1 -2 -1 -1]
[ 1 8 6 2]
[ 1 1 -1 1]
[-1 2 -2 -1]
sage: M[1:3]
[ 1 8 6 2]
[ 1 1 -1 1]
sage: A=matrix(QQ,10,range(100))
sage: A[0:3]
[ 0 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]
sage: A[:2]
[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
sage: A[8:]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]
sage: A[1:10:3]
[10 11 12 13 14 15 16 17 18 19]
[40 41 42 43 44 45 46 47 48 49]
[70 71 72 73 74 75 76 77 78 79]
sage: A[-1]
(90, 91, 92, 93, 94, 95, 96, 97, 98, 99)
sage: A[-1:-6:-2]
[90 91 92 93 94 95 96 97 98 99]
[70 71 72 73 74 75 76 77 78 79]
[50 51 52 53 54 55 56 57 58 59]
sage: A[3].is_immutable()
True
sage: A[1:3].is_immutable()
True
Slices that result in zero rows or zero columns are supported too::
sage: m = identity_matrix(QQ, 4)[4:,:]
sage: m.nrows(), m.ncols()
(0, 4)
sage: m * vector(QQ, 4)
()
TESTS:
If we're given lists as arguments, we should throw an
appropriate error when those lists do not contain valid
indices (:trac:`6569`)::
sage: A = matrix(4, range(1,17))
sage: A[[1.5], [1]]
Traceback (most recent call last):
...
IndexError: row indices must be integers
sage: A[[1], [1.5]]
Traceback (most recent call last):
...
IndexError: column indices must be integers
sage: A[[1.5]]
Traceback (most recent call last):
...
IndexError: row indices must be integers
Before :trac:`6569` was fixed, sparse/dense matrices behaved
differently due to implementation details. Given invalid
indices, they should fail in the same manner. These tests
just repeat the previous set with a sparse matrix::
sage: A = matrix(4, range(1,17), sparse=True)
sage: A[[1.5], [1]]
Traceback (most recent call last):
...
IndexError: row indices must be integers
sage: A[[1], [1.5]]
Traceback (most recent call last):
...
IndexError: column indices must be integers
sage: A[[1.5]]
Traceback (most recent call last):
...
IndexError: row indices must be integers
Check that submatrices with a specified implementation have the
same implementation::
sage: M = MatrixSpace(GF(2), 3, 3, implementation='generic')
sage: m = M(range(9))
sage: type(m)
<type 'sage.matrix.matrix_generic_dense.Matrix_generic_dense'>
sage: parent(m)
Full MatrixSpace of 3 by 3 dense matrices over Finite Field of size 2 (using Matrix_generic_dense)
sage: type(m[:2,:2])
<type 'sage.matrix.matrix_generic_dense.Matrix_generic_dense'>
sage: parent(m[:2,:2])
Full MatrixSpace of 2 by 2 dense matrices over Finite Field of size 2 (using Matrix_generic_dense)
"""
cdef list row_list
cdef list col_list
cdef Py_ssize_t i
cdef int row, col
cdef int nrows = self._nrows
cdef int ncols = self._ncols
cdef tuple key_tuple
cdef object row_index, col_index
cdef int ind
# used to keep track of when an index is a
# single number
cdef int single_row = 0, single_col = 0
if type(key) is tuple:
key_tuple = <tuple>key
#if PyTuple_Size(key_tuple) != 2:
if len(key_tuple) != 2:
raise IndexError("index must be an integer or pair of integers")
row_index = <object>PyTuple_GET_ITEM(key_tuple, 0)
col_index = <object>PyTuple_GET_ITEM(key_tuple, 1)
type_row = type(row_index)
if type_row is list or type_row is tuple or type_row is range:
if type_row is tuple or type_row is range:
row_list = list(row_index)
else:
row_list = row_index
for i from 0 <= i < len(row_list):
# The 'ind' variable is 'cdef int' and will
# truncate a float to a valid index. So, we have
# to test row_list[i] instead.
if not PyIndex_Check(row_list[i]):
raise IndexError('row indices must be integers')
ind = row_list[i]
if ind < 0:
ind += nrows
row_list[i] = ind
if ind < 0 or ind >= nrows:
raise IndexError("matrix index out of range")
elif isinstance(row_index, slice):
row_list = list(xrange(*row_index.indices(nrows)))
else:
if not PyIndex_Check(row_index):
raise TypeError("index must be an integer")
row = row_index
if row < 0:
row += nrows
if row < 0 or row >= nrows:
raise IndexError("matrix index out of range")
single_row = 1
type_col = type(col_index)
if type_col is list or type_col is tuple or type_col is range:
if type_col is tuple or type_col is range:
col_list = list(col_index)
else:
col_list = col_index
for i from 0 <= i < len(col_list):
# The 'ind' variable is 'cdef int' and will
# truncate a float to a valid index. So, we have
# to test col_list[i] instead.
if not PyIndex_Check(col_list[i]):
raise IndexError('column indices must be integers')
ind = col_list[i]
if ind < 0:
ind += ncols
col_list[i] = ind
if ind < 0 or ind >= ncols:
raise IndexError("matrix index out of range")
elif isinstance(col_index, slice):
col_list = list(xrange(*col_index.indices(ncols)))
else:
if not PyIndex_Check(col_index):
raise TypeError("index must be an integer")
col = col_index
if col < 0:
col += ncols
if col < 0 or col >= ncols:
raise IndexError("matrix index out of range")
single_col = 1
# if we had a single row entry and a single column entry,
# we want to just do a get_unsafe
if single_row and single_col:
return self.get_unsafe(row, col)
# otherwise, prep these for the call to
# matrix_from_rows_and_columns
if single_row:
row_list = [row]
if single_col:
col_list = [col]
if len(row_list) == 0 or len(col_list) == 0:
return self.new_matrix(nrows=len(row_list), ncols=len(col_list))
return self.matrix_from_rows_and_columns(row_list,col_list)
row_index = key
if type(row_index) is list or type(row_index) is tuple:
if type(row_index) is tuple:
row_list = list(row_index)
else:
row_list = row_index
for i from 0 <= i < len(row_list):
# The 'ind' variable is 'cdef int' and will
# truncate a float to a valid index. So, we have
# to test row_list[i] instead.
if not PyIndex_Check(row_list[i]):
raise IndexError('row indices must be integers')
ind = row_list[i]