diff options
Diffstat (limited to 'numpy/lib')
-rw-r--r-- | numpy/lib/arraysetops.py | 78 | ||||
-rw-r--r-- | numpy/lib/arrayterator.py | 29 | ||||
-rw-r--r-- | numpy/lib/benchmarks/bench_arraysetops.py | 65 | ||||
-rw-r--r-- | numpy/lib/function_base.py | 46 | ||||
-rw-r--r-- | numpy/lib/index_tricks.py | 66 | ||||
-rw-r--r-- | numpy/lib/npyio.py | 94 | ||||
-rw-r--r-- | numpy/lib/polynomial.py | 22 | ||||
-rw-r--r-- | numpy/lib/recfunctions.py | 2 | ||||
-rw-r--r-- | numpy/lib/src/_compiled_base.c | 533 | ||||
-rw-r--r-- | numpy/lib/tests/test__datasource.py | 48 | ||||
-rw-r--r-- | numpy/lib/tests/test_arraysetops.py | 45 | ||||
-rw-r--r-- | numpy/lib/tests/test_format.py | 2 | ||||
-rw-r--r-- | numpy/lib/tests/test_function_base.py | 96 | ||||
-rw-r--r-- | numpy/lib/tests/test_index_tricks.py | 67 | ||||
-rw-r--r-- | numpy/lib/tests/test_io.py | 12 | ||||
-rw-r--r-- | numpy/lib/tests/test_polynomial.py | 19 | ||||
-rw-r--r-- | numpy/lib/tests/test_recfunctions.py | 23 | ||||
-rw-r--r-- | numpy/lib/tests/test_regression.py | 28 | ||||
-rw-r--r-- | numpy/lib/tests/test_type_check.py | 9 | ||||
-rw-r--r-- | numpy/lib/tests/test_ufunclike.py | 13 | ||||
-rw-r--r-- | numpy/lib/ufunclike.py | 42 | ||||
-rw-r--r-- | numpy/lib/utils.py | 3 |
22 files changed, 863 insertions, 479 deletions
diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index 042866f30..721039238 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -10,11 +10,6 @@ Set operations for 1D numeric arrays based on sorting. union1d, setdiff1d -:Deprecated: - unique1d, - intersect1d_nu, - setmember1d - :Notes: For floating point arrays, inaccurate results may appear due to usual round-off @@ -28,8 +23,8 @@ To do: Optionally return indices analogously to unique for all functions. :Author: Robert Cimrman """ -__all__ = ['ediff1d', 'unique1d', 'intersect1d', 'intersect1d_nu', 'setxor1d', - 'setmember1d', 'union1d', 'setdiff1d', 'unique', 'in1d'] +__all__ = ['ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', + 'unique', 'in1d'] import numpy as np from numpy.lib.utils import deprecate @@ -417,72 +412,3 @@ def setdiff1d(ar1, ar2, assume_unique=False): return aux else: return np.asarray(ar1)[aux == 0] - -@deprecate -def unique1d(ar1, return_index=False, return_inverse=False): - """ - This function is deprecated. Use unique() instead. - """ - if return_index: - import warnings - warnings.warn("The order of the output arguments for " - "`return_index` has changed. Before, " - "the output was (indices, unique_arr), but " - "has now been reversed to be more consistent.") - - ar = np.asanyarray(ar1).flatten() - if ar.size == 0: - if return_inverse and return_index: - return ar, np.empty(0, np.bool), np.empty(0, np.bool) - elif return_inverse or return_index: - return ar, np.empty(0, np.bool) - else: - return ar - - if return_inverse or return_index: - perm = ar.argsort() - aux = ar[perm] - flag = np.concatenate(([True], aux[1:] != aux[:-1])) - if return_inverse: - iflag = np.cumsum(flag) - 1 - iperm = perm.argsort() - if return_index: - return aux[flag], perm[flag], iflag[iperm] - else: - return aux[flag], iflag[iperm] - else: - return aux[flag], perm[flag] - - else: - ar.sort() - flag = np.concatenate(([True], ar[1:] != ar[:-1])) - return ar[flag] - -@deprecate -def intersect1d_nu(ar1, ar2): - """ - This function is deprecated. Use intersect1d() - instead. - """ - # Might be faster than unique1d( intersect1d( ar1, ar2 ) )? - aux = np.concatenate((unique1d(ar1), unique1d(ar2))) - aux.sort() - return aux[aux[1:] == aux[:-1]] - -@deprecate -def setmember1d(ar1, ar2): - """ - This function is deprecated. Use in1d(assume_unique=True) - instead. - """ - # We need this to be a stable sort, so always use 'mergesort' here. The - # values from the first array should always come before the values from the - # second array. - ar = np.concatenate( (ar1, ar2 ) ) - order = ar.argsort(kind='mergesort') - sar = ar[order] - equal_adj = (sar[1:] == sar[:-1]) - flag = np.concatenate( (equal_adj, [False] ) ) - - indx = order.argsort(kind='mergesort')[:len( ar1 )] - return flag[indx] diff --git a/numpy/lib/arrayterator.py b/numpy/lib/arrayterator.py index 3f07cd263..2df05e514 100644 --- a/numpy/lib/arrayterator.py +++ b/numpy/lib/arrayterator.py @@ -141,12 +141,41 @@ class Arrayterator(object): @property def flat(self): + """ + A 1-D flat iterator for Arrayterator objects. + + This iterator returns elements of the array to be iterated over in + `Arrayterator` one by one. It is similar to `flatiter`. + + See Also + -------- + `Arrayterator` + flatiter + + Examples + -------- + >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) + >>> a_itor = np.lib.arrayterator.Arrayterator(a, 2) + + >>> for subarr in a_itor.flat: + ... if not subarr: + ... print subarr, type(subarr) + ... + 0 <type 'numpy.int32'> + + """ for block in self: for value in block.flat: yield value @property def shape(self): + """ + The shape of the array to be iterated over. + + For an example, see `Arrayterator`. + + """ return tuple(((stop-start-1)//step+1) for start, stop, step in zip(self.start, self.stop, self.step)) diff --git a/numpy/lib/benchmarks/bench_arraysetops.py b/numpy/lib/benchmarks/bench_arraysetops.py deleted file mode 100644 index 2c77fb758..000000000 --- a/numpy/lib/benchmarks/bench_arraysetops.py +++ /dev/null @@ -1,65 +0,0 @@ -import numpy as np -import time -from numpy.lib.arraysetops import * - -def bench_unique1d( plot_results = False ): - exponents = np.linspace( 2, 7, 9 ) - ratios = [] - nItems = [] - dt1s = [] - dt2s = [] - for ii in exponents: - - nItem = 10 ** ii - print 'using %d items:' % nItem - a = np.fix( nItem / 10 * np.random.random( nItem ) ) - - print 'unique:' - tt = time.clock() - b = np.unique( a ) - dt1 = time.clock() - tt - print dt1 - - print 'unique1d:' - tt = time.clock() - c = unique1d( a ) - dt2 = time.clock() - tt - print dt2 - - - if dt1 < 1e-8: - ratio = 'ND' - else: - ratio = dt2 / dt1 - print 'ratio:', ratio - print 'nUnique: %d == %d\n' % (len( b ), len( c )) - - nItems.append( nItem ) - ratios.append( ratio ) - dt1s.append( dt1 ) - dt2s.append( dt2 ) - - assert np.alltrue( b == c ) - - print nItems - print dt1s - print dt2s - print ratios - - if plot_results: - import pylab - - def plotMe( fig, fun, nItems, dt1s, dt2s ): - pylab.figure( fig ) - fun( nItems, dt1s, 'g-o', linewidth = 2, markersize = 8 ) - fun( nItems, dt2s, 'b-x', linewidth = 2, markersize = 8 ) - pylab.legend( ('unique', 'unique1d' ) ) - pylab.xlabel( 'nItem' ) - pylab.ylabel( 'time [s]' ) - - plotMe( 1, pylab.loglog, nItems, dt1s, dt2s ) - plotMe( 2, pylab.plot, nItems, dt1s, dt2s ) - pylab.show() - -if __name__ == '__main__': - bench_unique1d( plot_results = True ) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 292dbe41d..dd792c509 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -99,7 +99,7 @@ def histogram(a, bins=10, range=None, normed=False, weights=None): See Also -------- - histogramdd, bincount, searchsorted + histogramdd, bincount, searchsorted, digitize Notes ----- @@ -1447,8 +1447,7 @@ def nanmin(a, axis=None): 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, an integer type is returned unless - the input contains NaNs and infinity. + If the input has a integer type the function is equivalent to np.min. Examples @@ -1469,7 +1468,11 @@ def nanmin(a, axis=None): -inf """ - return _nanop(np.min, np.inf, a, axis) + a = np.asanyarray(a) + if axis is not None: + return np.fmin.reduce(a, axis) + else: + return np.fmin.reduce(a.flat) def nanargmin(a, axis=None): """ @@ -1541,8 +1544,7 @@ def nanmax(a, axis=None): 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, an integer type is returned unless - the input contains NaNs and infinity. + If the input has a integer type the function is equivalent to np.max. Examples -------- @@ -1562,7 +1564,11 @@ def nanmax(a, axis=None): inf """ - return _nanop(np.max, -np.inf, a, axis) + a = np.asanyarray(a) + if axis is not None: + return np.fmax.reduce(a, axis) + else: + return np.fmax.reduce(a.flat) def nanargmax(a, axis=None): """ @@ -2921,22 +2927,22 @@ def percentile(a, q, axis=None, out=None, overwrite_input=False): a : array_like Input array or object that can be converted to an array. q : float in range of [0,100] (or sequence of floats) - percentile to compute which must be between 0 and 100 inclusive - axis : {None, int}, optional - Axis along which the percentiles are computed. The default (axis=None) + Percentile to compute which must be between 0 and 100 inclusive. + axis : int, optional + Axis along which the percentiles are computed. The default (None) is to compute the median along a flattened version of the array. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. - overwrite_input : {False, True}, optional - If True, then allow use of memory of input array (a) for + overwrite_input : bool, optional + If True, then allow use of memory of input array `a` for calculations. The input array will be modified by the call to median. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, - but it will probably be fully or partially sorted. Default is - False. Note that, if `overwrite_input` is True and the input - is not already an ndarray, an error will be raised. + but it will probably be fully or partially sorted. + Default is False. Note that, if `overwrite_input` is True and the + input is not already an array, an error will be raised. Returns ------- @@ -2954,10 +2960,10 @@ def percentile(a, q, axis=None, out=None, overwrite_input=False): Notes ----- Given a vector V of length N, the qth percentile of V is the qth ranked - value in a sorted copy of V. A weighted average of the two nearest neighbors - is used if the normalized ranking does not match q exactly. - The same as the median if q is 0.5; the same as the min if q is 0; - and the same as the max if q is 1 + value in a sorted copy of V. A weighted average of the two nearest + neighbors is used if the normalized ranking does not match q exactly. + The same as the median if ``q=0.5``, the same as the minimum if ``q=0`` + and the same as the maximum if ``q=1``. Examples -------- @@ -2971,12 +2977,14 @@ def percentile(a, q, axis=None, out=None, overwrite_input=False): array([ 6.5, 4.5, 2.5]) >>> np.percentile(a, 0.5, axis=1) array([ 7., 2.]) + >>> m = np.percentile(a, 0.5, axis=0) >>> out = np.zeros_like(m) >>> np.percentile(a, 0.5, axis=0, out=m) array([ 6.5, 4.5, 2.5]) >>> m array([ 6.5, 4.5, 2.5]) + >>> b = a.copy() >>> np.percentile(b, 0.5, axis=1, overwrite_input=True) array([ 7., 2.]) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 264ebaad0..d1e925ead 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -1,4 +1,5 @@ -__all__ = ['unravel_index', +__all__ = ['ravel_coords', + 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_', 's_', @@ -16,70 +17,9 @@ import math import function_base import numpy.matrixlib as matrix from function_base import diff +from numpy.lib._compiled_base import ravel_coords, unravel_index makemat = matrix.matrix -# contributed by Stefan van der Walt -def unravel_index(x,dims): - """ - Convert a flat index to an index tuple for an array of given shape. - - Parameters - ---------- - x : int - Flattened index. - dims : tuple of ints - Input shape, the shape of an array into which indexing is - required. - - Returns - ------- - idx : tuple of ints - Tuple of the same shape as `dims`, containing the unraveled index. - - Notes - ----- - In the Examples section, since ``arr.flat[x] == arr.max()`` it may be - easier to use flattened indexing than to re-map the index to a tuple. - - Examples - -------- - >>> arr = np.arange(20).reshape(5, 4) - >>> arr - array([[ 0, 1, 2, 3], - [ 4, 5, 6, 7], - [ 8, 9, 10, 11], - [12, 13, 14, 15], - [16, 17, 18, 19]]) - >>> x = arr.argmax() - >>> x - 19 - >>> dims = arr.shape - >>> idx = np.unravel_index(x, dims) - >>> idx - (4, 3) - >>> arr[idx] == arr.max() - True - - """ - if x > _nx.prod(dims)-1 or x < 0: - raise ValueError("Invalid index, must be 0 <= x <= number of elements.") - - idx = _nx.empty_like(dims) - - # Take dimensions - # [a,b,c,d] - # Reverse and drop first element - # [d,c,b] - # Prepend [1] - # [1,d,c,b] - # Calculate cumulative product - # [1,d,dc,dcb] - # Reverse - # [dcb,dc,d,1] - dim_prod = _nx.cumprod([1] + list(dims)[:0:-1])[::-1] - # Indices become [x/dcb % a, x/dc % b, x/d % c, x/1 % d] - return tuple(x//dim_prod % dims) - def ix_(*args): """ Construct an open mesh from multiple sequences. diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index aeccc2a24..9fbacaa22 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -500,7 +500,7 @@ def savez_compressed(file, *args, **kwds): Parameters ---------- - file : string + file : str File name of .npz file. args : Arguments Function arguments. @@ -683,19 +683,44 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, X = [] def flatten_dtype(dt): - """Unpack a structured data-type.""" + """Unpack a structured data-type, and produce re-packing info.""" if dt.names is None: # If the dtype is flattened, return. # If the dtype has a shape, the dtype occurs # in the list more than once. - return [dt.base] * int(np.prod(dt.shape)) + shape = dt.shape + if len(shape) == 0: + return ([dt.base], None) + else: + packing = [(shape[-1], tuple)] + if len(shape) > 1: + for dim in dt.shape[-2:0:-1]: + packing = [(dim*packing[0][0],packing*dim)] + packing = packing*shape[0] + return ([dt.base] * int(np.prod(dt.shape)), packing) else: types = [] + packing = [] for field in dt.names: tp, bytes = dt.fields[field] - flat_dt = flatten_dtype(tp) + flat_dt, flat_packing = flatten_dtype(tp) types.extend(flat_dt) - return types + packing.append((len(flat_dt),flat_packing)) + return (types, packing) + + def pack_items(items, packing): + """Pack items into nested lists based on re-packing info.""" + if packing == None: + return items[0] + elif packing is tuple: + return tuple(items) + else: + start = 0 + ret = [] + for length, subpacking in packing: + ret.append(pack_items(items[start:start+length], subpacking)) + start += length + return tuple(ret) def split_line(line): """Chop off comments, strip, and split at delimiter.""" @@ -724,7 +749,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, first_vals = split_line(first_line) N = len(usecols or first_vals) - dtype_types = flatten_dtype(dtype) + dtype_types, packing = flatten_dtype(dtype) if len(dtype_types) > 1: # We're dealing with a structured array, each field of # the dtype matches a column @@ -732,6 +757,8 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, else: # All fields have the same dtype converters = [defconv for i in xrange(N)] + if N > 1: + packing = [(N, tuple)] # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): @@ -753,27 +780,16 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, vals = [vals[i] for i in usecols] # Convert each value according to its column and store - X.append(tuple([conv(val) for (conv, val) in zip(converters, vals)])) + items = [conv(val) for (conv, val) in zip(converters, vals)] + # Then pack it according to the dtype's nesting + items = pack_items(items, packing) + + X.append(items) finally: if own_fh: fh.close() - if len(dtype_types) > 1: - # We're dealing with a structured array, with a dtype such as - # [('x', int), ('y', [('s', int), ('t', float)])] - # - # First, create the array using a flattened dtype: - # [('x', int), ('s', int), ('t', float)] - # - # Then, view the array using the specified dtype. - try: - X = np.array(X, dtype=np.dtype([('', t) for t in dtype_types])) - X = X.view(dtype) - except TypeError: - # In the case we have an object dtype - X = np.array(X, dtype=dtype) - else: - X = np.array(X, dtype) + X = np.array(X, dtype) X = np.squeeze(X) if unpack: @@ -1012,7 +1028,7 @@ def fromregex(file, regexp, dtype): return output finally: if own_fh: - fh.close() + file.close() @@ -1033,7 +1049,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, """ Load data from a text file, with missing values handled as specified. - Each line past the first `skiprows` lines is split at the `delimiter` + Each line past the first `skip_header` lines is split at the `delimiter` character, and characters following the `comments` character are discarded. Parameters @@ -1056,20 +1072,20 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, The numbers of lines to skip at the beginning of the file. skip_footer : int, optional The numbers of lines to skip at the end of the file - converters : variable or None, optional + converters : variable, optional The set of functions that convert the data of a column to a value. The converters can also be used to provide a default value for missing data: ``converters = {3: lambda s: float(s or 0)}``. - missing_values : variable or None, optional + missing_values : variable, optional The set of strings corresponding to missing data. - filling_values : variable or None, optional + filling_values : variable, optional The set of values to be used as default when the data are missing. - usecols : sequence or None, optional + usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns. names : {None, True, str, sequence}, optional If `names` is True, the field names are read from the first valid line - after the first `skiprows` lines. + after the first `skip_header` lines. If `names` is a sequence or a single-string of comma-separated names, the names will be used to define the field names in a structured dtype. If `names` is None, the names of the dtype fields will be used, if any. @@ -1202,9 +1218,10 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, # Get the first valid lines after the first skiprows ones .. if skiprows: - warnings.warn("The use of `skiprows` is deprecated.\n"\ - "Please use `skip_header` instead.", - DeprecationWarning) + warnings.warn(\ + "The use of `skiprows` is deprecated, it will be removed in numpy 2.0.\n" \ + "Please use `skip_header` instead.", + DeprecationWarning) skip_header = skiprows # Skip the first `skip_header` rows for i in xrange(skip_header): @@ -1269,7 +1286,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, elif (names is not None) and (len(names) > nbcols): names = [names[_] for _ in usecols] elif (names is not None) and (dtype is not None): - names = dtype.names + names = list(dtype.names) # Process the missing values ............................... @@ -1327,9 +1344,10 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, # Process the deprecated `missing` if missing != asbytes(''): - warnings.warn("The use of `missing` is deprecated.\n"\ - "Please use `missing_values` instead.", - DeprecationWarning) + warnings.warn(\ + "The use of `missing` is deprecated, it will be removed in Numpy 2.0.\n" \ + "Please use `missing_values` instead.", + DeprecationWarning) values = [str(_) for _ in missing.split(asbytes(","))] for entry in missing_values: entry.extend(values) @@ -1486,7 +1504,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, if _[0] > nbrows + skip_header]) invalid = invalid[:nbinvalid - nbinvalid_skipped] skip_footer -= nbinvalid_skipped -# +# # nbrows -= skip_footer # errmsg = [template % (i, nb) # for (i, nb) in invalid if i < nbrows] diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 603655ec2..f3146d691 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -151,13 +151,14 @@ def roots(p): Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. - If the length of `p` is n+1 then the polynomial is described by - p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] + If the length of `p` is n+1 then the polynomial is described by:: + + p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- - p : array_like of shape(M,) - Rank-1 array of polynomial co-efficients. + p : array_like + Rank-1 array of polynomial coefficients. Returns ------- @@ -166,32 +167,29 @@ def roots(p): Raises ------ - ValueError: + ValueError : When `p` cannot be converted to a rank-1 array. See also -------- - - poly : Find the coefficients of a polynomial with - a given sequence of roots. + poly : Find the coefficients of a polynomial with a given sequence + of roots. polyval : Evaluate a polynomial at a point. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- - The algorithm relies on computing the eigenvalues of the companion matrix [1]_. References ---------- - .. [1] Wikipedia, "Companion matrix", - http://en.wikipedia.org/wiki/Companion_matrix + .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: + Cambridge University Press, 1999, pp. 146-7. Examples -------- - >>> coeff = [3.2, 2, 1] >>> np.roots(coeff) array([-0.3125+0.46351241j, -0.3125-0.46351241j]) diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index f722a89d1..b3c210fff 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -376,7 +376,7 @@ def merge_arrays(seqarrays, # Only one item in the input sequence ? if (len(seqarrays) == 1): seqarrays = np.asanyarray(seqarrays[0]) - # Do we have a single ndarary as input ? + # Do we have a single ndarray as input ? if isinstance(seqarrays, (ndarray, np.void)): seqdtype = seqarrays.dtype if (not flatten) or \ diff --git a/numpy/lib/src/_compiled_base.c b/numpy/lib/src/_compiled_base.c index 466fa0202..b44cfb471 100644 --- a/numpy/lib/src/_compiled_base.c +++ b/numpy/lib/src/_compiled_base.c @@ -90,27 +90,29 @@ mnx (intp *i , intp len) /* * arr_bincount is registered as bincount. * - * bincount accepts one or two arguments. The first is an array of - * non-negative integers and the second, if present, is an array of weights, - * which must be promotable to double. Call these arguments list and + * bincount accepts one, two or three arguments. The first is an array of + * non-negative integers The second, if present, is an array of weights, + * which must be promotable to double. Call these arguments list and * weight. Both must be one-dimensional with len(weight) == len(list). If * weight is not present then bincount(list)[i] is the number of occurrences * of i in list. If weight is present then bincount(self,list, weight)[i] * is the sum of all weight[j] where list [j] == i. Self is not used. + * The third argument, if present, is a minimum length desired for the + * output array. */ static PyObject * arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) { PyArray_Descr *type; - PyObject *list = NULL, *weight=Py_None; + PyObject *list = NULL, *weight=Py_None, *mlength=Py_None; PyObject *lst=NULL, *ans=NULL, *wts=NULL; - intp *numbers, *ians, len , mxi, mni, ans_size; + intp *numbers, *ians, len , mxi, mni, ans_size, minlength; int i; double *weights , *dans; - static char *kwlist[] = {"list", "weights", NULL}; + static char *kwlist[] = {"list", "weights", "minlength", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", - kwlist, &list, &weight)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO", + kwlist, &list, &weight, &mlength)) { goto fail; } if (!(lst = PyArray_ContiguousFromAny(list, PyArray_INTP, 1, 1))) { @@ -131,6 +133,20 @@ arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) goto fail; } ans_size = numbers [mxi] + 1; + if (mlength != Py_None) { + if (!(minlength = PyArray_PyIntAsIntp(mlength))) { + goto fail; + } + if (minlength <= 0) { + /* superfluous, but may catch incorrect usage */ + PyErr_SetString(PyExc_ValueError, + "minlength must be positive"); + goto fail; + } + if (ans_size < minlength) { + ans_size = minlength; + } + } type = PyArray_DescrFromType(PyArray_INTP); if (weight == Py_None) { if (!(ans = PyArray_Zeros(1, &ans_size, type, 0))) { @@ -549,6 +565,502 @@ fail: return NULL; } +/* + * Converts a Python sequence into 'count' PyArrayObjects + * + * seq - Input Python object, usually a tuple but any sequence works. + * op - Where the arrays are placed. + * count - How many arrays there should be (errors if it doesn't match). + * paramname - The name of the parameter that produced 'seq'. + */ +static int sequence_to_arrays(PyObject *seq, + PyArrayObject **op, int count, + char *paramname) +{ + int i; + + if (!PySequence_Check(seq) || PySequence_Size(seq) != count) { + PyErr_Format(PyExc_ValueError, + "parameter %s must be a sequence of length %d", + paramname, count); + return -1; + } + + for (i = 0; i < count; ++i) { + PyObject *item = PySequence_GetItem(seq, i); + if (item == NULL) { + while (--i >= 0) { + Py_DECREF(op[i]); + op[i] = NULL; + } + return -1; + } + + op[i] = (PyArrayObject *)PyArray_FromAny(item, NULL, 0, 0, 0, NULL); + if (op[i] == NULL) { + while (--i >= 0) { + Py_DECREF(op[i]); + op[i] = NULL; + } + Py_DECREF(item); + return -1; + } + + Py_DECREF(item); + } + + return 0; +} + +/* Inner loop for unravel_index */ +static int +ravel_coords_loop(int ravel_ndim, npy_intp *ravel_dims, + npy_intp *ravel_strides, + npy_intp count, + NPY_CLIPMODE *modes, + char **coords, npy_intp *coords_strides) +{ + int i; + npy_intp j, m; + + while (count--) { + npy_intp raveled = 0; + for (i = 0; i < ravel_ndim; ++i) { + m = ravel_dims[i]; + j = *(npy_intp *)coords[i]; + switch (modes[i]) { + case NPY_RAISE: + if(j < 0 || j>=m) { + PyErr_SetString(PyExc_ValueError, + "invalid entry in coordinates array"); + return NPY_FAIL; + } + break; + case NPY_WRAP: + if(j < 0) { + j += m; + if(j < 0) { + j = j%m; + if(j != 0) { + j += m; + } + } + } + else if(j >= m) { + j -= m; + if(j >= m) { + j = j%m; + } + } + break; + case NPY_CLIP: + if(j < 0) { + j = 0; + } + else if(j >= m) { + j = m-1; + } + break; + + } + raveled += j * ravel_strides[i]; + + coords[i] += coords_strides[i]; + } + *(npy_intp *)coords[ravel_ndim] = raveled; + coords[ravel_ndim] += coords_strides[ravel_ndim]; + } + + return NPY_SUCCEED; +} + +/* ravel_coords implementation - see add_newdocs.py */ +static PyObject * +arr_ravel_coords(PyObject *self, PyObject *args, PyObject *kwds) +{ + int i, s; + PyObject *mode0=NULL, *coords0=NULL, *ret; + PyArray_Dims dimensions={0,0}; + npy_intp ravel_strides[NPY_MAXDIMS]; + PyArray_ORDER order = NPY_CORDER; + NPY_CLIPMODE modes[NPY_MAXDIMS]; + + PyArrayObject *op[NPY_MAXARGS]; + PyArray_Descr *dtype[NPY_MAXARGS]; + npy_uint32 op_flags[NPY_MAXARGS]; + + NpyIter *iter = NULL; + + char *kwlist[] = {"coords", "dims", "mode", "order", NULL}; + + memset(op, 0, sizeof(op)); + dtype[0] = NULL; + + if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|OO&:ravel_coords", kwlist, + &coords0, + PyArray_IntpConverter, &dimensions, + &mode0, + PyArray_OrderConverter, &order)) { + goto fail; + } + + if (dimensions.len+1 > NPY_MAXARGS) { + PyErr_SetString(PyExc_ValueError, + "too many dimensions passed to ravel_coords"); + goto fail; + } + + if(!PyArray_ConvertClipmodeSequence(mode0, modes, dimensions.len)) { + goto fail; + } + + switch (order) { + case NPY_CORDER: + s = 1; + for (i = dimensions.len-1; i >= 0; --i) { + ravel_strides[i] = s; + s *= dimensions.ptr[i]; + } + break; + case NPY_FORTRANORDER: + s = 1; + for (i = 0; i < dimensions.len; ++i) { + ravel_strides[i] = s; + s *= dimensions.ptr[i]; + } + break; + default: + PyErr_SetString(PyExc_ValueError, + "only 'C' or 'F' order is permitted"); + goto fail; + } + + /* Get the coords into op */ + if (sequence_to_arrays(coords0, op, dimensions.len, "coords") < 0) { + goto fail; + } + + + for (i = 0; i < dimensions.len; ++i) { + op_flags[i] = NPY_ITER_READONLY| + NPY_ITER_ALIGNED; + } + op_flags[dimensions.len] = NPY_ITER_WRITEONLY| + NPY_ITER_ALIGNED| + NPY_ITER_ALLOCATE; + dtype[0] = PyArray_DescrFromType(NPY_INTP); + for (i = 1; i <= dimensions.len; ++i) { + dtype[i] = dtype[0]; + } + + iter = NpyIter_MultiNew(dimensions.len+1, op, NPY_ITER_BUFFERED| + NPY_ITER_NO_INNER_ITERATION| + NPY_ITER_ZEROSIZE_OK, + NPY_KEEPORDER, + NPY_SAME_KIND_CASTING, + op_flags, dtype, + 0, NULL, 0); + if (iter == NULL) { + goto fail; + } + + if (NpyIter_GetIterSize(iter) != 0) { + NpyIter_IterNextFunc *iternext; + char **dataptr; + npy_intp *strides; + npy_intp *countptr; + + iternext = NpyIter_GetIterNext(iter, NULL); + if (iternext == NULL) { + goto fail; + } + dataptr = NpyIter_GetDataPtrArray(iter); + strides = NpyIter_GetInnerStrideArray(iter); + countptr = NpyIter_GetInnerLoopSizePtr(iter); + + do { + if (ravel_coords_loop(dimensions.len, dimensions.ptr, + ravel_strides, *countptr, modes, + dataptr, strides) != NPY_SUCCEED) { + goto fail; + } + } while(iternext(iter)); + } + + ret = (PyObject *)NpyIter_GetOperandArray(iter)[dimensions.len]; + Py_INCREF(ret); + + Py_DECREF(dtype[0]); + for (i = 0; i < dimensions.len; ++i) { + Py_XDECREF(op[i]); + } + PyDimMem_FREE(dimensions.ptr); + NpyIter_Deallocate(iter); + return PyArray_Return(ret); + +fail: + Py_XDECREF(dtype[0]); + for (i = 0; i < dimensions.len; ++i) { + Py_XDECREF(op[i]); + } + if (dimensions.ptr) { + PyDimMem_FREE(dimensions.ptr); + } + if (iter != NULL) { + NpyIter_Deallocate(iter); + } + return NULL; +} + +/* C-order inner loop for unravel_index */ +static int +unravel_index_loop_corder(int unravel_ndim, npy_intp *unravel_dims, + npy_intp unravel_size, npy_intp count, + char *indices, npy_intp indices_stride, + npy_intp *coords) +{ + int i; + npy_intp val; + + while (count--) { + val = *(npy_intp *)indices; + if (val < 0 || val >= unravel_size) { + PyErr_SetString(PyExc_ValueError, + "invalid entry in index array"); + return NPY_FAIL; + } + for (i = unravel_ndim-1; i >= 0; --i) { + coords[i] = val % unravel_dims[i]; + val /= unravel_dims[i]; + } + coords += unravel_ndim; + indices += indices_stride; + } + + return NPY_SUCCEED; +} + +/* Fortran-order inner loop for unravel_index */ +static int +unravel_index_loop_forder(int unravel_ndim, npy_intp *unravel_dims, + npy_intp unravel_size, npy_intp count, + char *indices, npy_intp indices_stride, + npy_intp *coords) +{ + int i; + npy_intp val; + + while (count--) { + val = *(npy_intp *)indices; + if (val < 0 || val >= unravel_size) { + PyErr_SetString(PyExc_ValueError, + "invalid entry in index array"); + return NPY_FAIL; + } + for (i = 0; i < unravel_ndim; ++i) { + *coords++ = val % unravel_dims[i]; + val /= unravel_dims[i]; + } + indices += indices_stride; + } + + return NPY_SUCCEED; +} + +/* unravel_index implementation - see add_newdocs.py */ +static PyObject * +arr_unravel_index(PyObject *self, PyObject *args, PyObject *kwds) +{ + PyObject *indices0 = NULL, *ret_tuple = NULL; + PyArrayObject *ret_arr = NULL; + PyArrayObject *indices = NULL; + PyArray_Descr *dtype = NULL; + PyArray_Dims dimensions={0,0}; + PyArray_ORDER order = PyArray_CORDER; + npy_intp unravel_size; + + NpyIter *iter = NULL; + int i, ret_ndim; + npy_intp ret_dims[NPY_MAXDIMS], ret_strides[NPY_MAXDIMS]; + + char *kwlist[] = {"indices", "dims", "order", NULL}; + + if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|O&:unravel_index", + kwlist, + &indices0, + PyArray_IntpConverter, &dimensions, + PyArray_OrderConverter, &order)) { + goto fail; + } + + if (dimensions.len == 0) { + PyErr_SetString(PyExc_ValueError, + "dims must have at least one value"); + goto fail; + } + + unravel_size = PyArray_MultiplyList(dimensions.ptr, dimensions.len); + + if(!PyArray_Check(indices0)) { + indices = (PyArrayObject*)PyArray_FromAny(indices0, + NULL, 0, 0, 0, NULL); + if(indices == NULL) { + goto fail; + } + } + else { + indices = (PyArrayObject *)indices0; + Py_INCREF(indices); + } + + dtype = PyArray_DescrFromType(NPY_INTP); + if (dtype == NULL) { + goto fail; + } + + iter = NpyIter_New(indices, NPY_ITER_READONLY| + NPY_ITER_ALIGNED| + NPY_ITER_BUFFERED| + NPY_ITER_ZEROSIZE_OK| + NPY_ITER_DONT_NEGATE_STRIDES| + NPY_ITER_COORDS, + NPY_KEEPORDER, NPY_SAME_KIND_CASTING, + dtype, 0, NULL, 0); + if (iter == NULL) { + goto fail; + } + + /* + * Create the return array with a layout compatible with the indices + * and with a dimension added to the end for the coordinates + */ + ret_ndim = PyArray_NDIM(indices) + 1; + if (NpyIter_GetShape(iter, ret_dims) != NPY_SUCCEED) { + goto fail; + } + ret_dims[ret_ndim-1] = dimensions.len; + if (NpyIter_CreateCompatibleStrides(iter, + dimensions.len*sizeof(npy_intp), ret_strides) != NPY_SUCCEED) { + goto fail; + } + ret_strides[ret_ndim-1] = sizeof(npy_intp); + + /* Remove the coords and inner loop */ + if (NpyIter_RemoveCoords(iter) != NPY_SUCCEED) { + goto fail; + } + if (NpyIter_RemoveInnerLoop(iter) != NPY_SUCCEED) { + goto fail; + } + + ret_arr = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, + ret_ndim, ret_dims, ret_strides, NULL, 0, NULL); + dtype = NULL; + if (ret_arr == NULL) { + goto fail; + } + + if (order == NPY_CORDER) { + if (NpyIter_GetIterSize(iter) != 0) { + NpyIter_IterNextFunc *iternext; + char **dataptr; + npy_intp *strides; + npy_intp *countptr, count; + npy_intp *coordsptr = (npy_intp *)PyArray_DATA(ret_arr); + + iternext = NpyIter_GetIterNext(iter, NULL); + if (iternext == NULL) { + goto fail; + } + dataptr = NpyIter_GetDataPtrArray(iter); + strides = NpyIter_GetInnerStrideArray(iter); + countptr = NpyIter_GetInnerLoopSizePtr(iter); + + do { + count = *countptr; + if (unravel_index_loop_corder(dimensions.len, dimensions.ptr, + unravel_size, count, *dataptr, *strides, + coordsptr) != NPY_SUCCEED) { + goto fail; + } + coordsptr += count*dimensions.len; + } while(iternext(iter)); + } + } + else if (order == NPY_FORTRANORDER) { + if (NpyIter_GetIterSize(iter) != 0) { + NpyIter_IterNextFunc *iternext; + char **dataptr; + npy_intp *strides; + npy_intp *countptr, count; + npy_intp *coordsptr = (npy_intp *)PyArray_DATA(ret_arr); + + iternext = NpyIter_GetIterNext(iter, NULL); + if (iternext == NULL) { + goto fail; + } + dataptr = NpyIter_GetDataPtrArray(iter); + strides = NpyIter_GetInnerStrideArray(iter); + countptr = NpyIter_GetInnerLoopSizePtr(iter); + + do { + count = *countptr; + if (unravel_index_loop_forder(dimensions.len, dimensions.ptr, + unravel_size, count, *dataptr, *strides, + coordsptr) != NPY_SUCCEED) { + goto fail; + } + coordsptr += count*dimensions.len; + } while(iternext(iter)); + } + } + else { + PyErr_SetString(PyExc_ValueError, + "only 'C' or 'F' order is permitted"); + goto fail; + } + + /* Now make a tuple of views, one per coordinate */ + ret_tuple = PyTuple_New(dimensions.len); + if (ret_tuple == NULL) { + goto fail; + } + for (i = 0; i < dimensions.len; ++i) { + PyArrayObject *view; + + view = (PyArrayObject *)PyArray_New(&PyArray_Type, ret_ndim-1, + ret_dims, NPY_INTP, + ret_strides, + PyArray_BYTES(ret_arr) + i*sizeof(npy_intp), + 0, 0, NULL); + if (view == NULL) { + goto fail; + } + Py_INCREF(ret_arr); + view->base = (PyObject *)ret_arr; + PyTuple_SET_ITEM(ret_tuple, i, PyArray_Return(view)); + } + + Py_DECREF(ret_arr); + Py_XDECREF(indices); + PyDimMem_FREE(dimensions.ptr); + NpyIter_Deallocate(iter); + + return ret_tuple; + +fail: + Py_XDECREF(ret_tuple); + Py_XDECREF(ret_arr); + Py_XDECREF(dtype); + Py_XDECREF(indices); + if (dimensions.ptr) { + PyDimMem_FREE(dimensions.ptr); + } + if (iter != NULL) { + NpyIter_Deallocate(iter); + } + return NULL; +} static PyTypeObject *PyMemberDescr_TypePtr = NULL; @@ -889,6 +1401,7 @@ io_unpack(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds) return pack_or_unpack_bits(obj, axis, 1); } +/* The docstrings for many of these methods are in add_newdocs.py. */ static struct PyMethodDef methods[] = { {"_insert", (PyCFunction)arr_insert, METH_VARARGS | METH_KEYWORDS, arr_insert__doc__}, @@ -898,6 +1411,10 @@ static struct PyMethodDef methods[] = { METH_VARARGS | METH_KEYWORDS, NULL}, {"interp", (PyCFunction)arr_interp, METH_VARARGS | METH_KEYWORDS, NULL}, + {"ravel_coords", (PyCFunction)arr_ravel_coords, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"unravel_index", (PyCFunction)arr_unravel_index, + METH_VARARGS | METH_KEYWORDS, NULL}, {"add_docstring", (PyCFunction)arr_add_docstring, METH_VARARGS, NULL}, {"packbits", (PyCFunction)io_pack, diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index 29dbb7ae5..ed5af516f 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -83,7 +83,9 @@ class TestDataSourceOpen(TestCase): del self.ds def test_ValidHTTP(self): - assert self.ds.open(valid_httpurl()) + fh = self.ds.open(valid_httpurl()) + assert_(fh) + fh.close() def test_InvalidHTTP(self): url = invalid_httpurl() @@ -92,14 +94,16 @@ class TestDataSourceOpen(TestCase): self.ds.open(url) except IOError, e: # Regression test for bug fixed in r4342. - assert e.errno is None + assert_(e.errno is None) def test_InvalidHTTPCacheURLError(self): self.assertRaises(URLError, self.ds._cache, invalid_httpurl()) def test_ValidFile(self): local_file = valid_textfile(self.tmpdir) - assert self.ds.open(local_file) + fh = self.ds.open(local_file) + assert_(fh) + fh.close() def test_InvalidFile(self): invalid_file = invalid_textfile(self.tmpdir) @@ -150,7 +154,7 @@ class TestDataSourceExists(TestCase): del self.ds def test_ValidHTTP(self): - assert self.ds.exists(valid_httpurl()) + assert_(self.ds.exists(valid_httpurl())) def test_InvalidHTTP(self): self.assertEqual(self.ds.exists(invalid_httpurl()), False) @@ -158,11 +162,11 @@ class TestDataSourceExists(TestCase): def test_ValidFile(self): # Test valid file in destpath tmpfile = valid_textfile(self.tmpdir) - assert self.ds.exists(tmpfile) + assert_(self.ds.exists(tmpfile)) # Test valid local file not in destpath localdir = mkdtemp() tmpfile = valid_textfile(localdir) - assert self.ds.exists(tmpfile) + assert_(self.ds.exists(tmpfile)) rmtree(localdir) def test_InvalidFile(self): @@ -214,13 +218,13 @@ class TestDataSourceAbspath(TestCase): tmp_path = lambda x: os.path.abspath(self.ds.abspath(x)) - assert tmp_path(valid_httpurl()).startswith(self.tmpdir) - assert tmp_path(invalid_httpurl()).startswith(self.tmpdir) - assert tmp_path(tmpfile).startswith(self.tmpdir) - assert tmp_path(tmpfilename).startswith(self.tmpdir) + assert_(tmp_path(valid_httpurl()).startswith(self.tmpdir)) + assert_(tmp_path(invalid_httpurl()).startswith(self.tmpdir)) + assert_(tmp_path(tmpfile).startswith(self.tmpdir)) + assert_(tmp_path(tmpfilename).startswith(self.tmpdir)) for fn in malicious_files: - assert tmp_path(http_path+fn).startswith(self.tmpdir) - assert tmp_path(fn).startswith(self.tmpdir) + assert_(tmp_path(http_path+fn).startswith(self.tmpdir)) + assert_(tmp_path(fn).startswith(self.tmpdir)) def test_windows_os_sep(self): orig_os_sep = os.sep @@ -253,10 +257,10 @@ class TestRepositoryAbspath(TestCase): def test_sandboxing(self): tmp_path = lambda x: os.path.abspath(self.repos.abspath(x)) - assert tmp_path(valid_httpfile()).startswith(self.tmpdir) + assert_(tmp_path(valid_httpfile()).startswith(self.tmpdir)) for fn in malicious_files: - assert tmp_path(http_path+fn).startswith(self.tmpdir) - assert tmp_path(fn).startswith(self.tmpdir) + assert_(tmp_path(http_path+fn).startswith(self.tmpdir)) + assert_(tmp_path(fn).startswith(self.tmpdir)) def test_windows_os_sep(self): orig_os_sep = os.sep @@ -280,14 +284,14 @@ class TestRepositoryExists(TestCase): def test_ValidFile(self): # Create local temp file tmpfile = valid_textfile(self.tmpdir) - assert self.repos.exists(tmpfile) + assert_(self.repos.exists(tmpfile)) def test_InvalidFile(self): tmpfile = invalid_textfile(self.tmpdir) self.assertEqual(self.repos.exists(tmpfile), False) def test_RemoveHTTPFile(self): - assert self.repos.exists(valid_httpurl()) + assert_(self.repos.exists(valid_httpurl())) def test_CachedHTTPFile(self): localfile = valid_httpurl() @@ -298,7 +302,7 @@ class TestRepositoryExists(TestCase): local_path = os.path.join(self.repos._destpath, netloc) os.mkdir(local_path, 0700) tmpfile = valid_textfile(local_path) - assert self.repos.exists(tmpfile) + assert_(self.repos.exists(tmpfile)) class TestOpenFunc(TestCase): def setUp(self): @@ -310,9 +314,13 @@ class TestOpenFunc(TestCase): def test_DataSourceOpen(self): local_file = valid_textfile(self.tmpdir) # Test case where destpath is passed in - assert datasource.open(local_file, destpath=self.tmpdir) + fp = datasource.open(local_file, destpath=self.tmpdir) + assert_(fp) + fp.close() # Test case where default destpath is used - assert datasource.open(local_file) + fp = datasource.open(local_file) + assert_(fp) + fp.close() if __name__ == "__main__": diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index dac39cd50..907a27a8c 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -17,7 +17,7 @@ class TestAso(TestCase): assert_array_equal( c, ec ) vals, indices = unique( a, return_index=True ) - + ed = np.array( [2, 3, 0, 1] ) assert_array_equal(vals, ec) @@ -25,7 +25,7 @@ class TestAso(TestCase): vals, ind0, ind1 = unique( a, return_index=True, return_inverse=True ) - + ee = np.array( [2, 3, 0, 1, 0, 2, 3] ) assert_array_equal(vals, ec) @@ -53,21 +53,6 @@ class TestAso(TestCase): assert_array_equal([], intersect1d([],[])) - def test_intersect1d_nu( self ): - # This should be removed when intersect1d_nu is removed. - a = np.array( [5, 5, 7, 1, 2] ) - b = np.array( [2, 1, 4, 3, 3, 1, 5] ) - - ec = np.array( [1, 2, 5] ) - warnings.filterwarnings('ignore', message='\s*`intersect1d_nu` is deprecated!') - warnings.filterwarnings('ignore', message='\s*`unique1d` is deprecated!') - c = intersect1d_nu( a, b ) - assert_array_equal( c, ec ) - assert_array_equal([], intersect1d_nu([],[])) - warnings.filters.pop(0) - warnings.filters.pop(0) - - def test_setxor1d( self ): a = np.array( [5, 7, 1, 2] ) b = np.array( [2, 4, 3, 1, 5] ) @@ -104,30 +89,6 @@ class TestAso(TestCase): assert_array_equal([],ediff1d(one_elem)) assert_array_equal([1],ediff1d(two_elem)) - def test_setmember1d( self ): - # This should be removed when setmember1d is removed. - a = np.array( [5, 7, 1, 2] ) - b = np.array( [2, 4, 3, 1, 5] ) - - ec = np.array( [True, False, True, True] ) - warnings.filterwarnings('ignore', '\s*`setmember1d` is deprecated!') - c = setmember1d( a, b ) - - assert_array_equal( c, ec ) - - a[0] = 8 - ec = np.array( [False, False, True, True] ) - c = setmember1d( a, b ) - assert_array_equal( c, ec ) - - a[0], a[3] = 4, 8 - ec = np.array( [True, False, True, False] ) - c = setmember1d( a, b ) - assert_array_equal( c, ec ) - - assert_array_equal([], setmember1d([],[])) - warnings.filters.pop(0) - def test_in1d(self): a = np.array( [5, 7, 1, 2] ) b = np.array( [2, 4, 3, 1, 5] ) @@ -145,7 +106,7 @@ class TestAso(TestCase): ec = np.array( [True, False, True, False] ) c = in1d( a, b, assume_unique=True ) assert_array_equal( c, ec ) - + a = np.array([5,4,5,3,4,4,3,4,3,5,2,1,5,5]) b = [2,3,4] diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index 2e6935141..ff8e93704 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -463,7 +463,7 @@ def test_memmap_roundtrip(): # Check that reading the file using memmap works. ma = format.open_memmap(nfn, mode='r') #yield assert_array_equal, ma, arr - #del ma + del ma def test_write_version_1_0(): diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 4df13e5f9..13930c79e 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -13,13 +13,13 @@ class TestAny(TestCase): y1 = [0, 0, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 0, 1, 0] - assert(any(y1)) - assert(any(y3)) - assert(not any(y2)) + assert_(any(y1)) + assert_(any(y3)) + assert_(not any(y2)) def test_nd(self): y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]] - assert(any(y1)) + assert_(any(y1)) assert_array_equal(sometrue(y1, axis=0), [1, 1, 0]) assert_array_equal(sometrue(y1, axis=1), [0, 1, 1]) @@ -29,14 +29,14 @@ class TestAll(TestCase): y1 = [0, 1, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 1, 1, 1] - assert(not all(y1)) - assert(all(y3)) - assert(not all(y2)) - assert(all(~array(y2))) + assert_(not all(y1)) + assert_(all(y3)) + assert_(not all(y2)) + assert_(all(~array(y2))) def test_nd(self): y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]] - assert(not all(y1)) + assert_(not all(y1)) assert_array_equal(alltrue(y1, axis=0), [0, 0, 1]) assert_array_equal(alltrue(y1, axis=1), [0, 0, 1]) @@ -44,11 +44,11 @@ class TestAll(TestCase): class TestAverage(TestCase): def test_basic(self): y1 = array([1, 2, 3]) - assert(average(y1, axis=0) == 2.) + assert_(average(y1, axis=0) == 2.) y2 = array([1., 2., 3.]) - assert(average(y2, axis=0) == 2.) + assert_(average(y2, axis=0) == 2.) y3 = [0., 0., 0.] - assert(average(y3, axis=0) == 0.) + assert_(average(y3, axis=0) == 0.) y4 = ones((4, 4)) y4[0, 1] = 0 @@ -407,7 +407,7 @@ class TestDigitize(TestCase): def test_random(self): x = rand(10) bin = linspace(x.min(), x.max(), 10) - assert all(digitize(x, bin) != 0) + assert_(all(digitize(x, bin) != 0)) class TestUnwrap(TestCase): @@ -415,7 +415,7 @@ class TestUnwrap(TestCase): #check that unwrap removes jumps greather that 2*pi assert_array_equal(unwrap([1, 1 + 2 * pi]), [1, 1]) #check that unwrap maintans continuity - assert(all(diff(unwrap(rand(10) * 100)) < pi)) + assert_(all(diff(unwrap(rand(10) * 100)) < pi)) class TestFilterwindows(TestCase): @@ -520,7 +520,7 @@ class TestTrapz(TestCase): class TestSinc(TestCase): def test_simple(self): - assert(sinc(0) == 1) + assert_(sinc(0) == 1) w = sinc(linspace(-1, 1, 100)) #check symmetry assert_array_almost_equal(w, flipud(w), 7) @@ -565,7 +565,7 @@ class TestHistogram(TestCase): area = sum(a * diff(b)) assert_almost_equal(area, 1) - warnings.filterwarnings('ignore', + warnings.filterwarnings('ignore', message="\s*This release of NumPy fixes a normalization bug") # Check with non-constant bin widths v = np.arange(10) @@ -573,20 +573,20 @@ class TestHistogram(TestCase): a, b = histogram(v, bins, normed=True) assert_array_equal(a, .1) assert_equal(sum(a*diff(b)), 1) - + # Variale bin widths are especially useful to deal with # infinities. v = np.arange(10) bins = [0,1,3,6,np.inf] a, b = histogram(v, bins, normed=True) assert_array_equal(a, [.1,.1,.1,0.]) - + # Taken from a bug report from N. Becker on the numpy-discussion - # mailing list Aug. 6, 2010. + # mailing list Aug. 6, 2010. counts, dmy = np.histogram([1,2,3,4], [0.5,1.5,np.inf], normed=True) assert_equal(counts, [.25, 0]) warnings.filters.pop(0) - + def test_outliers(self): # Check that outliers are not tallied a = arange(10) + .5 @@ -615,16 +615,16 @@ class TestHistogram(TestCase): # Check the type of the returned histogram a = arange(10) + .5 h, b = histogram(a) - assert(issubdtype(h.dtype, int)) + assert_(issubdtype(h.dtype, int)) h, b = histogram(a, normed=True) - assert(issubdtype(h.dtype, float)) + assert_(issubdtype(h.dtype, float)) h, b = histogram(a, weights=ones(10, int)) - assert(issubdtype(h.dtype, int)) + assert_(issubdtype(h.dtype, int)) h, b = histogram(a, weights=ones(10, float)) - assert(issubdtype(h.dtype, float)) + assert_(issubdtype(h.dtype, float)) def test_weights(self): v = rand(100) @@ -655,7 +655,7 @@ class TestHistogram(TestCase): weights=[2,1,1,1,1,1,1,1,1], normed=True) assert_almost_equal(a, [.2, .1, .1, .075]) warnings.filters.pop(0) - + class TestHistogramdd(TestCase): def test_simple(self): @@ -668,7 +668,7 @@ class TestHistogramdd(TestCase): # Check normalization ed = [[-2, 0, 2], [0, 1, 2, 3], [0, 1, 2, 3]] H, edges = histogramdd(x, bins=ed, normed=True) - assert(all(H == answer / 12.)) + assert_(all(H == answer / 12.)) # Check that H has the correct shape. H, edges = histogramdd(x, (2, 3, 4), range=[[-1, 1], [0, 3], [0, 4]], normed=True) @@ -697,7 +697,7 @@ class TestHistogramdd(TestCase): r = rand(10, 3) for b in bins: H, edges = histogramdd(r, b) - assert(H.shape == b) + assert_(H.shape == b) def test_shape_4d(self): # All possible permutations for bins of different lengths in 4D. @@ -711,7 +711,7 @@ class TestHistogramdd(TestCase): r = rand(10, 4) for b in bins: H, edges = histogramdd(r, b) - assert(H.shape == b) + assert_(H.shape == b) def test_weights(self): v = rand(100, 2) @@ -733,12 +733,12 @@ class TestHistogramdd(TestCase): class TestUnique(TestCase): def test_simple(self): x = array([4, 3, 2, 1, 1, 2, 3, 4, 0]) - assert(all(unique(x) == [0, 1, 2, 3, 4])) - assert(unique(array([1, 1, 1, 1, 1])) == array([1])) + assert_(all(unique(x) == [0, 1, 2, 3, 4])) + assert_(unique(array([1, 1, 1, 1, 1])) == array([1])) x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham'] - assert(all(unique(x) == ['bar', 'foo', 'ham', 'widget'])) + assert_(all(unique(x) == ['bar', 'foo', 'ham', 'widget'])) x = array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j]) - assert(all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10])) + assert_(all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10])) class TestCheckFinite(TestCase): @@ -792,7 +792,7 @@ class TestNaNFuncts(TestCase): array([[ 0.01319214, 0.11704017, 0.1630199 ], [ 0.37910852, 0.87964135, 0.34306596], [ 0.72687499, 0.23913896, 0.33850425]])) - assert nanmin([nan, nan]) is nan + assert_(np.isnan(nanmin([nan, nan]))) def test_nanargmin(self): assert_almost_equal(nanargmin(self.A), 1) @@ -823,6 +823,7 @@ class TestNaNFuncts(TestCase): array([[ 0.01620964, 0.75157887, 0.28333658], [ 0.59541557, 0.87964135, 0.70543747], [ 0.91084584, 0.84386844, 0.37068164]])) + assert_(np.isnan(nanmax([nan, nan]))) def test_nanmin_allnan_on_axis(self): assert_array_equal(isnan(nanmin([[nan] * 2] * 3, axis=1)), @@ -923,7 +924,7 @@ class Test_i0(TestCase): class TestKaiser(TestCase): def test_simple(self): assert_almost_equal(kaiser(0, 1.0), array([])) - assert isfinite(kaiser(1, 1.0)) + assert_(isfinite(kaiser(1, 1.0))) assert_almost_equal(kaiser(2, 1.0), array([ 0.78984831, 0.78984831])) assert_almost_equal(kaiser(5, 1.0), array([ 0.78984831, 0.94503323, 1. , @@ -950,14 +951,14 @@ class TestMsort(TestCase): class TestMeshgrid(TestCase): def test_simple(self): [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7]) - assert all(X == array([[1, 2, 3], + assert_(all(X == array([[1, 2, 3], [1, 2, 3], [1, 2, 3], - [1, 2, 3]])) - assert all(Y == array([[4, 4, 4], + [1, 2, 3]]))) + assert_(all(Y == array([[4, 4, 4], [5, 5, 5], [6, 6, 6], - [7, 7, 7]])) + [7, 7, 7]]))) class TestPiecewise(TestCase): @@ -1001,8 +1002,8 @@ class TestPiecewise(TestCase): def test_0d(self): x = array(3) y = piecewise(x, x > 3, [4, 0]) - assert y.ndim == 0 - assert y == 0 + assert_(y.ndim == 0) + assert_(y == 0) class TestBincount(TestCase): @@ -1026,6 +1027,21 @@ class TestBincount(TestCase): y = np.bincount(x, w) assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1])) + def test_with_minlength(self): + x = np.array([0, 1, 0, 1, 1]) + y = np.bincount(x, minlength=3) + assert_array_equal(y, np.array([2, 3, 0])) + + def test_with_minlength_smaller_than_maxvalue(self): + x = np.array([0, 1, 1, 2, 2, 3, 3]) + y = np.bincount(x, minlength=2) + assert_array_equal(y, np.array([1, 2, 2, 2])) + + def test_with_minlength_and_weights(self): + x = np.array([1, 2, 4, 5, 2]) + w = np.array([0.2, 0.3, 0.5, 0.1, 0.2]) + y = np.bincount(x, w, 8) + assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0])) class TestInterp(TestCase): def test_exceptions(self): diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py index c17ee5d6a..40f75936e 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -4,12 +4,69 @@ from numpy import ( array, ones, r_, mgrid, unravel_index, zeros, where, ndenumerate, fill_diagonal, diag_indices, diag_indices_from, s_, index_exp ) -class TestUnravelIndex(TestCase): +class TestRavelUnravelIndex(TestCase): def test_basic(self): - assert unravel_index(2,(2,2)) == (1,0) - assert unravel_index(254,(17,94)) == (2, 66) - assert_raises(ValueError, unravel_index, 4,(2,2)) - + assert_equal(np.unravel_index(2,(2,2)), (1,0)) + assert_equal(np.ravel_coords((1,0),(2,2)), 2) + assert_equal(np.unravel_index(254,(17,94)), (2,66)) + assert_equal(np.ravel_coords((2,66),(17,94)), 254) + assert_raises(ValueError, np.unravel_index, -1, (2,2)) + assert_raises(TypeError, np.unravel_index, 0.5, (2,2)) + assert_raises(ValueError, np.unravel_index, 4, (2,2)) + assert_raises(ValueError, np.ravel_coords, (-3,1), (2,2)) + assert_raises(ValueError, np.ravel_coords, (2,1), (2,2)) + assert_raises(ValueError, np.ravel_coords, (0,-3), (2,2)) + assert_raises(ValueError, np.ravel_coords, (0,2), (2,2)) + assert_raises(TypeError, np.ravel_coords, (0.1,0.), (2,2)) + + assert_equal(np.unravel_index((2*3 + 1)*6 + 4, (4,3,6)), [2,1,4]) + assert_equal(np.ravel_coords([2,1,4], (4,3,6)), (2*3 + 1)*6 + 4) + + arr = np.array([[3,6,6],[4,5,1]]) + assert_equal(np.ravel_coords(arr, (7,6)), [22,41,37]) + assert_equal(np.ravel_coords(arr, (7,6), order='F'), [31,41,13]) + assert_equal(np.ravel_coords(arr, (4,6), mode='clip'), [22,23,19]) + assert_equal(np.ravel_coords(arr, (4,4), mode=('clip','wrap')), + [12,13,13]) + assert_equal(np.ravel_coords((3,1,4,1), (6,7,8,9)), 1621) + + assert_equal(np.unravel_index(np.array([22, 41, 37]), (7,6)), + [[3, 6, 6],[4, 5, 1]]) + assert_equal(np.unravel_index(np.array([31, 41, 13]), (7,6), order='F'), + [[3, 6, 6], [4, 5, 1]]) + assert_equal(np.unravel_index(1621, (6,7,8,9)), [3,1,4,1]) + + def test_dtypes(self): + # Test with different data types + for dtype in [np.int16, np.uint16, np.int32, + np.uint32, np.int64, np.uint64]: + coords = np.array([[1,0,1,2,3,4],[1,6,1,3,2,0]], dtype=dtype) + shape = (5,8) + uncoords = 8*coords[0]+coords[1] + assert_equal(np.ravel_coords(coords, shape), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape)) + uncoords = coords[0]+5*coords[1] + assert_equal(np.ravel_coords(coords, shape, order='F'), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) + + coords = np.array([[1,0,1,2,3,4],[1,6,1,3,2,0],[1,3,1,0,9,5]], + dtype=dtype) + shape = (5,8,10) + uncoords = 10*(8*coords[0]+coords[1])+coords[2] + assert_equal(np.ravel_coords(coords, shape), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape)) + uncoords = coords[0]+5*(coords[1]+8*coords[2]) + assert_equal(np.ravel_coords(coords, shape, order='F'), uncoords) + assert_equal(coords, np.unravel_index(uncoords, shape, order='F')) + + def test_clipmodes(self): + # Test clipmodes + assert_equal(np.ravel_coords([5,1,-1,2], (4,3,7,12), mode='wrap'), + np.ravel_coords([1,1,6,2], (4,3,7,12))) + assert_equal(np.ravel_coords([5,1,-1,2], (4,3,7,12), + mode=('wrap','raise','clip','raise')), + np.ravel_coords([1,1,0,2], (4,3,7,12))) + assert_raises(ValueError, np.ravel_coords, [5,1,-1,2], (4,3,7,12)) class TestGrid(TestCase): def test_basic(self): diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index a85b01909..5001f6bac 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -381,6 +381,15 @@ class TestLoadTxt(TestCase): dtype=dt) assert_array_equal(x, a) + def test_3d_shaped_dtype(self): + c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12") + dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), + ('block', int, (2, 2, 3))]) + x = np.loadtxt(c, dtype=dt) + a = np.array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])], + dtype=dt) + assert_array_equal(x, a) + def test_empty_file(self): c = StringIO() assert_raises(IOError, np.loadtxt, c) @@ -884,7 +893,6 @@ M 33 21.99 dtype=dt) assert_array_equal(x, a) - def test_withmissing(self): data = StringIO('A,B\n0,1\n2,N/A') kwargs = dict(delimiter=",", missing_values="N/A", names=True) @@ -1042,7 +1050,7 @@ M 33 21.99 converters = {4: lambda x:"(%s)" % x} kwargs = dict(delimiter=",", converters=converters, dtype=[(_, int) for _ in 'abcde'],) - assert_raises(TypeError, np.genfromtxt, mdata, **kwargs) + assert_raises(ValueError, np.genfromtxt, mdata, **kwargs) def test_default_field_format(self): diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py index 227413c19..2dbffa0b8 100644 --- a/numpy/lib/tests/test_polynomial.py +++ b/numpy/lib/tests/test_polynomial.py @@ -1,23 +1,20 @@ """ ->>> import numpy.core as nx ->>> from numpy.lib.polynomial import poly1d, polydiv - ->>> p = poly1d([1.,2,3]) +>>> p = np.poly1d([1.,2,3]) >>> p poly1d([ 1., 2., 3.]) >>> print(p) 2 1 x + 2 x + 3 ->>> q = poly1d([3.,2,1]) +>>> q = np.poly1d([3.,2,1]) >>> q poly1d([ 3., 2., 1.]) >>> print(q) 2 3 x + 2 x + 1 ->>> print(poly1d([1.89999+2j, -3j, -5.12345678, 2+1j])) +>>> print(np.poly1d([1.89999+2j, -3j, -5.12345678, 2+1j])) 3 2 (1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j) ->>> print(poly1d([-3, -2, -1])) +>>> print(np.poly1d([-3, -2, -1])) 2 -3 x - 2 x - 1 @@ -46,7 +43,7 @@ poly1d([ 9., 12., 16., 8., 6.]) >>> q(p) poly1d([ 3., 12., 32., 40., 34.]) ->>> nx.asarray(p) +>>> np.asarray(p) array([ 1., 2., 3.]) >>> len(p) 2 @@ -66,16 +63,16 @@ poly1d([ 2., 2.]) >>> p.deriv(2) poly1d([ 2.]) ->>> q = poly1d([1.,2,3], variable='y') +>>> q = np.poly1d([1.,2,3], variable='y') >>> print(q) 2 1 y + 2 y + 3 ->>> q = poly1d([1.,2,3], variable='lambda') +>>> q = np.poly1d([1.,2,3], variable='lambda') >>> print(q) 2 1 lambda + 2 lambda + 3 ->>> polydiv(poly1d([1,0,-1]), poly1d([1,1])) +>>> np.polydiv(np.poly1d([1,0,-1]), np.poly1d([1,1])) (poly1d([ 1., -1.]), poly1d([ 0.])) """ diff --git a/numpy/lib/tests/test_recfunctions.py b/numpy/lib/tests/test_recfunctions.py index 0a22e2a34..14af43a59 100644 --- a/numpy/lib/tests/test_recfunctions.py +++ b/numpy/lib/tests/test_recfunctions.py @@ -540,13 +540,17 @@ class TestStackArrays(TestCase): class TestJoinBy(TestCase): + def setUp(self): + self.a = np.array(zip(np.arange(10), np.arange(50, 60), + np.arange(100, 110)), + dtype=[('a', int), ('b', int), ('c', int)]) + self.b = np.array(zip(np.arange(5, 15), np.arange(65, 75), + np.arange(100, 110)), + dtype=[('a', int), ('b', int), ('d', int)]) # - def test_base(self): + def test_inner_join(self): "Basic test of join_by" - a = np.array(zip(np.arange(10), np.arange(50, 60), np.arange(100, 110)), - dtype=[('a', int), ('b', int), ('c', int)]) - b = np.array(zip(np.arange(5, 15), np.arange(65, 75), np.arange(100, 110)), - dtype=[('a', int), ('b', int), ('d', int)]) + a, b = self.a, self.b # test = join_by('a', a, b, jointype='inner') control = np.array([(5, 55, 65, 105, 100), (6, 56, 66, 106, 101), @@ -555,6 +559,9 @@ class TestJoinBy(TestCase): dtype=[('a', int), ('b1', int), ('b2', int), ('c', int), ('d', int)]) assert_equal(test, control) + + def test_join(self): + a, b = self.a, self.b # test = join_by(('a', 'b'), a, b) control = np.array([(5, 55, 105, 100), (6, 56, 106, 101), @@ -562,6 +569,9 @@ class TestJoinBy(TestCase): (9, 59, 109, 104)], dtype=[('a', int), ('b', int), ('c', int), ('d', int)]) + + def test_outer_join(self): + a, b = self.a, self.b # test = join_by(('a', 'b'), a, b, 'outer') control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1), @@ -587,6 +597,9 @@ class TestJoinBy(TestCase): dtype=[('a', int), ('b', int), ('c', int), ('d', int)]) assert_equal(test, control) + + def test_leftouter_join(self): + a, b = self.a, self.b # test = join_by(('a', 'b'), a, b, 'leftouter') control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1), diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index a67355957..ea4d75f6b 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -70,8 +70,8 @@ class TestRegression(TestCase): """Ticket #554""" x = np.poly1d([1,2,3]) y = np.poly1d([3,4]) - assert x != y - assert x == x + assert_(x != y) + assert_(x == x) def test_mem_insert(self, level=rlevel): """Ticket #572""" @@ -152,34 +152,34 @@ class TestRegression(TestCase): def test_void_coercion(self, level=rlevel): dt = np.dtype([('a','f4'),('b','i4')]) x = np.zeros((1,),dt) - assert(np.r_[x,x].dtype == dt) + assert_(np.r_[x,x].dtype == dt) def test_who_with_0dim_array(self, level=rlevel) : """ticket #1243""" import os, sys + oldstdout = sys.stdout sys.stdout = open(os.devnull, 'w') - try : - tmp = np.who({'foo' : np.array(1)}) - sys.stdout = sys.__stdout__ - except : - sys.stdout = sys.__stdout__ - raise AssertionError("ticket #1243") + try: + try: + tmp = np.who({'foo' : np.array(1)}) + except: + raise AssertionError("ticket #1243") + finally: + sys.stdout = oldstdout def test_bincount_empty(self): """Ticket #1387: empty array as input for bincount.""" assert_raises(ValueError, lambda : np.bincount(np.array([], dtype=np.intp))) - @dec.deprecated() def test_include_dirs(self): """As a sanity check, just test that get_include and get_numarray_include include something reasonable. Somewhat related to ticket #1405.""" - include_dirs = [np.get_include(), np.get_numarray_include(), - np.get_numpy_include()] + include_dirs = [np.get_include(), np.get_numarray_include()] for path in include_dirs: - assert isinstance(path, (str, unicode)) - assert path != '' + assert_(isinstance(path, (str, unicode))) + assert_(path != '') def test_polyder_return_type(self): """Ticket #1249""" diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py index 888c60420..941768aa5 100644 --- a/numpy/lib/tests/test_type_check.py +++ b/numpy/lib/tests/test_type_check.py @@ -3,6 +3,13 @@ from numpy.lib import * from numpy.core import * from numpy.compat import asbytes +try: + import ctypes + _HAS_CTYPE = True +except ImportError: + _HAS_CTYPE = False + + def assert_all(x): assert(all(x)), x @@ -375,9 +382,9 @@ class TestArrayConversion(TestCase): assert_equal(a.__class__,ndarray) assert issubdtype(a.dtype,float) - class TestDateTimeData: + @dec.skipif(not _HAS_CTYPE, "ctypes not available on this python installation") def test_basic(self): a = array(['1980-03-23'], dtype=datetime64) assert_equal(datetime_data(a.dtype), (asbytes('us'), 1, 1, 1)) diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py index e9c41d09c..29b47f257 100644 --- a/numpy/lib/tests/test_ufunclike.py +++ b/numpy/lib/tests/test_ufunclike.py @@ -27,17 +27,6 @@ class TestUfunclike(TestCase): assert_equal(res, tgt) assert_equal(out, tgt) - @deprecated() - def test_log2(self): - a = nx.array([4.5, 2.3, 6.5]) - out = nx.zeros(a.shape, float) - tgt = nx.array([2.169925, 1.20163386, 2.70043972]) - res = ufl.log2(a) - assert_almost_equal(res, tgt) - res = ufl.log2(a, out) - assert_almost_equal(res, tgt) - assert_almost_equal(out, tgt) - def test_fix(self): a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]]) out = nx.zeros(a.shape, float) @@ -64,7 +53,7 @@ class TestUfunclike(TestCase): m = MyArray(a, metadata='foo') f = ufl.fix(m) assert_array_equal(f, nx.array([1,-1])) - assert isinstance(f, MyArray) + assert_(isinstance(f, MyArray)) assert_equal(f.metadata, 'foo') if __name__ == "__main__": diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 8f81fe4b2..b51365f41 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -172,45 +172,3 @@ def isneginf(x, y=None): y = nx.empty(x.shape, dtype=nx.bool_) nx.logical_and(nx.isinf(x), nx.signbit(x), y) return y - - -_log2 = nx.log(2) -def log2(x, y=None): - """ - Return the base 2 logarithm of the input array, element-wise. - This function is now deprecated, use the np.log2 ufunc instead. - - Parameters - ---------- - x : array_like - Input array. - y : array_like - Optional output array with the same shape as `x`. - - Returns - ------- - y : ndarray - The logarithm to the base 2 of `x` element-wise. - NaNs are returned where `x` is negative. - - See Also - -------- - log, log1p, log10 - - Examples - -------- - >>> np.log2([-1, 2, 4]) - array([ NaN, 1., 2.]) - - """ - import warnings - msg = "numpy.lib.log2 is deprecated, use np.log2 instead." - warnings.warn(msg, DeprecationWarning) - - x = nx.asanyarray(x) - if y is None: - y = nx.log(x) - else: - nx.log(x, y) - y /= _log2 - return y diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index fb597a7ed..1e7364adc 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -6,7 +6,7 @@ import re from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype from numpy.core import product, ndarray, ufunc -__all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', +__all__ = ['issubclass_', 'issubsctype', 'issubdtype', 'deprecate', 'deprecate_with_doc', 'get_numarray_include', 'get_include', 'info', 'source', 'who', 'lookfor', 'byte_bounds', 'may_share_memory', 'safe_eval'] @@ -215,7 +215,6 @@ def deprecate(*args, **kwargs): return _Deprecate(*args, **kwargs) deprecate_with_doc = lambda msg: _Deprecate(message=msg) -get_numpy_include = deprecate(get_include, 'get_numpy_include', 'get_include') #-------------------------------------------- |