Mercurial > hg > vamp-build-and-test
comparison DEPENDENCIES/mingw32/Python27/Lib/site-packages/numpy/matrixlib/defmatrix.py @ 87:2a2c65a20a8b
Add Python libs and headers
author | Chris Cannam |
---|---|
date | Wed, 25 Feb 2015 14:05:22 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
86:413a9d26189e | 87:2a2c65a20a8b |
---|---|
1 from __future__ import division, absolute_import, print_function | |
2 | |
3 __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] | |
4 | |
5 import sys | |
6 import numpy.core.numeric as N | |
7 from numpy.core.numeric import concatenate, isscalar, binary_repr, identity, asanyarray | |
8 from numpy.core.numerictypes import issubdtype | |
9 | |
10 # make translation table | |
11 _numchars = '0123456789.-+jeEL' | |
12 | |
13 if sys.version_info[0] >= 3: | |
14 class _NumCharTable: | |
15 def __getitem__(self, i): | |
16 if chr(i) in _numchars: | |
17 return chr(i) | |
18 else: | |
19 return None | |
20 _table = _NumCharTable() | |
21 def _eval(astr): | |
22 str_ = astr.translate(_table) | |
23 if not str_: | |
24 raise TypeError("Invalid data string supplied: " + astr) | |
25 else: | |
26 return eval(str_) | |
27 | |
28 else: | |
29 _table = [None]*256 | |
30 for k in range(256): | |
31 _table[k] = chr(k) | |
32 _table = ''.join(_table) | |
33 | |
34 _todelete = [] | |
35 for k in _table: | |
36 if k not in _numchars: | |
37 _todelete.append(k) | |
38 _todelete = ''.join(_todelete) | |
39 del k | |
40 | |
41 def _eval(astr): | |
42 str_ = astr.translate(_table, _todelete) | |
43 if not str_: | |
44 raise TypeError("Invalid data string supplied: " + astr) | |
45 else: | |
46 return eval(str_) | |
47 | |
48 def _convert_from_string(data): | |
49 rows = data.split(';') | |
50 newdata = [] | |
51 count = 0 | |
52 for row in rows: | |
53 trow = row.split(',') | |
54 newrow = [] | |
55 for col in trow: | |
56 temp = col.split() | |
57 newrow.extend(map(_eval, temp)) | |
58 if count == 0: | |
59 Ncols = len(newrow) | |
60 elif len(newrow) != Ncols: | |
61 raise ValueError("Rows not the same size.") | |
62 count += 1 | |
63 newdata.append(newrow) | |
64 return newdata | |
65 | |
66 def asmatrix(data, dtype=None): | |
67 """ | |
68 Interpret the input as a matrix. | |
69 | |
70 Unlike `matrix`, `asmatrix` does not make a copy if the input is already | |
71 a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. | |
72 | |
73 Parameters | |
74 ---------- | |
75 data : array_like | |
76 Input data. | |
77 | |
78 Returns | |
79 ------- | |
80 mat : matrix | |
81 `data` interpreted as a matrix. | |
82 | |
83 Examples | |
84 -------- | |
85 >>> x = np.array([[1, 2], [3, 4]]) | |
86 | |
87 >>> m = np.asmatrix(x) | |
88 | |
89 >>> x[0,0] = 5 | |
90 | |
91 >>> m | |
92 matrix([[5, 2], | |
93 [3, 4]]) | |
94 | |
95 """ | |
96 return matrix(data, dtype=dtype, copy=False) | |
97 | |
98 def matrix_power(M, n): | |
99 """ | |
100 Raise a square matrix to the (integer) power `n`. | |
101 | |
102 For positive integers `n`, the power is computed by repeated matrix | |
103 squarings and matrix multiplications. If ``n == 0``, the identity matrix | |
104 of the same shape as M is returned. If ``n < 0``, the inverse | |
105 is computed and then raised to the ``abs(n)``. | |
106 | |
107 Parameters | |
108 ---------- | |
109 M : ndarray or matrix object | |
110 Matrix to be "powered." Must be square, i.e. ``M.shape == (m, m)``, | |
111 with `m` a positive integer. | |
112 n : int | |
113 The exponent can be any integer or long integer, positive, | |
114 negative, or zero. | |
115 | |
116 Returns | |
117 ------- | |
118 M**n : ndarray or matrix object | |
119 The return value is the same shape and type as `M`; | |
120 if the exponent is positive or zero then the type of the | |
121 elements is the same as those of `M`. If the exponent is | |
122 negative the elements are floating-point. | |
123 | |
124 Raises | |
125 ------ | |
126 LinAlgError | |
127 If the matrix is not numerically invertible. | |
128 | |
129 See Also | |
130 -------- | |
131 matrix | |
132 Provides an equivalent function as the exponentiation operator | |
133 (``**``, not ``^``). | |
134 | |
135 Examples | |
136 -------- | |
137 >>> from numpy import linalg as LA | |
138 >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit | |
139 >>> LA.matrix_power(i, 3) # should = -i | |
140 array([[ 0, -1], | |
141 [ 1, 0]]) | |
142 >>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix | |
143 matrix([[ 0, -1], | |
144 [ 1, 0]]) | |
145 >>> LA.matrix_power(i, 0) | |
146 array([[1, 0], | |
147 [0, 1]]) | |
148 >>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements | |
149 array([[ 0., 1.], | |
150 [-1., 0.]]) | |
151 | |
152 Somewhat more sophisticated example | |
153 | |
154 >>> q = np.zeros((4, 4)) | |
155 >>> q[0:2, 0:2] = -i | |
156 >>> q[2:4, 2:4] = i | |
157 >>> q # one of the three quarternion units not equal to 1 | |
158 array([[ 0., -1., 0., 0.], | |
159 [ 1., 0., 0., 0.], | |
160 [ 0., 0., 0., 1.], | |
161 [ 0., 0., -1., 0.]]) | |
162 >>> LA.matrix_power(q, 2) # = -np.eye(4) | |
163 array([[-1., 0., 0., 0.], | |
164 [ 0., -1., 0., 0.], | |
165 [ 0., 0., -1., 0.], | |
166 [ 0., 0., 0., -1.]]) | |
167 | |
168 """ | |
169 M = asanyarray(M) | |
170 if len(M.shape) != 2 or M.shape[0] != M.shape[1]: | |
171 raise ValueError("input must be a square array") | |
172 if not issubdtype(type(n), int): | |
173 raise TypeError("exponent must be an integer") | |
174 | |
175 from numpy.linalg import inv | |
176 | |
177 if n==0: | |
178 M = M.copy() | |
179 M[:] = identity(M.shape[0]) | |
180 return M | |
181 elif n<0: | |
182 M = inv(M) | |
183 n *= -1 | |
184 | |
185 result = M | |
186 if n <= 3: | |
187 for _ in range(n-1): | |
188 result=N.dot(result, M) | |
189 return result | |
190 | |
191 # binary decomposition to reduce the number of Matrix | |
192 # multiplications for n > 3. | |
193 beta = binary_repr(n) | |
194 Z, q, t = M, 0, len(beta) | |
195 while beta[t-q-1] == '0': | |
196 Z = N.dot(Z, Z) | |
197 q += 1 | |
198 result = Z | |
199 for k in range(q+1, t): | |
200 Z = N.dot(Z, Z) | |
201 if beta[t-k-1] == '1': | |
202 result = N.dot(result, Z) | |
203 return result | |
204 | |
205 | |
206 class matrix(N.ndarray): | |
207 """ | |
208 matrix(data, dtype=None, copy=True) | |
209 | |
210 Returns a matrix from an array-like object, or from a string of data. | |
211 A matrix is a specialized 2-D array that retains its 2-D nature | |
212 through operations. It has certain special operators, such as ``*`` | |
213 (matrix multiplication) and ``**`` (matrix power). | |
214 | |
215 Parameters | |
216 ---------- | |
217 data : array_like or string | |
218 If `data` is a string, it is interpreted as a matrix with commas | |
219 or spaces separating columns, and semicolons separating rows. | |
220 dtype : data-type | |
221 Data-type of the output matrix. | |
222 copy : bool | |
223 If `data` is already an `ndarray`, then this flag determines | |
224 whether the data is copied (the default), or whether a view is | |
225 constructed. | |
226 | |
227 See Also | |
228 -------- | |
229 array | |
230 | |
231 Examples | |
232 -------- | |
233 >>> a = np.matrix('1 2; 3 4') | |
234 >>> print a | |
235 [[1 2] | |
236 [3 4]] | |
237 | |
238 >>> np.matrix([[1, 2], [3, 4]]) | |
239 matrix([[1, 2], | |
240 [3, 4]]) | |
241 | |
242 """ | |
243 __array_priority__ = 10.0 | |
244 def __new__(subtype, data, dtype=None, copy=True): | |
245 if isinstance(data, matrix): | |
246 dtype2 = data.dtype | |
247 if (dtype is None): | |
248 dtype = dtype2 | |
249 if (dtype2 == dtype) and (not copy): | |
250 return data | |
251 return data.astype(dtype) | |
252 | |
253 if isinstance(data, N.ndarray): | |
254 if dtype is None: | |
255 intype = data.dtype | |
256 else: | |
257 intype = N.dtype(dtype) | |
258 new = data.view(subtype) | |
259 if intype != data.dtype: | |
260 return new.astype(intype) | |
261 if copy: return new.copy() | |
262 else: return new | |
263 | |
264 if isinstance(data, str): | |
265 data = _convert_from_string(data) | |
266 | |
267 # now convert data to an array | |
268 arr = N.array(data, dtype=dtype, copy=copy) | |
269 ndim = arr.ndim | |
270 shape = arr.shape | |
271 if (ndim > 2): | |
272 raise ValueError("matrix must be 2-dimensional") | |
273 elif ndim == 0: | |
274 shape = (1, 1) | |
275 elif ndim == 1: | |
276 shape = (1, shape[0]) | |
277 | |
278 order = False | |
279 if (ndim == 2) and arr.flags.fortran: | |
280 order = True | |
281 | |
282 if not (order or arr.flags.contiguous): | |
283 arr = arr.copy() | |
284 | |
285 ret = N.ndarray.__new__(subtype, shape, arr.dtype, | |
286 buffer=arr, | |
287 order=order) | |
288 return ret | |
289 | |
290 def __array_finalize__(self, obj): | |
291 self._getitem = False | |
292 if (isinstance(obj, matrix) and obj._getitem): return | |
293 ndim = self.ndim | |
294 if (ndim == 2): | |
295 return | |
296 if (ndim > 2): | |
297 newshape = tuple([x for x in self.shape if x > 1]) | |
298 ndim = len(newshape) | |
299 if ndim == 2: | |
300 self.shape = newshape | |
301 return | |
302 elif (ndim > 2): | |
303 raise ValueError("shape too large to be a matrix.") | |
304 else: | |
305 newshape = self.shape | |
306 if ndim == 0: | |
307 self.shape = (1, 1) | |
308 elif ndim == 1: | |
309 self.shape = (1, newshape[0]) | |
310 return | |
311 | |
312 def __getitem__(self, index): | |
313 self._getitem = True | |
314 | |
315 try: | |
316 out = N.ndarray.__getitem__(self, index) | |
317 finally: | |
318 self._getitem = False | |
319 | |
320 if not isinstance(out, N.ndarray): | |
321 return out | |
322 | |
323 if out.ndim == 0: | |
324 return out[()] | |
325 if out.ndim == 1: | |
326 sh = out.shape[0] | |
327 # Determine when we should have a column array | |
328 try: | |
329 n = len(index) | |
330 except: | |
331 n = 0 | |
332 if n > 1 and isscalar(index[1]): | |
333 out.shape = (sh, 1) | |
334 else: | |
335 out.shape = (1, sh) | |
336 return out | |
337 | |
338 def __mul__(self, other): | |
339 if isinstance(other, (N.ndarray, list, tuple)) : | |
340 # This promotes 1-D vectors to row vectors | |
341 return N.dot(self, asmatrix(other)) | |
342 if isscalar(other) or not hasattr(other, '__rmul__') : | |
343 return N.dot(self, other) | |
344 return NotImplemented | |
345 | |
346 def __rmul__(self, other): | |
347 return N.dot(other, self) | |
348 | |
349 def __imul__(self, other): | |
350 self[:] = self * other | |
351 return self | |
352 | |
353 def __pow__(self, other): | |
354 return matrix_power(self, other) | |
355 | |
356 def __ipow__(self, other): | |
357 self[:] = self ** other | |
358 return self | |
359 | |
360 def __rpow__(self, other): | |
361 return NotImplemented | |
362 | |
363 def __repr__(self): | |
364 s = repr(self.__array__()).replace('array', 'matrix') | |
365 # now, 'matrix' has 6 letters, and 'array' 5, so the columns don't | |
366 # line up anymore. We need to add a space. | |
367 l = s.splitlines() | |
368 for i in range(1, len(l)): | |
369 if l[i]: | |
370 l[i] = ' ' + l[i] | |
371 return '\n'.join(l) | |
372 | |
373 def __str__(self): | |
374 return str(self.__array__()) | |
375 | |
376 def _align(self, axis): | |
377 """A convenience function for operations that need to preserve axis | |
378 orientation. | |
379 """ | |
380 if axis is None: | |
381 return self[0, 0] | |
382 elif axis==0: | |
383 return self | |
384 elif axis==1: | |
385 return self.transpose() | |
386 else: | |
387 raise ValueError("unsupported axis") | |
388 | |
389 def _collapse(self, axis): | |
390 """A convenience function for operations that want to collapse | |
391 to a scalar like _align, but are using keepdims=True | |
392 """ | |
393 if axis is None: | |
394 return self[0, 0] | |
395 else: | |
396 return self | |
397 | |
398 # Necessary because base-class tolist expects dimension | |
399 # reduction by x[0] | |
400 def tolist(self): | |
401 """ | |
402 Return the matrix as a (possibly nested) list. | |
403 | |
404 See `ndarray.tolist` for full documentation. | |
405 | |
406 See Also | |
407 -------- | |
408 ndarray.tolist | |
409 | |
410 Examples | |
411 -------- | |
412 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
413 matrix([[ 0, 1, 2, 3], | |
414 [ 4, 5, 6, 7], | |
415 [ 8, 9, 10, 11]]) | |
416 >>> x.tolist() | |
417 [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] | |
418 | |
419 """ | |
420 return self.__array__().tolist() | |
421 | |
422 # To preserve orientation of result... | |
423 def sum(self, axis=None, dtype=None, out=None): | |
424 """ | |
425 Returns the sum of the matrix elements, along the given axis. | |
426 | |
427 Refer to `numpy.sum` for full documentation. | |
428 | |
429 See Also | |
430 -------- | |
431 numpy.sum | |
432 | |
433 Notes | |
434 ----- | |
435 This is the same as `ndarray.sum`, except that where an `ndarray` would | |
436 be returned, a `matrix` object is returned instead. | |
437 | |
438 Examples | |
439 -------- | |
440 >>> x = np.matrix([[1, 2], [4, 3]]) | |
441 >>> x.sum() | |
442 10 | |
443 >>> x.sum(axis=1) | |
444 matrix([[3], | |
445 [7]]) | |
446 >>> x.sum(axis=1, dtype='float') | |
447 matrix([[ 3.], | |
448 [ 7.]]) | |
449 >>> out = np.zeros((1, 2), dtype='float') | |
450 >>> x.sum(axis=1, dtype='float', out=out) | |
451 matrix([[ 3.], | |
452 [ 7.]]) | |
453 | |
454 """ | |
455 return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis) | |
456 | |
457 def mean(self, axis=None, dtype=None, out=None): | |
458 """ | |
459 Returns the average of the matrix elements along the given axis. | |
460 | |
461 Refer to `numpy.mean` for full documentation. | |
462 | |
463 See Also | |
464 -------- | |
465 numpy.mean | |
466 | |
467 Notes | |
468 ----- | |
469 Same as `ndarray.mean` except that, where that returns an `ndarray`, | |
470 this returns a `matrix` object. | |
471 | |
472 Examples | |
473 -------- | |
474 >>> x = np.matrix(np.arange(12).reshape((3, 4))) | |
475 >>> x | |
476 matrix([[ 0, 1, 2, 3], | |
477 [ 4, 5, 6, 7], | |
478 [ 8, 9, 10, 11]]) | |
479 >>> x.mean() | |
480 5.5 | |
481 >>> x.mean(0) | |
482 matrix([[ 4., 5., 6., 7.]]) | |
483 >>> x.mean(1) | |
484 matrix([[ 1.5], | |
485 [ 5.5], | |
486 [ 9.5]]) | |
487 | |
488 """ | |
489 return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis) | |
490 | |
491 def std(self, axis=None, dtype=None, out=None, ddof=0): | |
492 """ | |
493 Return the standard deviation of the array elements along the given axis. | |
494 | |
495 Refer to `numpy.std` for full documentation. | |
496 | |
497 See Also | |
498 -------- | |
499 numpy.std | |
500 | |
501 Notes | |
502 ----- | |
503 This is the same as `ndarray.std`, except that where an `ndarray` would | |
504 be returned, a `matrix` object is returned instead. | |
505 | |
506 Examples | |
507 -------- | |
508 >>> x = np.matrix(np.arange(12).reshape((3, 4))) | |
509 >>> x | |
510 matrix([[ 0, 1, 2, 3], | |
511 [ 4, 5, 6, 7], | |
512 [ 8, 9, 10, 11]]) | |
513 >>> x.std() | |
514 3.4520525295346629 | |
515 >>> x.std(0) | |
516 matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) | |
517 >>> x.std(1) | |
518 matrix([[ 1.11803399], | |
519 [ 1.11803399], | |
520 [ 1.11803399]]) | |
521 | |
522 """ | |
523 return N.ndarray.std(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) | |
524 | |
525 def var(self, axis=None, dtype=None, out=None, ddof=0): | |
526 """ | |
527 Returns the variance of the matrix elements, along the given axis. | |
528 | |
529 Refer to `numpy.var` for full documentation. | |
530 | |
531 See Also | |
532 -------- | |
533 numpy.var | |
534 | |
535 Notes | |
536 ----- | |
537 This is the same as `ndarray.var`, except that where an `ndarray` would | |
538 be returned, a `matrix` object is returned instead. | |
539 | |
540 Examples | |
541 -------- | |
542 >>> x = np.matrix(np.arange(12).reshape((3, 4))) | |
543 >>> x | |
544 matrix([[ 0, 1, 2, 3], | |
545 [ 4, 5, 6, 7], | |
546 [ 8, 9, 10, 11]]) | |
547 >>> x.var() | |
548 11.916666666666666 | |
549 >>> x.var(0) | |
550 matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) | |
551 >>> x.var(1) | |
552 matrix([[ 1.25], | |
553 [ 1.25], | |
554 [ 1.25]]) | |
555 | |
556 """ | |
557 return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis) | |
558 | |
559 def prod(self, axis=None, dtype=None, out=None): | |
560 """ | |
561 Return the product of the array elements over the given axis. | |
562 | |
563 Refer to `prod` for full documentation. | |
564 | |
565 See Also | |
566 -------- | |
567 prod, ndarray.prod | |
568 | |
569 Notes | |
570 ----- | |
571 Same as `ndarray.prod`, except, where that returns an `ndarray`, this | |
572 returns a `matrix` object instead. | |
573 | |
574 Examples | |
575 -------- | |
576 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
577 matrix([[ 0, 1, 2, 3], | |
578 [ 4, 5, 6, 7], | |
579 [ 8, 9, 10, 11]]) | |
580 >>> x.prod() | |
581 0 | |
582 >>> x.prod(0) | |
583 matrix([[ 0, 45, 120, 231]]) | |
584 >>> x.prod(1) | |
585 matrix([[ 0], | |
586 [ 840], | |
587 [7920]]) | |
588 | |
589 """ | |
590 return N.ndarray.prod(self, axis, dtype, out, keepdims=True)._collapse(axis) | |
591 | |
592 def any(self, axis=None, out=None): | |
593 """ | |
594 Test whether any array element along a given axis evaluates to True. | |
595 | |
596 Refer to `numpy.any` for full documentation. | |
597 | |
598 Parameters | |
599 ---------- | |
600 axis : int, optional | |
601 Axis along which logical OR is performed | |
602 out : ndarray, optional | |
603 Output to existing array instead of creating new one, must have | |
604 same shape as expected output | |
605 | |
606 Returns | |
607 ------- | |
608 any : bool, ndarray | |
609 Returns a single bool if `axis` is ``None``; otherwise, | |
610 returns `ndarray` | |
611 | |
612 """ | |
613 return N.ndarray.any(self, axis, out, keepdims=True)._collapse(axis) | |
614 | |
615 def all(self, axis=None, out=None): | |
616 """ | |
617 Test whether all matrix elements along a given axis evaluate to True. | |
618 | |
619 Parameters | |
620 ---------- | |
621 See `numpy.all` for complete descriptions | |
622 | |
623 See Also | |
624 -------- | |
625 numpy.all | |
626 | |
627 Notes | |
628 ----- | |
629 This is the same as `ndarray.all`, but it returns a `matrix` object. | |
630 | |
631 Examples | |
632 -------- | |
633 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
634 matrix([[ 0, 1, 2, 3], | |
635 [ 4, 5, 6, 7], | |
636 [ 8, 9, 10, 11]]) | |
637 >>> y = x[0]; y | |
638 matrix([[0, 1, 2, 3]]) | |
639 >>> (x == y) | |
640 matrix([[ True, True, True, True], | |
641 [False, False, False, False], | |
642 [False, False, False, False]], dtype=bool) | |
643 >>> (x == y).all() | |
644 False | |
645 >>> (x == y).all(0) | |
646 matrix([[False, False, False, False]], dtype=bool) | |
647 >>> (x == y).all(1) | |
648 matrix([[ True], | |
649 [False], | |
650 [False]], dtype=bool) | |
651 | |
652 """ | |
653 return N.ndarray.all(self, axis, out, keepdims=True)._collapse(axis) | |
654 | |
655 def max(self, axis=None, out=None): | |
656 """ | |
657 Return the maximum value along an axis. | |
658 | |
659 Parameters | |
660 ---------- | |
661 See `amax` for complete descriptions | |
662 | |
663 See Also | |
664 -------- | |
665 amax, ndarray.max | |
666 | |
667 Notes | |
668 ----- | |
669 This is the same as `ndarray.max`, but returns a `matrix` object | |
670 where `ndarray.max` would return an ndarray. | |
671 | |
672 Examples | |
673 -------- | |
674 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
675 matrix([[ 0, 1, 2, 3], | |
676 [ 4, 5, 6, 7], | |
677 [ 8, 9, 10, 11]]) | |
678 >>> x.max() | |
679 11 | |
680 >>> x.max(0) | |
681 matrix([[ 8, 9, 10, 11]]) | |
682 >>> x.max(1) | |
683 matrix([[ 3], | |
684 [ 7], | |
685 [11]]) | |
686 | |
687 """ | |
688 return N.ndarray.max(self, axis, out, keepdims=True)._collapse(axis) | |
689 | |
690 def argmax(self, axis=None, out=None): | |
691 """ | |
692 Indices of the maximum values along an axis. | |
693 | |
694 Parameters | |
695 ---------- | |
696 See `numpy.argmax` for complete descriptions | |
697 | |
698 See Also | |
699 -------- | |
700 numpy.argmax | |
701 | |
702 Notes | |
703 ----- | |
704 This is the same as `ndarray.argmax`, but returns a `matrix` object | |
705 where `ndarray.argmax` would return an `ndarray`. | |
706 | |
707 Examples | |
708 -------- | |
709 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
710 matrix([[ 0, 1, 2, 3], | |
711 [ 4, 5, 6, 7], | |
712 [ 8, 9, 10, 11]]) | |
713 >>> x.argmax() | |
714 11 | |
715 >>> x.argmax(0) | |
716 matrix([[2, 2, 2, 2]]) | |
717 >>> x.argmax(1) | |
718 matrix([[3], | |
719 [3], | |
720 [3]]) | |
721 | |
722 """ | |
723 return N.ndarray.argmax(self, axis, out)._align(axis) | |
724 | |
725 def min(self, axis=None, out=None): | |
726 """ | |
727 Return the minimum value along an axis. | |
728 | |
729 Parameters | |
730 ---------- | |
731 See `amin` for complete descriptions. | |
732 | |
733 See Also | |
734 -------- | |
735 amin, ndarray.min | |
736 | |
737 Notes | |
738 ----- | |
739 This is the same as `ndarray.min`, but returns a `matrix` object | |
740 where `ndarray.min` would return an ndarray. | |
741 | |
742 Examples | |
743 -------- | |
744 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x | |
745 matrix([[ 0, -1, -2, -3], | |
746 [ -4, -5, -6, -7], | |
747 [ -8, -9, -10, -11]]) | |
748 >>> x.min() | |
749 -11 | |
750 >>> x.min(0) | |
751 matrix([[ -8, -9, -10, -11]]) | |
752 >>> x.min(1) | |
753 matrix([[ -3], | |
754 [ -7], | |
755 [-11]]) | |
756 | |
757 """ | |
758 return N.ndarray.min(self, axis, out, keepdims=True)._collapse(axis) | |
759 | |
760 def argmin(self, axis=None, out=None): | |
761 """ | |
762 Return the indices of the minimum values along an axis. | |
763 | |
764 Parameters | |
765 ---------- | |
766 See `numpy.argmin` for complete descriptions. | |
767 | |
768 See Also | |
769 -------- | |
770 numpy.argmin | |
771 | |
772 Notes | |
773 ----- | |
774 This is the same as `ndarray.argmin`, but returns a `matrix` object | |
775 where `ndarray.argmin` would return an `ndarray`. | |
776 | |
777 Examples | |
778 -------- | |
779 >>> x = -np.matrix(np.arange(12).reshape((3,4))); x | |
780 matrix([[ 0, -1, -2, -3], | |
781 [ -4, -5, -6, -7], | |
782 [ -8, -9, -10, -11]]) | |
783 >>> x.argmin() | |
784 11 | |
785 >>> x.argmin(0) | |
786 matrix([[2, 2, 2, 2]]) | |
787 >>> x.argmin(1) | |
788 matrix([[3], | |
789 [3], | |
790 [3]]) | |
791 | |
792 """ | |
793 return N.ndarray.argmin(self, axis, out)._align(axis) | |
794 | |
795 def ptp(self, axis=None, out=None): | |
796 """ | |
797 Peak-to-peak (maximum - minimum) value along the given axis. | |
798 | |
799 Refer to `numpy.ptp` for full documentation. | |
800 | |
801 See Also | |
802 -------- | |
803 numpy.ptp | |
804 | |
805 Notes | |
806 ----- | |
807 Same as `ndarray.ptp`, except, where that would return an `ndarray` object, | |
808 this returns a `matrix` object. | |
809 | |
810 Examples | |
811 -------- | |
812 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
813 matrix([[ 0, 1, 2, 3], | |
814 [ 4, 5, 6, 7], | |
815 [ 8, 9, 10, 11]]) | |
816 >>> x.ptp() | |
817 11 | |
818 >>> x.ptp(0) | |
819 matrix([[8, 8, 8, 8]]) | |
820 >>> x.ptp(1) | |
821 matrix([[3], | |
822 [3], | |
823 [3]]) | |
824 | |
825 """ | |
826 return N.ndarray.ptp(self, axis, out)._align(axis) | |
827 | |
828 def getI(self): | |
829 """ | |
830 Returns the (multiplicative) inverse of invertible `self`. | |
831 | |
832 Parameters | |
833 ---------- | |
834 None | |
835 | |
836 Returns | |
837 ------- | |
838 ret : matrix object | |
839 If `self` is non-singular, `ret` is such that ``ret * self`` == | |
840 ``self * ret`` == ``np.matrix(np.eye(self[0,:].size)`` all return | |
841 ``True``. | |
842 | |
843 Raises | |
844 ------ | |
845 numpy.linalg.LinAlgError: Singular matrix | |
846 If `self` is singular. | |
847 | |
848 See Also | |
849 -------- | |
850 linalg.inv | |
851 | |
852 Examples | |
853 -------- | |
854 >>> m = np.matrix('[1, 2; 3, 4]'); m | |
855 matrix([[1, 2], | |
856 [3, 4]]) | |
857 >>> m.getI() | |
858 matrix([[-2. , 1. ], | |
859 [ 1.5, -0.5]]) | |
860 >>> m.getI() * m | |
861 matrix([[ 1., 0.], | |
862 [ 0., 1.]]) | |
863 | |
864 """ | |
865 M, N = self.shape | |
866 if M == N: | |
867 from numpy.dual import inv as func | |
868 else: | |
869 from numpy.dual import pinv as func | |
870 return asmatrix(func(self)) | |
871 | |
872 def getA(self): | |
873 """ | |
874 Return `self` as an `ndarray` object. | |
875 | |
876 Equivalent to ``np.asarray(self)``. | |
877 | |
878 Parameters | |
879 ---------- | |
880 None | |
881 | |
882 Returns | |
883 ------- | |
884 ret : ndarray | |
885 `self` as an `ndarray` | |
886 | |
887 Examples | |
888 -------- | |
889 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
890 matrix([[ 0, 1, 2, 3], | |
891 [ 4, 5, 6, 7], | |
892 [ 8, 9, 10, 11]]) | |
893 >>> x.getA() | |
894 array([[ 0, 1, 2, 3], | |
895 [ 4, 5, 6, 7], | |
896 [ 8, 9, 10, 11]]) | |
897 | |
898 """ | |
899 return self.__array__() | |
900 | |
901 def getA1(self): | |
902 """ | |
903 Return `self` as a flattened `ndarray`. | |
904 | |
905 Equivalent to ``np.asarray(x).ravel()`` | |
906 | |
907 Parameters | |
908 ---------- | |
909 None | |
910 | |
911 Returns | |
912 ------- | |
913 ret : ndarray | |
914 `self`, 1-D, as an `ndarray` | |
915 | |
916 Examples | |
917 -------- | |
918 >>> x = np.matrix(np.arange(12).reshape((3,4))); x | |
919 matrix([[ 0, 1, 2, 3], | |
920 [ 4, 5, 6, 7], | |
921 [ 8, 9, 10, 11]]) | |
922 >>> x.getA1() | |
923 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) | |
924 | |
925 """ | |
926 return self.__array__().ravel() | |
927 | |
928 def getT(self): | |
929 """ | |
930 Returns the transpose of the matrix. | |
931 | |
932 Does *not* conjugate! For the complex conjugate transpose, use ``.H``. | |
933 | |
934 Parameters | |
935 ---------- | |
936 None | |
937 | |
938 Returns | |
939 ------- | |
940 ret : matrix object | |
941 The (non-conjugated) transpose of the matrix. | |
942 | |
943 See Also | |
944 -------- | |
945 transpose, getH | |
946 | |
947 Examples | |
948 -------- | |
949 >>> m = np.matrix('[1, 2; 3, 4]') | |
950 >>> m | |
951 matrix([[1, 2], | |
952 [3, 4]]) | |
953 >>> m.getT() | |
954 matrix([[1, 3], | |
955 [2, 4]]) | |
956 | |
957 """ | |
958 return self.transpose() | |
959 | |
960 def getH(self): | |
961 """ | |
962 Returns the (complex) conjugate transpose of `self`. | |
963 | |
964 Equivalent to ``np.transpose(self)`` if `self` is real-valued. | |
965 | |
966 Parameters | |
967 ---------- | |
968 None | |
969 | |
970 Returns | |
971 ------- | |
972 ret : matrix object | |
973 complex conjugate transpose of `self` | |
974 | |
975 Examples | |
976 -------- | |
977 >>> x = np.matrix(np.arange(12).reshape((3,4))) | |
978 >>> z = x - 1j*x; z | |
979 matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j], | |
980 [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j], | |
981 [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]]) | |
982 >>> z.getH() | |
983 matrix([[ 0. +0.j, 4. +4.j, 8. +8.j], | |
984 [ 1. +1.j, 5. +5.j, 9. +9.j], | |
985 [ 2. +2.j, 6. +6.j, 10.+10.j], | |
986 [ 3. +3.j, 7. +7.j, 11.+11.j]]) | |
987 | |
988 """ | |
989 if issubclass(self.dtype.type, N.complexfloating): | |
990 return self.transpose().conjugate() | |
991 else: | |
992 return self.transpose() | |
993 | |
994 T = property(getT, None) | |
995 A = property(getA, None) | |
996 A1 = property(getA1, None) | |
997 H = property(getH, None) | |
998 I = property(getI, None) | |
999 | |
1000 def _from_string(str, gdict, ldict): | |
1001 rows = str.split(';') | |
1002 rowtup = [] | |
1003 for row in rows: | |
1004 trow = row.split(',') | |
1005 newrow = [] | |
1006 for x in trow: | |
1007 newrow.extend(x.split()) | |
1008 trow = newrow | |
1009 coltup = [] | |
1010 for col in trow: | |
1011 col = col.strip() | |
1012 try: | |
1013 thismat = ldict[col] | |
1014 except KeyError: | |
1015 try: | |
1016 thismat = gdict[col] | |
1017 except KeyError: | |
1018 raise KeyError("%s not found" % (col,)) | |
1019 | |
1020 coltup.append(thismat) | |
1021 rowtup.append(concatenate(coltup, axis=-1)) | |
1022 return concatenate(rowtup, axis=0) | |
1023 | |
1024 | |
1025 def bmat(obj, ldict=None, gdict=None): | |
1026 """ | |
1027 Build a matrix object from a string, nested sequence, or array. | |
1028 | |
1029 Parameters | |
1030 ---------- | |
1031 obj : str or array_like | |
1032 Input data. Names of variables in the current scope may be | |
1033 referenced, even if `obj` is a string. | |
1034 | |
1035 Returns | |
1036 ------- | |
1037 out : matrix | |
1038 Returns a matrix object, which is a specialized 2-D array. | |
1039 | |
1040 See Also | |
1041 -------- | |
1042 matrix | |
1043 | |
1044 Examples | |
1045 -------- | |
1046 >>> A = np.mat('1 1; 1 1') | |
1047 >>> B = np.mat('2 2; 2 2') | |
1048 >>> C = np.mat('3 4; 5 6') | |
1049 >>> D = np.mat('7 8; 9 0') | |
1050 | |
1051 All the following expressions construct the same block matrix: | |
1052 | |
1053 >>> np.bmat([[A, B], [C, D]]) | |
1054 matrix([[1, 1, 2, 2], | |
1055 [1, 1, 2, 2], | |
1056 [3, 4, 7, 8], | |
1057 [5, 6, 9, 0]]) | |
1058 >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]]) | |
1059 matrix([[1, 1, 2, 2], | |
1060 [1, 1, 2, 2], | |
1061 [3, 4, 7, 8], | |
1062 [5, 6, 9, 0]]) | |
1063 >>> np.bmat('A,B; C,D') | |
1064 matrix([[1, 1, 2, 2], | |
1065 [1, 1, 2, 2], | |
1066 [3, 4, 7, 8], | |
1067 [5, 6, 9, 0]]) | |
1068 | |
1069 """ | |
1070 if isinstance(obj, str): | |
1071 if gdict is None: | |
1072 # get previous frame | |
1073 frame = sys._getframe().f_back | |
1074 glob_dict = frame.f_globals | |
1075 loc_dict = frame.f_locals | |
1076 else: | |
1077 glob_dict = gdict | |
1078 loc_dict = ldict | |
1079 | |
1080 return matrix(_from_string(obj, glob_dict, loc_dict)) | |
1081 | |
1082 if isinstance(obj, (tuple, list)): | |
1083 # [[A,B],[C,D]] | |
1084 arr_rows = [] | |
1085 for row in obj: | |
1086 if isinstance(row, N.ndarray): # not 2-d | |
1087 return matrix(concatenate(obj, axis=-1)) | |
1088 else: | |
1089 arr_rows.append(concatenate(row, axis=-1)) | |
1090 return matrix(concatenate(arr_rows, axis=0)) | |
1091 if isinstance(obj, N.ndarray): | |
1092 return matrix(obj) | |
1093 | |
1094 mat = asmatrix |