This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
matrix2.pyx
15455 lines (12895 loc) · 586 KB
/
matrix2.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"""
Base class for matrices, part 2
For design documentation see matrix/docs.py.
AUTHORS:
- William Stein: initial version
- Miguel Marco (2010-06-19): modified eigenvalues and eigenvectors functions to
allow the option extend=False
- Rob Beezer (2011-02-05): refactored all of the matrix kernel routines
TESTS::
sage: m = matrix(ZZ['x'], 2, 3, [1..6])
sage: TestSuite(m).run()
Check that a pair consisting of a matrix and its echelon form is
pickled correctly (this used to give a wrong answer due to a Python
bug, see :trac:`17527`)::
sage: K.<x> = FractionField(QQ['x'])
sage: m = Matrix([[1], [x]])
sage: t = (m, m.echelon_form())
sage: loads(dumps(t))
(
[1] [1]
[x], [0]
)
"""
#*****************************************************************************
# Copyright (C) 2005, 2006 William Stein <wstein@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# 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/
#*****************************************************************************
from __future__ import print_function, absolute_import, division
from cpython cimport *
from cysignals.signals cimport sig_check
from sage.misc.randstate cimport randstate, current_randstate
from sage.structure.coerce cimport py_scalar_parent
from sage.structure.sequence import Sequence
from sage.structure.element import is_Vector
from sage.structure.element cimport have_same_parent, coercion_model
from sage.misc.misc import verbose, get_verbose
from sage.rings.ring import is_Ring
from sage.rings.number_field.number_field_base import is_NumberField
from sage.rings.integer_ring import ZZ, is_IntegerRing
from sage.rings.integer import Integer
from sage.rings.rational_field import QQ, is_RationalField
from sage.rings.real_double import RDF
from sage.rings.complex_double import CDF
from sage.rings.real_mpfr import RealField
from sage.rings.complex_field import ComplexField
from sage.rings.finite_rings.integer_mod_ring import IntegerModRing
from sage.misc.derivative import multi_derivative
from sage.arith.numerical_approx cimport digits_to_bits
from copy import copy
import sage.modules.free_module
from . import berlekamp_massey
from sage.modules.free_module_element import is_FreeModuleElement
from sage.matrix.matrix_misc import permanental_minor_polynomial
cdef class Matrix(Matrix1):
def _backslash_(self, B):
r"""
Used to compute `A \backslash B`, i.e., the backslash solver
operator.
EXAMPLES::
sage: A = matrix(QQ, 3, [1,2,4,2,3,1,0,1,2])
sage: B = matrix(QQ, 3, 2, [1,7,5, 2,1,3])
sage: C = A._backslash_(B); C
[ -1 1]
[13/5 -3/5]
[-4/5 9/5]
sage: A*C == B
True
sage: A._backslash_(B) == A \ B
True
sage: A._backslash_(B) == A.solve_right(B)
True
"""
return self.solve_right(B)
def subs(self, *args, **kwds):
"""
Substitute values to the variables in that matrix.
All the arguments are transmitted unchanged to the method ``subs`` of
the coefficients.
EXAMPLES::
sage: var('a,b,d,e')
(a, b, d, e)
sage: m = matrix([[a,b], [d,e]])
sage: m.substitute(a=1)
[1 b]
[d e]
sage: m.subs(a=b, b=d)
[b d]
[d e]
sage: m.subs({a: 3, b:2, d:1, e:-1})
[ 3 2]
[ 1 -1]
The parent of the newly created matrix might be different from the
initial one. It depends on what the method ``.subs`` does on
coefficients (see :trac:`19045`)::
sage: x = polygen(ZZ)
sage: m = matrix([[x]])
sage: m2 = m.subs(x=2)
sage: m2.parent()
Full MatrixSpace of 1 by 1 dense matrices over Integer Ring
sage: m1 = m.subs(x=RDF(1))
sage: m1.parent()
Full MatrixSpace of 1 by 1 dense matrices over Real Double Field
However, sparse matrices remain sparse::
sage: m = matrix({(3,2): -x, (59,38): x^2+2}, nrows=1000, ncols=1000)
sage: m1 = m.subs(x=1)
sage: m1.is_sparse()
True
"""
from sage.matrix.constructor import matrix
if self.is_sparse():
return matrix({ij: self[ij].subs(*args, **kwds) for ij in self.nonzero_positions()},
nrows=self._nrows, ncols=self._ncols, sparse=True)
else:
return matrix([a.subs(*args, **kwds) for a in self.list()],
nrows=self._nrows, ncols=self._ncols, sparse=False)
def solve_left(self, B, check=True):
"""
If self is a matrix `A`, then this function returns a
vector or matrix `X` such that `X A = B`. If
`B` is a vector then `X` is a vector and if
`B` is a matrix, then `X` is a matrix.
INPUT:
- ``B`` - a matrix
- ``check`` - bool (default: True) - if False and self
is nonsquare, may not raise an error message even if there is no
solution. This is faster but more dangerous.
EXAMPLES::
sage: A = matrix(QQ,4,2, [0, -1, 1, 0, -2, 2, 1, 0])
sage: B = matrix(QQ,2,2, [1, 0, 1, -1])
sage: X = A.solve_left(B)
sage: X*A == B
True
sage: M = matrix([(3,-1,0,0),(1,1,-2,0),(0,0,0,-3)])
sage: B = matrix(QQ,3,1, [0,0,-1])
sage: M.solve_left(B)
Traceback (most recent call last):
...
ValueError: number of columns of self must equal number of columns of B
TESTS::
sage: A = matrix(QQ,4,2, [0, -1, 1, 0, -2, 2, 1, 0])
sage: B = vector(QQ,2, [2,1])
sage: X = A.solve_left(B)
sage: X*A == B
True
sage: X
(-1, 2, 0, 0)
sage: A = Matrix(Zmod(128), 2, 3, [5, 29, 33, 64, 0, 7])
sage: B = vector(Zmod(128), [31,39,56])
sage: X = A.solve_left(B); X
(19, 83)
sage: X * A == B
True
sage: M = matrix([(3,-1,0,0),(1,1,-2,0),(0,0,0,-3)])
sage: B = matrix(QQ,3,1, [0,0,-1])
sage: M.solve_left(B)
Traceback (most recent call last):
...
ValueError: number of columns of self must equal number of columns of B
"""
if is_Vector(B):
try:
return self.transpose().solve_right(B, check=check)
except ValueError as e:
raise ValueError(str(e).replace('row', 'column'))
else:
try:
return self.transpose().solve_right(B.transpose(), check=check).transpose()
except ValueError as e:
raise ValueError(str(e).replace('row', 'column'))
def solve_right(self, B, check=True):
r"""
If self is a matrix `A`, then this function returns a
vector or matrix `X` such that `A X = B`. If
`B` is a vector then `X` is a vector and if
`B` is a matrix, then `X` is a matrix.
.. NOTE::
In Sage one can also write ``A \backslash B`` for
``A.solve_right(B)``, i.e., Sage implements the "the
MATLAB/Octave backslash operator".
INPUT:
- ``B`` - a matrix or vector
- ``check`` - bool (default: True) - if False and self
is nonsquare, may not raise an error message even if there is no
solution. This is faster but more dangerous.
OUTPUT: a matrix or vector
.. SEEALSO::
:meth:`solve_left`
EXAMPLES::
sage: A = matrix(QQ, 3, [1,2,3,-1,2,5,2,3,1])
sage: b = vector(QQ,[1,2,3])
sage: x = A \ b; x
(-13/12, 23/12, -7/12)
sage: A * x
(1, 2, 3)
We solve with A nonsquare::
sage: A = matrix(QQ,2,4, [0, -1, 1, 0, -2, 2, 1, 0]); B = matrix(QQ,2,2, [1, 0, 1, -1])
sage: X = A.solve_right(B); X
[-3/2 1/2]
[ -1 0]
[ 0 0]
[ 0 0]
sage: A*X == B
True
Another nonsingular example::
sage: A = matrix(QQ,2,3, [1,2,3,2,4,6]); v = vector([-1/2,-1])
sage: x = A \ v; x
(-1/2, 0, 0)
sage: A*x == v
True
Same example but over `\ZZ`::
sage: A = matrix(ZZ,2,3, [1,2,3,2,4,6]); v = vector([-1,-2])
sage: A \ v
(-1, 0, 0)
An example in which there is no solution::
sage: A = matrix(QQ,2,3, [1,2,3,2,4,6]); v = vector([1,1])
sage: A \ v
Traceback (most recent call last):
...
ValueError: matrix equation has no solutions
A ValueError is raised if the input is invalid::
sage: A = matrix(QQ,4,2, [0, -1, 1, 0, -2, 2, 1, 0])
sage: B = matrix(QQ,2,2, [1, 0, 1, -1])
sage: X = A.solve_right(B)
Traceback (most recent call last):
...
ValueError: number of rows of self must equal number of rows of B
We solve with A singular::
sage: A = matrix(QQ,2,3, [1,2,3,2,4,6]); B = matrix(QQ,2,2, [6, -6, 12, -12])
sage: X = A.solve_right(B); X
[ 6 -6]
[ 0 0]
[ 0 0]
sage: A*X == B
True
We illustrate left associativity, etc., of the backslash operator.
::
sage: A = matrix(QQ, 2, [1,2,3,4])
sage: A \ A
[1 0]
[0 1]
sage: A \ A \ A
[1 2]
[3 4]
sage: A.parent()(1) \ A
[1 2]
[3 4]
sage: A \ (A \ A)
[ -2 1]
[ 3/2 -1/2]
sage: X = A \ (A - 2); X
[ 5 -2]
[-3 2]
sage: A * X
[-1 2]
[ 3 2]
Solving over a polynomial ring::
sage: x = polygen(QQ, 'x')
sage: A = matrix(2, [x,2*x,-5*x^2+1,3])
sage: v = vector([3,4*x - 2])
sage: X = A \ v
sage: X
((-8*x^2 + 4*x + 9)/(10*x^3 + x), (19*x^2 - 2*x - 3)/(10*x^3 + x))
sage: A * X == v
True
Solving some systems over `\ZZ/n\ZZ`::
sage: A = Matrix(Zmod(6), 3, 2, [1,2,3,4,5,6])
sage: B = vector(Zmod(6), [1,1,1])
sage: A.solve_right(B)
(5, 1)
sage: B = vector(Zmod(6), [5,1,1])
sage: A.solve_right(B)
Traceback (most recent call last):
...
ValueError: matrix equation has no solutions
sage: A = Matrix(Zmod(128), 2, 3, [23,11,22,4,1,0])
sage: B = Matrix(Zmod(128), 2, 1, [1,0])
sage: A.solve_right(B)
[ 1]
[124]
[ 1]
sage: B = B.column(0)
sage: A.solve_right(B)
(1, 124, 1)
sage: A = Matrix(Zmod(15), 3,4, range(12))
sage: B = Matrix(Zmod(15), 3,3, range(3,12))
sage: X = A.solve_right(B)
sage: A*X == B
True
Solving a system over the p-adics::
sage: k = Qp(5,4)
sage: a = matrix(k, 3, [1,7,3,2,5,4,1,1,2]); a
[ 1 + O(5^4) 2 + 5 + O(5^4) 3 + O(5^4)]
[ 2 + O(5^4) 5 + O(5^5) 4 + O(5^4)]
[ 1 + O(5^4) 1 + O(5^4) 2 + O(5^4)]
sage: v = vector(k, 3, [1,2,3])
sage: x = a \ v; x
(4 + 5 + 5^2 + 3*5^3 + O(5^4), 2 + 5 + 3*5^2 + 5^3 + O(5^4), 1 + 5 + O(5^4))
sage: a * x == v
True
Solving a system of linear equation symbolically using symbolic matrices::
sage: var('a,b,c,d,x,y')
(a, b, c, d, x, y)
sage: A=matrix(SR,2,[a,b,c,d]); A
[a b]
[c d]
sage: result=vector(SR,[3,5]); result
(3, 5)
sage: soln=A.solve_right(result)
sage: soln
(-b*(3*c/a - 5)/(a*(b*c/a - d)) + 3/a, (3*c/a - 5)/(b*c/a - d))
sage: (a*x+b*y).subs(x=soln[0],y=soln[1]).simplify_full()
3
sage: (c*x+d*y).subs(x=soln[0],y=soln[1]).simplify_full()
5
sage: (A*soln).apply_map(lambda x: x.simplify_full())
(3, 5)
"""
if is_Vector(B):
if self.nrows() != B.degree():
raise ValueError("number of rows of self must equal degree of B")
else:
if self.nrows() != B.nrows():
raise ValueError("number of rows of self must equal number of rows of B")
K = self.base_ring()
if not K.is_integral_domain():
from sage.rings.finite_rings.integer_mod_ring import is_IntegerModRing
if is_IntegerModRing(K):
from sage.libs.pari import pari
A = pari(self.lift())
b = pari(B).lift()
if b.type() == "t_MAT":
X = []
for n in range(B.ncols()):
ret = A.matsolvemod(K.cardinality(), b[n])
if ret.type() == 't_INT':
raise ValueError("matrix equation has no solutions")
X.append(ret.sage())
X = self.matrix_space(B.ncols(), self.ncols())(X)
return X.T
elif b.type() == "t_VEC":
b = b.Col()
ret = A.matsolvemod(K.cardinality(), b)
if ret.type() == 't_INT':
raise ValueError("matrix equation has no solutions")
ret = ret.Vec().sage()
return (K ** self.ncols())(ret)
raise TypeError("base ring must be an integral domain or a ring of integers mod n")
if not K.is_field():
K = K.fraction_field()
self = self.change_ring(K)
matrix = True
if is_Vector(B):
matrix = False
C = self.matrix_space(self.nrows(), 1)(B.list())
else:
C = B
if not self.is_square():
X = self._solve_right_general(C, check=check)
if not matrix:
# Convert back to a vector
return (X.base_ring() ** X.nrows())(X.list())
else:
return X
if self.rank() != self.nrows():
X = self._solve_right_general(C, check=check)
else:
X = self._solve_right_nonsingular_square(C, check_rank=False)
if not matrix:
# Convert back to a vector
return X.column(0)
else:
return X
def _solve_right_nonsingular_square(self, B, check_rank=True):
r"""
If ``self`` is a matrix `A` of full rank, then this function
returns a matrix `X` such that `A X = B`.
.. SEEALSO::
:meth:`solve_right` and :meth:`solve_left`
INPUT:
- ``B`` -- a matrix
- ``check_rank`` -- boolean (default: ``True``)
OUTPUT: matrix
EXAMPLES::
sage: A = matrix(QQ,3,[1,2,4,5,3,1,1,2,-1])
sage: B = matrix(QQ,3,2,[1,5,1,2,1,5])
sage: A._solve_right_nonsingular_square(B)
[ -1/7 -11/7]
[ 4/7 23/7]
[ 0 0]
sage: A._solve_right_nonsingular_square(B, check_rank=False)
[ -1/7 -11/7]
[ 4/7 23/7]
[ 0 0]
sage: X = A._solve_right_nonsingular_square(B, check_rank=False)
sage: A*X == B
True
"""
D = self.augment(B)
D.echelonize()
return D.matrix_from_columns(range(self.ncols(),D.ncols()))
def pivot_rows(self):
"""
Return the pivot row positions for this matrix, which are a topmost
subset of the rows that span the row space and are linearly
independent.
OUTPUT: a tuple of integers
EXAMPLES::
sage: A = matrix(QQ,3,3, [0,0,0,1,2,3,2,4,6]); A
[0 0 0]
[1 2 3]
[2 4 6]
sage: A.pivot_rows()
(1,)
sage: A.pivot_rows() # testing cached value
(1,)
"""
v = self.fetch('pivot_rows')
if v is not None:
return tuple(v)
v = self.transpose().pivots()
self.cache('pivot_rows', v)
return v
def _solve_right_general(self, B, check=True):
r"""
This is used internally by the ``solve_right`` command
to solve for self\*X = B when self is not square or not of full
rank. It does some linear algebra, then solves a full-rank square
system.
INPUT:
- ``B`` - a matrix
- ``check`` - bool (default: True); if False, if there
is no solution this function will not detect that fact.
OUTPUT: matrix
EXAMPLES::
sage: A = matrix(QQ,2,3, [1,2,3,2,4,6]); B = matrix(QQ,2,2, [6, -6, 12, -12])
sage: A._solve_right_general(B)
[ 6 -6]
[ 0 0]
[ 0 0]
"""
pivot_cols = self.pivots()
A = self.matrix_from_columns(pivot_cols)
pivot_rows = A.pivot_rows()
A = A.matrix_from_rows(pivot_rows)
X = A.solve_right(B.matrix_from_rows(pivot_rows), check=False)
if len(pivot_cols) < self.ncols():
# Now we have to put in zeros for the non-pivot ROWS, i.e.,
# make a matrix from X with the ROWS of X interspersed with
# 0 ROWS.
Y = X.new_matrix(self.ncols(), X.ncols())
# Put the columns of X into the matrix Y at the pivot_cols positions
for i, c in enumerate(pivot_cols):
Y.set_row(c, X.row(i))
X = Y
if check:
# Have to check that we actually solved the equation.
if self*X != B:
raise ValueError("matrix equation has no solutions")
return X
def prod_of_row_sums(self, cols):
r"""
Calculate the product of all row sums of a submatrix of `A`
for a list of selected columns ``cols``.
EXAMPLES::
sage: a = matrix(QQ, 2,2, [1,2,3,2]); a
[1 2]
[3 2]
sage: a.prod_of_row_sums([0,1])
15
Another example::
sage: a = matrix(QQ, 2,3, [1,2,3,2,5,6]); a
[1 2 3]
[2 5 6]
sage: a.prod_of_row_sums([1,2])
55
AUTHORS:
- Jaap Spies (2006-02-18)
"""
cdef Py_ssize_t c, row
pr = 1
for row from 0 <= row < self._nrows:
tmp = []
for c in cols:
# if c<0 or c >= self._ncols:
# raise IndexError("matrix column index out of range")
tmp.append(self.get_unsafe(row, c))
pr = pr * sum(tmp)
return pr
def elementwise_product(self, right):
r"""
Returns the elementwise product of two matrices
of the same size (also known as the Hadamard product).
INPUT:
- ``right`` - the right operand of the product. A matrix
of the same size as ``self`` such that multiplication
of elements of the base rings of ``self`` and ``right``
is defined, once Sage's coercion model is applied. If
the matrices have different sizes, or if multiplication
of individual entries cannot be achieved, a ``TypeError``
will result.
OUTPUT:
A matrix of the same size as ``self`` and ``right``. The
entry in location `(i,j)` of the output is the product of
the two entries in location `(i,j)` of ``self`` and
``right`` (in that order).
The parent of the result is determined by Sage's coercion
model. If the base rings are identical, then the result
is dense or sparse according to this property for
the left operand. If the base rings must be adjusted
for one, or both, matrices then the result will be sparse
only if both operands are sparse. No subdivisions are
present in the result.
If the type of the result is not to your liking, or
the ring could be "tighter," adjust the operands with
:meth:`~sage.matrix.matrix0.Matrix.change_ring`.
Adjust sparse versus dense inputs with the methods
:meth:`~sage.matrix.matrix1.Matrix.sparse_matrix` and
:meth:`~sage.matrix.matrix1.Matrix.dense_matrix`.
EXAMPLES::
sage: A = matrix(ZZ, 2, 3, range(6))
sage: B = matrix(QQ, 2, 3, [5, 1/3, 2/7, 11/2, -3/2, 8])
sage: C = A.elementwise_product(B)
sage: C
[ 0 1/3 4/7]
[33/2 -6 40]
sage: C.parent()
Full MatrixSpace of 2 by 3 dense matrices over Rational Field
Notice the base ring of the results in the next two examples. ::
sage: D = matrix(ZZ['x'],2,[1+x^2,2,3,4-x])
sage: E = matrix(QQ,2,[1,2,3,4])
sage: F = D.elementwise_product(E)
sage: F
[ x^2 + 1 4]
[ 9 -4*x + 16]
sage: F.parent()
Full MatrixSpace of 2 by 2 dense matrices over Univariate Polynomial Ring in x over Rational Field
::
sage: G = matrix(GF(3),2,[0,1,2,2])
sage: H = matrix(ZZ,2,[1,2,3,4])
sage: J = G.elementwise_product(H)
sage: J
[0 2]
[0 2]
sage: J.parent()
Full MatrixSpace of 2 by 2 dense matrices over Finite Field of size 3
Non-commutative rings behave as expected. These are the usual quaternions. ::
sage: R.<i,j,k> = QuaternionAlgebra(-1, -1)
sage: A = matrix(R, 2, [1,i,j,k])
sage: B = matrix(R, 2, [i,i,i,i])
sage: A.elementwise_product(B)
[ i -1]
[-k j]
sage: B.elementwise_product(A)
[ i -1]
[ k -j]
Input that is not a matrix will raise an error. ::
sage: A = random_matrix(ZZ,5,10,x=20)
sage: A.elementwise_product(vector(ZZ, [1,2,3,4]))
Traceback (most recent call last):
...
TypeError: operand must be a matrix, not an element of Ambient free module of rank 4 over the principal ideal domain Integer Ring
Matrices of different sizes for operands will raise an error. ::
sage: A = random_matrix(ZZ,5,10,x=20)
sage: B = random_matrix(ZZ,10,5,x=40)
sage: A.elementwise_product(B)
Traceback (most recent call last):
...
TypeError: incompatible sizes for matrices from: Full MatrixSpace of 5 by 10 dense matrices over Integer Ring and Full MatrixSpace of 10 by 5 dense matrices over Integer Ring
Some pairs of rings do not have a common parent where
multiplication makes sense. This will raise an error. ::
sage: A = matrix(QQ, 3, 2, range(6))
sage: B = matrix(GF(3), 3, [2]*6)
sage: A.elementwise_product(B)
Traceback (most recent call last):
...
TypeError: no common canonical parent for objects with parents: 'Full MatrixSpace of 3 by 2 dense matrices over Rational Field' and 'Full MatrixSpace of 3 by 2 dense matrices over Finite Field of size 3'
We illustrate various combinations of sparse and dense matrices.
Notice how if base rings are unequal, both operands must be sparse
to get a sparse result. ::
sage: A = matrix(ZZ, 5, 6, range(30), sparse=False)
sage: B = matrix(ZZ, 5, 6, range(30), sparse=True)
sage: C = matrix(QQ, 5, 6, range(30), sparse=True)
sage: A.elementwise_product(C).is_dense()
True
sage: B.elementwise_product(C).is_sparse()
True
sage: A.elementwise_product(B).is_dense()
True
sage: B.elementwise_product(A).is_dense()
True
TESTS:
Implementation for dense and sparse matrices are
different, this will provide a trivial test that
they are working identically. ::
sage: A = random_matrix(ZZ, 10, x=1000, sparse=False)
sage: B = random_matrix(ZZ, 10, x=1000, sparse=False)
sage: C = A.sparse_matrix()
sage: D = B.sparse_matrix()
sage: E = A.elementwise_product(B)
sage: F = C.elementwise_product(D)
sage: E.is_dense() and F.is_sparse() and (E == F)
True
If the ring has zero divisors, the routines for setting
entries of a sparse matrix should intercept zero results
and not create an entry. ::
sage: R = Integers(6)
sage: A = matrix(R, 2, [3, 2, 0, 0], sparse=True)
sage: B = matrix(R, 2, [2, 3, 1, 0], sparse=True)
sage: C = A.elementwise_product(B)
sage: len(C.nonzero_positions()) == 0
True
AUTHOR:
- Rob Beezer (2009-07-13)
"""
# Optimized routines for specialized classes would likely be faster
# See the "pairwise_product" of vectors for some guidance on doing this
from sage.structure.element import canonical_coercion
if not isinstance(right, Matrix):
raise TypeError('operand must be a matrix, not an element of %s' % right.parent())
if (self.nrows() != right.nrows()) or (self.ncols() != right.ncols()):
raise TypeError('incompatible sizes for matrices from: %s and %s'%(self.parent(), right.parent()))
if self._parent is not (<Matrix>right)._parent:
self, right = canonical_coercion(self, right)
return self._elementwise_product(right)
def permanent(self, algorithm="Ryser"):
r"""
Return the permanent of this matrix.
Let `A = (a_{i,j})` be an `m \times n` matrix over any
commutative ring with `m \le n`. The permanent of `A` is
.. MATH::
\mathrm{per}(A)
= \sum_\pi a_{1,\pi(1)} a_{2,\pi(2)} \cdots a_{m,\pi(m)}
where the summation extends over all one-to-one functions
`\pi` from `\{1, \ldots, m\}` to `\{1, \ldots, n\}`.
The product
`a_{1,\pi(1)} a_{2,\pi(2)} \cdots a_{m,\pi(m)}` is
called *diagonal product*. So the permanent of an
`m \times n` matrix `A` is the sum of all the
diagonal products of `A`.
By default, this method uses Ryser's algorithm, but setting
``algorithm`` to "ButeraPernici" you can use the algorithm of Butera and
Pernici (which is well suited for band matrices, i.e. matrices whose
entries are concentrated near the diagonal).
INPUT:
- ``A`` -- matrix of size `m \times n` with `m \leq n`
- ``algorithm`` -- either "Ryser" (default) or "ButeraPernici". The
Butera-Pernici algorithm takes advantage of presence of zeros and is
very well suited for sparse matrices.
ALGORITHM:
The Ryser algorithm is implemented in the method
:meth:`_permanent_ryser`. It is a modification of theorem 7.1.1. from
Brualdi and Ryser: Combinatorial Matrix Theory. Instead of deleting
columns from `A`, we choose columns from `A` and calculate the product
of the row sums of the selected submatrix.
The Butera-Pernici algorithm is implemented in the function
:func:`~sage.matrix.matrix_misc.permanental_minor_polynomial`. It takes
advantage of cancellations that may occur in the computations.
EXAMPLES::
sage: A = ones_matrix(4,4)
sage: A.permanent()
24
sage: A = matrix(3,6,[1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1])
sage: A.permanent()
36
sage: B = A.change_ring(RR)
sage: B.permanent()
36.0000000000000
The permanent above is directed to the Sloane's sequence :oeis:`A079908`
("The Dancing School Problems") for which the third term is 36:
::
sage: oeis(79908) # optional -- internet
A079908: Solution to the Dancing School Problem with 3 girls and n+3 boys: f(3,n).
sage: _(3) # optional -- internet
36
::
sage: A = matrix(4,5,[1,1,0,1,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,0])
sage: A.permanent()
32
A huge permanent that can not be reasonably computed with the Ryser
algorithm (a `50 \times 50` band matrix with width `5`)::
sage: n, w = 50, 5
sage: A = matrix(ZZ, n, n, lambda i,j: (i+j)%5 + 1 if abs(i-j) <= w else 0)
sage: A.permanent(algorithm="ButeraPernici")
57766972735511097036962481710892268404670105604676932908
See Minc: Permanents, Example 2.1, p. 5.
::
sage: A = matrix(QQ,2,2,[1/5,2/7,3/2,4/5])
sage: A.permanent()
103/175
::
sage: R.<a> = PolynomialRing(ZZ)
sage: A = matrix(R,2,2,[a,1,a,a+1])
sage: A.permanent()
a^2 + 2*a
::
sage: R.<x,y> = PolynomialRing(ZZ,2)
sage: A = matrix(R,2,2,[x, y, x^2, y^2])
sage: A.permanent()
x^2*y + x*y^2
AUTHORS:
- Jaap Spies (2006-02-16 and 2006-02-21)
"""
if algorithm == "Ryser":
return self._permanent_ryser()
elif algorithm == "ButeraPernici":
return permanental_minor_polynomial(self, True)
else:
raise ValueError("algorithm must be one of \"Ryser\" or \"ButeraPernici\".")
def _permanent_ryser(self):
r"""
Return the permanent computed using Ryser algorithm.
See :meth:`permanent` for the documentation.
EXAMPLES::
sage: m = matrix([[1,1],[1,1]])
sage: m._permanent_ryser()
2
"""
cdef Py_ssize_t m, n, r
cdef int sn
perm = 0
m = self._nrows
n = self._ncols
if not m <= n:
raise ValueError("must have m <= n, but m (=%s) and n (=%s)"%(m,n))
for r from 1 <= r < m+1:
lst = _choose(n, r)
tmp = []
for cols in lst:
tmp.append(self.prod_of_row_sums(cols))
s = sum(tmp)
# sn = (-1)^(m-r)
if (m - r) % 2 == 0:
sn = 1
else:
sn = -1
perm = perm + sn * _binomial(n-r, m-r) * s
return perm
def permanental_minor(self, Py_ssize_t k, algorithm="Ryser"):
r"""
Return the permanental `k`-minor of this matrix.
The *permanental* `k`-*minor* of a matrix `A` is the sum of the
permanents of all possible `k` by `k` submatrices of `A`. Note that the
maximal permanental minor is just the permanent.
For a (0,1)-matrix `A` the permanental `k`-minor
counts the number of different selections of `k` 1's of
`A` with no two of the 1's on the same row and no two of the
1's on the same column.
See Brualdi and Ryser: Combinatorial Matrix Theory, p. 203. Note
the typo `p_0(A) = 0` in that reference! For applications
see Theorem 7.2.1 and Theorem 7.2.4.
.. SEEALSO::
The method :meth:`rook_vector` returns the list of all permanental
minors.
INPUT:
- ``k`` -- the size of the minor
- ``algorithm`` -- either "Ryser" (default) or "ButeraPernici". The
Butera-Pernici algorithm is well suited for band matrices.
EXAMPLES::
sage: A = matrix(4,[1,0,1,0,1,0,1,0,1,0,10,10,1,0,1,1])
sage: A.permanental_minor(2)
114
::
sage: A = matrix(3,6,[1,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1])
sage: A.permanental_minor(0)
1
sage: A.permanental_minor(1)
12
sage: A.permanental_minor(2)
40
sage: A.permanental_minor(3)
36
Note that if `k = m = n`, the permanental `k`-minor equals
`\mathrm{per}(A)`::
sage: A.permanent()
36
The permanental minors of the "complement" matrix of `A` is
related to the permanent of `A`::
sage: m, n = 3, 6
sage: C = matrix(m, n, lambda i,j: 1 - A[i,j])
sage: sum((-1)^k * C.permanental_minor(k)*factorial(n-k)/factorial(n-m) for k in range(m+1))
36
See Theorem 7.2.1 of Brualdi and Ryser: Combinatorial Matrix
Theory: per(A)
TESTS::
sage: A.permanental_minor(5)
0
AUTHORS:
- Jaap Spies (2006-02-19)
"""
if algorithm == "Ryser":
return self._permanental_minor_ryser(k)
elif algorithm == "ButeraPernici":
p = permanental_minor_polynomial(self, prec=k+1)