/
dense.py
1495 lines (1237 loc) · 38.7 KB
/
dense.py
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
import random
from sympy.core.basic import Basic
from sympy.core.compatibility import is_sequence
from sympy.core.function import count_ops
from sympy.core.decorators import call_highest_priority
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.simplify import simplify as _simplify
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.matrices.matrices import (MatrixBase,
ShapeError, a2idx, classof)
# uncomment the import of as_int and delete the function when merged with 0.7.2
#from sympy.core.compatibility import as_int
def as_int(i):
ii = int(i)
if i != ii:
raise TypeError()
return ii
def _iszero(x):
"""Returns True if x is zero."""
return x.is_zero
class DenseMatrix(MatrixBase):
is_MatrixExpr = False
_op_priority = 12.0
_class_priority = 10
def __getitem__(self, key):
"""Return portion of self defined by key. If the key involves a slice
then a list will be returned (if key is a single slice) or a matrix
(if key was a tuple involving a slice).
Examples
========
>>> from sympy import Matrix, I
>>> m = Matrix([
... [1, 2 + I],
... [3, 4 ]])
If the key is a tuple that doesn't involve a slice then that element
is returned:
>>> m[1, 0]
3
When a tuple key involves a slice, a matrix is returned. Here, the
first column is selected (all rows, column 0):
>>> m[:, 0]
[1]
[3]
If the slice is not a tuple then it selects from the underlying
list of elements that are arranged in row order and a list is
returned if a slice is involved:
>>> m[0]
1
>>> m[::2]
[1, 3]
"""
if type(key) is tuple:
i, j = key
if type(i) is slice or type(j) is slice:
return self.submatrix(key)
else:
i, j = self.key2ij(key)
return self._mat[i*self.cols + j]
else:
# row-wise decomposition of matrix
if type(key) is slice:
return self._mat[key]
return self._mat[a2idx(key)]
def __setitem__(self, key, value):
raise NotImplementedError()
def __hash__(self):
# issue 880 suggests that there should be no hash for a mutable
# object...but at least we aren't caching the result
return hash((type(self).__name__,) + (self.shape, tuple(self._mat)))
@property
def is_Identity(self):
if not self.is_square:
return False
if not all(self[i, i] == 1 for i in range(self.rows)):
return False
for i in range(self.rows):
for j in range(i + 1, self.cols):
if self[i, j] or self[j, i]:
return False
return True
def tolist(self):
"""
Return the Matrix as a nested Python list.
Examples
========
>>> from sympy import Matrix, ones
>>> m = Matrix(3, 3, range(9))
>>> m
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
>>> m.tolist()
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> ones(3, 0).tolist()
[[], [], []]
When there are no rows then it will not be possible to tell how
many columns were in the original matrix:
>>> ones(0, 3).tolist()
[]
"""
if not self.rows:
return []
if not self.cols:
return [[] for i in range(self.rows)]
return [self._mat[i: i + self.cols]
for i in range(0, len(self), self.cols)]
def row(self, i, f=None):
"""
Elementary row selector.
>>> from sympy import ones
>>> I = ones(3)
>>> I.row(1, lambda v, i: v*3)
>>> I
[1, 1, 1]
[3, 3, 3]
[1, 1, 1]
>>> I.row(1)
[3, 3, 3]
See Also
========
col
row_op
row_swap
row_del
row_join
row_insert
"""
if f is None:
return self[i, :]
SymPyDeprecationWarning(
feature="calling .row(i, f)",
useinstead=".row_op(i, f)",
deprecated_since_version="0.7.2",
).warn()
self.row_op(i, f)
def col(self, j, f=None):
"""
Elementary column selector (default) or operation using functor
which is a function of two args interpreted as (self[i, j], i).
>>> from sympy import ones
>>> I = ones(3)
>>> I.col(0, lambda v, i: v*3)
>>> I
[3, 1, 1]
[3, 1, 1]
[3, 1, 1]
>>> I.col(0)
[3]
[3]
[3]
See Also
========
row
col_op
col_swap
col_del
col_join
col_insert
"""
if f is None:
return self[:, j]
SymPyDeprecationWarning(
feature="calling .col(j, f)",
useinstead=".col_op(j, f)",
deprecated_since_version="0.7.2",
).warn()
self.col_op(j, f)
def _eval_trace(self):
"""
Calculate the trace of a square matrix.
Examples
========
>>> from sympy.matrices import eye
>>> eye(3).trace()
3
"""
trace = 0
for i in range(self.cols):
trace += self._mat[i*self.cols + i]
return trace
def _eval_transpose(self):
"""
Matrix transposition.
>>> from sympy import Matrix, I
>>> m=Matrix(((1, 2+I), (3, 4)))
>>> m
[1, 2 + I]
[3, 4]
>>> m.transpose()
[ 1, 3]
[2 + I, 4]
>>> m.T == m.transpose()
True
See Also
========
conjugate: By-element conjugation
"""
a = []
for i in range(self.cols):
a.extend(self._mat[i::self.cols])
return self._new(self.cols, self.rows, a)
def _eval_conjugate(self):
"""By-element conjugation.
See Also
========
transpose: Matrix transposition
H: Hermite conjugation
D: Dirac conjugation
"""
out = self._new(self.rows, self.cols,
lambda i, j: self[i, j].conjugate())
return out
def _eval_inverse(self, **kwargs):
"""Return the matrix inverse using the method indicated (default
is Gauss elimination).
kwargs
======
method : ('GE', 'LU', or 'ADJ')
iszerofunc
try_block_diag
Notes
=====
According to the ``method`` keyword, it calls the appropriate method:
GE .... inverse_GE(); default
LU .... inverse_LU()
ADJ ... inverse_ADJ()
According to the ``try_block_diag`` keyword, it will try to form block
diagonal matrices using the method get_diag_blocks(), invert these
individually, and then reconstruct the full inverse matrix.
Note, the GE and LU methods may require the matrix to be simplified
before it is inverted in order to properly detect zeros during
pivoting. In difficult cases a custom zero detection function can
be provided by setting the ``iszerosfunc`` argument to a function that
should return True if its argument is zero. The ADJ routine computes
the determinant and uses that to detect singular matrices in addition
to testing for zeros on the diagonal.
See Also
========
inverse_LU
inverse_GE
inverse_ADJ
"""
from sympy.matrices import diag
method = kwargs.get('method', 'GE')
iszerofunc = kwargs.get('iszerofunc', _iszero)
if kwargs.get('try_block_diag', False):
blocks = self.get_diag_blocks()
r = []
for block in blocks:
r.append(block.inv(method=method, iszerofunc=iszerofunc))
return diag(*r)
if method == "GE":
return self.inverse_GE(iszerofunc=iszerofunc)
elif method == "LU":
return self.inverse_LU(iszerofunc=iszerofunc)
elif method == "ADJ":
return self.inverse_ADJ(iszerofunc=iszerofunc)
else:
# make sure to add an invertibility check (as in inverse_LU)
# if a new method is added.
raise ValueError("Inversion method unrecognized")
def equals(self, other, failing_expression=False):
"""Applies ``equals`` to corresponding elements of the matrices,
trying to prove that the elements are equivalent, returning True
if they are, False if any pair is not, and None (or the first
failing expression if failing_expression is True) if it cannot
be decided if the expressions are equivalent or not. This is, in
general, an expensive operation.
Examples
========
>>> from sympy.matrices import Matrix
>>> from sympy.abc import x
>>> from sympy import cos
>>> A = Matrix([x*(x - 1), 0])
>>> B = Matrix([x**2 - x, 0])
>>> A == B
False
>>> A.simplify() == B.simplify()
True
>>> A.equals(B)
True
>>> A.equals(2)
False
See Also
========
sympy.core.expr.equals
"""
try:
if self.shape != other.shape:
return False
rv = True
for i in range(self.rows):
for j in range(self.cols):
ans = self[i, j].equals(other[i, j], failing_expression)
if ans is False:
return False
elif ans is not True and rv is True:
rv = ans
return rv
except AttributeError:
return False
def __eq__(self, other):
try:
if self.shape != other.shape:
return False
if isinstance(other, Matrix):
return self._mat == other._mat
elif isinstance(other, MatrixBase):
return self._mat == other.as_mutable()._mat
except AttributeError:
return False
def __ne__(self, other):
return not self == other
def _cholesky(self):
"""
Helper function of cholesky.
Without the error checks.
To be used privately. """
L = zeros(self.rows, self.rows)
for i in range(self.rows):
for j in range(i):
L[i, j] = (1 / L[j, j]) * (self[i, j] -
sum(L[i, k] * L[j, k] for k in range(j)))
L[i, i] = sqrt(self[i, i] -
sum(L[i, k]**2 for k in range(i)))
return self._new(L)
def _LDLdecomposition(self):
"""
Helper function of LDLdecomposition.
Without the error checks.
To be used privately.
"""
D = zeros(self.rows, self.rows)
L = eye(self.rows)
for i in range(self.rows):
for j in range(i):
L[i, j] = (1 / D[j, j]) * (self[i, j] - sum(
L[i, k] * L[j, k] * D[k, k] for k in range(j)))
D[i, i] = self[i, i] - sum(L[i, k]**2 * D[k, k]
for k in range(i))
return self._new(L), self._new(D)
def _lower_triangular_solve(self, rhs):
"""
Helper function of function lower_triangular_solve.
Without the error checks.
To be used privately.
"""
X = zeros(self.rows, 1)
for i in range(self.rows):
if self[i, i] == 0:
raise TypeError("Matrix must be non-singular.")
X[i, 0] = (rhs[i, 0] - sum(self[i, k] * X[k, 0]
for k in range(i))) / self[i, i]
return self._new(X)
def _upper_triangular_solve(self, rhs):
"""
Helper function of function upper_triangular_solve.
Without the error checks, to be used privately. """
X = zeros(self.rows, 1)
for i in reversed(range(self.rows)):
if self[i, i] == 0:
raise ValueError("Matrix must be non-singular.")
X[i, 0] = (rhs[i, 0] - sum(self[i, k] * X[k, 0]
for k in range(i+1, self.rows))) / self[i, i]
return self._new(X)
def _diagonal_solve(self, rhs):
"""
Helper function of function diagonal_solve,
without the error checks, to be used privately.
"""
return self._new(rhs.rows, 1, lambda i, j: rhs[i, 0] / self[i, i])
def applyfunc(self, f):
"""
Apply a function to each element of the matrix.
>>> from sympy import Matrix
>>> m = Matrix(2, 2, lambda i, j: i*2+j)
>>> m
[0, 1]
[2, 3]
>>> m.applyfunc(lambda i: 2*i)
[0, 2]
[4, 6]
"""
if not callable(f):
raise TypeError("`f` must be callable.")
out = self._new(self.rows, self.cols, map(f, self._mat))
return out
def reshape(self, rows, cols):
"""
Reshape the matrix. Total number of elements must remain the same.
>>> from sympy import Matrix
>>> m = Matrix(2, 3, lambda i, j: 1)
>>> m
[1, 1, 1]
[1, 1, 1]
>>> m.reshape(1, 6)
[1, 1, 1, 1, 1, 1]
>>> m.reshape(3, 2)
[1, 1]
[1, 1]
[1, 1]
"""
if len(self) != rows*cols:
raise ValueError("Invalid reshape parameters %d %d" % (rows, cols))
return self._new(rows, cols, lambda i, j: self._mat[i*cols + j])
############################
# Mutable matrix operators #
############################
@call_highest_priority('__radd__')
def __add__(self, other):
return MatrixBase.__add__(self, _force_mutable(other))
@call_highest_priority('__add__')
def __radd__(self, other):
return MatrixBase.__radd__(self, _force_mutable(other))
@call_highest_priority('__rsub__')
def __sub__(self, other):
return MatrixBase.__sub__(self, _force_mutable(other))
@call_highest_priority('__sub__')
def __rsub__(self, other):
return MatrixBase.__rsub__(self, _force_mutable(other))
@call_highest_priority('__rmul__')
def __mul__(self, other):
return MatrixBase.__mul__(self, _force_mutable(other))
@call_highest_priority('__mul__')
def __rmul__(self, other):
return MatrixBase.__rmul__(self, _force_mutable(other))
@call_highest_priority('__div__')
def __div__(self, other):
return MatrixBase.__div__(self, _force_mutable(other))
@call_highest_priority('__truediv__')
def __truediv__(self, other):
return MatrixBase.__truediv__(self, _force_mutable(other))
@call_highest_priority('__rpow__')
def __pow__(self, other):
return MatrixBase.__pow__(self, other)
@call_highest_priority('__pow__')
def __rpow__(self, other):
raise NotImplementedError("Matrix Power not defined")
def _force_mutable(x):
"""Return a matrix as a Matrix, otherwise return x."""
if getattr(x, 'is_Matrix', False):
return x.as_mutable()
elif isinstance(x, Basic):
return x
elif hasattr(x, '__array__'):
a = x.__array__()
if len(a.shape) == 0:
return sympify(a)
return Matrix(x)
return x
class MutableDenseMatrix(DenseMatrix, MatrixBase):
@classmethod
def _new(cls, *args, **kwargs):
rows, cols, flat_list = MatrixBase._handle_creation_inputs(*args, **kwargs)
self = object.__new__(cls)
self.rows = rows
self.cols = cols
self._mat = list(flat_list) # create a shallow copy
return self
def __new__(cls, *args, **kwargs):
return cls._new(*args, **kwargs)
def __setitem__(self, key, value):
"""
>>> from sympy import Matrix, I, zeros, ones
>>> m = Matrix(((1, 2+I), (3, 4)))
>>> m
[1, 2 + I]
[3, 4]
>>> m[1, 0] = 9
>>> m
[1, 2 + I]
[9, 4]
>>> m[1, 0] = [[0, 1]]
To replace row r you assign to position r*m where m
is the number of columns:
>>> M = zeros(4)
>>> m = M.cols
>>> M[3*m] = ones(1, m)*2; M
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]
[2, 2, 2, 2]
And to replace column c you can assign to position c:
>>> M[2] = ones(m, 1)*4; M
[0, 0, 4, 0]
[0, 0, 4, 0]
[0, 0, 4, 0]
[2, 2, 4, 2]
"""
rv = self._setitem(key, value)
if rv is not None:
i, j, value = rv
self._mat[i*self.cols + j] = value
def copyin_matrix(self, key, value):
"""
Copy in values from a matrix into the given bounds.
Parameters
==========
key : slice
The section of this matrix to replace.
value : Matrix
The matrix to copy values from.
Examples
========
>>> from sympy.matrices import Matrix, eye
>>> M = Matrix([[0, 1], [2, 3], [4, 5]])
>>> I = eye(3)
>>> I[:3, :2] = M
>>> I
[0, 1, 0]
[2, 3, 0]
[4, 5, 1]
>>> I[0, 1] = M
>>> I
[0, 0, 1]
[2, 2, 3]
[4, 4, 5]
See Also
========
copyin_list
"""
rlo, rhi, clo, chi = self.key2bounds(key)
shape = value.shape
dr, dc = rhi - rlo, chi - clo
if shape != (dr, dc):
raise ShapeError("The Matrix `value` doesn't have the same dimensions " +
"as the in sub-Matrix given by `key`.")
for i in range(value.rows):
for j in range(value.cols):
self[i + rlo, j + clo] = value[i, j]
def copyin_list(self, key, value):
"""
Copy in elements from a list.
Parameters
==========
key : slice
The section of this matrix to replace.
value : iterable
The iterable to copy values from.
Examples
========
>>> from sympy.matrices import eye
>>> I = eye(3)
>>> I[:2, 0] = [1, 2] # col
>>> I
[1, 0, 0]
[2, 1, 0]
[0, 0, 1]
>>> I[1, :2] = [[3, 4]]
>>> I
[1, 0, 0]
[3, 4, 0]
[0, 0, 1]
See Also
========
copyin_matrix
"""
if not is_sequence(value):
raise TypeError("`value` must be an ordered iterable, not %s." % type(value))
return self.copyin_matrix(key, Matrix(value))
def row_op(self, i, f):
"""In-place operation on row i using two-arg functor whose args are
interpreted as (self[i, j], j).
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M
[1, 0, 0]
[2, 1, 0]
[0, 0, 1]
See Also
========
row
col_op
"""
i0 = i*self.cols
self._mat[i0: i0 + self.cols] = map(lambda t: f(*t),
zip(self._mat[i0: i0 + self.cols], range(self.cols)))
def col_op(self, j, f):
"""In-place operation on col j using two-arg functor whose args are
interpreted as (self[i, j], i).
Examples
========
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M
[1, 2, 0]
[0, 1, 0]
[0, 0, 1]
See Also
========
col
row_op
"""
self._mat[j::self.cols] = map(lambda t: f(*t),
zip(self._mat[j::self.cols], range(self.rows)))
def row_swap(self, i, j):
"""
Swap the two given rows of the matrix in-place.
>>> from sympy.matrices import Matrix
>>> M = Matrix([[0, 1], [1, 0]])
>>> M
[0, 1]
[1, 0]
>>> M.row_swap(0, 1)
>>> M
[1, 0]
[0, 1]
See Also
========
row
col_swap
"""
for k in range(0, self.cols):
self[i, k], self[j, k] = self[j, k], self[i, k]
def col_swap(self, i, j):
"""
Swap the two given columns of the matrix in-place.
>>> from sympy.matrices import Matrix
>>> M = Matrix([[1, 0], [1, 0]])
>>> M
[1, 0]
[1, 0]
>>> M.col_swap(0, 1)
>>> M
[0, 1]
[0, 1]
See Also
========
col
row_swap
"""
for k in range(0, self.rows):
self[k, i], self[k, j] = self[k, j], self[k, i]
def row_del(self, i):
"""
Delete the given row.
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.row_del(1)
>>> M
[1, 0, 0]
[0, 0, 1]
See Also
========
row
col_del
"""
self._mat = self._mat[:i*self.cols] + self._mat[(i+1)*self.cols:]
self.rows -= 1
def col_del(self, i):
"""
Delete the given column.
>>> from sympy.matrices import eye
>>> M = eye(3)
>>> M.col_del(1)
>>> M
[1, 0]
[0, 0]
[0, 1]
See Also
========
col
row_del
"""
for j in range(self.rows - 1, -1, -1):
del self._mat[i + j*self.cols]
self.cols -= 1
# Utility functions
def simplify(self, ratio=1.7, measure=count_ops):
"""Applies simplify to the elements of a matrix in place.
This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))
See Also
========
sympy.simplify.simplify.simplify
"""
for i in range(len(self._mat)):
self._mat[i] = _simplify(self._mat[i], ratio=ratio, measure=measure)
def fill(self, value):
"""Fill the matrix with the scalar value.
See Also
========
zeros
ones
"""
self._mat = [value]*len(self)
MutableMatrix = Matrix = MutableDenseMatrix
###########
# Numpy Utility Functions:
# list2numpy, matrix2numpy, symmarray, rot_axis[123]
###########
def list2numpy(l): # pragma: no cover
"""Converts python list of SymPy expressions to a NumPy array.
See Also
========
matrix2numpy
"""
from numpy import empty
a = empty(len(l), dtype=object)
for i, s in enumerate(l):
a[i] = s
return a
def matrix2numpy(m): # pragma: no cover
"""Converts SymPy's matrix to a NumPy array.
See Also
========
list2numpy
"""
from numpy import empty
a = empty(m.shape, dtype=object)
for i in range(m.rows):
for j in range(m.cols):
a[i, j] = m[i, j]
return a
def symarray(prefix, shape):
"""Create a numpy ndarray of symbols (as an object array).
The created symbols are named ``prefix_i1_i2_``... You should thus provide a
non-empty prefix if you want your symbols to be unique for different output
arrays, as SymPy symbols with identical names are the same object.
Parameters
----------
prefix : string
A prefix prepended to the name of every symbol.
shape : int or tuple
Shape of the created array. If an int, the array is one-dimensional; for
more than one dimension the shape must be a tuple.
Examples
--------
These doctests require numpy.
>>> from sympy import symarray
>>> symarray('', 3) #doctest: +SKIP
[_0, _1, _2]
If you want multiple symarrays to contain distinct symbols, you *must*
provide unique prefixes:
>>> a = symarray('', 3) #doctest: +SKIP
>>> b = symarray('', 3) #doctest: +SKIP
>>> a[0] is b[0] #doctest: +SKIP
True
>>> a = symarray('a', 3) #doctest: +SKIP
>>> b = symarray('b', 3) #doctest: +SKIP
>>> a[0] is b[0] #doctest: +SKIP
False
Creating symarrays with a prefix:
>>> symarray('a', 3) #doctest: +SKIP
[a_0, a_1, a_2]
For more than one dimension, the shape must be given as a tuple:
>>> symarray('a', (2, 3)) #doctest: +SKIP
[[a_0_0, a_0_1, a_0_2],
[a_1_0, a_1_1, a_1_2]]
>>> symarray('a', (2, 3, 2)) #doctest: +SKIP
[[[a_0_0_0, a_0_0_1],
[a_0_1_0, a_0_1_1],
[a_0_2_0, a_0_2_1]],
<BLANKLINE>
[[a_1_0_0, a_1_0_1],
[a_1_1_0, a_1_1_1],
[a_1_2_0, a_1_2_1]]]
"""
try:
import numpy as np
except ImportError:
raise ImportError("symarray requires numpy to be installed")
arr = np.empty(shape, dtype=object)
for index in np.ndindex(shape):
arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))))
return arr
def rot_axis3(theta):
"""Returns a rotation matrix for a rotation of theta (in radians) about
the 3-axis.
Examples
--------
>>> from sympy import pi
>>> from sympy.matrices import rot_axis3
A rotation of pi/3 (60 degrees):
>>> theta = pi/3
>>> rot_axis3(theta)
[ 1/2, sqrt(3)/2, 0]
[-sqrt(3)/2, 1/2, 0]
[ 0, 0, 1]
If we rotate by pi/2 (90 degrees):
>>> rot_axis3(pi/2)
[ 0, 1, 0]
[-1, 0, 0]
[ 0, 0, 1]
See Also
========
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
about the 1-axis
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
about the 2-axis
"""
ct = cos(theta)
st = sin(theta)
lil = ((ct, st, 0),
(-st, ct, 0),
(0, 0, 1))
return Matrix(lil)
def rot_axis2(theta):
"""Returns a rotation matrix for a rotation of theta (in radians) about
the 2-axis.
Examples
--------
>>> from sympy import pi
>>> from sympy.matrices import rot_axis2
A rotation of pi/3 (60 degrees):
>>> theta = pi/3
>>> rot_axis2(theta)
[ 1/2, 0, -sqrt(3)/2]
[ 0, 1, 0]
[sqrt(3)/2, 0, 1/2]
If we rotate by pi/2 (90 degrees):
>>> rot_axis2(pi/2)
[0, 0, -1]
[0, 1, 0]
[1, 0, 0]