我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用builtins.any()。
def updatelocals(self, **vardict): '''Update variables in the local scope. This is a shortcut function to inject variables in the local scope without extensive checks (as in define()). Vardict must not contain any entries which have been made global via addglobal() before. In order to ensure this, updatelocals() should be called immediately after openscope(), or with variable names, which are warrantedly not globals (e.g variables starting with forbidden prefix) Args: **vardict: variable defintions. ''' self._scope.update(vardict) if self._locals is not None: self._locals.update(vardict)
def __iadd__(self, other): """ Add other to self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m else: if m is not nomask: self._mask += m self._data.__iadd__(np.where(self._mask, self.dtype.type(0), getdata(other))) return self
def __ifloordiv__(self, other): """ Floor divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where(dom_mask, fval, other_data) self._mask |= new_mask self._data.__ifloordiv__(np.where(self._mask, self.dtype.type(1), other_data)) return self
def __itruediv__(self, other): """ True divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.true_divide] other_data = np.where(dom_mask, fval, other_data) self._mask |= new_mask self._data.__itruediv__(np.where(self._mask, self.dtype.type(1), other_data)) return self
def __ipow__(self, other): """ Raise self to the power other, in place. """ other_data = getdata(other) other_mask = getmask(other) with np.errstate(divide='ignore', invalid='ignore'): self._data.__ipow__(np.where(self._mask, self.dtype.type(1), other_data)) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): if self._mask is not nomask: self._mask |= invalid else: self._mask = invalid np.copyto(self._data, self.fill_value, where=invalid) new_mask = mask_or(other_mask, invalid) self._mask = mask_or(self._mask, new_mask) return self
def __idiv__(self, other): """ Divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.divide] other_data = np.where(dom_mask, fval, other_data) self._mask |= new_mask self._data.__idiv__(np.where(self._mask, self.dtype.type(1), other_data)) return self
def count(iterable): """Return the element count of ``iterable``. This is similar to the built-in :func:`len() <python:len>`, except that it can also handle any argument that supports iteration, including generators. """ try: return builtins.len(iterable) except TypeError: # Try to determine length by iterating over the iterable ret = 0 for ret, _ in builtins.enumerate(iterable, start=1): pass return ret
def updateglobals(self, **vardict): '''Update variables in the global scope. This is a shortcut function to inject protected variables in the global scope without extensive checks (as in define()). Vardict must not contain any global entries which can be shadowed in local scopes (e.g. should only contain variables with forbidden prefix). Args: **vardict: variable defintions. ''' self._scope.update(vardict) if self._locals is not None: self._globals.update(vardict)
def __call__(self, line): '''Returns the entire line without any folding. Returns: list of str: Components of folded line. They should be assembled via ``\\n.join()`` to obtain the string representation. ''' return [line]
def any(iterable): """ Returns True if any element of the iterable is true. """ for element in iterable: if element: return True return False
def get_fill_value(a): """ Return the filling value of a, if any. Otherwise, returns the default filling value for that type. """ if isinstance(a, MaskedArray): result = a.fill_value else: result = default_fill_value(a) return result
def common_fill_value(a, b): """ Return the common filling value of two masked arrays, if any. If ``a.fill_value == b.fill_value``, return the fill value, otherwise return None. Parameters ---------- a, b : MaskedArray The masked arrays for which to compare fill values. Returns ------- fill_value : scalar or None The common fill value, or None. Examples -------- >>> x = np.ma.array([0, 1.], fill_value=3) >>> y = np.ma.array([0, 1.], fill_value=3) >>> np.ma.common_fill_value(x, y) 3.0 """ t1 = get_fill_value(a) t2 = get_fill_value(b) if t1 == t2: return t1 return None
def __call__(self, a, b, *args, **kwargs): "Execute the call behavior." # Get the data (da, db) = (getdata(a), getdata(b)) # Get the result with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) # Get the mask as a combination of the source masks and invalid m = ~umath.isfinite(result) m |= getmask(a) m |= getmask(b) # Apply the domain domain = ufunc_domain.get(self.f, None) if domain is not None: m |= filled(domain(da, db), True) # Take care of the scalar case first if (not m.ndim): if m: return masked else: return result # When the mask is True, put back da if possible # any errors, just abort; impossible to guarantee masked values try: np.copyto(result, 0, casting='unsafe', where=m) # avoid using "*" since this may be overlaid masked_da = umath.multiply(m, da) # only add back if it can be cast safely if np.can_cast(masked_da.dtype, result.dtype, casting='safe'): result += masked_da except: pass # Transforms to a (subclass of) MaskedArray masked_result = result.view(get_masked_subclass(a, b)) masked_result._mask = m if isinstance(a, MaskedArray): masked_result._update_from(a) elif isinstance(b, MaskedArray): masked_result._update_from(b) return masked_result
def shrink_mask(self): """ Reduce a mask to nomask when possible. Parameters ---------- None Returns ------- None Examples -------- >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) >>> x.mask array([[False, False], [False, False]], dtype=bool) >>> x.shrink_mask() >>> x.mask False """ m = self._mask if m.ndim and not m.any(): self._mask = nomask return self
def __isub__(self, other): """ Subtract other from self in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m self._data.__isub__(np.where(self._mask, self.dtype.type(0), getdata(other))) return self
def __imul__(self, other): """ Multiply self by other in-place. """ m = getmask(other) if self._mask is nomask: if m is not nomask and m.any(): self._mask = make_mask_none(self.shape, self.dtype) self._mask += m elif m is not nomask: self._mask += m self._data.__imul__(np.where(self._mask, self.dtype.type(1), getdata(other))) return self
def any(self, axis=None, out=None, keepdims=np._NoValue): """ Returns True if any of the elements of `a` evaluate to True. Masked values are considered as False during computation. Refer to `numpy.any` for full documentation. See Also -------- ndarray.any : corresponding function for ndarrays numpy.any : equivalent function """ kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims} mask = _check_mask_axis(self._mask, axis, **kwargs) if out is None: d = self.filled(False).any(axis=axis, **kwargs).view(type(self)) if d.ndim: d.__setmask__(mask) elif mask: d = masked return d self.filled(False).any(axis=axis, out=out, **kwargs) if isinstance(out, MaskedArray): if out.ndim or mask: out.__setmask__(mask) return out
def append(a, b, axis=None): """Append values to the end of an array. .. versionadded:: 1.9.0 Parameters ---------- a : array_like Values are appended to a copy of this array. b : array_like These values are appended to a copy of `a`. It must be of the correct shape (the same shape as `a`, excluding `axis`). If `axis` is not specified, `b` can be any shape and will be flattened before use. axis : int, optional The axis along which `v` are appended. If `axis` is not given, both `a` and `b` are flattened before use. Returns ------- append : MaskedArray A copy of `a` with `b` appended to `axis`. Note that `append` does not occur in-place: a new array is allocated and filled. If `axis` is None, the result is a flattened array. See Also -------- numpy.append : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_values([1, 2, 3], 2) >>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7) >>> print(ma.append(a, b)) [1 -- 3 4 5 6 -- 8 9] """ return concatenate([a, b], axis)
def _median(a, axis=None, out=None, overwrite_input=False): # can't be reasonably be implemented in terms of percentile as we have to # call mean to not break astropy a = np.asanyarray(a) # Set the partition indexes if axis is None: sz = a.size else: sz = a.shape[axis] if sz % 2 == 0: szh = sz // 2 kth = [szh - 1, szh] else: kth = [(sz - 1) // 2] # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact): kth.append(-1) if overwrite_input: if axis is None: part = a.ravel() part.partition(kth) else: a.partition(kth, axis=axis) part = a else: part = partition(a, kth, axis=axis) if part.shape == (): # make 0-D arrays work return part.item() if axis is None: axis = 0 indexer = [slice(None)] * part.ndim index = part.shape[axis] // 2 if part.shape[axis] % 2 == 1: # index with slice to allow mean (below) to work indexer[axis] = slice(index, index+1) else: indexer[axis] = slice(index-1, index+1) # Check if the array contains any nan's if np.issubdtype(a.dtype, np.inexact) and sz > 0: # warn and return nans like mean would rout = mean(part[indexer], axis=axis, out=out) return np.lib.utils._median_nancheck(part, rout, axis, out) else: # if there are no nans # Use mean in odd and even case to coerce data type # and check, use out array. return mean(part[indexer], axis=axis, out=out)
def __call__(self, a, b, *args, **kwargs): "Execute the call behavior." # Get the data (da, db) = (getdata(a), getdata(b)) # Get the result with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) # Get the mask as a combination of the source masks and invalid m = ~umath.isfinite(result) m |= getmask(a) m |= getmask(b) # Apply the domain domain = ufunc_domain.get(self.f, None) if domain is not None: m |= domain(da, db) # Take care of the scalar case first if (not m.ndim): if m: return masked else: return result # When the mask is True, put back da if possible # any errors, just abort; impossible to guarantee masked values try: np.copyto(result, 0, casting='unsafe', where=m) # avoid using "*" since this may be overlaid masked_da = umath.multiply(m, da) # only add back if it can be cast safely if np.can_cast(masked_da.dtype, result.dtype, casting='safe'): result += masked_da except: pass # Transforms to a (subclass of) MaskedArray masked_result = result.view(get_masked_subclass(a, b)) masked_result._mask = m if isinstance(a, MaskedArray): masked_result._update_from(a) elif isinstance(b, MaskedArray): masked_result._update_from(b) return masked_result
def correlate(a, v, mode='valid', propagate_mask=True): """ Cross-correlation of two 1-dimensional sequences. Parameters ---------- a, v : array_like Input sequences. mode : {'valid', 'same', 'full'}, optional Refer to the `np.convolve` docstring. Note that the default is 'valid', unlike `convolve`, which uses 'full'. propagate_mask : bool If True, then a result element is masked if any masked element contributes towards it. If False, then a result element is only masked if no non-masked element contribute towards it Returns ------- out : MaskedArray Discrete cross-correlation of `a` and `v`. See Also -------- numpy.correlate : Equivalent function in the top-level NumPy module. """ return _convolve_or_correlate(np.correlate, a, v, mode, propagate_mask)
def convolve(a, v, mode='full', propagate_mask=True): """ Returns the discrete, linear convolution of two one-dimensional sequences. Parameters ---------- a, v : array_like Input sequences. mode : {'valid', 'same', 'full'}, optional Refer to the `np.convolve` docstring. propagate_mask : bool If True, then if any masked element is included in the sum for a result element, then the result is masked. If False, then the result element is only masked if no non-masked cells contribute towards it Returns ------- out : MaskedArray Discrete, linear convolution of `a` and `v`. See Also -------- numpy.convolve : Equivalent function in the top-level NumPy module. """ return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask)
def any(iterable): """Replacement for the built-in :func:`any() <python:any>` function.""" return builtins.any(iterable)
def or_(a, b): """Deferrable version of the :keyword:`or` operator. :returns: ``a or b``.""" return builtins.any([a, b])
def extractsingle(patt, filename, tag=0, conv=None, item=0, encoding='utf-8'): """Extract a single value from the capturing group ``tag`` of a matching regex ``patt`` in the file ``filename``. This function is equivalent to ``extractall(patt, filename, tag, conv)[item]``, except that it raises a ``SanityError`` if ``item`` is out of bounds. :arg patt: as in :func:`extractall`. :arg filename: as in :func:`extractall`. :arg encoding: as in :func:`extractall`. :arg tag: as in :func:`extractall`. :arg conv: as in :func:`extractall`. :arg item: the specific element to extract. :returns: The extracted value. :raises reframe.core.exceptions.SanityError: In case of errors. """ try: # Explicitly evaluate the expression here, so as to force any exception # to be thrown in this context and not during the evaluation of an # expression containing this one. return evaluate(extractall(patt, filename, tag, conv, encoding)[item]) except IndexError: raise SanityError("not enough matches of pattern `%s' in file `%s' " "so as to extract item `%s'" % (patt, filename, item)) # Numeric functions
def getitem(container, item): """Get ``item`` from ``container``. ``container`` may refer to any container that can be indexed. :raises reframe.core.exceptions.SanityError: In case ``item`` cannot be retrieved from ``container``. """ try: return container[item] except KeyError: raise SanityError('key not found: %s' % item) except IndexError: raise SanityError('index out of bounds: %s' % item)
def getdata(a, subok=True): """ Return the data of a masked array as an ndarray. Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``, else return `a` as a ndarray or subclass (depending on `subok`) if not. Parameters ---------- a : array_like Input ``MaskedArray``, alternatively a ndarray or a subclass thereof. subok : bool Whether to force the output to be a `pure` ndarray (False) or to return a subclass of ndarray if appropriate (True, default). See Also -------- getmask : Return the mask of a masked array, or nomask. getmaskarray : Return the mask of a masked array, or full array of False. Examples -------- >>> import numpy.ma as ma >>> a = ma.masked_equal([[1,2],[3,4]], 2) >>> a masked_array(data = [[1 --] [3 4]], mask = [[False True] [False False]], fill_value=999999) >>> ma.getdata(a) array([[1, 2], [3, 4]]) Equivalently use the ``MaskedArray`` `data` attribute. >>> a.data array([[1, 2], [3, 4]]) """ try: data = a._data except AttributeError: data = np.array(a, copy=False, subok=subok) if not subok: return data.view(ndarray) return data
def __call__(self, a, b, *args, **kwargs): """ Execute the call behavior. """ # Get the data, as ndarray (da, db) = (getdata(a), getdata(b)) # Get the result with np.errstate(): np.seterr(divide='ignore', invalid='ignore') result = self.f(da, db, *args, **kwargs) # Get the mask for the result (ma, mb) = (getmask(a), getmask(b)) if ma is nomask: if mb is nomask: m = nomask else: m = umath.logical_or(getmaskarray(a), mb) elif mb is nomask: m = umath.logical_or(ma, getmaskarray(b)) else: m = umath.logical_or(ma, mb) # Case 1. : scalar if not result.ndim: if m: return masked return result # Case 2. : array # Revert result to da where masked if m is not nomask and m.any(): # any errors, just abort; impossible to guarantee masked values try: np.copyto(result, 0, casting='unsafe', where=m) # avoid using "*" since this may be overlaid masked_da = umath.multiply(m, da) # only add back if it can be cast safely if np.can_cast(masked_da.dtype, result.dtype, casting='safe'): result += masked_da except: pass # Transforms to a (subclass of) MaskedArray masked_result = result.view(get_masked_subclass(a, b)) masked_result._mask = m if isinstance(a, MaskedArray): masked_result._update_from(a) elif isinstance(b, MaskedArray): masked_result._update_from(b) return masked_result
def __str__(self): """ String representation. """ if masked_print_option.enabled(): f = masked_print_option if self is masked: return str(f) m = self._mask if m is nomask: res = self._data else: if m.shape == () and m.itemsize==len(m.dtype): if m.dtype.names: m = m.view((bool, len(m.dtype))) if m.any(): return str(tuple((f if _m else _d) for _d, _m in zip(self._data.tolist(), m))) else: return str(self._data) elif m: return str(f) else: return str(self._data) # convert to object array to make filled work names = self.dtype.names if names is None: data = self._data mask = m # For big arrays, to avoid a costly conversion to the # object dtype, extract the corners before the conversion. print_width = (self._print_width if self.ndim > 1 else self._print_width_1d) for axis in range(self.ndim): if data.shape[axis] > print_width: ind = print_width // 2 arr = np.split(data, (ind, -ind), axis=axis) data = np.concatenate((arr[0], arr[2]), axis=axis) arr = np.split(mask, (ind, -ind), axis=axis) mask = np.concatenate((arr[0], arr[2]), axis=axis) res = data.astype("O") res.view(ndarray)[mask] = f else: rdtype = _recursive_make_descr(self.dtype, "O") res = self._data.astype(rdtype) _recursive_printoption(res, m, f) else: res = self.filled(self.fill_value) return str(res)
def is_masked(x): """ Determine whether input has masked values. Accepts any object as input, but always returns False unless the input is a MaskedArray containing masked values. Parameters ---------- x : array_like Array to check for masked values. Returns ------- result : bool True if `x` is a MaskedArray with masked values, False otherwise. Examples -------- >>> import numpy.ma as ma >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0) >>> x masked_array(data = [-- 1 -- 2 3], mask = [ True False True False False], fill_value=999999) >>> ma.is_masked(x) True >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42) >>> x masked_array(data = [0 1 0 2 3], mask = False, fill_value=999999) >>> ma.is_masked(x) False Always returns False if `x` isn't a MaskedArray. >>> x = [False, True, False] >>> ma.is_masked(x) False >>> x = 'a string' >>> ma.is_masked(x) False """ m = getmask(x) if m is nomask: return False elif m.any(): return True return False ############################################################################## # Extrema functions # ##############################################################################
def concatenate(arrays, axis=0): """ Concatenate a sequence of arrays along the given axis. Parameters ---------- arrays : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- result : MaskedArray The concatenated array with any masked entries preserved. See Also -------- numpy.concatenate : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(3) >>> a[1] = ma.masked >>> b = ma.arange(2, 5) >>> a masked_array(data = [0 -- 2], mask = [False True False], fill_value = 999999) >>> b masked_array(data = [2 3 4], mask = False, fill_value = 999999) >>> ma.concatenate([a, b]) masked_array(data = [0 -- 2 2 3 4], mask = [False True False False False False], fill_value = 999999) """ d = np.concatenate([getdata(a) for a in arrays], axis) rcls = get_masked_subclass(*arrays) data = d.view(rcls) # Check whether one of the arrays has a non-empty mask. for x in arrays: if getmask(x) is not nomask: break else: return data # OK, so we have to concatenate the masks dm = np.concatenate([getmaskarray(a) for a in arrays], axis) # If we decide to keep a '_shrinkmask' option, we want to check that # all of them are True, and then check for dm.any() if not dm.dtype.fields and not dm.any(): data._mask = nomask else: data._mask = dm.reshape(d.shape) return data
def allequal(a, b, fill_value=True): """ Return True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked. Parameters ---------- a, b : array_like Input arrays to compare. fill_value : bool, optional Whether masked values in a or b are considered equal (True) or not (False). Returns ------- y : bool Returns True if the two arrays are equal within the given tolerance, False otherwise. If either array contains NaN, then False is returned. See Also -------- all, any numpy.ma.allclose Examples -------- >>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1]) >>> a masked_array(data = [10000000000.0 1e-07 --], mask = [False False True], fill_value=1e+20) >>> b = array([1e10, 1e-7, -42.0]) >>> b array([ 1.00000000e+10, 1.00000000e-07, -4.20000000e+01]) >>> ma.allequal(a, b, fill_value=False) False >>> ma.allequal(a, b) True """ m = mask_or(getmask(a), getmask(b)) if m is nomask: x = getdata(a) y = getdata(b) d = umath.equal(x, y) return d.all() elif fill_value: x = getdata(a) y = getdata(b) d = umath.equal(x, y) dm = array(d, mask=m, copy=False) return dm.filled(True).all(None) else: return False
def asarray(a, dtype=None, order=None): """ Convert the input to a masked array of the given data-type. No copy is performed if the input is already an `ndarray`. If `a` is a subclass of `MaskedArray`, a base class `MaskedArray` is returned. Parameters ---------- a : array_like Input data, in any form that can be converted to a masked array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray Masked array interpretation of `a`. See Also -------- asanyarray : Similar to `asarray`, but conserves subclasses. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.]]) >>> np.ma.asarray(x) masked_array(data = [[ 0. 1. 2. 3. 4.] [ 5. 6. 7. 8. 9.]], mask = False, fill_value = 1e+20) >>> type(np.ma.asarray(x)) <class 'numpy.ma.core.MaskedArray'> """ order = order or 'C' return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False, order=order)
def asanyarray(a, dtype=None): """ Convert the input to a masked array, conserving subclasses. If `a` is a subclass of `MaskedArray`, its class is conserved. No copy is performed if the input is already an `ndarray`. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. dtype : dtype, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major ('C') or column-major ('FORTRAN') memory representation. Default is 'C'. Returns ------- out : MaskedArray MaskedArray interpretation of `a`. See Also -------- asarray : Similar to `asanyarray`, but does not conserve subclass. Examples -------- >>> x = np.arange(10.).reshape(2, 5) >>> x array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.]]) >>> np.ma.asanyarray(x) masked_array(data = [[ 0. 1. 2. 3. 4.] [ 5. 6. 7. 8. 9.]], mask = False, fill_value = 1e+20) >>> type(np.ma.asanyarray(x)) <class 'numpy.ma.core.MaskedArray'> """ return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True) ############################################################################## # Pickling # ##############################################################################
def _get_ufunc_and_otypes(self, func, args): """Return (ufunc, otypes).""" # frompyfunc will fail if args is empty if not args: raise ValueError('args can not be empty') if self.otypes is not None: otypes = self.otypes nout = len(otypes) # Note logic here: We only *use* self._ufunc if func is self.pyfunc # even though we set self._ufunc regardless. if func is self.pyfunc and self._ufunc is not None: ufunc = self._ufunc else: ufunc = self._ufunc = frompyfunc(func, len(args), nout) else: # Get number of outputs and output types by calling the function on # the first entries of args. We also cache the result to prevent # the subsequent call when the ufunc is evaluated. # Assumes that ufunc first evaluates the 0th elements in the input # arrays (the input values are not checked to ensure this) args = [asarray(arg) for arg in args] if builtins.any(arg.size == 0 for arg in args): raise ValueError('cannot call `vectorize` on size 0 inputs ' 'unless `otypes` is set') inputs = [arg.flat[0] for arg in args] outputs = func(*inputs) # Performance note: profiling indicates that -- for simple # functions at least -- this wrapping can almost double the # execution time. # Hence we make it optional. if self.cache: _cache = [outputs] def _func(*vargs): if _cache: return _cache.pop() else: return func(*vargs) else: _func = func if isinstance(outputs, tuple): nout = len(outputs) else: nout = 1 outputs = (outputs,) otypes = ''.join([asarray(outputs[_k]).dtype.char for _k in range(nout)]) # Performance note: profiling indicates that creating the ufunc is # not a significant cost compared with wrapping so it seems not # worth trying to cache this. ufunc = frompyfunc(_func, len(args), nout) return ufunc, otypes
def append(arr, values, axis=None): """ Append values to the end of an array. Parameters ---------- arr : array_like Values are appended to a copy of this array. values : array_like These values are appended to a copy of `arr`. It must be of the correct shape (the same shape as `arr`, excluding `axis`). If `axis` is not specified, `values` can be any shape and will be flattened before use. axis : int, optional The axis along which `values` are appended. If `axis` is not given, both `arr` and `values` are flattened before use. Returns ------- append : ndarray A copy of `arr` with `values` appended to `axis`. Note that `append` does not occur in-place: a new array is allocated and filled. If `axis` is None, `out` is a flattened array. See Also -------- insert : Insert elements into an array. delete : Delete elements from an array. Examples -------- >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) When `axis` is specified, `values` must have the correct shape. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... ValueError: arrays must have same number of dimensions """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis)
def __call__(self, a, b, *args, **kwargs): """ Execute the call behavior. """ # Get the data, as ndarray (da, db) = (getdata(a), getdata(b)) # Get the result with np.errstate(): np.seterr(divide='ignore', invalid='ignore') result = self.f(da, db, *args, **kwargs) # Get the mask for the result (ma, mb) = (getmask(a), getmask(b)) if ma is nomask: if mb is nomask: m = nomask else: m = umath.logical_or(getmaskarray(a), mb) elif mb is nomask: m = umath.logical_or(ma, getmaskarray(b)) else: m = umath.logical_or(ma, mb) # Case 1. : scalar if not result.ndim: if m: return masked return result # Case 2. : array # Revert result to da where masked if m is not nomask and m.any(): # any errors, just abort; impossible to guarantee masked values try: np.copyto(result, da, casting='unsafe', where=m) except: pass # Transforms to a (subclass of) MaskedArray masked_result = result.view(get_masked_subclass(a, b)) masked_result._mask = m if isinstance(a, MaskedArray): masked_result._update_from(a) elif isinstance(b, MaskedArray): masked_result._update_from(b) return masked_result
def masked_invalid(a, copy=True): """ Mask an array where invalid values occur (NaNs or infs). This function is a shortcut to ``masked_where``, with `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but accepts any array_like object. See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(5, dtype=np.float) >>> a[2] = np.NaN >>> a[3] = np.PINF >>> a array([ 0., 1., NaN, Inf, 4.]) >>> ma.masked_invalid(a) masked_array(data = [0.0 1.0 -- -- 4.0], mask = [False False True True False], fill_value=1e+20) """ a = np.array(a, copy=copy, subok=True) mask = getattr(a, '_mask', None) if mask is not None: condition = ~(np.isfinite(getdata(a))) if mask is not nomask: condition |= mask cls = type(a) else: condition = ~(np.isfinite(a)) cls = MaskedArray result = a.view(cls) result._mask = condition return result ############################################################################### # Printing options # ###############################################################################
def __array_wrap__(self, obj, context=None): """ Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ result = obj.view(type(self)) result._update_from(self) if context is not None: result._mask = result._mask.copy() (func, args, _) = context m = reduce(mask_or, [getmaskarray(arg) for arg in args]) # Get the domain mask domain = ufunc_domain.get(func, None) if domain is not None: # Take the domain, and make sure it's a ndarray if len(args) > 2: with np.errstate(divide='ignore', invalid='ignore'): d = filled(reduce(domain, args), True) else: with np.errstate(divide='ignore', invalid='ignore'): d = filled(domain(*args), True) if d.any(): # Fill the result where the domain is wrong try: # Binary domain: take the last value fill_value = ufunc_fills[func][-1] except TypeError: # Unary domain: just use this one fill_value = ufunc_fills[func] except KeyError: # Domain not recognized, use fill_value instead fill_value = self.fill_value result = result.copy() np.copyto(result, fill_value, where=d) # Update the mask if m is nomask: m = d else: # Don't modify inplace, we risk back-propagation m = (m | d) # Make sure the mask has the proper size if result.shape == () and m: return masked else: result._mask = m result._sharedmask = False return result