diff options
Diffstat (limited to 'numpy')
34 files changed, 270 insertions, 164 deletions
diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py index f5ac3f9f8..4607d9502 100644 --- a/numpy/compat/py3k.py +++ b/numpy/compat/py3k.py @@ -36,7 +36,7 @@ if sys.version_info[0] >= 3: return str(s) def isfileobj(f): - return isinstance(f, (io.FileIO, io.BufferedReader)) + return isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)) def open_latin1(filename, mode='r'): return open(filename, mode=mode, encoding='iso-8859-1') diff --git a/numpy/compat/tests/test_compat.py b/numpy/compat/tests/test_compat.py new file mode 100644 index 000000000..3df142e04 --- /dev/null +++ b/numpy/compat/tests/test_compat.py @@ -0,0 +1,19 @@ +from os.path import join + +from numpy.compat import isfileobj +from numpy.testing import TestCase, assert_ +from numpy.testing.utils import tempdir + + +def test_isfileobj(): + with tempdir(prefix="numpy_test_compat_") as folder: + filename = join(folder, 'a.bin') + + with open(filename, 'wb') as f: + assert_(isfileobj(f)) + + with open(filename, 'ab') as f: + assert_(isfileobj(f)) + + with open(filename, 'rb') as f: + assert_(isfileobj(f)) diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index 79bc72a8c..0b8d5bb17 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -52,7 +52,11 @@ bench = Tester().bench # The name numpy.core._ufunc_reconstruct must be # available for unpickling to work. def _ufunc_reconstruct(module, name): - mod = __import__(module) + # The `fromlist` kwarg is required to ensure that `mod` points to the + # inner-most module rather than the parent package when module name is + # nested. This makes it possible to pickle non-toplevel ufuncs such as + # scipy.special.expit for instance. + mod = __import__(module, fromlist=[name]) return getattr(mod, name) def _ufunc_reduce(func): diff --git a/numpy/core/code_generators/cversions.txt b/numpy/core/code_generators/cversions.txt index d62115224..acfced812 100644 --- a/numpy/core/code_generators/cversions.txt +++ b/numpy/core/code_generators/cversions.txt @@ -28,4 +28,4 @@ # Version 9 (NumPy 1.9) Added function annotations. # The interface has not changed, but the hash is different due to # the annotations, so keep the previous version number. -0x00000009 = 49b27dc2dc7206a775a7376fdbc3b80c +0x00000009 = 982c4ebb6e7e4c194bf46b1535b4ef1b diff --git a/numpy/core/code_generators/genapi.py b/numpy/core/code_generators/genapi.py index 5ab60a37c..84bd042f5 100644 --- a/numpy/core/code_generators/genapi.py +++ b/numpy/core/code_generators/genapi.py @@ -473,9 +473,9 @@ def fullapi_hash(api_dicts): of the list of items in the API (as a string).""" a = [] for d in api_dicts: - for name, index in order_dict(d): + for name, data in order_dict(d): a.extend(name) - a.extend(str(index)) + a.extend(','.join(map(str, data))) return md5new(''.join(a).encode('ascii')).hexdigest() diff --git a/numpy/core/code_generators/generate_numpy_api.py b/numpy/core/code_generators/generate_numpy_api.py index a590cfb48..415cbf7fc 100644 --- a/numpy/core/code_generators/generate_numpy_api.py +++ b/numpy/core/code_generators/generate_numpy_api.py @@ -8,8 +8,9 @@ from genapi import \ import numpy_api +# use annotated api when running under cpychecker h_template = r""" -#ifdef _MULTIARRAYMODULE +#if defined(_MULTIARRAYMODULE) || defined(WITH_CPYCHECKER_STEALS_REFERENCE_TO_ARG_ATTRIBUTE) typedef struct { PyObject_HEAD diff --git a/numpy/core/include/numpy/ufuncobject.h b/numpy/core/include/numpy/ufuncobject.h index 38e3dcf0f..a24a0d837 100644 --- a/numpy/core/include/numpy/ufuncobject.h +++ b/numpy/core/include/numpy/ufuncobject.h @@ -152,13 +152,13 @@ typedef struct _tagPyUFuncObject { int check_return; /* The name of the ufunc */ - char *name; + const char *name; /* Array of type numbers, of size ('nargs' * 'ntypes') */ char *types; /* Documentation string */ - char *doc; + const char *doc; void *ptr; PyObject *obj; diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index a85e8514c..12e690f1e 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -6,9 +6,11 @@ import warnings import collections from . import multiarray from . import umath -from .umath import * +from .umath import (invert, sin, UFUNC_BUFSIZE_DEFAULT, ERR_IGNORE, + ERR_WARN, ERR_RAISE, ERR_CALL, ERR_PRINT, ERR_LOG, + ERR_DEFAULT, PINF, NAN) from . import numerictypes -from .numerictypes import * +from .numerictypes import longlong, intc, int_, float_, complex_, bool_ if sys.version_info[0] >= 3: import pickle @@ -356,9 +358,6 @@ def extend_all(module): if a not in adict: __all__.append(a) -extend_all(umath) -extend_all(numerictypes) - newaxis = None @@ -2832,6 +2831,10 @@ nan = NaN = NAN False_ = bool_(False) True_ = bool_(True) +from .umath import * +from .numerictypes import * from . import fromnumeric from .fromnumeric import * extend_all(fromnumeric) +extend_all(umath) +extend_all(numerictypes) diff --git a/numpy/core/src/multiarray/arraytypes.c.src b/numpy/core/src/multiarray/arraytypes.c.src index d2532ccf0..8a0b1826b 100644 --- a/numpy/core/src/multiarray/arraytypes.c.src +++ b/numpy/core/src/multiarray/arraytypes.c.src @@ -3922,7 +3922,8 @@ NPY_NO_EXPORT PyArray_Descr @from@_Descr = { /* elsize */ @num@ * sizeof(@fromtype@), /* alignment */ - @num@ * _ALIGN(@fromtype@), + @num@ * _ALIGN(@fromtype@) > NPY_MAX_COPY_ALIGNMENT ? + NPY_MAX_COPY_ALIGNMENT : @num@ * _ALIGN(@fromtype@), /* subarray */ NULL, /* fields */ @@ -4264,7 +4265,8 @@ set_typeinfo(PyObject *dict) #endif NPY_@name@, NPY_BITSOF_@name@, - @num@ * _ALIGN(@type@), + @num@ * _ALIGN(@type@) > NPY_MAX_COPY_ALIGNMENT ? + NPY_MAX_COPY_ALIGNMENT : @num@ * _ALIGN(@type@), (PyObject *) &Py@Name@ArrType_Type)); Py_DECREF(s); diff --git a/numpy/core/src/multiarray/common.c b/numpy/core/src/multiarray/common.c index 2b3d3c3d2..54b9e3c1a 100644 --- a/numpy/core/src/multiarray/common.c +++ b/numpy/core/src/multiarray/common.c @@ -676,7 +676,7 @@ _IsAligned(PyArrayObject *ap) /* alignment 1 types should have a efficient alignment for copy loops */ if (PyArray_ISFLEXIBLE(ap) || PyArray_ISSTRING(ap)) { - alignment = 16; + alignment = NPY_MAX_COPY_ALIGNMENT; } if (alignment == 1) { diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index d93995c8a..3da2dfae7 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -1054,12 +1054,12 @@ PyArray_NewFromDescr_int(PyTypeObject *subtype, PyArray_Descr *descr, int nd, fa->data = data; /* - * If the strides were provided to the function, need to - * update the flags to get the right CONTIGUOUS, ALIGN properties + * always update the flags to get the right CONTIGUOUS, ALIGN properties + * not owned data and input strides may not be aligned and on some + * platforms (debian sparc) malloc does not provide enough alignment for + * long double types */ - if (strides != NULL) { - PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL); - } + PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL); /* * call the __array_finalize__ diff --git a/numpy/core/src/multiarray/lowlevel_strided_loops.c.src b/numpy/core/src/multiarray/lowlevel_strided_loops.c.src index b9063273f..38e7656f3 100644 --- a/numpy/core/src/multiarray/lowlevel_strided_loops.c.src +++ b/numpy/core/src/multiarray/lowlevel_strided_loops.c.src @@ -1490,7 +1490,9 @@ mapiter_@name@(PyArrayMapIterObject *mit) /* Constant information */ npy_intp fancy_dims[NPY_MAXDIMS]; npy_intp fancy_strides[NPY_MAXDIMS]; +#if @isget@ int iteraxis; +#endif char *baseoffset = mit->baseoffset; char **outer_ptrs = mit->outer_ptrs; @@ -1498,7 +1500,9 @@ mapiter_@name@(PyArrayMapIterObject *mit) PyArrayObject *array= mit->array; /* Fill constant information */ +#if @isget@ iteraxis = mit->iteraxes[0]; +#endif for (i = 0; i < numiter; i++) { fancy_dims[i] = mit->fancy_dims[i]; fancy_strides[i] = mit->fancy_strides[i]; diff --git a/numpy/core/src/multiarray/shape.c b/numpy/core/src/multiarray/shape.c index d5fde5b97..8b73f4709 100644 --- a/numpy/core/src/multiarray/shape.c +++ b/numpy/core/src/multiarray/shape.c @@ -776,7 +776,8 @@ PyArray_Transpose(PyArrayObject *ap, PyArray_Dims *permute) PyArray_DIMS(ret)[i] = PyArray_DIMS(ap)[permutation[i]]; PyArray_STRIDES(ret)[i] = PyArray_STRIDES(ap)[permutation[i]]; } - PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); + PyArray_UpdateFlags(ret, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS | + NPY_ARRAY_ALIGNED); return (PyObject *)ret; } diff --git a/numpy/core/src/npysort/selection.c.src b/numpy/core/src/npysort/selection.c.src index 920c07ec6..4167b2694 100644 --- a/numpy/core/src/npysort/selection.c.src +++ b/numpy/core/src/npysort/selection.c.src @@ -390,7 +390,10 @@ int /* move pivot into position */ SWAP(SORTEE(low), SORTEE(hh)); - store_pivot(hh, kth, pivots, npiv); + /* kth pivot stored later */ + if (hh != kth) { + store_pivot(hh, kth, pivots, npiv); + } if (hh >= kth) high = hh - 1; @@ -400,10 +403,11 @@ int /* two elements */ if (high == low + 1) { - if (@TYPE@_LT(v[IDX(high)], v[IDX(low)])) + if (@TYPE@_LT(v[IDX(high)], v[IDX(low)])) { SWAP(SORTEE(high), SORTEE(low)) - store_pivot(low, kth, pivots, npiv); + } } + store_pivot(kth, kth, pivots, npiv); return 0; } diff --git a/numpy/core/src/private/npy_config.h b/numpy/core/src/private/npy_config.h index 453dbd065..71d448ee9 100644 --- a/numpy/core/src/private/npy_config.h +++ b/numpy/core/src/private/npy_config.h @@ -10,6 +10,17 @@ #undef HAVE_HYPOT #endif +/* + * largest alignment the copy loops might require + * required as string, void and complex types might get copied using larger + * instructions than required to operate on them. E.g. complex float is copied + * in 8 byte moves but arithmetic on them only loads in 4 byte moves. + * the sparc platform may need that alignment for long doubles. + * amd64 is not harmed much by the bloat as the system provides 16 byte + * alignment by default. + */ +#define NPY_MAX_COPY_ALIGNMENT 16 + /* Safe to use ldexp and frexp for long double for MSVC builds */ #if (NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE) || defined(_MSC_VER) #ifdef HAVE_LDEXP diff --git a/numpy/core/src/private/ufunc_override.h b/numpy/core/src/private/ufunc_override.h index 6b0f73fcf..c47c46a66 100644 --- a/numpy/core/src/private/ufunc_override.h +++ b/numpy/core/src/private/ufunc_override.h @@ -26,6 +26,7 @@ normalize___call___args(PyUFuncObject *ufunc, PyObject *args, else { obj = PyTuple_GetSlice(args, nin, nargs); PyDict_SetItemString(*normal_kwds, "out", obj); + Py_DECREF(obj); } } } diff --git a/numpy/core/src/umath/loops.c.src b/numpy/core/src/umath/loops.c.src index 89f1206b4..035a27fd2 100644 --- a/numpy/core/src/umath/loops.c.src +++ b/numpy/core/src/umath/loops.c.src @@ -2572,6 +2572,7 @@ OBJECT_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUS return; } ret = PyObject_IsTrue(ret_obj); + Py_DECREF(ret_obj); if (ret == -1) { #if @identity@ != -1 if (in1 == in2) { @@ -2621,6 +2622,7 @@ OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED } ret = PyLong_FromLong(v); if (PyErr_Occurred()) { + Py_DECREF(zero); return; } Py_XDECREF(*out); @@ -2635,6 +2637,7 @@ OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED PyObject *ret = PyInt_FromLong( PyObject_Compare(in1 ? in1 : Py_None, zero)); if (PyErr_Occurred()) { + Py_DECREF(zero); return; } Py_XDECREF(*out); diff --git a/numpy/core/src/umath/ufunc_object.c b/numpy/core/src/umath/ufunc_object.c index d825f15e9..45966902b 100644 --- a/numpy/core/src/umath/ufunc_object.c +++ b/numpy/core/src/umath/ufunc_object.c @@ -73,7 +73,7 @@ static int _does_loop_use_arrays(void *data); static int -_extract_pyvals(PyObject *ref, char *name, int *bufsize, +_extract_pyvals(PyObject *ref, const char *name, int *bufsize, int *errmask, PyObject **errobj); static int @@ -237,7 +237,7 @@ static int PyUFunc_NUM_NODEFAULTS = 0; #endif static PyObject * -_get_global_ext_obj(char * name) +get_global_ext_obj(void) { PyObject *thedict; PyObject *ref = NULL; @@ -259,12 +259,12 @@ _get_global_ext_obj(char * name) static int -_get_bufsize_errmask(PyObject * extobj, char * ufunc_name, +_get_bufsize_errmask(PyObject * extobj, const char *ufunc_name, int *buffersize, int *errormask) { /* Get the buffersize and errormask */ if (extobj == NULL) { - extobj = _get_global_ext_obj(ufunc_name); + extobj = get_global_ext_obj(); } if (_extract_pyvals(extobj, ufunc_name, buffersize, errormask, NULL) < 0) { @@ -430,7 +430,7 @@ _find_array_prepare(PyObject *args, PyObject *kwds, * if an error handling method is 'call' */ static int -_extract_pyvals(PyObject *ref, char *name, int *bufsize, +_extract_pyvals(PyObject *ref, const char *name, int *bufsize, int *errmask, PyObject **errobj) { PyObject *retval; @@ -518,41 +518,41 @@ _extract_pyvals(PyObject *ref, char *name, int *bufsize, NPY_NO_EXPORT int PyUFunc_GetPyValues(char *name, int *bufsize, int *errmask, PyObject **errobj) { - PyObject *ref = _get_global_ext_obj(name); + PyObject *ref = get_global_ext_obj(); return _extract_pyvals(ref, name, bufsize, errmask, errobj); } -#define _GETATTR_(str, rstr) do {if (strcmp(name, #str) == 0) \ +#define GETATTR(str, rstr) do {if (strcmp(name, #str) == 0) \ return PyObject_HasAttrString(op, "__" #rstr "__");} while (0); static int -_has_reflected_op(PyObject *op, char *name) +_has_reflected_op(PyObject *op, const char *name) { - _GETATTR_(add, radd); - _GETATTR_(subtract, rsub); - _GETATTR_(multiply, rmul); - _GETATTR_(divide, rdiv); - _GETATTR_(true_divide, rtruediv); - _GETATTR_(floor_divide, rfloordiv); - _GETATTR_(remainder, rmod); - _GETATTR_(power, rpow); - _GETATTR_(left_shift, rlshift); - _GETATTR_(right_shift, rrshift); - _GETATTR_(bitwise_and, rand); - _GETATTR_(bitwise_xor, rxor); - _GETATTR_(bitwise_or, ror); + GETATTR(add, radd); + GETATTR(subtract, rsub); + GETATTR(multiply, rmul); + GETATTR(divide, rdiv); + GETATTR(true_divide, rtruediv); + GETATTR(floor_divide, rfloordiv); + GETATTR(remainder, rmod); + GETATTR(power, rpow); + GETATTR(left_shift, rlshift); + GETATTR(right_shift, rrshift); + GETATTR(bitwise_and, rand); + GETATTR(bitwise_xor, rxor); + GETATTR(bitwise_or, ror); /* Comparisons */ - _GETATTR_(equal, eq); - _GETATTR_(not_equal, ne); - _GETATTR_(greater, lt); - _GETATTR_(less, gt); - _GETATTR_(greater_equal, le); - _GETATTR_(less_equal, ge); + GETATTR(equal, eq); + GETATTR(not_equal, ne); + GETATTR(greater, lt); + GETATTR(less, gt); + GETATTR(greater_equal, le); + GETATTR(less_equal, ge); return 0; } -#undef _GETATTR_ +#undef GETATTR /* Return the position of next non-white-space char in the string */ @@ -779,7 +779,7 @@ static int get_ufunc_arguments(PyUFuncObject *ufunc, int i, nargs, nin = ufunc->nin; PyObject *obj, *context; PyObject *str_key_obj = NULL; - char *ufunc_name; + const char *ufunc_name; int type_num; int any_flexible = 0, any_object = 0, any_flexible_userloops = 0; @@ -1762,7 +1762,7 @@ make_arr_prep_args(npy_intp nin, PyObject *args, PyObject *kwds) * - ufunc_name: name of ufunc */ static int -_check_ufunc_fperr(int errmask, PyObject *extobj, char* ufunc_name) { +_check_ufunc_fperr(int errmask, PyObject *extobj, const char *ufunc_name) { int fperr; PyObject *errobj = NULL; int ret; @@ -1778,7 +1778,7 @@ _check_ufunc_fperr(int errmask, PyObject *extobj, char* ufunc_name) { /* Get error object globals */ if (extobj == NULL) { - extobj = _get_global_ext_obj(ufunc_name); + extobj = get_global_ext_obj(); } if (_extract_pyvals(extobj, ufunc_name, NULL, NULL, &errobj) < 0) { @@ -1800,7 +1800,7 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, { int nin, nout; int i, j, idim, nop; - char *ufunc_name; + const char *ufunc_name; int retval = -1, subok = 1; int needs_api = 0; @@ -2325,7 +2325,7 @@ PyUFunc_GenericFunction(PyUFuncObject *ufunc, { int nin, nout; int i, nop; - char *ufunc_name; + const char *ufunc_name; int retval = -1, subok = 1; int need_fancy = 0; @@ -2640,7 +2640,7 @@ reduce_type_resolver(PyUFuncObject *ufunc, PyArrayObject *arr, int i, retcode; PyArrayObject *op[3] = {arr, arr, NULL}; PyArray_Descr *dtypes[3] = {NULL, NULL, NULL}; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; PyObject *type_tup = NULL; *out_dtype = NULL; @@ -2816,7 +2816,7 @@ PyUFunc_Reduce(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, PyArray_Descr *dtype; PyArrayObject *result; PyArray_AssignReduceIdentityFunc *assign_identity = NULL; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* These parameters come from a TLS global */ int buffersize = 0, errormask = 0; @@ -2912,7 +2912,7 @@ PyUFunc_Accumulate(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *out, PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; /* These parameters come from extobj= or from a TLS global */ int buffersize = 0, errormask = 0; @@ -3265,7 +3265,7 @@ PyUFunc_Reduceat(PyUFuncObject *ufunc, PyArrayObject *arr, PyArrayObject *ind, PyUFuncGenericFunction innerloop = NULL; void *innerloopdata = NULL; - char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; + const char *ufunc_name = ufunc->name ? ufunc->name : "(unknown)"; char *opname = "reduceat"; /* These parameters come from extobj= or from a TLS global */ @@ -4305,7 +4305,7 @@ NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, - char *name, char *doc, int check_return) + const char *name, const char *doc, int check_return) { return PyUFunc_FromFuncAndDataAndSignature(func, data, types, ntypes, nin, nout, identity, name, doc, check_return, NULL); @@ -4316,7 +4316,7 @@ NPY_NO_EXPORT PyObject * PyUFunc_FromFuncAndDataAndSignature(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, int nin, int nout, int identity, - char *name, char *doc, + const char *name, const char *doc, int check_return, const char *signature) { PyUFuncObject *ufunc; diff --git a/numpy/core/src/umath/ufunc_type_resolution.c b/numpy/core/src/umath/ufunc_type_resolution.c index ffdb15bbe..3beb25cf1 100644 --- a/numpy/core/src/umath/ufunc_type_resolution.c +++ b/numpy/core/src/umath/ufunc_type_resolution.c @@ -58,7 +58,7 @@ PyUFunc_ValidateCasting(PyUFuncObject *ufunc, PyArray_Descr **dtypes) { int i, nin = ufunc->nin, nop = nin + ufunc->nout; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -186,7 +186,7 @@ PyUFunc_SimpleBinaryComparisonTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, type_num1, type_num2; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -292,7 +292,7 @@ PyUFunc_SimpleUnaryOperationTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, type_num1; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -433,7 +433,7 @@ PyUFunc_SimpleBinaryOperationTypeResolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, type_num1, type_num2; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -591,7 +591,7 @@ PyUFunc_AdditionTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -781,7 +781,7 @@ PyUFunc_SubtractionTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -963,7 +963,7 @@ PyUFunc_MultiplicationTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -1106,7 +1106,7 @@ PyUFunc_DivisionTypeResolver(PyUFuncObject *ufunc, { int type_num1, type_num2; int i; - char *ufunc_name; + const char *ufunc_name; ufunc_name = ufunc->name ? ufunc->name : "<unnamed ufunc>"; @@ -1875,7 +1875,7 @@ linear_search_type_resolver(PyUFuncObject *self, { npy_intp i, j, nin = self->nin, nop = nin + self->nout; int types[NPY_MAXARGS]; - char *ufunc_name; + const char *ufunc_name; int no_castable_output, use_min_scalar; /* For making a better error message on coercion error */ @@ -1984,7 +1984,7 @@ type_tuple_type_resolver(PyUFuncObject *self, npy_intp i, j, n, nin = self->nin, nop = nin + self->nout; int n_specified = 0; int specified_types[NPY_MAXARGS], types[NPY_MAXARGS]; - char *ufunc_name; + const char *ufunc_name; int no_castable_output, use_min_scalar; /* For making a better error message on coercion error */ diff --git a/numpy/core/src/umath/umathmodule.c b/numpy/core/src/umath/umathmodule.c index 3ed7ee771..741037a6b 100644 --- a/numpy/core/src/umath/umathmodule.c +++ b/numpy/core/src/umath/umathmodule.c @@ -54,16 +54,15 @@ object_ufunc_type_resolver(PyUFuncObject *ufunc, PyArray_Descr **out_dtypes) { int i, nop = ufunc->nin + ufunc->nout; - PyArray_Descr *obj_dtype; - obj_dtype = PyArray_DescrFromType(NPY_OBJECT); - if (obj_dtype == NULL) { + out_dtypes[0] = PyArray_DescrFromType(NPY_OBJECT); + if (out_dtypes[0] == NULL) { return -1; } - for (i = 0; i < nop; ++i) { - Py_INCREF(obj_dtype); - out_dtypes[i] = obj_dtype; + for (i = 1; i < nop; ++i) { + Py_INCREF(out_dtypes[0]); + out_dtypes[i] = out_dtypes[0]; } return 0; diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 2e40a2b7c..cb5c0095c 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -1356,6 +1356,12 @@ class TestMethods(TestCase): d[i:].partition(0, kind=k) assert_array_equal(d, tgt) + d = np.array([0, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 9]) + kth = [0, 3, 19, 20] + assert_equal(np.partition(d, kth, kind=k)[kth], (0, 3, 7, 7)) + assert_equal(d[np.argpartition(d, kth, kind=k)][kth], (0, 3, 7, 7)) + d = np.array([2, 1]) d.partition(0, kind=k) assert_raises(ValueError, d.partition, 2) @@ -1551,6 +1557,18 @@ class TestMethods(TestCase): assert_raises(ValueError, d.partition, 2, kind=k) assert_raises(ValueError, d.argpartition, 2, kind=k) + def test_partition_fuzz(self): + # a few rounds of random data testing + for j in range(10, 30): + for i in range(1, j - 2): + d = np.arange(j) + np.random.shuffle(d) + d = d % np.random.randint(2, 30) + idx = np.random.randint(d.size) + kth = [0, idx, i, i + 1] + tgt = np.sort(d)[kth] + assert_array_equal(np.partition(d, kth)[kth], tgt, + err_msg="data: %r\n kth: %r" % (d, kth)) def test_flatten(self): x0 = np.array([[1, 2, 3], [4, 5, 6]], np.int32) diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index 40bbe5aec..c85c5cf3e 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -5,6 +5,7 @@ import platform from decimal import Decimal import warnings import itertools +import platform import numpy as np from numpy.core import * @@ -931,6 +932,7 @@ class TestNonzero(TestCase): assert_equal(np.nonzero(x['a']), ([0, 1, 1, 2], [2, 0, 1, 1])) assert_equal(np.nonzero(x['b']), ([0, 0, 1, 2, 2], [0, 2, 0, 1, 2])) + assert_(not x['a'].T.flags.aligned) assert_equal(np.count_nonzero(x['a'].T), 4) assert_equal(np.count_nonzero(x['b'].T), 5) assert_equal(np.nonzero(x['a'].T), ([0, 1, 1, 2], [1, 1, 2, 0])) @@ -1048,7 +1050,15 @@ class TestArrayComparisons(TestCase): def assert_array_strict_equal(x, y): assert_array_equal(x, y) # Check flags - assert_(x.flags == y.flags) + if 'sparc' not in platform.platform().lower(): + assert_(x.flags == y.flags) + else: + # sparc arrays may not be aligned for long double types + assert_(x.flags.owndata == y.flags.owndata) + assert_(x.flags.writeable == y.flags.writeable) + assert_(x.flags.c_contiguous == y.flags.c_contiguous) + assert_(x.flags.f_contiguous == y.flags.f_contiguous) + assert_(x.flags.updateifcopy == y.flags.updateifcopy) # check endianness assert_(x.dtype.isnative == y.dtype.isnative) diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index 080606dce..c9267671f 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -14,6 +14,10 @@ class TestUfunc(TestCase): import pickle assert pickle.loads(pickle.dumps(np.sin)) is np.sin + # Check that ufunc not defined in the top level numpy namespace such as + # numpy.core.test_rational.test_add can also be pickled + assert pickle.loads(pickle.dumps(test_add)) is test_add + def test_pickle_withstring(self): import pickle astring = asbytes("cnumpy.core\n_ufunc_reconstruct\np0\n" diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index 3a148e72c..de954c374 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -4,6 +4,7 @@ import unittest import os import sys import copy +import platform import nose @@ -81,37 +82,45 @@ class Intent(object): intent = Intent() -class Type(object): - _type_names = ['BOOL', 'BYTE', 'UBYTE', 'SHORT', 'USHORT', 'INT', 'UINT', - 'LONG', 'ULONG', 'LONGLONG', 'ULONGLONG', - 'FLOAT', 'DOUBLE', 'LONGDOUBLE', 'CFLOAT', 'CDOUBLE', - 'CLONGDOUBLE'] - _type_cache = {} - - _cast_dict = {'BOOL':['BOOL']} - _cast_dict['BYTE'] = _cast_dict['BOOL'] + ['BYTE'] - _cast_dict['UBYTE'] = _cast_dict['BOOL'] + ['UBYTE'] - _cast_dict['BYTE'] = ['BYTE'] - _cast_dict['UBYTE'] = ['UBYTE'] - _cast_dict['SHORT'] = _cast_dict['BYTE'] + ['UBYTE', 'SHORT'] - _cast_dict['USHORT'] = _cast_dict['UBYTE'] + ['BYTE', 'USHORT'] - _cast_dict['INT'] = _cast_dict['SHORT'] + ['USHORT', 'INT'] - _cast_dict['UINT'] = _cast_dict['USHORT'] + ['SHORT', 'UINT'] - - _cast_dict['LONG'] = _cast_dict['INT'] + ['LONG'] - _cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG'] - - _cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG'] - _cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG'] - - _cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT'] - _cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE'] - _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE'] - - _cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT'] +_type_names = ['BOOL', 'BYTE', 'UBYTE', 'SHORT', 'USHORT', 'INT', 'UINT', + 'LONG', 'ULONG', 'LONGLONG', 'ULONGLONG', + 'FLOAT', 'DOUBLE', 'CFLOAT'] + +_cast_dict = {'BOOL':['BOOL']} +_cast_dict['BYTE'] = _cast_dict['BOOL'] + ['BYTE'] +_cast_dict['UBYTE'] = _cast_dict['BOOL'] + ['UBYTE'] +_cast_dict['BYTE'] = ['BYTE'] +_cast_dict['UBYTE'] = ['UBYTE'] +_cast_dict['SHORT'] = _cast_dict['BYTE'] + ['UBYTE', 'SHORT'] +_cast_dict['USHORT'] = _cast_dict['UBYTE'] + ['BYTE', 'USHORT'] +_cast_dict['INT'] = _cast_dict['SHORT'] + ['USHORT', 'INT'] +_cast_dict['UINT'] = _cast_dict['USHORT'] + ['SHORT', 'UINT'] + +_cast_dict['LONG'] = _cast_dict['INT'] + ['LONG'] +_cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG'] + +_cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG'] +_cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG'] + +_cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT'] +_cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE'] + +_cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT'] + +# (debian) sparc system malloc does not provide the alignment required by +# 16 byte long double types this means the inout intent cannot be satisfied and +# several tests fail as the alignment flag can be randomly true or fals +# when numpy gains an aligned allocator the tests could be enabled again +if 'sparc' not in platform.platform().lower(): + _type_names.extend(['LONGDOUBLE', 'CDOUBLE', 'CLONGDOUBLE']) + _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + \ + ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE'] + _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + \ + ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE'] _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE'] - _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE'] +class Type(object): + _type_cache = {} def __new__(cls, name): if isinstance(name, dtype): @@ -138,15 +147,15 @@ class Type(object): self.dtypechar = typeinfo[self.NAME][0] def cast_types(self): - return [self.__class__(_m) for _m in self._cast_dict[self.NAME]] + return [self.__class__(_m) for _m in _cast_dict[self.NAME]] def all_types(self): - return [self.__class__(_m) for _m in self._type_names] + return [self.__class__(_m) for _m in _type_names] def smaller_types(self): bits = typeinfo[self.NAME][3] types = [] - for name in self._type_names: + for name in _type_names: if typeinfo[name][3]<bits: types.append(Type(name)) return types @@ -154,7 +163,7 @@ class Type(object): def equal_types(self): bits = typeinfo[self.NAME][3] types = [] - for name in self._type_names: + for name in _type_names: if name==self.NAME: continue if typeinfo[name][3]==bits: types.append(Type(name)) @@ -163,7 +172,7 @@ class Type(object): def larger_types(self): bits = typeinfo[self.NAME][3] types = [] - for name in self._type_names: + for name in _type_names: if typeinfo[name][3]>bits: types.append(Type(name)) return types @@ -532,7 +541,7 @@ class _test_shared_memory: assert_(obj.dtype.type is self.type.dtype) # obj type is changed inplace! -for t in Type._type_names: +for t in _type_names: exec('''\ class test_%s_gen(unittest.TestCase, _test_shared_memory diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 00bfab6ba..f625bcb90 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -336,6 +336,11 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 + # avoid rounding issues for comparisons when dealing with inexact types + if np.issubdtype(sample.dtype, np.inexact): + edge_dt = sample.dtype + else: + edge_dt = float # Create edge arrays for i in arange(D): if isscalar(bins[i]): @@ -344,9 +349,9 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): "Element at index %s in `bins` should be a positive " "integer." % i) nbin[i] = bins[i] + 2 # +2 for outlier bins - edges[i] = linspace(smin[i], smax[i], nbin[i]-1) + edges[i] = linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt) else: - edges[i] = asarray(bins[i], float) + edges[i] = asarray(bins[i], edge_dt) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = diff(edges[i]) if np.any(np.asarray(dedges[i]) <= 0): diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index c1813512a..42a539f78 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -285,8 +285,7 @@ def load(file, mmap_mode=None): Parameters ---------- file : file-like object or string - The file to read. Compressed files with the filename extension - ``.gz`` are acceptable. File-like objects must support the + The file to read. File-like objects must support the ``seek()`` and ``read()`` methods. Pickled files require that the file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index ee38b3573..ac677a308 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1070,6 +1070,13 @@ class TestHistogram(TestCase): h, b = histogram(a, weights=np.ones(10, float)) assert_(issubdtype(h.dtype, float)) + def test_f32_rounding(self): + # gh-4799, check that the rounding of the edges works with float32 + x = np.array([276.318359 , -69.593948 , 21.329449], dtype=np.float32) + y = np.array([5005.689453, 4481.327637, 6010.369629], dtype=np.float32) + counts_hist, xedges, yedges = np.histogram2d(x, y, bins=100) + assert_equal(counts_hist.sum(), 3.) + def test_weights(self): v = rand(100) w = np.ones(100) * 5 diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 49ad1ba5b..03e238261 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -4,9 +4,7 @@ import sys import gzip import os import threading -import shutil -import contextlib -from tempfile import mkstemp, mkdtemp, NamedTemporaryFile +from tempfile import mkstemp, NamedTemporaryFile import time import warnings import gc @@ -24,13 +22,7 @@ from numpy.ma.testutils import ( assert_raises, assert_raises_regex, run_module_suite ) from numpy.testing import assert_warns, assert_, build_err_msg - - -@contextlib.contextmanager -def tempdir(change_dir=False): - tmpdir = mkdtemp() - yield tmpdir - shutil.rmtree(tmpdir) +from numpy.testing.utils import tempdir class TextIO(BytesIO): @@ -202,7 +194,7 @@ class TestSavezLoad(RoundtripTest, TestCase): def test_big_arrays(self): L = (1 << 31) + 100000 a = np.empty(L, dtype=np.uint8) - with tempdir() as tmpdir: + with tempdir(prefix="numpy_test_big_arrays_") as tmpdir: tmp = os.path.join(tmpdir, "file.npz") np.savez(tmp, a=a) del a @@ -311,7 +303,7 @@ class TestSavezLoad(RoundtripTest, TestCase): # Check that zipfile owns file and can close it. # This needs to pass a file name to load for the # test. - with tempdir() as tmpdir: + with tempdir(prefix="numpy_test_closing_zipfile_after_load_") as tmpdir: fd, tmp = mkstemp(suffix='.npz', dir=tmpdir) os.close(fd) np.savez(tmp, lab='place holder') diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 617f1921e..6c0a8f345 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -843,8 +843,7 @@ class _MaskedUnaryOperation: d = getdata(a) # Case 1.1. : Domained function if self.domain is not None: - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = self.f(d, *args, **kwargs) # Make a mask m = ~umath.isfinite(result) @@ -932,8 +931,7 @@ class _MaskedBinaryOperation: else: m = umath.logical_or(ma, mb) # Get the result - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) # check it worked if result is NotImplemented: @@ -945,11 +943,8 @@ class _MaskedBinaryOperation: return result # Case 2. : array # Revert result to da where masked - if m.any(): - np.copyto(result, 0, casting='unsafe', where=m) - # This only makes sense if the operation preserved the dtype - if result.dtype == da.dtype: - result += m * da + if m is not nomask: + np.copyto(result, da, casting='unsafe', where=m) # Transforms to a (subclass of) MaskedArray result = result.view(get_masked_subclass(a, b)) result._mask = m @@ -1073,8 +1068,7 @@ class _DomainedBinaryOperation: (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) (ma, mb) = (getmask(a), getmask(b)) # Get the result - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = self.f(da, db, *args, **kwargs) # check it worked if result is NotImplemented: @@ -1094,8 +1088,7 @@ class _DomainedBinaryOperation: else: return result # When the mask is True, put back da - np.copyto(result, 0, casting='unsafe', where=m) - result += m * da + np.copyto(result, da, casting='unsafe', where=m) result = result.view(get_masked_subclass(a, b)) result._mask = m if isinstance(b, MaskedArray): @@ -3840,8 +3833,7 @@ class MaskedArray(ndarray): "Raise self to the power other, in place." other_data = getdata(other) other_mask = getmask(other) - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): ndarray.__ipow__(self._data, np.where(self._mask, 1, other_data)) invalid = np.logical_not(np.isfinite(self._data)) if invalid.any(): @@ -6110,8 +6102,7 @@ def power(a, b, third=None): else: basetype = MaskedArray # Get the result and view it as a (subclass of) MaskedArray - with np.errstate(): - np.seterr(divide='ignore', invalid='ignore') + with np.errstate(divide='ignore', invalid='ignore'): result = np.where(m, fa, umath.power(fa, fb)).view(basetype) result._update_from(a) # Find where we're in trouble w/ NaNs and Infs diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index e6f659041..8172335a8 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -194,8 +194,7 @@ class TestMaskedArray(TestCase): def test_fix_invalid(self): # Checks fix_invalid. - with np.errstate(): - np.seterr(invalid='ignore') + with np.errstate(invalid='ignore'): data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1]) data_fixed = fix_invalid(data) assert_equal(data_fixed._data, [data.fill_value, 0., 1.]) diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py index 87c2133d7..047f91c77 100644 --- a/numpy/ma/tests/test_old_ma.py +++ b/numpy/ma/tests/test_old_ma.py @@ -607,8 +607,7 @@ class TestMa(TestCase): def test_testScalarArithmetic(self): xm = array(0, mask=1) #TODO FIXME: Find out what the following raises a warning in r8247 - with np.errstate(): - np.seterr(divide='ignore') + with np.errstate(divide='ignore'): self.assertTrue((1 / array(0)).mask) self.assertTrue((1 + xm).mask) self.assertTrue((-xm).mask) diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 60aaff83f..92cc83821 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -113,7 +113,7 @@ def polyline(off, scl) : Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> P.polyline(1,-1) array([ 1, -1]) >>> P.polyval(1, P.polyline(1,-1)) # should be 0 @@ -176,7 +176,7 @@ def polyfromroots(roots) : Examples -------- - >>> import numpy.polynomial as P + >>> from numpy.polynomial import polynomial as P >>> P.polyfromroots((-1,0,1)) # x(x - 1)(x + 1) = x^3 - x array([ 0., -1., 0., 1.]) >>> j = complex(0,1) @@ -225,7 +225,7 @@ def polyadd(c1, c2): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum @@ -270,7 +270,7 @@ def polysub(c1, c2): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polysub(c1,c2) @@ -352,7 +352,7 @@ def polymul(c1, c2): Examples -------- - >>> import numpy.polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polymul(c1,c2) @@ -389,7 +389,7 @@ def polydiv(c1, c2): Examples -------- - >>> import numpy.polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polydiv(c1,c2) @@ -513,7 +513,7 @@ def polyder(c, m=1, scl=1, axis=0): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c = (1,2,3,4) # 1 + 2x + 3x**2 + 4x**3 >>> P.polyder(c) # (d/dx)(c) = 2 + 6x + 12x**2 array([ 2., 6., 12.]) @@ -624,7 +624,7 @@ def polyint(c, m=1, k=[], lbnd=0, scl=1, axis=0): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> c = (1,2,3) >>> P.polyint(c) # should return array([0, 1, 1, 1]) array([ 0., 1., 1., 1.]) @@ -1310,7 +1310,7 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None): Examples -------- - >>> from numpy import polynomial as P + >>> from numpy.polynomial import polynomial as P >>> x = np.linspace(-1,1,51) # x "data": [-1, -0.96, ..., 0.96, 1] >>> y = x**3 - x + np.random.randn(len(x)) # x^3 - x + N(0,1) "noise" >>> c, stats = P.polyfit(x,y,3,full=True) diff --git a/numpy/random/mtrand/mtrand.pyx b/numpy/random/mtrand/mtrand.pyx index c2603543d..55138cba7 100644 --- a/numpy/random/mtrand/mtrand.pyx +++ b/numpy/random/mtrand/mtrand.pyx @@ -3752,8 +3752,9 @@ cdef class RandomState: Parameters ---------- - lam : float - Expectation of interval, should be >= 0. + lam : float or sequence of float + Expectation of interval, should be >= 0. A sequence of expectation + intervals must be broadcastable over the requested size. size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Default is None, in which case a @@ -3793,6 +3794,10 @@ cdef class RandomState: >>> count, bins, ignored = plt.hist(s, 14, normed=True) >>> plt.show() + Draw each 100 values for lambda 100 and 500: + + >>> s = np.random.poisson(lam=(100., 500.), size=(100, 2)) + """ cdef ndarray olam cdef double flam diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index ddf21e2bc..13c3e4610 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -10,6 +10,9 @@ import re import operator import warnings from functools import partial +import shutil +import contextlib +from tempfile import mkdtemp from .nosetester import import_nose from numpy.core import float32, empty, arange, array_repr, ndarray @@ -1692,3 +1695,16 @@ def _gen_alignment_data(dtype=float32, type='binary', max_size=24): class IgnoreException(Exception): "Ignoring this exception due to disabled feature" + + +@contextlib.contextmanager +def tempdir(*args, **kwargs): + """Context manager to provide a temporary test folder. + + All arguments are passed as this to the underlying tempfile.mkdtemp + function. + + """ + tmpdir = mkdtemp(*args, **kwargs) + yield tmpdir + shutil.rmtree(tmpdir) |