def nonzero(array): """Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with: Parameters: a : array_like Input array. Returns: tuple_of_arrays : tuple Indices of elements that are non-zero. >>> x = np.eye(3) >>> x array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> np.nonzero(x) (array([0, 1, 2]), array([0, 1, 2])) >>> x[np.nonzero(x)] array([ 1., 1., 1.]) >>> np.transpose(np.nonzero(x)) array([[0, 0], [1, 1], [2, 2]])""" rowList = IntArrayList() columnList = IntArrayList() coordinateList = DoubleArrayList() array._M.getNonZeros(rowList, columnList, coordinateList) #TODO update array function to deal with Int.... return (array(rowList), array(columnList))
def nonzero(array): """Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with: Parameters: a : array_like Input array. Returns: tuple_of_arrays : tuple Indices of elements that are non-zero. >>> x = np.eye(3) >>> x array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> np.nonzero(x) (array([0, 1, 2]), array([0, 1, 2])) >>> x[np.nonzero(x)] array([ 1., 1., 1.]) >>> np.transpose(np.nonzero(x)) array([[0, 0], [1, 1], [2, 2]])""" rowList = IntArrayList() columnList = IntArrayList() coordinateList = DoubleArrayList() array._M.getNonZeros(rowList, columnList, coordinateList) #TODO update array function to deal with Int.... return(array(rowList), array(columnList))
def vdot(a, b): """Returns the dot product of 2 vectors (or anything that can be made into a vector). NB: this is not the same as `dot`, as it takes the conjugate of its first argument if complex and always returns a scalar.""" try: return _dotblas.vdot(Numeric.ravel(a), Numeric.ravel(b)) # in case we get an integer Value except TypeError: return multiarray.matrixproduct(multiarray.array(a).flat, multiarray.array(b).flat)
def innerproduct(a, b): """returns inner product between a and b. The product-sum is over the last dimension of a and b. NB: No conjugation of complex arguments is performed. This version uses the BLAS optimized routines where possible. """ try: return _dotblas.innerproduct(a, b) except TypeError: try: return multiarray.innerproduct(a, b) except TypeError,detail: if multiarray.array(a).shape == () or multiarray.array(b).shape == (): return a*b else: raise TypeError, detail or "invalid types for innerproduct"
def _index_fields(ary, fields): from multiarray import empty, dtype, array dt = ary.dtype names = [name for name in fields if name in dt.names] formats = [dt.fields[name][0] for name in fields if name in dt.names] offsets = [dt.fields[name][1] for name in fields if name in dt.names] view_dtype = {'names':names, 'formats':formats, 'offsets':offsets, 'itemsize':dt.itemsize} view = ary.view(dtype=view_dtype) # Return a copy for now until behavior is fully deprecated # in favor of returning view copy_dtype = {'names':view_dtype['names'], 'formats':view_dtype['formats']} return array(view, dtype=copy_dtype, copy=True)
def sign(x): """ sign(x[, out]) Returns an element-wise indication of the sign of a number. The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray The sign of `x`. Examples -------- >>> numjy.sign([-5., 4.5]) array([-1., 1.]) >>> numjy.sign(0) 0 """ def sign_int(a_number): if a_number < 0: return(-1) elif a_number == 0: return(0) else: return(1) if hasattr(x, '__iter__' ) or isinstance(x, ndarray): return_value = array([map(sign_int, list(array(x)._M.toArray()))]) else: #In the case the input is just a number return the sign of the number. return_value = sign_int(x) return(return_value)
def sign(x): """ sign(x[, out]) Returns an element-wise indication of the sign of a number. The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Parameters ---------- x : array_like Input values. Returns ------- y : ndarray The sign of `x`. Examples -------- >>> numjy.sign([-5., 4.5]) array([-1., 1.]) >>> numjy.sign(0) 0 """ def sign_int(a_number): if a_number < 0: return (-1) elif a_number == 0: return (0) else: return (1) if hasattr(x, '__iter__') or isinstance(x, ndarray): return_value = array([map(sign_int, list(array(x)._M.toArray()))]) else: #In the case the input is just a number return the sign of the number. return_value = sign_int(x) return (return_value)
def __init__(self, data): if data.dtype.kind == 'm': nat_value = array(['NaT'], dtype=data.dtype)[0] int_dtype = dtype(data.dtype.byteorder + 'i8') int_view = data.view(int_dtype) v = int_view[not_equal(int_view, nat_value.view(int_dtype))] if len(v) > 0: # Max str length of non-NaT elements max_str_len = max(len(str(maximum.reduce(v))), len(str(minimum.reduce(v)))) else: max_str_len = 0 if len(v) < len(data): # data contains a NaT max_str_len = max(max_str_len, 5) self.format = '%' + str(max_str_len) + 'd' self._nat = "'NaT'".rjust(max_str_len)
def _copy_fields(ary): """Return copy of structured array with padding between fields removed. Parameters ---------- ary : ndarray Structured array from which to remove padding bytes Returns ------- ary_copy : ndarray Copy of ary with padding bytes removed """ dt = ary.dtype copy_dtype = { 'names': dt.names, 'formats': [dt.fields[name][0] for name in dt.names] } return array(ary, dtype=copy_dtype, copy=True)
def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=repr, formatter=None): """ Return a string representation of an array. Parameters ---------- a : ndarray Input array. max_line_width : int, optional The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements. precision : int, optional Floating point precision. Default is the current printing precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent very small numbers as zero. A number is "very small" if it is smaller than the current printing precision. separator : str, optional Inserted between elements. prefix : str, optional An array is typically printed as:: 'prefix(' + array2string(a) + ')' The length of the prefix string is used to align the output correctly. style : function, optional A function that accepts an ndarray and returns a string. Used only when the shape of `a` is equal to ``()``, i.e. for 0-D arrays. formatter : dict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:: - 'bool' - 'int' - 'timedelta' : a `numpy.timedelta64` - 'datetime' : a `numpy.datetime64` - 'float' - 'longfloat' : 128-bit floats - 'complexfloat' - 'longcomplexfloat' : composed of two 128-bit floats - 'numpystr' : types `numpy.string_` and `numpy.unicode_` - 'str' : all other strings Other keys that can be used to set a group of types at once are:: - 'all' : sets all types - 'int_kind' : sets 'int' - 'float_kind' : sets 'float' and 'longfloat' - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' - 'str_kind' : sets 'str' and 'numpystr' Returns ------- array_str : str String representation of the array. Raises ------ TypeError if a callable in `formatter` does not return a string. See Also -------- array_str, array_repr, set_printoptions, get_printoptions Notes ----- If a formatter is specified for a certain type, the `precision` keyword is ignored for that type. This is a very flexible function; `array_repr` and `array_str` are using `array2string` internally so keywords with the same name should work identically in all three functions. Examples -------- >>> x = np.array([1e-16,1,2,3]) >>> print(np.array2string(x, precision=2, separator=',', ... suppress_small=True)) [ 0., 1., 2., 3.] >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0L 0x1L 0x2L]' """ if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if formatter is None: formatter = _formatter if a.shape == (): x = a.item() if a.dtype.fields is not None: arr = array([x], dtype=a.dtype) format_function = _get_format_function( arr, precision, suppress_small, formatter) lst = format_function(arr[0]) else: lst = style(x) elif functools.reduce(product, a.shape) == 0: # treat as a null array if any of shape elements == 0 lst = "[]" else: lst = _array2string(a, max_line_width, precision, suppress_small, separator, prefix, formatter=formatter) return lst
"""Numeric module defining a multi-dimensional array and useful procedures for
def sarray(a, typecode=None, copy=0): """sarray(a, typecode=None, copy=0) calls array with savespace=1.""" return multiarray.array(a, typecode, copy, savespace=1)
def asarray(a, typecode=None, savespace=0): """asarray(a,typecode=None) returns a as a NumPy array. Unlike array(), no copy is performed if a is already an array. """ return multiarray.array(a, typecode, copy=0, savespace=savespace)
def asanyarray(a, dtype=None, order=None): """ Convert the input to an ndarray, but pass ndarray subclasses through """ return ma.array(a, dtype, copy=False, order=order, subok=True)
cast = _typedict() try: ScalarType = [ _types.IntType, _types.FloatType, _types.ComplexType, _types.LongType, _types.BooleanType, _types.StringType, _types.UnicodeType, _types.BufferType ] except AttributeError: # Py3K ScalarType = [int, float, complex, int, bool, bytes, str, memoryview] ScalarType.extend(_sctype2char_dict.keys()) ScalarType = tuple(ScalarType) for key in _sctype2char_dict.keys(): cast[key] = lambda x, k=key: array(x, copy=False).astype(k) # Create the typestring lookup dictionary _typestr = _typedict() for key in _sctype2char_dict.keys(): if issubclass(key, allTypes['flexible']): _typestr[key] = _sctype2char_dict[key] else: _typestr[key] = empty((1, ), key).dtype.str[1:] # Make sure all typestrings are in sctypeDict for key, val in _typestr.items(): if val not in sctypeDict: sctypeDict[val] = key # Add additional strings to the sctypeDict
a -= 3 print a a *= a print a a *= 3 print a a /= a print a a /= 3 print a print a.__nonzero__() print where(a) b = array(a) print b c = random.rand(3) print c d = array([1.,2.,0.]) print c.dtype print d.dtype print a[a] print c[a] e = (c > 0.5) print e.dtype print c[(c > 0.5)] print c[d] #print d[a]