def _nan_inf_care(v, n): v_tmp = v.flatten() n_tmp = n.flatten() for i, (ve, ne) in enumerate(zip(v_tmp, n_tmp)): if numpy.isinf(ne) and nlcpy.isinf(ve): v_tmp[i] = n_tmp[i] elif numpy.isnan(ne) and nlcpy.isnan(ve): v_tmp[i] = n_tmp[i] return nlcpy.reshape(v_tmp, v.shape), numpy.reshape(n_tmp, n.shape)
def nanargmax(a, axis=None): """ Returns the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax : Returns the indices of the maximum values along an axis. nanargmin : Returns the indices of the minimum values in the specified axis ignoring NaNs. Examples -------- >>> import nlcpy as vp >>> a = vp.array([[vp.nan, 4], [2, 3]]) >>> vp.argmax(a) array(0) >>> vp.nanargmax(a) array(1) >>> vp.nanargmax(a, axis=0) array([1, 0]) >>> vp.nanargmax(a, axis=1) array([1, 1]) """ a = nlcpy.array(a) if a.dtype.kind not in 'fc': return nlcpy.argmax(a, axis=axis) mask = nlcpy.isnan(a) if nlcpy.any(nlcpy.all(mask, axis=axis)): raise ValueError("All-NaN slice encountered") nlcpy.copyto(a, -nlcpy.inf, where=mask) return nlcpy.argmax(a, axis=axis)
def _check_ufunc_result(op, worst_dtype, v, n, in1=None, in2=None, out=None, where=None, dtype=None, ufunc_name='', n_calc=1): # nan/inf care if numpy.isscalar(n): if numpy.isinf(n) and nlcpy.isinf(v) or numpy.isnan(n) and nlcpy.isnan(v): return else: v, n = _nan_inf_care(v, n) v_array = nlcpy.asarray(v) n_array = numpy.asarray(n) atol, rtol = _guess_tolerance(op, worst_dtype, ufunc_name) if ufunc_name in ('reduce', 'accumulate', 'reduceat'): atol *= n_calc rtol *= n_calc if numpy.asarray(n).dtype.char in '?ilIL' and \ (numpy.asarray(in1).dtype.char not in '?ilIL' or numpy.dtype(dtype).char not in '?ilIL' or op in ('logaddexp', 'logaddexp2', 'arctan2', 'hypot')): atol = 1 # prepare error message msg = "\n" msg += "***** parameters when pytest raised an error *****" msg += "\nout={}, where={}, dtype={}".format( True if out is not None else False, True if where is not None else False, dtype) msg += "\nop: {}".format(op) if in1 is not None: if isinstance(in1, numpy.ndarray): msg += "\nin1: dtype={}\n{}".format(in1.dtype, in1) else: msg += "\nin1: dtype={}\n{}".format(type(in1), in1) if in2 is not None: if isinstance(in2, numpy.ndarray): msg += "\nin2: dtype={}\n{}".format(in2.dtype, in2) else: msg += "\nin2: dtype={}\n{}".format(type(in2), in2) if out is not None: msg += "\nout: dtype={}\n{}".format(out.dtype, out) if where is not None: msg += "\nwhere: dtype={}\n{}".format(where.dtype, where) msg += "\n\nnlcpy_result: dtype={}\n{}".format(v_array.dtype, v_array) msg += "\nnumpy_result: dtype={}\n{}".format(n_array.dtype, n_array) msg += "\n" # compare results try: if v_array.dtype == DT_BOOL and n_array.dtype == DT_BOOL: array.assert_array_equal(v_array, n_array, verbose=True, err_msg=msg) elif atol == 0 and rtol == 0: array.assert_array_equal(v_array, n_array, verbose=True, err_msg=msg) else: array.assert_allclose( v_array, n_array, rtol, atol, verbose=True, err_msg=msg) except Exception: raise # if contiguous_check and isinstance(n, numpy.ndarray): if isinstance(n, numpy.ndarray): if n.flags.c_contiguous and not v.flags.c_contiguous: raise AssertionError( 'The state of c_contiguous flag is false. \n\n' 'nlcpy_flags:\n{} \n\nnumpy_flags:\n{})'.format( v.flags, n.flags)) if n.flags.f_contiguous and not v.flags.f_contiguous: raise AssertionError( 'The state of f_contiguous flag is false. \n\n' 'nlcpy_flags:\n{} \n\nnumpy_flags:\n{})'.format( v.flags, n.flags))
def nanmin(a, axis=None, out=None, keepdims=nlcpy._NoValue): """Returns minimum of an array or minimum along an axis, ignoring any NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is raised and Nan is returned for that slice. Parameters ---------- a : array_like Array containing numbers whose minimum is desired. If a is not an array, a conversion is attempted. axis : None or int or tuple of ints, optional Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of ints, the minimum is selected over multiple axes. out : ndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- nanmin : ndarray Minimum of *a*. An array with the same shape as *a*, with the specified axis removed. If *a* is a scalar, or if axis is None, this function returns the result as a 0-dimention array. The same dtype as *a* is returned. Note ---- NLCPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number. If the input has a integer type the function is equivalent to :func:`amin`. See Also -------- nanmax : Returns the maximum of an array or maximum along an axis, ignoring any NaNs. amin : Returns the minimum of an array or maximum along an axis. fmin : Element-wise minimum of array elements. minimum : Element-wise minimum of array elements. isnan : Tests element-wise for NaN and return result as a boolean array. isfinite : Tests element-wise for finiteness (not infinity or not Not a Number). amax : Returns the maximum of an array or maximum along an axis. fmax : Element-wise maximum of array elements. maximum : Element-wise maximum of array elements. Examples -------- >>> import nlcpy as vp >>> a = vp.array([[1, 2], [3, vp.nan]]) >>> vp.nanmin(a) array(1.) >>> vp.nanmin(a, axis=0) array([1., 2.]) >>> vp.nanmin(a, axis=1) array([1., 3.]) When positive infinity and negative infinity are present: >>> vp.nanmin([1, 2, vp.nan, vp.inf]) array(1.) >>> vp.nanmin([1, 2, vp.nan, vp.NINF]) array(-inf) """ a = nlcpy.core.argument_conversion(a) args = dict() if keepdims is not nlcpy._NoValue: args["keepdims"] = keepdims res = nlcpy.fmin.reduce(a, axis=axis, out=out, **args) if type(res) is nlcpy.ndarray and nlcpy.any(nlcpy.isnan(res)): warnings.warn("All-NaN slice encountered", RuntimeWarning) return res