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
17828 lines (14814 loc) · 677 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
- Jaap Spies (2006-02-24): added ``prod_of_row_sums``, ``permanent``,
``permanental_minor``, ``rook_vector`` methods
- Robert Bradshaw (2007-06-14): added ``subdivide`` method
- Jaap Spies (2007-11-14): implemented ``_binomial``, ``_choose`` auxiliary functions
- William Stein (2007-11-18): added ``_gram_schmidt_noscale`` method
- David Loeffler (2008-12-05): added ``smith_form`` method
- David Loeffler (2009-06-01): added ``_echelon_form_PID`` method
- Sebastian Pancratz (2009-06-25): implemented ``adjoint`` and ``charpoly``
methods; fixed ``adjoint`` reflecting the change that ``_adjoint`` is now
implemented in :class:`Matrix`; used the division-free algorithm for
``charpoly``
- Rob Beezer (2009-07-13): added ``elementwise_product`` method
- Miguel Marco (2010-06-19): modified eigenvalues and eigenvectors functions to
allow the option ``extend=False``
- Thierry Monteil (2010-10-05): bugfix for :trac:`10063`, so that the
determinant is computed even for rings for which the ``is_field`` method is not
implemented.
- Rob Beezer (2010-12-13): added ``conjugate_transpose`` method
- Rob Beezer (2011-02-05): refactored all of the matrix kernel routines; added
``extended_echelon_form``, ``right_kernel_matrix``, ``QR``,
``_gram_schmidt_noscale``, ``is_similar`` methods
- Moritz Minzlaff (2011-03-17): corrected ``_echelon_form_PID`` method for
matrices of one row, fixed in :trac:`9053`
- Rob Beezer (2011-06-09): added ``is_normal``, ``is_diagonalizable``, ``LU``,
``cyclic_subspace``, ``zigzag_form``, ``rational_form`` methods
- Rob Beezer (2012-05-27): added ``indefinite_factorization``,
``is_positive_definite``, ``cholesky`` methods
- Darij Grinberg (2013-10-01): added first (slow) pfaffian implementation
- Mario Pernici (2014-07-01): modified ``rook_vector`` method
- Rob Beezer (2015-05-25): modified ``is_similar`` method
- Samuel Lelièvre (2020-09-18): improved method ``LLL_gram`` based on a patch
by William Stein posted at :trac:`5178`, moving the method from its initial
location in ``sage.matrix.integer_matrix_dense``
- Michael Jung (2020-10-02): added Bär-Faddeev-LeVerrier algorithm for the
Pfaffian
"""
# ****************************************************************************
# 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.
# https://www.gnu.org/licenses/
# ****************************************************************************
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.coerce cimport coercion_model
from sage.structure.element import is_Vector
from sage.structure.element cimport have_same_parent
from sage.misc.verbose import verbose, get_verbose
from sage.categories.all import Fields, IntegralDomains
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_mpfr 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
# used to deprecate only adjoint method
from sage.misc.superseded import deprecated_function_alias
_Fields = Fields()
cdef class Matrix(Matrix1):
"""
Base class for matrices, part 2
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]
)
"""
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):
"""
Try to find a solution `X` to the equation `X A = B`.
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.
Over inexact rings, the output of this function may not be an
exact solution. For example, over the real or complex double
field, this method computes a least-squares solution if the
system is not square.
.. NOTE::
In Sage one can also write ``B / A`` for
``A.solve_left(B)``, that is, Sage implements "the
MATLAB/Octave slash operator".
INPUT:
- ``B`` -- a matrix or vector
- ``check`` -- boolean (default: ``True``); verify the answer
if the system is non-square or rank-deficient, and if its
entries lie in an exact ring. Meaningless over inexact rings,
or when the system is square and of full rank.
OUTPUT:
If the system is square and has full rank, the unique solution
is returned, and no check is done on the answer. Over inexact
rings, you should expect this answer to be inexact.
Moreover, due to the numerical issues involved, an error
may be thrown in this case -- specifically if the system is
singular but if SageMath fails to notice that.
If the system is not square or does not have full rank, then a
solution is attempted via other means. For example, over
``RDF`` or ``CDF`` a least-squares solution is returned, as
with MATLAB's "backslash" operator. For inexact rings, the
``check`` parameter is ignored because an approximate solution
will be returned in any case. Over exact rings, on the other
hand, setting the ``check`` parameter results in an additional
test to determine whether or not the answer actually solves the
system exactly.
If `B` is a vector, the result is returned as a vector, as well,
and as a matrix, otherwise.
.. SEEALSO::
:meth:`solve_right`
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: X == B / A
True
::
sage: A = matrix([(3, -1, 0, 0), (1, 1, -2, 0), (0, 0, 0, -3)])
sage: B = matrix(QQ, 3, 1, [0, 0, -1])
sage: A.solve_left(B)
Traceback (most recent call last):
...
ValueError: number of columns of self must equal number of columns
of right-hand side
Over the reals::
sage: A = matrix(RDF, 3,3, [1,2,5,7.6,2.3,1,1,2,-1]); A
[ 1.0 2.0 5.0]
[ 7.6 2.3 1.0]
[ 1.0 2.0 -1.0]
sage: b = vector(RDF,[1,2,3])
sage: x = A.solve_left(b); x.zero_at(2e-17) # fix noisy zeroes
(0.666666666..., 0.0, 0.333333333...)
sage: x.parent()
Vector space of dimension 3 over Real Double Field
sage: x*A # tol 1e-14
(0.9999999999999999, 1.9999999999999998, 3.0)
Over the complex numbers::
sage: A = matrix(CDF, [[ 0, -1 + 2*I, 1 - 3*I, I],
....: [2 + 4*I, -2 + 3*I, -1 + 2*I, -1 - I],
....: [ 2 + I, 1 - I, -1, 5],
....: [ 3*I, -1 - I, -1 + I, -3 + I]])
sage: b = vector(CDF, [2 -3*I, 3, -2 + 3*I, 8])
sage: x = A.solve_left(b); x
(-1.55765124... - 0.644483985...*I, 0.183274021... + 0.286476868...*I, 0.270818505... + 0.246619217...*I, -1.69003558... - 0.828113879...*I)
sage: x.parent()
Vector space of dimension 4 over Complex Double Field
sage: abs(x*A - b) < 1e-14
True
If ``b`` is given as a matrix, the result will be a matrix, as well::
sage: A = matrix(RDF, 3, 3, [2, 5, 0, 7, 7, -2, -4.3, 0, 1])
sage: b = matrix(RDF, 2, 3, [2, -4, -5, 1, 1, 0.1])
sage: A.solve_left(b) # tol 1e-14
[ -6.495454545454545 4.068181818181818 3.1363636363636354]
[ 0.5277272727272727 -0.2340909090909091 -0.36818181818181817]
If `A` is a non-square matrix, the result is a least-squares solution.
For a tall matrix, this may give a solution with a least-squares error
of almost zero::
sage: A = matrix(RDF, 3, 2, [1, 3, 4, 2, 0, -3])
sage: b = vector(RDF, [5, 6])
sage: x = A.solve_left(b)
sage: (x * A - b).norm() < 1e-14
True
For a wide matrix `A`, the error is usually not small::
sage: A = matrix(RDF, 2, 3, [1, 3, 4, 2, 0, -3])
sage: b = vector(RDF, [5, 6, 1])
sage: x = A.solve_left(b)
sage: (x * A - b).norm() # tol 1e-14
0.9723055853282466
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 right-hand side
A degenerate case::
sage: A = matrix(RDF, 0, 0, [])
sage: A.solve_left(vector(RDF,[]))
()
Over an inexact ring like ``RDF``, the coefficient matrix of a
square system must be nonsingular::
sage: A = matrix(RDF, 5, range(25))
sage: b = vector(RDF, [1,2,3,4,5])
sage: A.solve_left(b)
Traceback (most recent call last):
...
LinAlgError: Matrix is singular.
The vector of constants needs the correct degree::
sage: A = matrix(RDF, 5, range(25))
sage: b = vector(RDF, [1,2,3,4])
sage: A.solve_left(b)
Traceback (most recent call last):
...
ValueError: number of columns of self must equal degree of
right-hand side
The vector of constants needs to be compatible with
the base ring of the coefficient matrix::
sage: F.<a> = FiniteField(27)
sage: b = vector(F, [a,a,a,a,a])
sage: A.solve_left(b)
Traceback (most recent call last):
...
TypeError: no common canonical parent for objects with parents: ...
Check that coercions work correctly (:trac:`17405`)::
sage: A = matrix(RDF, 2, range(4))
sage: b = vector(CDF, [1+I, 2])
sage: A.solve_left(b)
(0.5 - 1.5*I, 0.5 + 0.5*I)
sage: b = vector(QQ[I], [1+I, 2])
sage: x = A.solve_left(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"""
Try to find a solution `X` to the equation `A X = B`.
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.
Over inexact rings, the output of this function may not be an
exact solution. For example, over the real or complex double
field, this method computes a least-squares solution if the
system is not square.
.. NOTE::
In Sage one can also write ``A \ B`` for
``A.solve_right(B)``, that is, Sage implements "the
MATLAB/Octave backslash operator".
INPUT:
- ``B`` -- a matrix or vector
- ``check`` -- boolean (default: ``True``); verify the answer
if the system is non-square or rank-deficient, and if its
entries lie in an exact ring. Meaningless over inexact rings,
or when the system is square and of full rank.
OUTPUT:
If the system is square and has full rank, the unique solution
is returned, and no check is done on the answer. Over inexact
rings, you should expect this answer to be inexact.
Moreover, due to the numerical issues involved, an error
may be thrown in this case -- specifically if the system is
singular but if SageMath fails to notice that.
If the system is not square or does not have full rank, then a
solution is attempted via other means. For example, over
``RDF`` or ``CDF`` a least-squares solution is returned, as
with MATLAB's "backslash" operator. For inexact rings, the
``check`` parameter is ignored because an approximate solution
will be returned in any case. Over exact rings, on the other
hand, setting the ``check`` parameter results in an additional
test to determine whether or not the answer actually solves the
system exactly.
If `B` is a vector, the result is returned as a vector, as well,
and as a matrix, otherwise.
.. 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
right-hand side
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
((-4/5*x^2 + 2/5*x + 9/10)/(x^3 + 1/10*x), (19/10*x^2 - 1/5*x - 3/10)/(x^3 + 1/10*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)
[ 5]
[108]
[127]
sage: B = B.column(0)
sage: A.solve_right(B)
(5, 108, 127)
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 equations 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)
Over inexact rings, the output of this function may not be an exact
solution. For example, over the real or complex double field,
this computes a least-squares solution::
sage: A = matrix(RDF, 3, 2, [1, 3, 4, 2, 0, -3])
sage: b = vector(RDF, [5, 6, 1])
sage: A.solve_right(b) # tol 1e-14
(1.4782608695652177, 0.35177865612648235)
sage: ~(A.T * A) * A.T * b # closed form solution, tol 1e-14
(1.4782608695652177, 0.35177865612648235)
Over the reals::
sage: A = matrix(RDF, 3,3, [1,2,5,7.6,2.3,1,1,2,-1]); A
[ 1.0 2.0 5.0]
[ 7.6 2.3 1.0]
[ 1.0 2.0 -1.0]
sage: b = vector(RDF,[1,2,3])
sage: x = A.solve_right(b); x # tol 1e-14
(-0.1136950904392765, 1.3901808785529717, -0.33333333333333337)
sage: x.parent()
Vector space of dimension 3 over Real Double Field
sage: A*x # tol 1e-14
(1.0, 1.9999999999999996, 3.0000000000000004)
Over the complex numbers::
sage: A = matrix(CDF, [[ 0, -1 + 2*I, 1 - 3*I, I],
....: [2 + 4*I, -2 + 3*I, -1 + 2*I, -1 - I],
....: [ 2 + I, 1 - I, -1, 5],
....: [ 3*I, -1 - I, -1 + I, -3 + I]])
sage: b = vector(CDF, [2 -3*I, 3, -2 + 3*I, 8])
sage: x = A.solve_right(b); x
(1.96841637... - 1.07606761...*I, -0.614323843... + 1.68416370...*I, 0.0733985765... + 1.73487544...*I, -1.6018683... + 0.524021352...*I)
sage: x.parent()
Vector space of dimension 4 over Complex Double Field
sage: abs(A*x - b) < 1e-14
True
If ``b`` is given as a matrix, the result will be a matrix, as well::
sage: A = matrix(RDF, 3, 3, [1, 2, 2, 3, 4, 5, 2, 2, 2])
sage: b = matrix(RDF, 3, 2, [3, 2, 3, 2, 3, 2])
sage: A.solve_right(b) # tol 1e-14
[ 0.0 0.0]
[ 4.5 3.0]
[-3.0 -2.0]
If `A` is a non-square matrix, the result is a least-squares solution.
For a wide matrix, this may give a solution with a least-squares error
of almost zero::
sage: A = matrix(RDF, 2, 3, [1, 3, 4, 2, 0, -3])
sage: b = vector(RDF, [5, 6])
sage: x = A.solve_right(b)
sage: (A * x - b).norm() < 1e-14
True
For a tall matrix `A`, the error is usually not small::
sage: A = matrix(RDF, 3, 2, [1, 3, 4, 2, 0, -3])
sage: b = vector(RDF, [5, 6, 1])
sage: x = A.solve_right(b)
sage: (A * x - b).norm() # tol 1e-14
3.2692119900020438
TESTS:
Check that the arguments are coerced to a suitable parent
(:trac:`12406`)::
sage: A = matrix(QQ, 2, [1, 2, 3, 4])
sage: b = vector(RDF, [pi, e])
sage: A.solve_right(b) # tol 1e-15
(-3.564903478720541, 3.353248066155167)
sage: R.<t> = ZZ[]
sage: b = vector(R, [1, t])
sage: x = A.solve_right(b); x
(t - 2, -1/2*t + 3/2)
sage: A * x == b
True
sage: x.base_ring()
Fraction Field of Univariate Polynomial Ring in t over Rational Field
::
sage: A = Matrix(Zmod(6), 3, 2, [1,2,3,4,5,6])
sage: b = vector(ZZ, [1,1,1])
sage: A.solve_right(b).base_ring() is Zmod(6)
True
Check that the coercion mechanism gives consistent results
(:trac:`12406`)::
sage: A = matrix(ZZ, [[1, 2, 3], [2, 0, 2], [3, 2, 5]])
sage: b = vector(RDF, [1, 1, 1])
sage: A.solve_right(b) == A.change_ring(RDF).solve_right(b)
...
True
A degenerate case::
sage: A = matrix(RDF, 0, 0, [])
sage: A.solve_right(vector(RDF,[]))
()
Over an inexact ring like ``RDF``, the coefficient matrix of a
square system must be nonsingular::
sage: A = matrix(RDF, 5, range(25))
sage: b = vector(RDF, [1,2,3,4,5])
sage: A.solve_right(b)
Traceback (most recent call last):
...
LinAlgError: Matrix is singular.
The vector of constants needs the correct degree. ::
sage: A = matrix(RDF, 5, range(25))
sage: b = vector(RDF, [1,2,3,4])
sage: A.solve_right(b)
Traceback (most recent call last):
...
ValueError: number of rows of self must equal degree of
right-hand side
The vector of constants needs to be compatible with
the base ring of the coefficient matrix. ::
sage: F.<a> = FiniteField(27)
sage: b = vector(F, [a,a,a,a,a])
sage: A.solve_right(b)
Traceback (most recent call last):
...
TypeError: no common canonical parent for objects with parents: ...
Check that coercions work correctly (:trac:`17405`)::
sage: A = matrix(RDF, 2, range(4))
sage: b = vector(CDF, [1+I, 2])
sage: A.solve_right(b)
(-0.5 - 1.5*I, 1.0 + 1.0*I)
sage: b = vector(QQ[I], [1+I, 2])
sage: x = A.solve_right(b)
Calling this method with anything but a vector or matrix is
deprecated::
sage: A = matrix(CDF, 5, [1/(i+j+1) for i in range(5) for j in range(5)])
sage: x = A.solve_right([1]*5)
doctest:...: DeprecationWarning: solve_right should be called with
a vector or matrix
See http://trac.sagemath.org/17405 for details.
Over inexact rings, the ``check`` parameter is ignored as the result is
only an approximate solution (:trac:`13932`)::
sage: RF = RealField(52)
sage: B = matrix(RF, 2, 2, 1)
sage: A = matrix(RF, [[0.24, 1, 0], [1, 0, 0]])
sage: 0 < (A * A.solve_right(B) - B).norm() < 1e-14
True
"""
try:
L = B.base_ring()
except AttributeError:
from sage.misc.superseded import deprecation
deprecation(17405, "solve_right should be called with a vector "
"or matrix")
from sage.modules.free_module_element import vector
B = vector(B)
b_is_vec = is_Vector(B)
if b_is_vec:
if self.nrows() != B.degree():
raise ValueError("number of rows of self must equal "
"degree of right-hand side")
else:
if self.nrows() != B.nrows():
raise ValueError("number of rows of self must equal "
"number of rows of right-hand side")
K = self.base_ring()
L = B.base_ring()
# first coerce both elements to parent over same base ring
P = K if L is K else coercion_model.common_parent(K, L)
if P not in _Fields and P.is_integral_domain():
# the non-integral-domain case is handled separatedly below
P = P.fraction_field()
if L is not P:
B = B.change_ring(P)
if K is not P:
K = P
self = self.change_ring(P)
# If our field is inexact, checking the answer is doomed anyway.
check = (check and K.is_exact())
if not K.is_integral_domain():
# The non-integral-domain case is handled almost entirely
# separately.
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")
C = B.column() if b_is_vec else B
if not self.is_square():
X = self._solve_right_general(C, check=check)
else:
try:
X = self._solve_right_nonsingular_square(C, check_rank=True)
except NotFullRankError:
X = self._solve_right_general(C, check=check)
if b_is_vec:
# 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
"""
# this could probably be optimized so that the rank computation is
# avoided
if check_rank and self.rank() < self.nrows():
raise NotFullRankError
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
"""
cdef Py_ssize_t c, row
pr = 1
for row from 0 <= row < self._nrows: