annotate DEPENDENCIES/mingw32/Python27/Lib/site-packages/numpy/matrixlib/defmatrix.py @ 133:4acb5d8d80b6 tip

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