def _wrapit(obj, method, *args, **kwds): try: wrap = obj.__array_wrap__ except AttributeError: wrap = None result = getattr(asarray(obj),method)(*args, **kwds) if wrap and isinstance(result, mu.ndarray): if not isinstance(result, mu.ndarray): result = asarray(result) result = wrap(result) return result
def size (a, axis=None): "Get the number of elements in sequence a, or along a certain axis." if axis is None: try: return a.size except AttributeError: return asarray(a).size else: try: return a.shape[axis] except AttributeError: return asarray(a).shape[axis]
def ravel(m,order='C'): """ravel(m) returns a 1d array corresponding to all the elements of it's argument. The new array is a view of m if possible, otherwise it is a copy. """ a = asarray(m) return a.ravel(order)
def shape(a): """Return the shape of a. *Parameters*: a : {array_like} Array whose shape is desired. If a is not an array, a conversion is attempted. *Returns*: tuple_of_integers : The elements of the tuple are the length of the corresponding array dimension. *Examples* >>> shape(eye(3)) (3, 3) >>> shape([[1,2]]) (1, 2) """ try: result = a.shape except AttributeError: result = asarray(a).shape return result
def rank(a): """Get the rank of sequence a (the number of dimensions, not a matrix rank) The rank of a scalar is zero. """ try: return a.ndim except AttributeError: return asarray(a).ndim
def size(a, axis=None): """Return the number of elements along given axis. *Parameters*: a : {array_like} Array whose axis size is desired. If a is not an array, a conversion is attempted. axis : {None, integer}, optional Axis along which the elements are counted. None means all elements in the array. *Returns*: element_count : {integer} Count of elements along specified axis. *See Also*: `shape` : dimensions of array `ndarray.shape` : dimensions of array `ndarray.size` : number of elements in array *Examples* >>> a = array([[1,2,3],[4,5,6]]) >>> size(a) 6 >>> size(a,1) 3 >>> size(a,0) 2 """ if axis is None: try: return a.size except AttributeError: return asarray(a).size else: try: return a.shape[axis] except AttributeError: return asarray(a).shape[axis]
def shape(a): """shape(a) returns the shape of a (as a function call which also works on nested sequences). """ try: result = a.shape except AttributeError: result = asarray(a).shape return result
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """Return the sum along diagonals of the array. If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the collection of elements of the form a[i,i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-d subarray whose trace is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. Arrays of integer type are summed *Parameters*: a : {array_like} Array from whis the diagonals are taken. offset : {0, integer}, optional Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to main diagonal. axis1 : {0, integer}, optional Axis to be used as the first axis of the 2-d subarrays from which the diagonals should be taken. Defaults to first axis. axis2 : {1, integer}, optional Axis to be used as the second axis of the 2-d subarrays from which the diagonals should be taken. Defaults to second axis. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a. out : {None, array}, optional Array into which the sum can be placed. It's type is preserved and it must be of the right shape to hold the output. *Returns*: sum_along_diagonals : array If a is 2-d, a 0-d array containing the diagonal is returned. If a has larger dimensions, then an array of diagonals is returned. *Examples* >>> trace(eye(3)) 3.0 >>> a = arange(8).reshape((2,2,2)) >>> trace(a) array([6, 8]) """ return asarray(a).trace(offset, axis1, axis2, dtype, out)
def rank(a): """Return the number of dimensions of a. In old Numeric, rank was the term used for the number of dimensions. If a is not already an array, a conversion is attempted. Scalars are zero dimensional. *Parameters*: a : {array_like} Array whose number of dimensions is desired. If a is not an array, a conversion is attempted. *Returns*: number_of_dimensions : {integer} Returns the number of dimensions. *See Also*: `ndim` : equivalent function `ndarray.ndim` : equivalent method `shape` : dimensions of array `ndarray.shape` : dimensions of array *Examples* >>> rank([[1,2,3],[4,5,6]]) 2 >>> rank(array([[1,2,3],[4,5,6]])) 2 >>> rank(1) 0 """ try: return a.ndim except AttributeError: return asarray(a).ndim
def ravel(a, order='C'): """Return a 1d array containing the elements of a. Returns the elements of a as a 1d array. The elements in the new array are taken in the order specified by the order keyword. The new array is a view of a if possible, otherwise it is a copy. *Parameters*: a : {array_like} order : {'C','F'}, optional If order is 'C' the elements are taken in row major order. If order is 'F' they are taken in column major order. *Returns*: 1d_array : {array} *See Also*: `ndarray.flat` : 1d iterator over the array. `ndarray.flatten` : 1d array copy of the elements of a in C order. *Examples* >>> x = array([[1,2,3],[4,5,6]]) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> ravel(x) array([1, 2, 3, 4, 5, 6]) """ return asarray(a).ravel(order)
def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a record array from a (flat) list of arrays >>> x1=np.array([1,2,3,4]) >>> x2=np.array(['a','dd','xyz','12']) >>> x3=np.array([1.1,2,3,4]) >>> r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c') >>> print r[1] (2, 'dd', 2.0) >>> x1[1]=34 >>> r.a array([1, 2, 3, 4]) """ arrayList = [sb.asarray(x) for x in arrayList] if shape is None or shape == 0: shape = arrayList[0].shape if isinstance(shape, int): shape = (shape,) if formats is None and dtype is None: # go through each object in the list to see if it is an ndarray # and determine the formats. formats = '' for obj in arrayList: if not isinstance(obj, ndarray): raise ValueError, "item in the array list must be an ndarray." formats += _typestr[obj.dtype.type] if issubclass(obj.dtype.type, nt.flexible): formats += `obj.itemsize` formats += ',' formats = formats[:-1] if dtype is not None: descr = sb.dtype(dtype) _names = descr.names else: parsed = format_parser(formats, names, titles, aligned, byteorder) _names = parsed._names descr = parsed._descr # Determine shape from data-type. if len(descr) != len(arrayList): raise ValueError, "mismatch between the number of fields "\ "and the number of arrays" d0 = descr[0].shape nn = len(d0) if nn > 0: shape = shape[:-nn] for k, obj in enumerate(arrayList): nn = len(descr[k].shape) testshape = obj.shape[:len(obj.shape) - nn] if testshape != shape: raise ValueError, "array-shape mismatch in array %d" % k _array = recarray(shape, descr) # populate the record array (makes a copy) for i in range(len(arrayList)): _array[_names[i]] = arrayList[i] return _array
def atleast_3d(*arys): """ View inputs as arrays with at least three dimensions. Parameters ---------- array1, array2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape ``N`` becomes a view of shape ``(1, N, 1)``. A 2-D array of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> np.atleast_3d(3.0) array([[[ 3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape (1, 3, 1) >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape (4, 3, 1) >>> np.atleast_3d(x).base is x True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print arr, arr.shape ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2) """ res = [] for ary in arys: ary = asarray(ary) if len(ary.shape) == 0: result = ary.reshape(1,1,1) elif len(ary.shape) == 1: result = ary[newaxis,:,newaxis] elif len(ary.shape) == 2: result = ary[:,:,newaxis] else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res
def ndim(a): try: return a.ndim except AttributeError: return asarray(a).ndim
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array. """ return asarray(a).trace(offset, axis1, axis2, dtype, out)
def diagonal(a, offset=0, axis1=0, axis2=1): """Return specified diagonals. Uses first two indices by default. *Description* If a is 2-d, returns the diagonal of self with the given offset, i.e., the collection of elements of the form a[i,i+offset]. If a is n-d with n > 2, then the axes specified by axis1 and axis2 are used to determine the 2-d subarray whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. *Parameters*: offset : integer Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to main diagonal. axis1 : integer Axis to be used as the first axis of the 2-d subarrays from which the diagonals should be taken. Defaults to first axis. axis2 : integer Axis to be used as the second axis of the 2-d subarrays from which the diagonals should be taken. Defaults to second axis. *Returns*: array_of_diagonals : type of original array If a is 2-d, then a 1-d array containing the diagonal is returned. If a is n-d, n > 2, then an array of diagonals is returned. *SeeAlso*: diag : matlab workalike for 1-d and 2-d arrays diagflat : creates diagonal arrays trace : sum along diagonals *Examples*: >>> a = arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> a.diagonal() array([0, 3]) >>> a.diagonal(1) array([1]) >>> a = arange(8).reshape(2,2,2) >>> a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> a.diagonal(0,-2,-1) array([[0, 3], [4, 7]]) """ return asarray(a).diagonal(offset, axis1, axis2)
def diagonal(a, offset=0, axis1=0, axis2=1): """Return specified diagonals. If a is 2-d, returns the diagonal of self with the given offset, i.e., the collection of elements of the form a[i,i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-d subarray whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. *Parameters*: a : {array_like} Array from whis the diagonals are taken. offset : {0, integer}, optional Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to main diagonal. axis1 : {0, integer}, optional Axis to be used as the first axis of the 2-d subarrays from which the diagonals should be taken. Defaults to first axis. axis2 : {1, integer}, optional Axis to be used as the second axis of the 2-d subarrays from which the diagonals should be taken. Defaults to second axis. *Returns*: array_of_diagonals : array of same type as a If a is 2-d, a 1-d array containing the diagonal is returned. If a has larger dimensions, then an array of diagonals is returned. *See Also*: `diag` : Matlab workalike for 1-d and 2-d arrays. `diagflat` : Create diagonal arrays. `trace` : Sum along diagonals. *Examples* >>> a = arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> a.diagonal() array([0, 3]) >>> a.diagonal(1) array([1]) >>> a = arange(8).reshape(2,2,2) >>> a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> a.diagonal(0,-2,-1) array([[0, 3], [4, 7]]) """ return asarray(a).diagonal(offset, axis1, axis2)