diff options
33 files changed, 2046 insertions, 627 deletions
diff --git a/doc/source/reference/arrays.ndarray.rst b/doc/source/reference/arrays.ndarray.rst index 0def05ced..1bf7d1ac8 100644 --- a/doc/source/reference/arrays.ndarray.rst +++ b/doc/source/reference/arrays.ndarray.rst @@ -9,14 +9,14 @@ The N-dimensional array (:class:`ndarray`) An :class:`ndarray` is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its :attr:`shape <ndarray.shape>`, -which is a :class:`tuple` of *N* integers that specify the sizes of +which is a :class:`tuple` of *N* positive integers that specify the sizes of each dimension. The type of items in the array is specified by a separate :ref:`data-type object (dtype) <arrays.dtypes>`, one of which is associated with each ndarray. -As with other container objects in Python, the contents of a +As with other container objects in Python, the contents of an :class:`ndarray` can be accessed and modified by :ref:`indexing or -slicing <arrays.indexing>` the array (using for example *N* integers), +slicing <arrays.indexing>` the array (using, for example, *N* integers), and via the methods and attributes of the :class:`ndarray`. .. index:: view, base @@ -42,15 +42,19 @@ objects implementing the :class:`buffer` or :ref:`array >>> x.dtype dtype('int32') - The array can be indexed using a Python container-like syntax: + The array can be indexed using Python container-like syntax: - >>> x[1,2] + >>> x[1,2] # i.e., the element of x in the *second* row, *third* column 6 For example :ref:`slicing <arrays.indexing>` can produce views of the array: >>> y = x[:,1] - >>> y[0] = 9 + >>> y + array([2, 5]) + >>> y[0] = 9 # this also changes the corresponding element in x + >>> y + array([9, 5]) >>> x array([[1, 9, 3], [4, 5, 6]]) @@ -95,7 +99,7 @@ the bytes are interpreted is defined by the :ref:`data-type object .. index:: C-order, Fortran-order, row-major, column-major, stride, offset A segment of memory is inherently 1-dimensional, and there are many -different schemes of arranging the items of an *N*-dimensional array to +different schemes for arranging the items of an *N*-dimensional array in a 1-dimensional block. Numpy is flexible, and :class:`ndarray` objects can accommodate any *strided indexing scheme*. In a strided scheme, the N-dimensional index :math:`(n_0, n_1, ..., n_{N-1})` corresponds @@ -105,10 +109,10 @@ to the offset (in bytes) from the beginning of the memory block associated with the array. Here, :math:`s_k` are integers which specify the :obj:`strides -<ndarray.strides>` of the array. The :term:`column-major` order (used -for example in the Fortran language and in *Matlab*) and -:term:`row-major` order (used in C) are special cases of the strided -scheme, and correspond to the strides: +<ndarray.strides>` of the array. The :term:`column-major` order (used, +for example, in the Fortran language and in *Matlab*) and +:term:`row-major` order (used in C) schemes are just specific kinds of +strided scheme, and correspond to the strides: .. math:: @@ -116,12 +120,12 @@ scheme, and correspond to the strides: .. index:: single-segment, contiguous, non-contiguous -Both the C and Fortran orders are :term:`contiguous`, *i.e.* +Both the C and Fortran orders are :term:`contiguous`, *i.e.,* :term:`single-segment`, memory layouts, in which every part of the memory block can be accessed by some combination of the indices. Data in new :class:`ndarrays <ndarray>` is in the :term:`row-major` -(C) order, unless otherwise specified, but for example :ref:`basic +(C) order, unless otherwise specified, but, for example, :ref:`basic array slicing <arrays.indexing>` often produces :term:`views <view>` in a different scheme. @@ -227,7 +231,8 @@ Array methods An :class:`ndarray` object has many methods which operate on or with the array in some fashion, typically returning an array result. These -methods are explained below. +methods are briefly explained below. (Each method's doc string has a +more complete description.) For the following methods there are also corresponding functions in :mod:`numpy`: :func:`all`, :func:`any`, :func:`argmax`, @@ -433,7 +438,7 @@ Arithmetic: .. note:: - Any third argument to :func:`pow()` is silently ignored, - as the underlying :func:`ufunc <power>` only takes two arguments. + as the underlying :func:`ufunc <power>` takes only two arguments. - The three division operators are all defined; :obj:`div` is active by default, :obj:`truediv` is active when @@ -472,7 +477,7 @@ Arithmetic, in-place: the array. Therefore, for mixed precision calculations, ``A {op}= B`` can be different than ``A = A {op} B``. For example, suppose ``a = ones((3,3))``. Then, ``a += 3j`` is different than ``a = a + - 3j``: While they both perform the same computation, ``a += 3`` + 3j``: while they both perform the same computation, ``a += 3`` casts the result to fit back in ``a``, whereas ``a = a + 3j`` re-binds the name ``a`` to the result. diff --git a/doc/source/reference/arrays.scalars.rst b/doc/source/reference/arrays.scalars.rst index 33d5ceff6..75daf2a08 100644 --- a/doc/source/reference/arrays.scalars.rst +++ b/doc/source/reference/arrays.scalars.rst @@ -204,8 +204,6 @@ elements the data type consists of.) :mod:`struct` module. -.. note:: XXX: what to put in the type docstrings, and where to put them? - Attributes ========== @@ -235,7 +233,6 @@ attribute. Otherwise, they share the same attributes as arrays: generic.__array_priority__ generic.__array_wrap__ -.. note:: XXX: import the documentation into the docstrings? Indexing ======== @@ -273,7 +270,6 @@ The exceptions to the above rules are given below: generic.__setstate__ generic.setflags -.. note:: XXX: import the documentation into the docstrings? Defining new types ================== diff --git a/doc/source/reference/generalized_ufuncs.rst b/doc/source/reference/c-api.generalized-ufuncs.rst index d9f3818b9..870e5dbc4 100644 --- a/doc/source/reference/generalized_ufuncs.rst +++ b/doc/source/reference/c-api.generalized-ufuncs.rst @@ -1,6 +1,6 @@ -=============================== -Generalized Universal Functions -=============================== +================================== +Generalized Universal Function API +================================== There is a general need for looping over not only functions on scalars but also over functions on vectors (or arrays), as explained on @@ -91,14 +91,14 @@ dimensions. The signature is represented by a string of the following format: * Core dimensions of each input or output array are represented by a - list of dimension names in parentheses, ``(i_1,...,i_N)``; a scalar + list of dimension names in parentheses, ``(i_1,...,i_N)``; a scalar input/output is denoted by ``()``. Instead of ``i_1``, ``i_2``, etc, one can use any valid Python variable name. * Dimension lists for different arguments are separated by ``","``. Input/output arguments are separated by ``"->"``. * If one uses the same dimension name in multiple locations, this enforces the same size (or broadcastable size) of the corresponding - dimensions. + dimensions. The formal syntax of signatures is as follows:: diff --git a/doc/source/reference/c-api.rst b/doc/source/reference/c-api.rst index 158e04a16..9bcc68b49 100644 --- a/doc/source/reference/c-api.rst +++ b/doc/source/reference/c-api.rst @@ -45,4 +45,5 @@ code. c-api.dtype c-api.array c-api.ufunc + c-api.generalized-ufuncs c-api.coremath diff --git a/doc/source/reference/c-api.ufunc.rst b/doc/source/reference/c-api.ufunc.rst index bd0ee8e02..6a6a0dff0 100644 --- a/doc/source/reference/c-api.ufunc.rst +++ b/doc/source/reference/c-api.ufunc.rst @@ -70,43 +70,45 @@ Functions operation. Each ufunc object contains pointers to 1-d loops implementing the basic functionality for each supported type. - :param nin: - - The number of inputs to this operation. - - :param nout: - - The number of outputs - - :param ntypes: + .. note:: - How many different data-type "signatures" the ufunc has implemented. + The *func*, *data*, *types*, *name*, and *doc* arguments are not + copied by :cfunc:`PyUFunc_FromFuncAndData`. The caller must ensure + that the memory used by these arrays is not freed as long as the + ufunc object is alive. :param func: - Must to an array of length *ntypes* containing :ctype:`PyUFuncGenericFunction` items. These items are pointers to - functions that acutally implement the underlying - (element-by-element) function :math:`N` times. T + functions that actually implement the underlying + (element-by-element) function :math:`N` times. - :param types: + :param data: + Should be ``NULL`` or a pointer to an array of size *ntypes* + . This array may contain arbitrary extra-data to be passed to + the corresponding 1-d loop function in the func array. + :param types: Must be of length (*nin* + *nout*) \* *ntypes*, and it contains the data-types (built-in only) that the corresponding function in the *func* array can deal with. - :param data: + :param ntypes: + How many different data-type "signatures" the ufunc has implemented. - Should be ``NULL`` or a pointer to an array of size *ntypes* - . This array may contain arbitrary extra-data to be passed to - the corresponding 1-d loop function in the func array. + :param nin: + The number of inputs to this operation. - :param name: + :param nout: + The number of outputs + :param identity: + XXX: Undocumented + + :param name: The name for the ufunc. :param doc: - Allows passing in a documentation string to be stored with the ufunc. The documentation string should not contain the name of the function or the calling signature as that will be @@ -114,7 +116,6 @@ Functions accessing the **__doc__** attribute of the ufunc. :param check_return: - Unused and present for backwards compatibility of the C-API. A corresponding *check_return* integer does exist in the ufunc structure and it does get set with this value when the ufunc diff --git a/doc/source/reference/index.rst b/doc/source/reference/index.rst index 0d83053ac..00317a18e 100644 --- a/doc/source/reference/index.rst +++ b/doc/source/reference/index.rst @@ -19,7 +19,6 @@ For learning how to use NumPy, see also :ref:`user`. arrays ufuncs - generalized_ufuncs routines ctypes distutils @@ -37,8 +36,6 @@ the functions are written by numerous contributors and developers of Numpy, both prior to and during the `Numpy Documentation Marathon <http://scipy.org/Developer_Zone/DocMarathon2008>`__. -The Documentation Marathon is still ongoing. Please help us write -better documentation for Numpy by joining it! Instructions on how to -join and what to do can be found +Please help to improve NumPy's documentation! Instructions on how to +join the ongoing documentation marathon can be found `on the scipy.org website <http://scipy.org/Developer_Zone/DocMarathon2008>`__ - diff --git a/doc/source/reference/routines.statistics.rst b/doc/source/reference/routines.statistics.rst index b41b62839..578cbd09a 100644 --- a/doc/source/reference/routines.statistics.rst +++ b/doc/source/reference/routines.statistics.rst @@ -35,6 +35,7 @@ Correlating :toctree: generated/ corrcoef + acorrelate correlate cov diff --git a/doc/source/user/index.rst b/doc/source/user/index.rst index 8d8812c80..a9945a0d1 100644 --- a/doc/source/user/index.rst +++ b/doc/source/user/index.rst @@ -19,9 +19,9 @@ and classes, see :ref:`reference`. .. toctree:: :maxdepth: 2 + install howtofind basics performance misc c-info - diff --git a/doc/source/user/install.rst b/doc/source/user/install.rst new file mode 100644 index 000000000..472ee20e3 --- /dev/null +++ b/doc/source/user/install.rst @@ -0,0 +1,148 @@ +***************************** +Building and installing NumPy +***************************** + +Binary installers +================= + +In most use cases the best way to install NumPy on your system is by using an +installable binary package for your operating system. + +Windows +------- + +Good solutions for Windows are, The Enthought Python Distribution `(EPD) +<http://www.enthought.com/products/epd.php>`_ (which provides binary installers +for Windows, OS X and Redhat) and `Python (x, y) <http://www.pythonxy.com>`_. +Both of these packages include Python, NumPy and many additional packages. +A lightweight alternative is to download the Python installer from +`www.python.org <http://www.python.org>`_ and the NumPy installer for your +Python version from the Sourceforge `download site +<http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103>`_ + +Linux +----- + +Most of the major distributions provide packages for NumPy, but these can lag +behind the most recent NumPy release. Pre-built binary packages for Ubuntu are +available on the `scipy ppa <https://edge.launchpad.net/~scipy/+archive/ppa>`_. +Redhat binaries are available in the `EPD +<http://www.enthought.com/products/epd.php>`_. + +Mac OS X +-------- + +A universal binary installer for NumPy is available from the `download site +<http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103>`_. +The `EPD <http://www.enthought.com/products/epd.php>`_ provides NumPy binaries. + +Building from source +==================== + +A general overview of building NumPy from source is given here, with detailed +instructions for specific platforms given seperately. + +Prerequisites +------------- + +Building NumPy requires the following software installed: + +1) Python 2.4.x, 2.5.x or 2.6.x + + On Debian and derivative (Ubuntu): python, python-dev + + On Windows: the official python installer at + `www.python.org <http://www.python.org>`_ is enough + + Make sure that the Python package distutils is installed before + continuing. For example, in Debian GNU/Linux, distutils is included + in the python-dev package. + + Python must also be compiled with the zlib module enabled. + +2) Compilers + + To build any extension modules for Python, you'll need a C compiler. Various + NumPy modules use FORTRAN 77 libraries, so you'll also need a FORTRAN 77 + compiler installed. + + Note that NumPy is developed mainly using GNU compilers. Compilers from other + vendors such as Intel, Absoft, Sun, NAG, Compaq, Vast, Porland, Lahey, HP, + IBM, Microsoft are only supported in the form of community feedback, and may + not work out of the box. GCC 3.x (and later) compilers are recommended. + +3) Linear Algebra libraries + + NumPy does not require any external linear algebra libraries to be installed. + However, if these are available, NumPy's setup script can detect them and use + them for building. A number of different LAPACK library setups can be used, + including optimized LAPACK libraries such as ATLAS, MKL or the + Accelerate/vecLib framework on OS X. + +FORTRAN ABI mismatch +-------------------- + +The two most popular open source fortran compilers are g77 and gfortran. +Unfortunately, they are not ABI compatible, which means that concretely you +should avoid mixing libraries built with one with another. In particular, if +your blas/lapack/atlas is built with g77, you *must* use g77 when building +numpy and scipy; on the contrary, if your atlas is built with gfortran, you +*must* build numpy/scipy with gfortran. This applies for most other cases where +different FORTRAN compilers might have been used. + +Choosing the fortran compiler +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To build with g77: + + python setup.py build --fcompiler=gnu + +To build with gfortran: + + python setup.py build --fcompiler=gnu95 + +For more information see: + + python setup.py build --help-fcompiler + +How to check the ABI of blas/lapack/atlas +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +One relatively simple and reliable way to check for the compiler used to build +a library is to use ldd on the library. If libg2c.so is a dependency, this +means that g77 has been used. If libgfortran.so is a a dependency, gfortran has +been used. If both are dependencies, this means both have been used, which is +almost always a very bad idea. + +Building with ATLAS support +--------------------------- + +Ubuntu 8.10 (Intrepid) +~~~~~~~~~~~~~~~~~~~~~~ + +You can install the necessary packages for optimized ATLAS with this command: + + sudo apt-get install libatlas-base-dev + +If you have a recent CPU with SIMD suppport (SSE, SSE2, etc...), you should +also install the corresponding package for optimal performances. For example, +for SSE2: + + sudo apt-get install libatlas3gf-sse2 + +*NOTE*: if you build your own atlas, Intrepid changed its default fortran +compiler to gfortran. So you should rebuild everything from scratch, including +lapack, to use it on Intrepid. + +Ubuntu 8.04 and lower +~~~~~~~~~~~~~~~~~~~~~ + +You can install the necessary packages for optimized ATLAS with this command: + + sudo apt-get install atlas3-base-dev + +If you have a recent CPU with SIMD suppport (SSE, SSE2, etc...), you should +also install the corresponding package for optimal performances. For example, +for SSE2: + + sudo apt-get install atlas3-sse2 diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 121b8088f..e541e7cb0 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -747,12 +747,19 @@ add_newdoc('numpy.core.multiarray', 'set_string_function', Parameters ---------- - f : Python function + f : function or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of - the array. - repr : int - Unknown. + the array. If None, the function is reset to the default NumPy function + to print arrays. + repr : bool, optional + If True (default), the function for pretty printing (``__repr__``) + is set, if False the function that returns the default string + representation (``__str__``) is set. + + See Also + -------- + set_printoptions, get_printoptions Examples -------- @@ -766,6 +773,24 @@ add_newdoc('numpy.core.multiarray', 'set_string_function', >>> print a [0 1 2 3 4 5 6 7 8 9] + We can reset the function to the default: + + >>> np.set_string_function(None) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'l') + + `repr` affects either pretty printing or normal string representation. + Note that ``__repr__`` is still affected by setting ``__str__`` + because the width of each array element in the returned string becomes + equal to the length of the result of ``__str__()``. + + >>> x = np.arange(4) + >>> np.set_string_function(lambda x:'random', repr=False) + >>> x.__str__() + 'random' + >>> x.__repr__() + 'array([ 0, 1, 2, 3])' + """) add_newdoc('numpy.core.multiarray', 'set_numeric_ops', @@ -973,12 +998,37 @@ add_newdoc('numpy.core.multiarray','newbuffer', """) -add_newdoc('numpy.core.multiarray','getbuffer', - """getbuffer(obj [,offset[, size]]) +add_newdoc('numpy.core.multiarray', 'getbuffer', + """ + getbuffer(obj [,offset[, size]]) Create a buffer object from the given object referencing a slice of - length size starting at offset. Default is the entire buffer. A - read-write buffer is attempted followed by a read-only buffer. + length size starting at offset. + + Default is the entire buffer. A read-write buffer is attempted followed + by a read-only buffer. + + Parameters + ---------- + obj : object + + offset : int, optional + + size : int, optional + + Returns + ------- + buffer_obj : buffer + + Examples + -------- + >>> buf = np.getbuffer(np.ones(5), 1, 3) + >>> len(buf) + 3 + >>> buf[0] + '\\x00' + >>> buf + <read-write buffer for 0x8af1e70, size 3, offset 1 at 0x8ba4ec0> """) @@ -2668,6 +2718,21 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', type : python type Type of the returned view, e.g. ndarray or matrix. + + Notes + ----- + + `a.view()` is used two different ways. + + `a.view(some_dtype)` or `a.view(dtype=some_dtype)` constructs a view of + the array's memory with a different dtype. This can cause a + reinterpretation of the bytes of memory. + + `a.view(ndarray_subclass)`, or `a.view(type=ndarray_subclass)`, just + returns an instance of ndarray_subclass that looks at the same array (same + shape, dtype, etc.). This does not cause a reinterpretation of the memory. + + Examples -------- >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) @@ -2675,12 +2740,27 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix) - >>> print y.dtype - int16 - + >>> y + matrix([[513]], dtype=int16) >>> print type(y) <class 'numpy.core.defmatrix.matrix'> + Creating a view on a structured array so it can be used in calculations + + >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) + >>> xv = x.view(dtype=np.int8).reshape(-1,2) + >>> xv + array([[1, 2], + [3, 4]], dtype=int8) + >>> xv.mean(0) + array([ 2., 3.]) + + Making changes to the view changes the underlying array + + >>> xv[0,1] = 20 + >>> print x + [(1, 20) (3, 4)] + Using a view to convert an array to a record array: >>> z = x.view(np.recarray) @@ -2704,9 +2784,9 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', add_newdoc('numpy.core.umath', 'frexp', """ - Return normalized fraction and exponent of 2, element-wise of input array. + Return normalized fraction and exponent of 2 of input array, element-wise. - Returns (`out1`, `out2`) from equation `x` = `out1` * ( 2 ** `out2` ) + Returns (`out1`, `out2`) from equation ``x` = out1 * 2**out2``. Parameters ---------- @@ -2715,19 +2795,29 @@ add_newdoc('numpy.core.umath', 'frexp', Returns ------- - (out1, out2) : tuple of ndarray, (float, int) - The `out1` ndarray is a float array with numbers between -1 and 1. - The `out2` array is an int array represent the exponent of 2. + (out1, out2) : tuple of ndarrays, (float, int) + `out1` is a float array with values between -1 and 1. + `out2` is an int array which represent the exponent of 2. + + See Also + -------- + ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`. + + Notes + ----- + Complex dtypes are not supported, they will raise a TypeError. Examples -------- - >>> y1,y2 = np.frexp([3.4, 5.7, 1, 10, -100, 0]) + >>> x = np.arange(9) + >>> y1, y2 = np.frexp(x) >>> y1 - array([ 0.85 , 0.7125 , 0.5 , 0.625 , -0.78125, 0. ]) + array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, + 0.5 ]) >>> y2 - array([2, 3, 1, 4, 7, 0], dtype=int32) + array([0, 1, 2, 2, 3, 3, 3, 3, 4]) >>> y1 * 2**y2 - array([ 3.4, 5.7, 1. , 10. , -100. , 0. ]) + array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.]) """) @@ -2764,31 +2854,97 @@ add_newdoc('numpy.core.umath', 'ldexp', Parameters ---------- x1 : array_like - The significand. + The array of multipliers. x2 : array_like - The exponent. + The array of exponents. Returns ------- y : array_like - y = x1 * 2**x2 + The output array, the result of ``x1 * 2**x2``. + + See Also + -------- + frexp : Return (y1, y2) from ``x = y1 * 2**y2``, the inverse of `ldexp`. + + Notes + ----- + Complex dtypes are not supported, they will raise a TypeError. + + `ldexp` is useful as the inverse of `frexp`, if used by itself it is + more clear to simply use the expression ``x1 * 2**x2``. Examples -------- - >>> np.ldexp(5., 2) - 20. + >>> np.ldexp(5, np.arange(4)) + array([ 5., 10., 20., 40.], dtype=float32) + + >>> x = np.arange(6) + >>> np.ldexp(*np.frexp(x)) + array([ 0., 1., 2., 3., 4., 5.]) """) -add_newdoc('numpy.core.umath','geterrobj', - """geterrobj() +add_newdoc('numpy.core.umath', 'geterrobj', + """ + geterrobj() + + Return the current object that defines floating-point error handling. - Used internally by `geterr`. + The error object contains all information that defines the error handling + behavior in Numpy. `geterrobj` is used internally by the other + functions that get and set error handling behavior (`geterr`, `seterr`, + `geterrcall`, `seterrcall`). Returns ------- errobj : list - Internal numpy buffer size, error mask, error callback function. + The error object, a list containing three elements: + [internal numpy buffer size, error mask, error callback function]. + + The error mask is a single integer that holds the treatment information + on all four floating point errors. If we print it in base 8, we can see + what treatment is set for "invalid", "under", "over", and "divide" (in + that order). The printed string can be interpreted with + + * 0 : 'ignore' + * 1 : 'warn' + * 2 : 'raise' + * 3 : 'call' + * 4 : 'print' + * 5 : 'log' + + See Also + -------- + seterrobj, seterr, geterr, seterrcall, geterrcall + getbufsize, setbufsize + + Notes + ----- + For complete documentation of the types of floating-point exceptions and + treatment options, see `seterr`. + + Examples + -------- + >>> np.geterrobj() # first get the defaults + [10000, 0, None] + + >>> def err_handler(type, flag): + ... print "Floating point error (%s), with flag %s" % (type, flag) + ... + >>> old_bufsize = np.setbufsize(20000) + >>> old_err = np.seterr(divide='raise') + >>> old_handler = np.seterrcall(err_handler) + >>> np.geterrobj() + [20000, 2, <function err_handler at 0x91dcaac>] + + >>> old_err = np.seterr(all='ignore') + >>> np.base_repr(np.geterrobj()[1], 8) + '0' + >>> old_err = np.seterr(divide='warn', over='log', under='call', + invalid='print') + >>> np.base_repr(np.geterrobj()[1], 8) + '4351' """) @@ -2796,16 +2952,57 @@ add_newdoc('numpy.core.umath', 'seterrobj', """ seterrobj(errobj) - Used internally by `seterr`. + Set the object that defines floating-point error handling. + + The error object contains all information that defines the error handling + behavior in Numpy. `seterrobj` is used internally by the other + functions that set error handling behavior (`seterr`, `seterrcall`). Parameters ---------- errobj : list - [buffer_size, error_mask, callback_func] + The error object, a list containing three elements: + [internal numpy buffer size, error mask, error callback function]. + + The error mask is a single integer that holds the treatment information + on all four floating point errors. If we print it in base 8, we can see + what treatment is set for "invalid", "under", "over", and "divide" (in + that order). The printed string can be interpreted with + + * 0 : 'ignore' + * 1 : 'warn' + * 2 : 'raise' + * 3 : 'call' + * 4 : 'print' + * 5 : 'log' See Also -------- - seterrcall + geterrobj, seterr, geterr, seterrcall, geterrcall + getbufsize, setbufsize + + Notes + ----- + For complete documentation of the types of floating-point exceptions and + treatment options, see `seterr`. + + Examples + -------- + >>> old_errobj = np.geterrobj() # first get the defaults + >>> old_errobj + [10000, 0, None] + + >>> def err_handler(type, flag): + ... print "Floating point error (%s), with flag %s" % (type, flag) + ... + >>> new_errobj = [20000, 12, err_handler] + >>> np.seterrobj(new_errobj) + >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn') + '14' + >>> np.geterr() + {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'} + >>> np.geterrcall() + <function err_handler at 0xb75e9304> """) @@ -2822,32 +3019,49 @@ add_newdoc('numpy.lib._compiled_base', 'digitize', Return the indices of the bins to which each value in input array belongs. - Each index returned is such that `bins[i-1]` <= `x` < `bins[i]` if `bins` - is monotonically increasing, or `bins[i-1]` > `x` >= `bins[i]` if `bins` - is monotonically decreasing. Beyond the bounds of `bins`, 0 or len(`bins`) - is returned as appropriate. + Each index ``i`` returned is such that ``bins[i-1] <= x < bins[i]`` if + `bins` is monotonically increasing, or ``bins[i-1] > x >= bins[i]`` if + `bins` is monotonically decreasing. If values in `x` are beyond the + bounds of `bins`, 0 or ``len(bins)`` is returned as appropriate. Parameters ---------- x : array_like - Input array to be binned. + Input array to be binned. It has to be 1-dimensional. bins : array_like - Array of bins. + Array of bins. It has to be 1-dimensional and monotonic. Returns ------- - out : ndarray - Output array of indices of same shape as `x`. + out : ndarray of ints + Output array of indices, of same shape as `x`. + + Raises + ------ + ValueError + If the input is not 1-dimensional, or if `bins` is not monotonic. + TypeError + If the type of the input is complex. + + See Also + -------- + bincount, histogram, unique + + Notes + ----- + If values in `x` are such that they fall outside the bin range, + attempting to index `bins` with the indices that `digitize` returns + will result in an IndexError. Examples -------- >>> x = np.array([0.2, 6.4, 3.0, 1.6]) >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) - >>> d = np.digitize(x,bins) - >>> d + >>> inds = np.digitize(x, bins) + >>> inds array([1, 4, 3, 2]) - >>> for n in range(len(x)): - ... print bins[d[n]-1], "<=", x[n], "<", bins[d[n]] + >>> for n in range(x.size): + ... print bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]] ... 0.0 <= 0.2 < 1.0 4.0 <= 6.4 < 10.0 @@ -2860,24 +3074,54 @@ add_newdoc('numpy.lib._compiled_base', 'bincount', """ bincount(x, weights=None) - Return the number of occurrences of each value in array of nonnegative - integers. + Count number of occurrences of each value in array of non-negative ints. - The output, b[i], represents the number of times that i is found in `x`. - If `weights` is specified, every occurrence of i at a position p - contributes `weights` [p] instead of 1. + The number of bins (of size 1) is one larger than the largest value in + `x`. Each bin gives the number of occurrences of its index value in `x`. + If `weights` is specified the input array is weighted by it, i.e. if a + value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead + of ``out[n] += 1``. Parameters ---------- - x : array_like, 1 dimension, nonnegative integers - Input array. - weights : array_like, same shape as `x`, optional - Weights. + x : array_like, 1 dimension, nonnegative ints + Input array. The length of `x` is equal to ``np.amax(x)+1``. + weights : array_like, optional + Weights, array of the same shape as `x`. + + Returns + ------- + out : ndarray of ints + The result of binning the input array. + + Raises + ------ + ValueError + If the input is not 1-dimensional, or contains elements with negative + values. + TypeError + If the type of the input is float or complex. See Also -------- histogram, digitize, unique + Examples + -------- + >>> np.bincount(np.arange(5)) + array([1, 1, 1, 1, 1]) + >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) + array([1, 3, 1, 1, 0, 0, 0, 1]) + + >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) + >>> np.bincount(x).size == np.amax(x)+1 + True + + >>> np.bincount(np.arange(5, dtype=np.float)) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + TypeError: array cannot be safely cast to required type + """) add_newdoc('numpy.lib._compiled_base', 'add_docstring', @@ -3440,6 +3684,8 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin', """ Integer indicating how this dtype relates to the built-in dtypes. + Read-only. + = ======================================================================== 0 if this is a structured array type, with fields 1 if this is a dtype compiled into numpy (such as ints, floats etc) @@ -3642,7 +3888,7 @@ add_newdoc('numpy.lib.index_tricks', 'mgrid', Examples -------- - >>> mgrid[0:5,0:5] + >>> np.mgrid[0:5,0:5] array([[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], @@ -3653,7 +3899,7 @@ add_newdoc('numpy.lib.index_tricks', 'mgrid', [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]]) - >>> mgrid[-1:1:5j] + >>> np.mgrid[-1:1:5j] array([-1. , -0.5, 0. , 0.5, 1. ]) """) diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index a3edb64d4..5e5a96b68 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -56,10 +56,14 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). - nanstr : string, optional - String representation of floating point not-a-number (default nan). - infstr : string, optional - String representation of floating point infinity (default inf). + nanstr : str, optional + String representation of floating point not-a-number (default NaN). + infstr : str, optional + String representation of floating point infinity (default Inf). + + See Also + -------- + get_printoptions, set_string_function Examples -------- @@ -79,12 +83,9 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, >>> eps = np.finfo(float).eps >>> x = np.arange(4.) - >>> x**2 - (x + eps)**2 array([ -4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) - >>> np.set_printoptions(suppress=True) - >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index e880f21a2..76bbd3a65 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -93,6 +93,9 @@ add_newdoc('numpy.core.umath', 'arccos', `x`-coordinate on the unit circle. For real arguments, the domain is [-1, 1]. + out : ndarray, optional + Array to store results in. + Returns ------- angle : ndarray @@ -153,6 +156,8 @@ add_newdoc('numpy.core.umath', 'arccosh', ---------- x : array_like Input array. + out : ndarray, optional + Array of the same shape as `x`. Returns ------- @@ -715,16 +720,44 @@ add_newdoc('numpy.core.umath', 'cos', ---------- x : array_like Input array in radians. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- - out : ndarray - Output array of same shape as `x`. + y : ndarray + The corresponding cosine values. + + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972. Examples -------- >>> np.cos(np.array([0, np.pi/2, np.pi])) array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00]) + >>> + >>> # Example of providing the optional output parameter + >>> out2 = np.cos([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape """) @@ -903,7 +936,7 @@ add_newdoc('numpy.core.umath', 'equal', add_newdoc('numpy.core.umath', 'exp', """ - Calculate the exponential of the elements in the input array. + Calculate the exponential of all elements in the input array. Parameters ---------- @@ -913,7 +946,12 @@ add_newdoc('numpy.core.umath', 'exp', Returns ------- out : ndarray - Element-wise exponential of `x`. + Output array, element-wise exponential of `x`. + + See Also + -------- + expm1 : Calculate ``exp(x) - 1`` for all elements in the array. + exp2 : Calculate ``2**x`` for all elements in the array. Notes ----- @@ -968,20 +1006,34 @@ add_newdoc('numpy.core.umath', 'exp2', x : array_like Input values. + out : ndarray, optional + \tArray to insert results into. + Returns ------- out : ndarray Element-wise 2 to the power `x`. + See Also + -------- + exp : calculate x**p. + Notes ----- .. versionadded:: 1.3.0 + + + Examples + -------- + >>> np.exp2([2,3]) + array([4,9]) + """) add_newdoc('numpy.core.umath', 'expm1', """ - Compute ``exp(x) - 1`` for all elements in the array. + Calculate ``exp(x) - 1`` for all elements in the array. Parameters ---------- @@ -1621,7 +1673,7 @@ add_newdoc('numpy.core.umath', 'log', add_newdoc('numpy.core.umath', 'log10', """ - Compute the logarithm in base 10 element-wise. + Return the base 10 logarithm of the input array, element-wise. Parameters ---------- @@ -1631,7 +1683,8 @@ add_newdoc('numpy.core.umath', 'log10', Returns ------- y : ndarray - Base-10 logarithm of `x`. + The logarithm to the base 10 of `x`, element-wise. NaNs are + returned where x is negative. Notes ----- @@ -1656,7 +1709,7 @@ add_newdoc('numpy.core.umath', 'log10', Examples -------- - >>> np.log10([1.e-15,-3.]) + >>> np.log10([1e-15, -3.]) array([-15., NaN]) """) @@ -1687,71 +1740,91 @@ add_newdoc('numpy.core.umath', 'log2', add_newdoc('numpy.core.umath', 'logaddexp', """ - Logarithm of `exp(x) + exp(y)`. + Logarithm of the sum of exponentiations of the inputs. - This function is useful in statistics where the calculated probabilities of - events may be so small as to excede the range of normal floating point - numbers. In such cases the logarithm of the calculated probability is - stored. This function allows adding probabilities stored in such a fashion. + Calculates ``log(exp(x1) + exp(x2))``. This function is useful in + statistics where the calculated probabilities of events may be so small + as to exceed the range of normal floating point numbers. In such cases + the logarithm of the calculated probability is stored. This function + allows adding probabilities stored in such a fashion. Parameters ---------- - x : array_like - Input values. - y : array_like + x1, x2 : array_like Input values. - Returns ------- result : ndarray - Logarithm of `exp(x) + exp(y)`. + Logarithm of ``exp(x1) + exp(x2)``. See Also -------- - logaddexp2 + logaddexp2: Logarithm of the sum of exponentiations of inputs in base-2. Notes ----- .. versionadded:: 1.3.0 + Examples + -------- + >>> prob1 = np.log(1e-50) + >>> prob2 = np.log(2.5e-50) + >>> prob12 = np.logaddexp(prob1, prob2) + >>> prob12 + -113.87649168120691 + >>> np.exp(prob12) + 3.5000000000000057e-50 + """) add_newdoc('numpy.core.umath', 'logaddexp2', """ - Base-2 Logarithm of `2**x + 2**y`. + Logarithm of the sum of exponentiations of the inputs in base-2. - This function is useful in machine learning when the calculated probabilities of - events may be so small as to excede the range of normal floating point - numbers. In such cases the base-2 logarithm of the calculated probability - can be used instead. This function allows adding probabilities stored in such a fashion. + Calculates ``log2(2**x1 + 2**x2)``. This function is useful in machine + learning when the calculated probabilities of events may be so small + as to exceed the range of normal floating point numbers. In such cases + the base-2 logarithm of the calculated probability can be used instead. + This function allows adding probabilities stored in such a fashion. Parameters ---------- - x : array_like - Input values. - y : array_like + x1, x2 : array_like Input values. - + out : ndarray, optional + Array to store results in. Returns ------- result : ndarray - Base-2 logarithm of `2**x + 2**y`. + Base-2 logarithm of ``2**x1 + 2**x2``. See Also -------- - logaddexp + logaddexp: Logarithm of the sum of exponentiations of the inputs. Notes ----- .. versionadded:: 1.3.0 + Examples + -------- + >>> prob1 = np.log2(1e-50) + >>> prob2 = np.log2(2.5e-50) + >>> prob12 = np.logaddexp2(prob1, prob2) + >>> prob1, prob2, prob12 + (-166.09640474436813, -164.77447664948076, -164.28904982231052) + >>> 2**prob12 + 3.4999999999999914e-50 + """) add_newdoc('numpy.core.umath', 'log1p', """ - `log(1 + x)` in base `e`, elementwise. + Return the natural logarithm of one plus the input array, element-wise. + + Calculates ``log(1 + x)``. Parameters ---------- @@ -1761,7 +1834,11 @@ add_newdoc('numpy.core.umath', 'log1p', Returns ------- y : ndarray - Natural logarithm of `1 + x`, elementwise. + Natural logarithm of `1 + x`, element-wise. + + See Also + -------- + expm1 : ``exp(x) - 1``, the inverse of `log1p`. Notes ----- @@ -2022,8 +2099,6 @@ add_newdoc('numpy.core.umath', 'minimum', add_newdoc('numpy.core.umath', 'fmax', """ - fmax(x1, x2[, out]) - Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise @@ -2132,7 +2207,7 @@ add_newdoc('numpy.core.umath', 'fmin', add_newdoc('numpy.core.umath', 'modf', """ - Return the fractional and integral part of a number. + Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative. @@ -2140,7 +2215,7 @@ add_newdoc('numpy.core.umath', 'modf', Parameters ---------- x : array_like - Input number. + Input array. Returns ------- @@ -2149,33 +2224,37 @@ add_newdoc('numpy.core.umath', 'modf', y2 : ndarray Integral part of `x`. + Notes + ----- + For integer input the return values are floats. + Examples -------- - >>> np.modf(2.5) - (0.5, 2.0) - >>> np.modf(-.4) - (-0.40000000000000002, -0.0) + >>> np.modf([0, 3.5]) + (array([ 0. , 0.5]), array([ 0., 3.])) + >>> np.modf(-0.5) + (-0.5, -0) """) add_newdoc('numpy.core.umath', 'multiply', """ - Multiply arguments elementwise. + Multiply arguments element-wise. Parameters ---------- x1, x2 : array_like - The arrays to be multiplied. + Input arrays to be multiplied. Returns ------- y : ndarray - The product of `x1` and `x2`, elementwise. Returns a scalar if + The product of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes ----- - Equivalent to `x1` * `x2` in terms of array-broadcasting. + Equivalent to `x1` * `x2` in terms of array broadcasting. Examples -------- @@ -2353,23 +2432,34 @@ add_newdoc('numpy.core.umath', 'deg2rad', add_newdoc('numpy.core.umath', 'reciprocal', """ - Return element-wise reciprocal. + Return the reciprocal of the argument, element-wise. + + Calculates ``1/x``. Parameters ---------- x : array_like - Input value. + Input array. Returns ------- y : ndarray - Return value. + Return array. + + Notes + ----- + .. note:: + This function is not designed to work with integers. + + For integer arguments with absolute value larger than 1 the result is + always zero because of the way Python handles integer division. + For integer zero the result is an overflow. Examples -------- - >>> reciprocal(2.) + >>> np.reciprocal(2.) 0.5 - >>> reciprocal([1, 2., 3.33]) + >>> np.reciprocal([1, 2., 3.33]) array([ 1. , 0.5 , 0.3003003]) """) @@ -2378,7 +2468,7 @@ add_newdoc('numpy.core.umath', 'remainder', """ Returns element-wise remainder of division. - Computes `x1 - floor(x1/x2)*x2`. + Computes ``x1 - floor(x1/x2)*x2``. Parameters ---------- @@ -2390,22 +2480,23 @@ add_newdoc('numpy.core.umath', 'remainder', Returns ------- y : ndarray - The remainder of the quotient `x1/x2`, element-wise. Returns a scalar + The remainder of the quotient ``x1/x2``, element-wise. Returns a scalar if both `x1` and `x2` are scalars. See Also -------- - divide - floor + divide, floor Notes ----- - Returns 0 when `x2` is 0. + Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of) integers. Examples -------- - >>> np.remainder([4,7],[2,3]) + >>> np.remainder([4,7], [2,3]) array([0, 1]) + >>> np.remainder(np.arange(7), 5) + array([0, 1, 2, 3, 4, 0, 1]) """) @@ -2590,11 +2681,50 @@ add_newdoc('numpy.core.umath', 'sinh', ---------- x : array_like Input array. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- - out : ndarray - Output array of same shape as `x`. + y : ndarray + The corresponding hyperbolic sine values. + + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972, pg. 83. + + Examples + -------- + >>> import numpy as np + >>> np.sinh(0) + 0.0 + >>> np.sinh(np.pi*1j/2) + 1j + >>> np.sinh(np.pi*1j) + 1.2246063538223773e-016j (exact value is 0) + >>> # Discrepancy due to vagaries of floating point arithmetic. + >>> + >>> # Example of providing the optional output parameter + >>> out2 = np.sinh([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.sinh(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape """) @@ -2667,13 +2797,12 @@ add_newdoc('numpy.core.umath', 'square', add_newdoc('numpy.core.umath', 'subtract', """ - Subtract arguments element-wise. + Subtract arguments, element-wise. Parameters ---------- x1, x2 : array_like - The arrays to be subtracted from each other. If type is 'array_like' - the `x1` and `x2` shapes must be identical. + The arrays to be subtracted from each other. Returns ------- @@ -2683,7 +2812,7 @@ add_newdoc('numpy.core.umath', 'subtract', Notes ----- - Equivalent to `x1` - `x2` in terms of array-broadcasting. + Equivalent to ``x1 - x2`` in terms of array broadcasting. Examples -------- @@ -2703,39 +2832,107 @@ add_newdoc('numpy.core.umath', 'tan', """ Compute tangent element-wise. + Equivalent to ``np.sin(x)/np.cos(x)`` element-wise. + Parameters ---------- x : array_like - Angles in radians. + Input array. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- y : ndarray The corresponding tangent values. + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972. Examples -------- >>> from math import pi >>> np.tan(np.array([-pi,pi/2,pi])) array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16]) + >>> + >>> # Example of providing the optional output parameter illustrating + >>> # that what is returned is a reference to said parameter + >>> out2 = np.cos([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape """) add_newdoc('numpy.core.umath', 'tanh', """ - Hyperbolic tangent element-wise. + Compute hyperbolic tangent element-wise. + + Equivalent to ``np.sinh(x)/np.cosh(x)`` or + ``-1j * np.tan(1j*x)``. Parameters ---------- x : array_like Input array. + out : ndarray, optional + Output array of same shape as `x`. Returns ------- y : ndarray The corresponding hyperbolic tangent values. + Raises + ------ + ValueError: invalid return array shape + if `out` is provided and `out.shape` != `x.shape` (See Examples) + + Notes + ----- + If `out` is provided, the function writes the result into it, + and returns a reference to `out`. (See Examples) + + References + ---------- + M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. + New York, NY: Dover, 1972, pg. 83. + + Examples + -------- + >>> import numpy as np + >>> np.tanh((0, np.pi*1j, np.pi*1j/2)) + array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j]) + >>> + >>> # Example of providing the optional output parameter illustrating + >>> # that what is returned is a reference to said parameter + >>> out2 = np.tanh([0.1], out1) + >>> out2 is out1 + True + >>> + >>> # Example of ValueError due to provision of shape mis-matched `out` + >>> np.tanh(np.zeros((3,3)),np.zeros((2,2))) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: invalid return array shape + """) add_newdoc('numpy.core.umath', 'true_divide', diff --git a/numpy/core/defmatrix.py b/numpy/core/defmatrix.py index d1636e8b5..cbb338469 100644 --- a/numpy/core/defmatrix.py +++ b/numpy/core/defmatrix.py @@ -490,6 +490,26 @@ class matrix(N.ndarray): return N.ndarray.prod(self, axis, dtype, out)._align(axis) def any(self, axis=None, out=None): + """ + Test whether any array element along a given axis evaluates to True. + + Refer to `numpy.any` for full documentation. + + Parameters + ---------- + axis: int, optional + Axis along which logical OR is performed + out: ndarray, optional + Output to existing array instead of creating new one, must have + same shape as expected output + + Returns + ------- + any : bool, ndarray + Returns a single bool if `axis` is ``None``; otherwise, + returns `ndarray` + + """ return N.ndarray.any(self, axis, out)._align(axis) def all(self, axis=None, out=None): diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index 99b837ba2..176ef3e6f 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -256,15 +256,14 @@ def repeat(a, repeats, axis=None): def put(a, ind, v, mode='raise'): """ - Changes specific elements of one array by replacing from another array. + Replaces specified elements of an array with given values. - The indexing works on the flattened target array, `put` is roughly + The indexing works on the flattened target array. `put` is roughly equivalent to: :: - for i, val in zip(ind, v): - x.flat[i] = val + a.flat[ind] = v Parameters ---------- @@ -292,14 +291,14 @@ def put(a, ind, v, mode='raise'): Examples -------- - >>> x = np.arange(5) - >>> np.put(x, [0, 2], [-44, -55]) - >>> x + >>> a = np.arange(5) + >>> np.put(a, [0, 2], [-44, -55]) + >>> a array([-44, 1, -55, 3, 4]) - >>> x = np.arange(5) - >>> np.put(x, 22, -5, mode='clip') - >>> x + >>> a = np.arange(5) + >>> np.put(a, 22, -5, mode='clip') + >>> a array([ 0, 1, 2, 3, -5]) """ @@ -1086,10 +1085,14 @@ def compress(condition, a, axis=None, out=None): """ Return selected slices of an array along given axis. + When working along a given axis, a slice along that axis is returned in + `output` for each index where `condition` evaluates to True. When + working on a 1-D array, `compress` is equivalent to `extract`. + Parameters ---------- - condition : array_like - Boolean 1-D array selecting which entries to return. If len(condition) + condition : 1-D array of bools + Array that selects which entries to return. If len(condition) is less than the size of `a` along the given axis, then output is truncated to the length of the condition array. a : array_like @@ -1109,18 +1112,31 @@ def compress(condition, a, axis=None, out=None): See Also -------- - ndarray.compress: Equivalent method. + take, choose, diag, diagonal, select + ndarray.compress : Equivalent method. Examples -------- - >>> a = np.array([[1, 2], [3, 4]]) + >>> a = np.array([[1, 2], [3, 4], [5, 6]]) + >>> a + array([[1, 2], + [3, 4], + [5, 6]]) >>> np.compress([0, 1], a, axis=0) array([[3, 4]]) - >>> np.compress([1], a, axis=1) - array([[1], - [3]]) - >>> np.compress([0,1,1], a) - array([2, 3]) + >>> np.compress([False, True, True], a, axis=0) + array([[3, 4], + [5, 6]]) + >>> np.compress([False, True], a, axis=1) + array([[2], + [4], + [6]]) + + Working on the flattened array does not return slices along an axis but + selects elements. + + >>> np.compress([False, True], a) + array([2]) """ try: @@ -1306,6 +1322,8 @@ def any(a,axis=None, out=None): """ Test whether any array element along a given axis evaluates to True. + Returns single boolean unless `axis` is not ``None`` + Parameters ---------- a : array_like @@ -1322,8 +1340,8 @@ def any(a,axis=None, out=None): Returns ------- - any : ndarray, bool - A new boolean or array is returned unless `out` is + any : bool, ndarray + A new boolean or `ndarray` is returned unless `out` is specified, in which case a reference to `out` is returned. See Also @@ -1429,12 +1447,10 @@ def cumsum (a, axis=None, dtype=None, out=None): Parameters ---------- a : array_like - Input array or object that can be converted to an array. + Input array. axis : int, optional Axis along which the cumulative sum is computed. The default - (`axis` = `None`) is to compute the cumsum over the flattened - array. `axis` may be negative, in which case it counts from the - last to the first axis. + (None) is to compute the cumsum over the flattened array. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults @@ -1459,11 +1475,12 @@ def cumsum (a, axis=None, dtype=None, out=None): Examples -------- - >>> a = np.array([[1,2,3],[4,5,6]]) + >>> a = np.array([[1,2,3], [4,5,6]]) >>> np.cumsum(a) array([ 1, 3, 6, 10, 15, 21]) - >>> np.cumsum(a,dtype=float) # specifies type of output value(s) + >>> np.cumsum(a, dtype=float) # specifies type of output value(s) array([ 1., 3., 6., 10., 15., 21.]) + >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns array([[1, 2, 3], [5, 7, 9]]) @@ -2122,14 +2139,13 @@ def std(a, axis=None, dtype=None, out=None, ddof=0): Returns ------- - standard_deviation : {ndarray, scalar}; see dtype parameter above. + standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. See Also -------- - numpy.var : Variance - numpy.mean : Average + var, mean Notes ----- @@ -2145,7 +2161,7 @@ def std(a, axis=None, dtype=None, out=None, ddof=0): is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. - Note that, for complex numbers, std takes the absolute + Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. Examples @@ -2153,9 +2169,9 @@ def std(a, axis=None, dtype=None, out=None, ddof=0): >>> a = np.array([[1, 2], [3, 4]]) >>> np.std(a) 1.1180339887498949 - >>> np.std(a, 0) + >>> np.std(a, axis=0) array([ 1., 1.]) - >>> np.std(a, 1) + >>> np.std(a, axis=1) array([ 0.5, 0.5]) """ diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 65f4938fe..2392c3aa7 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -17,7 +17,7 @@ mode_equivalents = { class memmap(ndarray): """ - Create a memory-map to an array stored in a file on disk. + Create a memory-map to an array stored in a *binary* file on disk. Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory. Numpy's @@ -58,7 +58,7 @@ class memmap(ndarray): order : {'C', 'F'}, optional Specify the order of the ndarray memory layout: C (row-major) or Fortran (column-major). This only has an effect if the shape is - greater than 1-D. The defaullt order is 'C'. + greater than 1-D. The default order is 'C'. Methods ------- diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 50e3fd75b..aacd476b6 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -362,24 +362,52 @@ def require(a, dtype=None, requirements=None): Parameters ---------- a : array_like - The object to be converted to a type-and-requirement satisfying array + The object to be converted to a type-and-requirement-satisfying array. dtype : data-type - The required data-type (None is the default data-type -- float64) - requirements : list of strings + The required data-type, the default data-type is float64). + requirements : str or list of str The requirements list can be any of the following - * 'ENSUREARRAY' ('E') - ensure that a base-class ndarray * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array * 'ALIGNED' ('A') - ensure a data-type aligned array - * 'WRITEABLE' ('W') - ensure a writeable array + * 'WRITEABLE' ('W') - ensure a writable array * 'OWNDATA' ('O') - ensure an array that owns its own data + See Also + -------- + asarray : Convert input to an ndarray. + asanyarray : Convert to an ndarray, but pass through ndarray subclasses. + ascontiguousarray : Convert input to a contiguous array. + asfortranarray : Convert input to an ndarray with column-major + memory order. + ndarray.flags : Information about the memory layout of the array. + Notes ----- The returned array will be guaranteed to have the listed requirements by making a copy if needed. + Examples + -------- + >>> x = np.arange(6).reshape(2,3) + >>> x.flags + C_CONTIGUOUS : True + F_CONTIGUOUS : False + OWNDATA : False + WRITEABLE : True + ALIGNED : True + UPDATEIFCOPY : False + + >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) + >>> y.flags + C_CONTIGUOUS : False + F_CONTIGUOUS : True + OWNDATA : True + WRITEABLE : True + ALIGNED : True + UPDATEIFCOPY : False + """ if requirements is None: requirements = [] @@ -582,6 +610,16 @@ def correlate(a,v,mode='valid'): acorrelate: Discrete correlation following the usual signal processing definition for complex arrays, and without assuming that correlate(a, b) == correlate(b, a) + + Examples + -------- + >>> np.correlate([1, 2, 3], [0, 1, 0.5]) + array([ 3.5]) + >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") + array([ 2. , 3.5, 3. ]) + >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") + array([ 0.5, 2. , 3.5, 3. , 0. ]) + """ mode = _mode_from_name(mode) return multiarray.correlate(a,v,mode) @@ -591,9 +629,9 @@ def acorrelate(a, v, mode='valid'): Discrete, linear correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal - processing texts: + processing texts:: - z[k] = sum_n a[n] * conj(v[n+k]) + z[k] = sum_n a[n] * conj(v[n+k]) with a and v sequences being zero-padded where necessary and conj being the conjugate. @@ -606,15 +644,16 @@ def acorrelate(a, v, mode='valid'): Refer to the `convolve` docstring. Note that the default is `valid`, unlike `convolve`, which uses `full`. - Note - ---- - This is the function which corresponds to matlab xcorr. - See Also -------- convolve : Discrete, linear convolution of two one-dimensional sequences. correlate: Deprecated function to compute correlation + + Notes + ----- + This is the function which corresponds to matlab xcorr. + """ mode = _mode_from_name(mode) return multiarray.acorrelate(a, v, mode) @@ -1170,20 +1209,26 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): Parameters ---------- arr : ndarray - Input array. - max_line_width : int - The maximum number of columns the string should span. Newline - characters splits the string appropriately after array elements. - precision : int - Floating point precision. - suppress_small : bool - Represent very small numbers as zero. + Input array. + max_line_width : int, optional + The maximum number of columns the string should span. Newline + characters split the string appropriately after array elements. + precision : int, optional + Floating point precision. Default is the current printing precision + (usually 8), which can be altered using `set_printoptions`. + suppress_small : bool, optional + Represent very small numbers as zero, default is False. Very small + is defined by `precision`, if the precision is 8 then + numbers smaller than 5e-9 are represented as zero. Returns ------- string : str The string representation of an array. + See Also + -------- + array_str, array2string, set_printoptions Examples -------- @@ -1194,6 +1239,10 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' + >>> x = np.array([1e-6, 4e-7, 2, 3]) + >>> np.array_repr(x, precision=6, suppress_small=True) + 'array([ 0.000001, 0. , 2. , 3. ])' + """ if arr.size > 0 or arr.shape==(0,): lst = array2string(arr, max_line_width, precision, suppress_small, @@ -1221,7 +1270,11 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): def array_str(a, max_line_width=None, precision=None, suppress_small=None): """ - Return a string representation of an array. + Return a string representation of the data in an array. + + The data in the array is returned as a single string. This function + is similar to `array_repr`, the difference is that `array_repr` also + returns information on the type of array and data type. Parameters ---------- @@ -1230,13 +1283,16 @@ def array_str(a, max_line_width=None, precision=None, suppress_small=None): max_line_width : int, optional Inserts newlines if text is longer than `max_line_width`. precision : int, optional - If `a` is float, `precision` sets floating point precision. - suppress_small : boolean, optional - Represent very small numbers as zero. + Floating point precision. Default is the current printing precision + (usually 8), which can be altered using set_printoptions. + suppress_small : bool, optional + Represent very small numbers as zero, default is False. Very small is + defined by precision, if the precision is 8 then numbers smaller than + 5e-9 are represented as zero. See Also -------- - array2string, array_repr + array2string, array_repr, set_printoptions Examples -------- @@ -1264,8 +1320,8 @@ def indices(dimensions, dtype=int): ---------- dimensions : sequence of ints The shape of the grid. - dtype : optional - Data_type of the result. + dtype : dtype, optional + Data type of the result. Returns ------- @@ -1291,7 +1347,7 @@ def indices(dimensions, dtype=int): Examples -------- - >>> grid = np.indices((2,3)) + >>> grid = np.indices((2, 3)) >>> grid.shape (2,2,3) >>> grid[0] # row indices @@ -1301,6 +1357,17 @@ def indices(dimensions, dtype=int): array([[0, 1, 2], [0, 1, 2]]) + The indices can be used as an index into an array. + + >>> x = np.arange(20).reshape(5, 4) + >>> row, col = np.indices((2, 3)) + >>> x[row, col] + array([[0, 1, 2], + [4, 5, 6]]) + + Note that it would be more straightforward in the above example to + extract the required elements directly with ``x[:2, :3]``. + """ dimensions = tuple(dimensions) N = len(dimensions) @@ -1816,22 +1883,24 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): Parameters ---------- - all : {'ignore', 'warn', 'raise', 'call'}, optional + all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Set treatment for all types of floating-point errors at once: - - ignore: Take no action when the exception occurs - - warn: Print a `RuntimeWarning` (via the Python `warnings` module) - - raise: Raise a `FloatingPointError` + - ignore: Take no action when the exception occurs. + - warn: Print a `RuntimeWarning` (via the Python `warnings` module). + - raise: Raise a `FloatingPointError`. - call: Call a function specified using the `seterrcall` function. + - print: Print a warning directly to ``stdout``. + - log: Record error in a Log object specified by `seterrcall`. The default is not to change the current behavior. - divide : {'ignore', 'warn', 'raise', 'call'}, optional + divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for division by zero. - over : {'ignore', 'warn', 'raise', 'call'}, optional + over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for floating-point overflow. - under : {'ignore', 'warn', 'raise', 'call'}, optional + under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for floating-point underflow. - invalid : {'ignore', 'warn', 'raise', 'call'}, optional + invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Treatment for invalid floating-point operation. Returns @@ -1859,22 +1928,25 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): Examples -------- - - Set mode: - - >>> seterr(over='raise') # doctest: +SKIP + >>> np.seterr(over='raise') {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + >>> np.seterr(all='ignore') # reset to default + {'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} - >>> old_settings = seterr(all='warn', over='raise') # doctest: +SKIP - - >>> int16(32000) * int16(3) # doctest: +SKIP + >>> np.int16(32000) * np.int16(3) + 30464 + >>> old_settings = np.seterr(all='warn', over='raise') + >>> np.int16(32000) * np.int16(3) Traceback (most recent call last): - File "<stdin>", line 1, in ? + File "<stdin>", line 1, in <module> FloatingPointError: overflow encountered in short_scalars - >>> seterr(all='ignore') # doctest: +SKIP - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', - 'under': 'ignore'} + + >>> np.seterr(all='print') + {'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'print'} + >>> np.int16(32000) * np.int16(3) + Warning: overflow encountered in short_scalars + 30464 """ @@ -1897,11 +1969,41 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None): def geterr(): - """Get the current way of handling floating-point errors. + """ + Get the current way of handling floating-point errors. + + Returns + ------- + res : dict + A dictionary with keys "divide", "over", "under", and "invalid", + whose values are from the strings "ignore", "print", "log", "warn", + "raise", and "call". The keys represent possible floating-point + exceptions, and the values define how these exceptions are handled. + + See Also + -------- + geterrcall, seterr, seterrcall + + Notes + ----- + For complete documentation of the types of floating-point exceptions and + treatment options, see `seterr`. + + Examples + -------- + >>> np.geterr() # default is all set to 'ignore' + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} + >>> np.arange(3.) / np.arange(3.) + array([ NaN, 1., 1.]) + + >>> oldsettings = np.seterr(all='warn', over='raise') + >>> np.geterr() + {'over': 'raise', 'divide': 'warn', 'invalid': 'warn', 'under': 'warn'} + >>> np.arange(3.) / np.arange(3.) + __main__:1: RuntimeWarning: invalid value encountered in divide + array([ NaN, 1., 1.]) - Returns a dictionary with entries "divide", "over", "under", and - "invalid", whose values are from the strings - "ignore", "print", "log", "warn", "raise", and "call". """ maskvalue = umath.geterrobj()[1] mask = 7 @@ -1952,13 +2054,13 @@ def seterrcall(func): is to set the error-handler to 'call', using `seterr`. Then, set the function to call using this function. - The second is to set the error-handler to `log`, using `seterr`. + The second is to set the error-handler to 'log', using `seterr`. Floating-point errors then trigger a call to the 'write' method of the provided object. Parameters ---------- - log_func_or_obj : callable f(err, flag) or object with write method + func : callable f(err, flag) or object with write method Function to call upon floating-point errors ('call'-mode) or object whose 'write' method is used to log such message ('log'-mode). @@ -1971,7 +2073,7 @@ def seterrcall(func): In other words, ``flags = divide + 2*over + 4*under + 8*invalid``. - If an object is provided, it's write method should take one argument, + If an object is provided, its write method should take one argument, a string. Returns @@ -1979,6 +2081,10 @@ def seterrcall(func): h : callable or log instance The old error handler. + See Also + -------- + seterr, geterr, geterrcall + Examples -------- Callback upon error: @@ -2025,7 +2131,45 @@ def seterrcall(func): return old def geterrcall(): - """Return the current callback function used on floating-point errors. + """ + Return the current callback function used on floating-point errors. + + When the error handling for a floating-point error (one of "divide", + "over", "under", or "invalid") is set to 'call' or 'log', the function + that is called or the log instance that is written to is returned by + `geterrcall`. This function or log instance has been set with + `seterrcall`. + + Returns + ------- + errobj : callable, log instance or None + The current error handler. If no handler was set through `seterrcall`, + ``None`` is returned. + + See Also + -------- + seterrcall, seterr, geterr + + Notes + ----- + For complete documentation of the types of floating-point exceptions and + treatment options, see `seterr`. + + Examples + -------- + >>> np.geterrcall() # we did not yet set a handler, returns None + + >>> oldsettings = np.seterr(all='call') + >>> def err_handler(type, flag): + ... print "Floating point error (%s), with flag %s" % (type, flag) + >>> oldhandler = np.seterrcall(err_handler) + >>> np.array([1,2,3])/0.0 + Floating point error (divide by zero), with flag 1 + array([ Inf, Inf, Inf]) + >>> cur_handler = np.geterrcall() + >>> cur_handler is err_handler + True + """ return umath.geterrobj()[2] diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 3d34ceb7f..e773c77ae 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -517,6 +517,9 @@ def issubdtype(arg1, arg2): arg2 : dtype_like dtype or string representing a typecode. + Returns + ------- + out : bool See Also -------- diff --git a/numpy/doc/constants.py b/numpy/doc/constants.py index 22e353b0e..154c74621 100644 --- a/numpy/doc/constants.py +++ b/numpy/doc/constants.py @@ -64,9 +64,9 @@ add_newdoc('numpy', 'NAN', See Also -------- - isnan : Shows which elements are Not a Number. - isfinite : Shows which elements are finite (not one of - Not a Number, positive infinity and negative infinity) + isnan: Shows which elements are Not a Number. + + isfinite: Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes ----- @@ -182,8 +182,8 @@ add_newdoc('numpy', 'NaN', -------- isnan : Shows which elements are Not a Number. - isfinite : Shows which elements are finite (not one of - Not a Number, positive infinity and negative infinity) + + isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes ----- diff --git a/numpy/doc/creation.py b/numpy/doc/creation.py index 133765678..d57c7c261 100644 --- a/numpy/doc/creation.py +++ b/numpy/doc/creation.py @@ -76,7 +76,7 @@ generally will not do for arbitrary start, stop, and step values. indices() will create a set of arrays (stacked as a one-higher dimensioned array), one per dimension with each representing variation in that dimension. -An examples illustrates much better than a verbal description: :: +An example illustrates much better than a verbal description: :: >>> np.indices((3,3)) array([[[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]) diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index 5fd56246e..fd973a123 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -141,7 +141,6 @@ def fft(a, n=None, axis=-1): 1.14383329e-17 +1.22460635e-16j, -1.64863782e-15 +1.77635684e-15j]) - >>> from numpy.fft import fft, fftfreq >>> import matplotlib.pyplot as plt >>> t = np.arange(256) @@ -591,7 +590,6 @@ def fftn(a, s=None, axes=None): [[-2.+0.j, -2.+0.j, -2.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j]]]) - >>> from numpy import meshgrid, pi, arange, sin, cos, log, abs >>> from numpy.fft import fftn, fftshift >>> import matplotlib.pyplot as plt diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index c5e7822f2..b1a730efa 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -46,23 +46,45 @@ def ediff1d(ary, to_end=None, to_begin=None): ---------- ary : array This array will be flattened before the difference is taken. - to_end : number, optional - If provided, this number will be tacked onto the end of the returned + to_end : array_like, optional + If provided, this number will be appended to the end of the returned differences. - to_begin : number, optional - If provided, this number will be taked onto the beginning of the + to_begin : array_like, optional + If provided, this array will be appended to the beginning of the returned differences. Returns ------- ed : array - The differences. Loosely, this will be (ary[1:] - ary[:-1]). + The differences. Loosely, this will be ``ary[1:] - ary[:-1]``. + + See Also + -------- + diff, gradient Notes ----- When applied to masked arrays, this function drops the mask information if the `to_begin` and/or `to_end` parameters are used + Examples + -------- + >>> x = np.array([1, 2, 4, 7, 0]) + >>> np.ediff1d(x) + array([ 1, 2, 3, -7]) + + >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) + array([-99, 1, 2, 3, -7, 88, 99]) + + The returned array is always 1D. + + >>> y = np.array([[1, 2, 4], [1, 6, 24]]) + >>> y + array([[ 1, 2, 4], + [ 1, 6, 24]]) + >>> np.ediff1d(y) + array([ 1, 2, -3, 5, 18]) + """ ary = np.asanyarray(ary).flat ed = ary[1:] - ary[:-1] @@ -168,28 +190,41 @@ def unique1d(ar1, return_index=False, return_inverse=False): def intersect1d(ar1, ar2): """ - Intersection returning repeated or unique elements common to both arrays. + Find elements that are common to two arrays. + + For speed, it is assumed the two input arrays do not have any + repeated elements. To find the intersection of two arrays that + have repeated elements, use `intersect1d_nu`. Parameters ---------- ar1,ar2 : array_like - Input arrays. + Input arrays. These must be 1D and must not have repeated elements. Returns ------- out : ndarray, shape(N,) - Sorted 1D array of common elements with repeating elements. + Sorted array of common elements. See Also -------- - intersect1d_nu : Returns only unique common elements. + intersect1d_nu : Find the intersection for input arrays with + repeated elements. numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- - >>> np.intersect1d([1,3,3],[3,1,1]) - array([1, 1, 3, 3]) + >>> np.intersect1d([1, 2, 3], [2, 3, 4]) + array([2, 3]) + >>> np.intersect1d(['a','b','c'], ['b','c','d']) + array(['b', 'c'], + dtype='|S1') + + This function fails if the input arrays have repeated elements. + + >>> np.intersect1d([1, 1, 2, 3, 3, 4], [1, 4]) + array([1, 1, 3, 4]) """ aux = np.concatenate((ar1,ar2)) @@ -198,7 +233,11 @@ def intersect1d(ar1, ar2): def intersect1d_nu(ar1, ar2): """ - Intersection returning unique elements common to both arrays. + Find elements common to two arrays. + + Returns an array of unique elements that represents the intersection + of the two input arrays. Unlike `intersect1d`, the input arrays can + have repeated elements. Parameters ---------- @@ -208,17 +247,18 @@ def intersect1d_nu(ar1, ar2): Returns ------- out : ndarray, shape(N,) - Sorted 1D array of common and unique elements. + Sorted 1D array of common, unique elements. See Also -------- - intersect1d : Returns repeated or unique common elements. + intersect1d : Faster version of `intersect1d_nu` for 1D input arrays + without repeated elements. numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- - >>> np.intersect1d_nu([1,3,3],[3,1,1]) + >>> np.intersect1d_nu([1, 3 ,3], [3, 3, 1, 1]) array([1, 3]) """ @@ -265,43 +305,49 @@ def setxor1d(ar1, ar2): def setmember1d(ar1, ar2): """ - Return a boolean array set True where first element is in second array. + Test whether elements of one array are also present in a second array. - Boolean array is the shape of `ar1` containing True where the elements - of `ar1` are in `ar2` and False otherwise. - - Use unique1d() to generate arrays with only unique elements to use as - inputs to this function. + Returns a boolean array the same length as `ar1` that is True where an + element of `ar1` is also in `ar2` and False otherwise. The input arrays + must not contain any repeated elements. If they do, unique arrays can + be created using `unique1d()` to use as inputs to this function. Parameters ---------- ar1 : array_like - Input array. + Input array. It must not have any repeated elements ar2 : array_like - Input array. + Input array. Again, it must not have any repeated elements. Returns ------- mask : ndarray, bool The values `ar1[mask]` are in `ar2`. - See Also -------- setmember1d_nu : Works for arrays with non-unique elements. numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. + unique1d : Find unique elements in an array. Examples -------- - >>> test = np.arange(5) + >>> test = [0, 1, 2, 3, 4, 5] >>> states = [0, 2] - >>> mask = np.setmember1d(test,states) + >>> mask = np.setmember1d(test, states) >>> mask array([ True, False, True, False, False], dtype=bool) >>> test[mask] array([0, 2]) + This function fails if there are repeated elements in the input arrays: + + >>> test = [0, 1, 1, 2, 3, 3] + >>> states = [0, 2] + >>> np.setmember1d(test,states) + array([ True, True, False, True, True, False], dtype=bool) # Wrong! + """ # 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 diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index 0cef1c4d2..0b9372515 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -28,6 +28,18 @@ def fv(rate, nper, pmt, pv, when='end'): """ Compute the future value. + Given: + * a present value, `pv` + * an interest `rate` compounded once per period, of which + there are + * `nper` total + * a (fixed) payment, `pmt`, paid either + * at the beginning (`when` = {'begin', 1}) or the end + (`when` = {'end', 0}) of each period + + Return: + the value at the end of the `nper` periods + Parameters ---------- rate : scalar or array_like of shape(M, ) @@ -61,6 +73,17 @@ def fv(rate, nper, pmt, pv, when='end'): fv + pv + pmt * nper == 0 + References + ---------- + .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). + Open Document Format for Office Applications (OpenDocument)v1.2, + Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, + Pre-Draft 12. Organization for the Advancement of Structured Information + Standards (OASIS). Billerica, MA, USA. [ODT Document]. + Available: + http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula + OpenDocument-formula-20090508.odt + Examples -------- What is the future value after 10 years of saving $100 now, with @@ -94,6 +117,19 @@ def pmt(rate, nper, pv, fv=0, when='end'): """ Compute the payment against loan principal plus interest. + Given: + * a present value, `pv` (e.g., an amount borrowed) + * a future value, `fv` (e.g., 0) + * an interest `rate` compounded once per period, of which + there are + * `nper` total + * and (optional) specification of whether payment is made + at the beginning (`when` = {'begin', 1}) or the end + (`when` = {'end', 0}) of each period + + Return: + the (fixed) periodic payment. + Parameters ---------- rate : array_like @@ -102,8 +138,8 @@ def pmt(rate, nper, pv, fv=0, when='end'): Number of compounding periods pv : array_like Present value - fv : array_like - Future value + fv : array_like (optional) + Future value (default = 0) when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) @@ -117,7 +153,7 @@ def pmt(rate, nper, pv, fv=0, when='end'): Notes ----- - The payment ``pmt`` is computed by solving the equation:: + The payment is computed by solving the equation:: fv + pv*(1 + rate)**nper + @@ -127,16 +163,37 @@ def pmt(rate, nper, pv, fv=0, when='end'): fv + pv + pmt * nper == 0 + for ``pmt``. + + Note that computing a monthly mortgage payment is only + one use for this function. For example, pmt returns the + periodic deposit one must make to achieve a specified + future balance given an initial deposit, a fixed, + periodically compounded interest rate, and the total + number of periods. + + References + ---------- + .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). + Open Document Format for Office Applications (OpenDocument)v1.2, + Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, + Pre-Draft 12. Organization for the Advancement of Structured Information + Standards (OASIS). Billerica, MA, USA. [ODT Document]. + Available: + http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula + OpenDocument-formula-20090508.odt + Examples -------- - What would the monthly payment need to be to pay off a $200,000 loan in 15 + What is the monthly payment needed to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%? >>> np.pmt(0.075/12, 12*15, 200000) -1854.0247200054619 - In order to pay-off (i.e. have a future-value of 0) the $200,000 obtained - today, a monthly payment of $1,854.02 would be required. + In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained + today, a monthly payment of $1,854.02 would be required. Note that this + example illustrates usage of `fv` having a default value of 0. """ when = _convert_when(when) @@ -282,6 +339,18 @@ def pv(rate, nper, pmt, fv=0.0, when='end'): """ Compute the present value. + Given: + * a future value, `fv` + * an interest `rate` compounded once per period, of which + there are + * `nper` total + * a (fixed) payment, `pmt`, paid either + * at the beginning (`when` = {'begin', 1}) or the end + (`when` = {'end', 0}) of each period + + Return: + the value now + Parameters ---------- rate : array_like @@ -302,7 +371,7 @@ def pv(rate, nper, pmt, fv=0.0, when='end'): Notes ----- - The present value ``pv`` is computed by solving the equation:: + The present value is computed by solving the equation:: fv + pv*(1 + rate)**nper + @@ -312,6 +381,45 @@ def pv(rate, nper, pmt, fv=0.0, when='end'): fv + pv + pmt * nper = 0 + for `pv`, which is then returned. + + References + ---------- + .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). + Open Document Format for Office Applications (OpenDocument)v1.2, + Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, + Pre-Draft 12. Organization for the Advancement of Structured Information + Standards (OASIS). Billerica, MA, USA. [ODT Document]. + Available: + http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula + OpenDocument-formula-20090508.odt + + Examples + -------- + What is the present value (e.g., the initial investment) + of an investment that needs to total $15692.93 + after 10 years of saving $100 every month? Assume the + interest rate is 5% (annually) compounded monthly. + + >>> np.pv(0.05/12, 10*12, -100, 15692.93) + -100.00067131625819 + + By convention, the negative sign represents cash flow out + (i.e., money not available today). Thus, to end up with + $15,692.93 in 10 years saving $100 a month at 5% annual + interest, one's initial deposit should also be $100. + + If any input is array_like, ``pv`` returns an array of equal shape. + Let's compare different interest rates in the example above: + + >>> a = np.array((0.05, 0.04, 0.03))/12 + >>> np.pv(a, 10*12, -100, 15692.93) + array([ -100.00067132, -649.26771385, -1273.78633713]) + + So, to end up with the same $15692.93 under the same $100 per month + "savings plan," for annual interest rates of 4% and 3%, one would + need initial investments of $649.27 and $1273.79, respectively. + """ when = _convert_when(when) rate, nper, pmt, fv, when = map(np.asarray, [rate, nper, pmt, fv, when]) @@ -391,24 +499,54 @@ def irr(values): """ Return the Internal Rate of Return (IRR). - This is the rate of return that gives a net present value of 0.0. + This is the "average" periodically compounded rate of return + that gives a net present value of 0.0; for a more complete explanation, + see Notes below. Parameters ---------- values : array_like, shape(N,) - Input cash flows per time period. At least the first value would be - negative to represent the investment in the project. + Input cash flows per time period. By convention, net "deposits" + are negative and net "withdrawals" are positive. Thus, for example, + at least the first element of `values`, which represents the initial + investment, will typically be negative. Returns ------- out : float Internal Rate of Return for periodic input values. + Notes + ----- + The IRR is perhaps best understood through an example (illustrated + using np.irr in the Examples section below). Suppose one invests + 100 units and then makes the following withdrawals at regular + (fixed) intervals: 39, 59, 55, 20. Assuming the ending value is 0, + one's 100 unit investment yields 173 units; however, due to the + combination of compounding and the periodic withdrawals, the + "average" rate of return is neither simply 0.73/4 nor (1.73)^0.25-1. + Rather, it is the solution (for :math:`r`) of the equation: + + .. math:: -100 + \\frac{39}{1+r} + \\frac{59}{(1+r)^2} + + \\frac{55}{(1+r)^3} + \\frac{20}{(1+r)^4} = 0 + + In general, for `values` :math:`= [v_0, v_1, ... v_M]`, + irr is the solution of the equation: [G]_ + + .. math:: \\sum_{t=0}^M{\\frac{v_t}{(1+irr)^{t}}} = 0 + + References + ---------- + .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed., + Addison-Wesley, 2003, pg. 348. + Examples -------- >>> np.irr([-100, 39, 59, 55, 20]) 0.2809484211599611 + (Compare with the Example given for numpy.lib.financial.npv) + """ res = np.roots(values[::-1]) # Find the root(s) between 0 and 1 @@ -430,8 +568,14 @@ def npv(rate, values): rate : scalar The discount rate. values : array_like, shape(M, ) - The values of the time series of cash flows. Must be the same - increment as the `rate`. + The values of the time series of cash flows. The (fixed) time + interval between cash flow "events" must be the same as that + for which `rate` is given (i.e., if `rate` is per year, then + precisely a year is understood to elapse between each cash flow + event). By convention, investments or "deposits" are negative, + income or "withdrawals" are positive; `values` must begin with + the initial investment, thus `values[0]` will typically be + negative. Returns ------- @@ -440,9 +584,21 @@ def npv(rate, values): Notes ----- - Returns the result of: + Returns the result of: [G]_ + + .. math :: \\sum_{t=0}^M{\\frac{values_t}{(1+rate)^{t}}} + + References + ---------- + .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed., + Addison-Wesley, 2003, pg. 346. + + Examples + -------- + >>> np.npv(0.281,[-100, 39, 59, 55, 20]) + -0.0066187288356340801 - .. math :: \\sum_{t=1}^M{\\frac{values_t}{(1+rate)^{t}}} + (Compare with the Example given for numpy.lib.financial.irr) """ values = np.asarray(values) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index b493801df..e596d8810 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -717,9 +717,9 @@ def piecewise(x, condlist, funclist, *args, **kw): Parameters ---------- - x : (N,) ndarray + x : ndarray The input domain. - condlist : list of M (N,)-shaped boolean arrays + condlist : list of bool arrays Each boolean array corresponds to a function in `funclist`. Wherever `condlist[i]` is True, `funclist[i](x)` is used as the output value. @@ -727,24 +727,24 @@ def piecewise(x, condlist, funclist, *args, **kw): and should therefore be of the same shape as `x`. The length of `condlist` must correspond to that of `funclist`. - If one extra function is given, i.e. if the length of `funclist` is - M+1, then that extra function is the default value, used wherever - all conditions are false. - funclist : list of M or M+1 callables, f(x,*args,**kw), or values + If one extra function is given, i.e. if + ``len(funclist) - len(condlist) == 1``, then that extra function + is the default value, used wherever all conditions are false. + funclist : list of callables, f(x,*args,**kw), or scalars Each function is evaluated over `x` wherever its corresponding condition is True. It should take an array as input and give an array or a scalar value as output. If, instead of a callable, - a value is provided then a constant function (``lambda x: value``) is + a scalar is provided then a constant function (``lambda x: scalar``) is assumed. args : tuple, optional Any further arguments given to `piecewise` are passed to the functions - upon execution, i.e., if called ``piecewise(...,...,1,'a')``, then - each function is called as ``f(x,1,'a')``. - kw : dictionary, optional + upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then + each function is called as ``f(x, 1, 'a')``. + kw : dict, optional Keyword arguments used in calling `piecewise` are passed to the functions upon execution, i.e., if called - ``piecewise(...,...,lambda=1)``, then each function is called as - ``f(x,lambda=1)``. + ``piecewise(..., ..., lambda=1)``, then each function is called as + ``f(x, lambda=1)``. Returns ------- @@ -754,6 +754,11 @@ def piecewise(x, condlist, funclist, *args, **kw): as defined by the boolean arrays in `condlist`. Portions not covered by any condition have undefined values. + + See Also + -------- + choose, select, where + Notes ----- This is similar to choose or select, except that functions are @@ -773,8 +778,8 @@ def piecewise(x, condlist, funclist, *args, **kw): -------- Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. - >>> x = np.arange(6) - 2.5 # x runs from -2.5 to 2.5 in steps of 1 - >>> np.piecewise(x, [x < 0, x >= 0.5], [-1,1]) + >>> x = np.arange(6) - 2.5 + >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.]) Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for @@ -836,39 +841,35 @@ def select(condlist, choicelist, default=0): Parameters ---------- - condlist : list of N boolean arrays of length M - The conditions C_0 through C_(N-1) which determine - from which vector the output elements are taken. - choicelist : list of N arrays of length M - Th vectors V_0 through V_(N-1), from which the output - elements are chosen. + condlist : list of bool ndarrays + The list of conditions which determine from which array in `choicelist` + the output elements are taken. When multiple conditions are satisfied, + the first one encountered in `condlist` is used. + choicelist : list of ndarrays + The list of arrays from which the output elements are taken. It has + to be of the same length as `condlist`. + default : scalar, optional + The element inserted in `output` when all conditions evaluate to False. Returns ------- - output : 1-dimensional array of length M - The output at position m is the m-th element of the first - vector V_n for which C_n[m] is non-zero. Note that the - output depends on the order of conditions, since the - first satisfied condition is used. - - Notes - ----- - Equivalent to: - :: + output : ndarray + The output at position m is the m-th element of the array in + `choicelist` where the m-th element of the corresponding array in + `condlist` is True. - output = [] - for m in range(M): - output += [V[m] for V,C in zip(values,cond) if C[m]] - or [default] + See Also + -------- + where : Return elements from one of two arrays depending on condition. + take, choose, compress, diag, diagonal Examples -------- - >>> t = np.arange(10) - >>> s = np.arange(10)*100 - >>> condlist = [t == 4, t > 5] - >>> choicelist = [s, t] + >>> x = np.arange(10) + >>> condlist = [x<3, x>5] + >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist) - array([ 0, 0, 0, 0, 400, 0, 6, 7, 8, 9]) + array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81]) """ n = len(condlist) @@ -960,11 +961,17 @@ def gradient(f, *varargs): Examples -------- - >>> np.gradient(np.array([[1,1],[3,4]])) - [array([[ 2., 3.], - [ 2., 3.]]), - array([[ 0., 0.], - [ 1., 1.]])] + >>> x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) + >>> np.gradient(x) + array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) + >>> np.gradient(x, 2) + array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ]) + + >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)) + [array([[ 2., 2., -1.], + [ 2., 2., -1.]]), + array([[ 1. , 2.5, 4. ], + [ 1. , 1. , 1. ]])] """ N = len(f.shape) # number of dimensions @@ -1026,7 +1033,11 @@ def gradient(f, *varargs): def diff(a, n=1, axis=-1): """ - Calculate the nth order discrete difference along given axis. + Calculate the n-th order discrete difference along given axis. + + The first order difference is given by ``out[n] = a[n+1] - a[n]`` along + the given axis, higher order differences are calculated by using `diff` + recursively. Parameters ---------- @@ -1035,26 +1046,31 @@ def diff(a, n=1, axis=-1): n : int, optional The number of times values are differenced. axis : int, optional - The axis along which the difference is taken. + The axis along which the difference is taken, default is the last axis. Returns ------- out : ndarray - The `n` order differences. The shape of the output is the same as `a` - except along `axis` where the dimension is `n` less. + The `n` order differences. The shape of the output is the same as `a` + except along `axis` where the dimension is smaller by `n`. + + See Also + -------- + gradient, ediff1d Examples -------- - >>> x = np.array([0,1,3,9,5,10]) + >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) - array([ 1, 2, 6, -4, 5]) - >>> np.diff(x,n=2) - array([ 1, 4, -10, 9]) - >>> x = np.array([[1,3,6,10],[0,5,6,8]]) + array([ 1, 2, 3, -7]) + >>> np.diff(x, n=2) + array([ 1, 1, -10]) + + >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], - [5, 1, 2]]) - >>> np.diff(x,axis=0) + [5, 1, 2]]) + >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) """ @@ -1201,15 +1217,34 @@ def unwrap(p, discont=pi, axis=-1): ---------- p : array_like Input array. - discont : float - Maximum discontinuity between values. - axis : integer - Axis along which unwrap will operate. + discont : float, optional + Maximum discontinuity between values, default is ``pi``. + axis : int, optional + Axis along which unwrap will operate, default is the last axis. Returns ------- out : ndarray - Output array + Output array. + + See Also + -------- + rad2deg, deg2rad + + Notes + ----- + If the discontinuity in `p` is smaller than ``pi``, but larger than + `discont`, no unwrapping is done because taking the 2*pi complement + would only make the discontinuity larger. + + Examples + -------- + >>> phase = np.linspace(0, np.pi, num=5) + >>> phase[3:] += np.pi + >>> phase + array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) + >>> np.unwrap(phase) + array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) """ p = asarray(p) @@ -1365,53 +1400,64 @@ def extract(condition, arr): See Also -------- - take, put, putmask + take, put, putmask, compress Examples -------- - >>> arr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) + >>> arr = np.arange(12).reshape((3, 4)) >>> arr - array([[ 1, 2, 3, 4], - [ 5, 6, 7, 8], - [ 9, 10, 11, 12]]) + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition - array([[False, False, True, False], - [False, True, False, False], - [ True, False, False, True]], dtype=bool) + array([[ True, False, False, True], + [False, False, True, False], + [False, True, False, False]], dtype=bool) >>> np.extract(condition, arr) - array([ 3, 6, 9, 12]) + array([0, 3, 6, 9]) + If `condition` is boolean: >>> arr[condition] - array([ 3, 6, 9, 12]) + array([0, 3, 6, 9]) """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): """ - Changes elements of an array based on conditional and input values. + Change elements of an array based on conditional and input values. - Similar to ``putmask(a, mask, vals)`` but the 1D array `vals` has the - same number of elements as the non-zero values of `mask`. Inverse of - ``extract``. + Similar to ``np.putmask(a, mask, vals)``, the difference is that `place` + uses the first N elements of `vals`, where N is the number of True values + in `mask`, while `putmask` uses the elements where `mask` is True. - Sets `a`.flat[n] = `values`\\[n] for each n where `mask`.flat[n] is true. + Note that `extract` does the exact opposite of `place`. Parameters ---------- a : array_like Array to put data into. mask : array_like - Boolean mask array. - values : array_like, shape(number of non-zero `mask`, ) - Values to put into `a`. + Boolean mask array. Must have the same size as `a`. + vals : 1-D sequence + Values to put into `a`. Only the first N elements are used, where + N is the number of True values in `mask`. If `vals` is smaller + than N it will be repeated. See Also -------- - putmask, put, take + putmask, put, take, extract + + Examples + -------- + >>> x = np.arange(6).reshape(2, 3) + >>> np.place(x, x>2, [44, 55]) + >>> x + array([[ 0, 1, 2], + [44, 55, 44]]) """ return _insert(arr, mask, vals) @@ -2841,6 +2887,25 @@ def trapz(y, x=None, dx=1.0, axis=-1): axis : int, optional Specify the axis. + Returns + ------- + out : float + Definite integral as approximated by trapezoidal rule. + + Notes + ----- + Image [2]_ illustrates trapezoidal rule -- y-axis locations of points will + be taken from `y` array, by default x-axis distances between points will be + 1.0, alternatively they can be provided with `x` array or with `dx` scalar. + Return value will be equal to combined area under the red lines. + + + References + ---------- + .. [1] Wikipedia page: http://en.wikipedia.org/wiki/Trapezoidal_rule + + .. [2] Illustration image: http://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png + Examples -------- >>> np.trapz([1,2,3]) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index b8add9ed7..b6eaae29f 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -18,14 +18,20 @@ makemat = matrix.matrix # contributed by Stefan van der Walt def unravel_index(x,dims): """ - Convert a flat index into an index tuple for an array of given shape. + Convert a flat index to an index tuple for an array of given shape. Parameters ---------- x : int Flattened index. - dims : shape tuple - Input shape. + 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 ----- @@ -34,7 +40,7 @@ def unravel_index(x,dims): Examples -------- - >>> arr = np.arange(20).reshape(5,4) + >>> arr = np.arange(20).reshape(5, 4) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], @@ -72,21 +78,45 @@ def unravel_index(x,dims): return tuple(x/dim_prod % dims) def ix_(*args): - """ Construct an open mesh from multiple sequences. + """ + Construct an open mesh from multiple sequences. + + This function takes N 1-D sequences and returns N outputs with N + dimensions each, such that the shape is 1 in all but one dimension + and the dimension with the non-unit shape value cycles through all + N dimensions. + + Using `ix_` one can quickly construct index arrays that will index + the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array + ``[a[1,2] a[1,5] a[3,2] a[3,5]]``. + + Parameters + ---------- + args : 1-D sequences - This function takes n 1-d sequences and returns n outputs with n - dimensions each such that the shape is 1 in all but one dimension and - the dimension with the non-unit shape value cycles through all n - dimensions. + Returns + ------- + out : ndarrays + N arrays with N dimensions each, with N the number of input + sequences. Together these arrays form an open mesh. - Using ix_() one can quickly construct index arrays that will index - the cross product. + See Also + -------- + ogrid, mgrid, meshgrid - a[ix_([1,3,7],[2,5,8])] returns the array + Examples + -------- + >>> a = np.arange(10).reshape(2, 5) + >>> ixgrid = np.ix_([0,1], [2,4]) + >>> ixgrid + (array([[0], + [1]]), array([[2, 4]])) + >>> print ixgrid[0].shape, ixgrid[1].shape + (2, 1) (1, 2) + >>> a[ixgrid] + array([[2, 4], + [7, 9]]) - a[1,2] a[1,5] a[1,8] - a[3,2] a[3,5] a[3,8] - a[7,2] a[7,5] a[7,8] """ out = [] nd = len(args) @@ -215,7 +245,11 @@ mgrid.__doc__ = None # set in numpy.add_newdocs ogrid.__doc__ = None # set in numpy.add_newdocs class AxisConcatenator(object): - """Translates slice objects to concatenation along an axis. + """ + Translates slice objects to concatenation along an axis. + + For detailed documentation on usage, see `r_`. + """ def _retval(self, res): if self.matrix: @@ -338,11 +372,96 @@ class AxisConcatenator(object): # in help(r_) class RClass(AxisConcatenator): - """Translates slice objects to concatenation along the first axis. + """ + Translates slice objects to concatenation along the first axis. + + This is a simple way to build up arrays quickly. There are two use cases. + + 1. If the index expression contains comma separated arrays, then stack + them along their first axis. + 2. If the index expression contains slice notation or scalars then create + a 1-D array with a range indicated by the slice notation. + + If slice notation is used, the syntax ``start:stop:step`` is equivalent + to ``np.arange(start, stop, step)`` inside of the brackets. However, if + ``step`` is an imaginary number (i.e. 100j) then its integer portion is + interpreted as a number-of-points desired and the start and stop are + inclusive. In other words ``start:stop:stepj`` is interpreted as + ``np.linspace(start, stop, step, endpoint=1)`` inside of the brackets. + After expansion of slice notation, all comma separated sequences are + concatenated together. + + Optional character strings placed as the first element of the index + expression can be used to change the output. The strings 'r' or 'c' result + in matrix output. If the result is 1-D and 'r' is specified a 1 x N (row) + matrix is produced. If the result is 1-D and 'c' is specified, then a N x 1 + (column) matrix is produced. If the result is 2-D then both provide the + same matrix result. + + A string integer specifies which axis to stack multiple comma separated + arrays along. A string of two comma-separated integers allows indication + of the minimum number of dimensions to force each entry into as the + second integer (the axis to concatenate along is still the first integer). + + A string with three comma-separated integers allows specification of the + axis to concatenate along, the minimum number of dimensions to force the + entries to, and which axis should contain the start of the arrays which + are less than the specified number of dimensions. In other words the third + integer allows you to specify where the 1's should be placed in the shape + of the arrays that have their shapes upgraded. By default, they are placed + in the front of the shape tuple. The third argument allows you to specify + where the start of the array should be instead. Thus, a third argument of + '0' would place the 1's at the end of the array shape. Negative integers + specify where in the new shape tuple the last dimension of upgraded arrays + should be placed, so the default is '-1'. + + Parameters + ---------- + Not a function, so takes no parameters + + + Returns + ------- + A concatenated ndarray or matrix. + + See Also + -------- + concatenate : Join a sequence of arrays together. + c_ : Translates slice objects to concatenation along the second axis. - For example: + Examples + -------- >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])] array([1, 2, 3, 0, 0, 4, 5, 6]) + >>> np.r_[-1:1:6j, [0]*3, 5, 6] + array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ]) + + String integers specify the axis to concatenate along or the minimum + number of dimensions to force entries into. + + >>> np.r_['-1', a, a] # concatenate along last axis + array([[0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5]]) + >>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2 + array([[1, 2, 3], + [4, 5, 6]]) + + >>> np.r_['0,2,0', [1,2,3], [4,5,6]] + array([[1], + [2], + [3], + [4], + [5], + [6]]) + >>> np.r_['1,2,0', [1,2,3], [4,5,6]] + array([[1, 4], + [2, 5], + [3, 6]]) + + Using 'r' or 'c' as a first string argument creates a matrix. + + >>> np.r_['r',[1,2,3], [4,5,6]] + matrix([[1, 2, 3, 4, 5, 6]]) """ def __init__(self): @@ -351,11 +470,21 @@ class RClass(AxisConcatenator): r_ = RClass() class CClass(AxisConcatenator): - """Translates slice objects to concatenation along the second axis. + """ + Translates slice objects to concatenation along the second axis. + + This is short-hand for ``np.r_['-1,2,0', index expression]``, which is + useful because of its common occurrence. In particular, arrays will be + stacked along their last axis after being upgraded to at least 2-D with + 1's post-pended to the shape (column vectors made out of 1-D arrays). - For example: + For detailed documentation, see `r_`. + + Examples + -------- >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])] - array([1, 2, 3, 0, 0, 4, 5, 6]) + array([[1, 2, 3, 0, 0, 4, 5, 6]]) + """ def __init__(self): AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0) @@ -373,9 +502,13 @@ class ndenumerate(object): a : ndarray Input array. + See Also + -------- + ndindex, flatiter + Examples -------- - >>> a = np.array([[1,2],[3,4]]) + >>> a = np.array([[1, 2], [3, 4]]) >>> for index, x in np.ndenumerate(a): ... print index, x (0, 0) 1 @@ -388,6 +521,17 @@ class ndenumerate(object): self.iter = asarray(arr).flat def next(self): + """ + Standard iterator method, returns the index tuple and array value. + + Returns + ------- + coords : tuple of ints + The indices of the current iteration. + val : scalar + The array element of the current iteration. + + """ return self.iter.coords, self.iter.next() def __iter__(self): @@ -399,17 +543,21 @@ class ndindex(object): An N-dimensional iterator object to index arrays. Given the shape of an array, an `ndindex` instance iterates over - the N-dimensional index of the array. At each iteration, the index of the - last dimension is incremented by one. + the N-dimensional index of the array. At each iteration a tuple + of indices is returned, the last dimension is iterated over first. Parameters ---------- - `*args` : integers - The size of each dimension in the counter. + `*args` : ints + The size of each dimension of the array. + + See Also + -------- + ndenumerate, flatiter Examples -------- - >>> for index in np.ndindex(3,2,1): + >>> for index in np.ndindex(3, 2, 1): ... print index (0, 0, 0) (0, 1, 0) @@ -442,9 +590,25 @@ class ndindex(object): self._incrementone(axis-1) def ndincr(self): + """ + Increment the multi-dimensional index by one. + + `ndincr` takes care of the "wrapping around" of the axes. + It is called by `ndindex.next` and not normally used directly. + + """ self._incrementone(self.nd-1) def next(self): + """ + Standard iterator method, updates the index and returns the index tuple. + + Returns + ------- + val : tuple of ints + Returns a tuple containing the indices of the current iteration. + + """ if (self.index >= self.total): raise StopIteration val = tuple(self.ind) diff --git a/numpy/lib/io.py b/numpy/lib/io.py index 98d071fab..3464b568c 100644 --- a/numpy/lib/io.py +++ b/numpy/lib/io.py @@ -126,6 +126,7 @@ def load(file, mmap_mode=None): ---------- file : file-like object or string The file to read. It must support ``seek()`` and ``read()`` methods. + If the filename extension is ``.gz``, the file is first decompressed. mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional If not None, then memory-map the file, using the given mode (see `numpy.memmap`). The mode has no effect for pickled or @@ -146,6 +147,11 @@ def load(file, mmap_mode=None): IOError If the input file does not exist or cannot be read. + See Also + -------- + save, savez, loadtxt + memmap : Create a memory-map to an array stored in a file on disk. + Notes ----- - If the file contains pickle data, then whatever is stored in the @@ -202,20 +208,20 @@ def load(file, mmap_mode=None): def save(file, arr): """ - Save an array to a binary file in NumPy format. + Save an array to a binary file in NumPy ``.npy`` format. Parameters ---------- - f : file or string + file : file or string File or filename to which the data is saved. If the filename does not already have a ``.npy`` extension, it is added. - x : array_like - Array data. + arr : array_like + Array data to be saved. See Also -------- - savez : Save several arrays into an .npz compressed archive - savetxt : Save an array to a file as plain text + savez : Save several arrays into a .npz compressed archive + savetxt, load Examples -------- @@ -225,7 +231,7 @@ def save(file, arr): >>> x = np.arange(10) >>> np.save(outfile, x) - >>> outfile.seek(0) + >>> outfile.seek(0) # only necessary in this example (with tempfile) >>> np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) @@ -523,20 +529,20 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, def savetxt(fname, X, fmt='%.18e',delimiter=' '): """ - Save an array to file. + Save an array to a text file. Parameters ---------- - fname : filename or a file handle - If the filename ends in .gz, the file is automatically saved in - compressed gzip format. The load() command understands gzipped - files transparently. + fname : filename or file handle + If the filename ends in ``.gz``, the file is automatically saved in + compressed gzip format. `loadtxt` understands gzipped files + transparently. X : array_like - Data. - fmt : string or sequence of strings + Data to be saved to a text file. + fmt : str or sequence of strs A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d -- %10.5f', in which - case delimiter is ignored. + case `delimiter` is ignored. delimiter : str Character separating columns. @@ -588,15 +594,20 @@ def savetxt(fname, X, fmt='%.18e',delimiter=' '): ``x,X`` : unsigned hexadecimal integer - This is not an exhaustive specification. - + This explanation of ``fmt`` is not complete, for an exhaustive + specification see [1]_. + References + ---------- + .. [1] `Format Specification Mini-Language + <http://docs.python.org/library/string.html# + format-specification-mini-language>`_, Python Documentation. Examples -------- - >>> savetxt('test.out', x, delimiter=',') # X is an array - >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays - >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation + >>> savetxt('test.out', x, delimiter=',') # X is an array + >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays + >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation """ @@ -712,15 +723,13 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skiprows=0, Each line past the first `skiprows` ones is split at the `delimiter` character, and characters following the `comments` character are discarded. - - Parameters ---------- - fname : file or string - File or filename to read. If the filename extension is `.gz` or `.bz2`, - the file is first decompressed. - dtype : data-type + fname : {file, string} + File or filename to read. If the filename extension is `.gz` or + `.bz2`, the file is first decompressed. + dtype : dtype Data type of the resulting array. If this is a flexible data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number @@ -729,20 +738,20 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skiprows=0, of the dtype. If None, the dtypes will be determined by the contents of each column, individually. - comments : {string}, optional + comments : string, optional The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discarded - delimiter : {string}, optional + delimiter : string, optional The string used to separate values. By default, any consecutive whitespace act as delimiter. - skiprows : {int}, optional + skiprows : int, optional Numbers of lines to skip at the beginning of the file. converters : {None, dictionary}, optional A dictionary mapping column number to a function that will convert values in the column to a number. Converters can also be used to provide a default value for missing data: ``converters = {3: lambda s: float(s or 0)}``. - missing : {string}, optional + missing : string, optional A string representing a missing value, irrespective of the column where it appears (e.g., `'missing'` or `'unused'`). missing_values : {None, dictionary}, optional @@ -757,20 +766,21 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skiprows=0, 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 flexible dtype. If `names` is None, the names of the dtype fields will be used, if any. - excludelist : {sequence}, optional + excludelist : sequence, optional A list of names to exclude. This list is appended to the default list ['return','file','print']. Excluded names are appended an underscore: for example, `file` would become `file_`. - deletechars : {string}, optional - A string combining invalid characters that must be deleted from the names. + deletechars : string, optional + A string combining invalid characters that must be deleted from the + names. case_sensitive : {True, False, 'upper', 'lower'}, optional If True, field names are case_sensitive. If False or 'upper', field names are converted to upper case. If 'lower', field names are converted to lower case. - unpack : {bool}, optional + unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = loadtxt(...)`` - usemask : {bool}, optional + usemask : bool, optional If True, returns a masked array. If False, return a regular standard array. @@ -779,23 +789,20 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skiprows=0, out : MaskedArray Data read from the text file. - Notes + See Also -------- + numpy.loadtxt : equivalent function when no data is missing. + + Notes + ----- * When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields. * When the variable are named (either by a flexible dtype or with `names`, - there must not be any header in the file (else a :exc:ValueError exception - is raised). - - Warnings - -------- + there must not be any header in the file (else a :exc:ValueError + exception is raised). * Individual values are not stripped of spaces by default. When using a custom converter, make sure the function does remove spaces. - See Also - -------- - numpy.loadtxt : equivalent function when no data is missing. - """ # if usemask: @@ -1128,20 +1135,21 @@ def recfromtxt(fname, dtype=None, comments='#', delimiter=None, skiprows=0, excludelist=None, deletechars=None, case_sensitive=True, usemask=False): """ - Load ASCII data stored in fname and returns a standard recarray (if + Load ASCII data stored in fname and returns a standard recarray (if `usemask=False`) or a MaskedRecords (if `usemask=True`). - + Complete description of all the optional input parameters is available in the docstring of the `genfromtxt` function. - + See Also -------- numpy.genfromtxt : generic function - Warnings - -------- + Notes + ----- * by default, `dtype=None`, which means that the dtype of the output array will be determined from the data. + """ kwargs = dict(dtype=dtype, comments=comments, delimiter=delimiter, skiprows=skiprows, converters=converters, diff --git a/numpy/lib/scimath.py b/numpy/lib/scimath.py index 269d332bf..0e1bafa91 100644 --- a/numpy/lib/scimath.py +++ b/numpy/lib/scimath.py @@ -166,7 +166,8 @@ def _fix_real_abs_gt_1(x): return x def sqrt(x): - """Return the square root of x. + """ + Return the square root of x. Parameters ---------- @@ -174,12 +175,29 @@ def sqrt(x): Returns ------- - array_like output. + out : array_like + + Notes + ----- + + As the numpy.sqrt, this returns the principal square root of x, which is + what most people mean when they use square root; the principal square root + of x is not any number z such as z^2 = x. + + For positive numbers, the principal square root is defined as the positive + number z such as z^2 = x. + + The principal square root of -1 is i, the principal square root of any + negative number -x is defined a i * sqrt(x). For any non zero complex + number, it is defined by using the following branch cut: x = r e^(i t) with + r > 0 and -pi < t <= pi. The principal square root is then + sqrt(r) e^(i t/2). Examples -------- For real, non-negative inputs this works just like numpy.sqrt(): + >>> np.lib.scimath.sqrt(1) 1.0 @@ -187,33 +205,20 @@ def sqrt(x): array([ 1., 2.]) But it automatically handles negative inputs: + >>> np.lib.scimath.sqrt(-1) (0.0+1.0j) >>> np.lib.scimath.sqrt([-1,4]) array([ 0.+1.j, 2.+0.j]) - Notes - ----- - - As the numpy.sqrt, this returns the principal square root of x, which is - what most people mean when they use square root; the principal square root - of x is not any number z such as z^2 = x. - - For positive numbers, the principal square root is defined as the positive - number z such as z^2 = x. - - The principal square root of -1 is i, the principal square root of any - negative number -x is defined a i * sqrt(x). For any non zero complex - number, it is defined by using the following branch cut: x = r e^(i t) with - r > 0 and -pi < t <= pi. The principal square root is then - sqrt(r) e^(i t/2). """ x = _fix_real_lt_zero(x) return nx.sqrt(x) def log(x): - """Return the natural logarithm of x. + """ + Return the natural logarithm of x. If x contains negative inputs, the answer is computed and returned in the complex domain. @@ -224,7 +229,7 @@ def log(x): Returns ------- - array_like + out : array_like Examples -------- @@ -237,12 +242,14 @@ def log(x): >>> np.lib.scimath.log(-math.exp(1)) == (1+1j*math.pi) True + """ x = _fix_real_lt_zero(x) return nx.log(x) def log10(x): - """Return the base 10 logarithm of x. + """ + Return the base 10 logarithm of x. If x contains negative inputs, the answer is computed and returned in the complex domain. @@ -253,12 +260,13 @@ def log10(x): Returns ------- - array_like + out : array_like Examples -------- (We set the printing precision so the example can be auto-tested) + >>> np.set_printoptions(precision=4) >>> np.lib.scimath.log10([10**1,10**2]) @@ -267,12 +275,14 @@ def log10(x): >>> np.lib.scimath.log10([-10**1,-10**2,10**2]) array([ 1.+1.3644j, 2.+1.3644j, 2.+0.j ]) + """ x = _fix_real_lt_zero(x) return nx.log10(x) def logn(n, x): - """Take log base n of x. + """ + Take log base n of x. If x contains negative inputs, the answer is computed and returned in the complex domain. @@ -283,12 +293,13 @@ def logn(n, x): Returns ------- - array_like + out : array_like Examples -------- (We set the printing precision so the example can be auto-tested) + >>> np.set_printoptions(precision=4) >>> np.lib.scimath.logn(2,[4,8]) @@ -296,13 +307,15 @@ def logn(n, x): >>> np.lib.scimath.logn(2,[-4,-8,8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) + """ x = _fix_real_lt_zero(x) n = _fix_real_lt_zero(n) return nx.log(x)/nx.log(n) def log2(x): - """ Take log base 2 of x. + """ + Take log base 2 of x. If x contains negative inputs, the answer is computed and returned in the complex domain. @@ -313,12 +326,13 @@ def log2(x): Returns ------- - array_like + out : array_like Examples -------- (We set the printing precision so the example can be auto-tested) + >>> np.set_printoptions(precision=4) >>> np.lib.scimath.log2([4,8]) @@ -326,12 +340,14 @@ def log2(x): >>> np.lib.scimath.log2([-4,-8,8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) + """ x = _fix_real_lt_zero(x) return nx.log2(x) def power(x, p): - """Return x**p. + """ + Return x**p. If x contains negative values, it is converted to the complex domain. @@ -344,11 +360,12 @@ def power(x, p): Returns ------- - array_like + out : array_like Examples -------- (We set the printing precision so the example can be auto-tested) + >>> np.set_printoptions(precision=4) >>> np.lib.scimath.power([2,4],2) @@ -359,6 +376,7 @@ def power(x, p): >>> np.lib.scimath.power([-2,4],2) array([ 4.+0.j, 16.+0.j]) + """ x = _fix_real_lt_zero(x) p = _fix_int_lt_zero(p) @@ -393,7 +411,8 @@ def arccos(x): return nx.arccos(x) def arcsin(x): - """Compute the inverse sine of x. + """ + Compute the inverse sine of x. For real x with abs(x)<=1, this returns the principal value. @@ -410,6 +429,7 @@ def arcsin(x): Examples -------- (We set the printing precision so the example can be auto-tested) + >>> np.set_printoptions(precision=4) >>> np.lib.scimath.arcsin(0) @@ -417,12 +437,14 @@ def arcsin(x): >>> np.lib.scimath.arcsin([0,1]) array([ 0. , 1.5708]) + """ x = _fix_real_abs_gt_1(x) return nx.arcsin(x) def arctanh(x): - """Compute the inverse hyperbolic tangent of x. + """ + Compute the inverse hyperbolic tangent of x. For real x with abs(x)<=1, this returns the principal value. @@ -434,7 +456,7 @@ def arctanh(x): Returns ------- - array_like + out : array_like Examples -------- @@ -446,6 +468,7 @@ def arctanh(x): >>> np.lib.scimath.arctanh([0,2]) array([ 0.0000+0.j , 0.5493-1.5708j]) + """ x = _fix_real_abs_gt_1(x) return nx.arctanh(x) diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index 19dd54f7a..69ef0be4f 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -1007,6 +1007,19 @@ def tile(A, reps): """ Construct an array by repeating A the number of times given by reps. + If `reps` has length ``d``, the result will have dimension of + ``max(d, A.ndim)``. + + If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new + axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, + or shape (1, 1, 3) for 3-D replication. If this is not the desired + behavior, promote `A` to d-dimensions manually before calling this + function. + + If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it. + Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as + (1, 1, 2, 2). + Parameters ---------- A : array_like @@ -1017,24 +1030,11 @@ def tile(A, reps): Returns ------- c : ndarray - The output array. + The tiled output array. See Also -------- - repeat - - Notes - ----- - If `reps` has length d, the result will have dimension of max(d, `A`.ndim). - - If `A`.ndim < d, `A` is promoted to be d-dimensional by prepending new - axes. So a shape (3,) array is promoted to (1,3) for 2-D replication, - or shape (1,1,3) for 3-D replication. If this is not the desired behavior, - promote `A` to d-dimensions manually before calling this function. - - If `A`.ndim > d, `reps` is promoted to `A`.ndim by pre-pending 1's to it. - Thus for an `A` of shape (2,3,4,5), a `reps` of (2,2) is treated as - (1,1,2,2). + repeat : Repeat elements of an array. Examples -------- @@ -1046,7 +1046,6 @@ def tile(A, reps): [0, 1, 2, 0, 1, 2]]) >>> np.tile(a, (2, 1, 2)) array([[[0, 1, 2, 0, 1, 2]], - <BLANKLINE> [[0, 1, 2, 0, 1, 2]]]) >>> b = np.array([[1, 2], [3, 4]]) diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 113cec682..69f4f2193 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -85,8 +85,8 @@ def real(val): Returns ------- out : ndarray - If `val` is real, the type of `val` is used for the output. If `val` - has complex elements, the returned type is float. + Output array. If `val` is real, the type of `val` is used for the + output. If `val` has complex elements, the returned type is float. See Also -------- @@ -94,13 +94,13 @@ def real(val): Examples -------- - >>> a = np.array([1+2j,3+4j,5+6j]) + >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.real array([ 1., 3., 5.]) >>> a.real = 9 >>> a array([ 9.+2.j, 9.+4.j, 9.+6.j]) - >>> a.real = np.array([9,8,7]) + >>> a.real = np.array([9, 8, 7]) >>> a array([ 9.+2.j, 8.+4.j, 7.+6.j]) @@ -109,7 +109,7 @@ def real(val): def imag(val): """ - Return the imaginary part of array. + Return the imaginary part of the elements of the array. Parameters ---------- @@ -118,8 +118,22 @@ def imag(val): Returns ------- - out : ndarray, real or int - Real part of each element, same shape as `val`. + out : ndarray + Output array. If `val` is real, the type of `val` is used for the + output. If `val` has complex elements, the returned type is float. + + See Also + -------- + real, angle, real_if_close + + Examples + -------- + >>> a = np.array([1+2j, 3+4j, 5+6j]) + >>> a.imag + array([ 2., 4., 6.]) + >>> a.imag = np.array([8, 10, 12]) + >>> a + array([ 1. +8.j, 3.+10.j, 5.+12.j]) """ return asanyarray(val).imag diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 5dbc3f225..5e89b0930 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -176,7 +176,7 @@ def isneginf(x, y=None): _log2 = nx.log(2) def log2(x, y=None): """ - Return the base 2 logarithm. + Return the base 2 logarithm of the input array, element-wise. Parameters ---------- @@ -188,7 +188,7 @@ def log2(x, y=None): Returns ------- y : ndarray - The logarithm to the base 2 of `x` elementwise. + The logarithm to the base 2 of `x` element-wise. NaNs are returned where `x` is negative. See Also @@ -197,7 +197,7 @@ def log2(x, y=None): Examples -------- - >>> np.log2([-1,2,4]) + >>> np.log2([-1, 2, 4]) array([ NaN, 1., 2.]) """ diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 3de0579df..908c4995d 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -81,12 +81,34 @@ else: return func def deprecate(func, oldname=None, newname=None): - """Deprecate old functions. + """ + Deprecate old functions. + Issues a DeprecationWarning, adds warning to oldname's docstring, rebinds oldname.__name__ and returns new function object. - Example: - oldfunc = deprecate(newfunc, 'oldfunc', 'newfunc') + Parameters + ---------- + func : function + + oldname : string + + newname : string + + Returns + ------- + old_func : function + + Examples + -------- + Note that olduint returns a value after printing Deprecation Warning. + + >>> olduint = np.deprecate(np.uint) + >>> olduint(6) + /usr/lib/python2.5/site-packages/numpy/lib/utils.py:114: + DeprecationWarning: uint32 is deprecated + warnings.warn(str1, DeprecationWarning) + 6 """ @@ -186,13 +208,28 @@ def byte_bounds(a): def may_share_memory(a, b): - """Determine if two arrays can share memory + """ + Determine if two arrays can share memory The memory-bounds of a and b are computed. If they overlap then this function returns True. Otherwise, it returns False. A return of True does not necessarily mean that the two arrays share any element. It just means that they *might*. + + Parameters + ---------- + a, b : ndarray + + Returns + ------- + out : bool + + Examples + -------- + >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) + False + """ a_low, a_high = byte_bounds(a) b_low, b_high = byte_bounds(b) @@ -349,24 +386,46 @@ def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): Parameters ---------- - object : optional - Input object to get information about. + object : object or str, optional + Input object or name to get information about. If `object` is a + numpy object, its docstring is given. If it is a string, available + modules are searched for matching objects. + If None, information about `info` itself is returned. maxwidth : int, optional Printing width. - output : file like object open for writing, optional - Write into file like object. - toplevel : string, optional + output : file like object, optional + File like object that the output is written to, default is ``stdout``. + The object has to be opened in 'w' or 'a' mode. + toplevel : str, optional Start search at this level. + See Also + -------- + source, lookfor + + Notes + ----- + When used interactively with an object, ``np.info(obj)`` is equivalent to + ``help(obj)`` on the Python prompt or ``obj?`` on the IPython prompt. + Examples -------- >>> np.info(np.polyval) # doctest: +SKIP - polyval(p, x) + Evaluate the polynomial p at x. + ... - Evaluate the polymnomial p at x. + When using a string for `object` it is possible to get multiple results. - ... + >>> np.info('fft') # doctest: +SKIP + *** Found in numpy *** + Core FFT routines + ... + *** Found in numpy.fft *** + fft(a, n=None, axis=-1) + ... + *** Repeat reference found in numpy.fft.fftpack *** + *** Total of 3 references found. *** """ global _namedict, _dictlist @@ -512,15 +571,39 @@ def source(object, output=sys.stdout): """ Print or write to a file the source code for a Numpy object. + The source code is only returned for objects written in Python. Many + functions and classes are defined in C and will therefore not return + useful information. + Parameters ---------- object : numpy object - Input object. + Input object. This can be any object (function, class, module, ...). output : file object, optional If `output` not supplied then source code is printed to screen (sys.stdout). File object must be created with either write 'w' or append 'a' modes. + See Also + -------- + lookfor, info + + Examples + -------- + >>> np.source(np.interp) + In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py + def interp(x, xp, fp, left=None, right=None): + \"\"\".... (full docstring printed)\"\"\" + if isinstance(x, (float, int, number)): + return compiled_interp([x], xp, fp, left, right).item() + else: + return compiled_interp(x, xp, fp, left, right) + + The source code is only returned for objects written in Python. + + >>> np.source(np.array) + Not available for this object. + """ # Local import to speed up numpy's import time. import inspect @@ -544,28 +627,41 @@ def lookfor(what, module=None, import_modules=True, regenerate=False): Do a keyword search on docstrings. A list of of objects that matched the search is displayed, - sorted by relevance. + sorted by relevance. All given keywords need to be found in the + docstring for it to be returned as a result, but the order does + not matter. Parameters ---------- what : str String containing words to look for. - module : str, module - Module whose docstrings to go through. - import_modules : bool + module : str, optional + Name of module whose docstrings to go through. + import_modules : bool, optional Whether to import sub-modules in packages. - Will import only modules in ``__all__``. - regenerate : bool - Whether to re-generate the docstring cache. + Will import only modules in ``__all__``. Default is True. + regenerate : bool, optional + Whether to re-generate the docstring cache. Default is False. - Examples + See Also -------- + source, info + + Notes + ----- + Relevance is determined only roughly, by checking if the keywords occur + in the function name, at the start of a docstring, etc. + Examples + -------- >>> np.lookfor('binary representation') Search results for 'binary representation' ------------------------------------------ numpy.binary_repr Return the binary representation of the input number as a string. + numpy.base_repr + Return a string representation of a number in the given base system. + ... """ import pydoc diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index dcf7fde26..df888b754 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -1237,7 +1237,7 @@ def lstsq(a, b, rcond=-1): Notes ----- - If `b` is a matrix, then all array results returned as + If `b` is a matrix, then all array results are returned as matrices. Examples diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 5cf11ffb9..65e44673c 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -210,7 +210,49 @@ def minimum_fill_value(obj): def maximum_fill_value(obj): """ - Calculate the default fill value suitable for taking the maximum of ``obj``. + Return the minimum value that can be represented by the dtype of an object. + + This function is useful for calculating a fill value suitable for + taking the maximum of an array with a given dtype. + + Parameters + ---------- + obj : {ndarray, dtype} + An object that can be queried for it's numeric type. + + Returns + ------- + val : scalar + The minimum representable value. + + Raises + ------ + TypeError + If `obj` isn't a suitable numeric type. + + See Also + -------- + set_fill_value : Set the filling value of a masked array. + MaskedArray.fill_value : Return current fill value. + + Examples + -------- + >>> import numpy.ma as ma + >>> a = np.int8() + >>> ma.maximum_fill_value(a) + -128 + >>> a = np.int32() + >>> ma.maximum_fill_value(a) + -2147483648 + + An array of numeric data can also be passed. + + >>> a = np.array([1, 2, 3], dtype=np.int8) + >>> ma.maximum_fill_value(a) + -128 + >>> a = np.array([1, 2, 3], dtype=np.float32) + >>> ma.maximum_fill_value(a) + -inf """ errmsg = "Unsuitable type for calculating maximum." @@ -452,7 +494,7 @@ def getdata(a, subok=True): Input ``MaskedArray``, alternatively a ndarray or a subclass thereof. subok : bool Whether to force the output to be a `pure` ndarray (False) or to - return a subclass of ndarray if approriate (True, default). + return a subclass of ndarray if appropriate (True, default). See Also -------- @@ -3723,52 +3765,49 @@ class MaskedArray(ndarray): def cumsum(self, axis=None, dtype=None, out=None): """ - Return the cumulative sum of the elements along the given axis. - The cumulative sum is calculated over the flattened array by - default, otherwise over the specified axis. + Return the cumulative sum of the elements along the given axis. + The cumulative sum is calculated over the flattened array by + default, otherwise over the specified axis. - Masked values are set to 0 internally during the computation. - However, their position is saved, and the result will be masked at - the same locations. + Masked values are set to 0 internally during the computation. + However, their position is saved, and the result will be masked at + the same locations. - Parameters - ---------- - axis : {None, -1, int}, optional - Axis along which the sum is computed. The default (`axis` = None) is to - compute over the flattened array. `axis` may be negative, in which case - it counts from the last to the first axis. - dtype : {None, dtype}, optional - Type of the returned array and of the accumulator in which the - elements are summed. If `dtype` is not specified, it defaults - to the dtype of `a`, unless `a` has an integer dtype with a - precision less than that of the default platform integer. In - that case, the default platform integer is used. - 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 will be cast if necessary. - - Warnings - -------- - The mask is lost if out is not a valid :class:`MaskedArray` ! + Parameters + ---------- + axis : {None, -1, int}, optional + Axis along which the sum is computed. The default (`axis` = None) is to + compute over the flattened array. `axis` may be negative, in which case + it counts from the last to the first axis. + dtype : {None, dtype}, optional + Type of the returned array and of the accumulator in which the + elements are summed. If `dtype` is not specified, it defaults + to the dtype of `a`, unless `a` has an integer dtype with a + precision less than that of the default platform integer. In + that case, the default platform integer is used. + 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 will be cast if necessary. - Returns - ------- - cumsum : ndarray. - A new array holding the result is returned unless ``out`` is - specified, in which case a reference to ``out`` is returned. + Returns + ------- + cumsum : ndarray. + A new array holding the result is returned unless ``out`` is + specified, in which case a reference to ``out`` is returned. - Examples - -------- - >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) - >>> print marr.cumsum() - [0 1 3 -- -- -- 9 16 24 33] + Notes + ----- + The mask is lost if `out` is not a valid :class:`MaskedArray` ! + Arithmetic is modular when using integer types, and no error is + raised on overflow. - Notes - ----- - Arithmetic is modular when using integer types, and no error is - raised on overflow. + Examples + -------- + >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) + >>> print marr.cumsum() + [0 1 3 -- -- -- 9 16 24 33] """ result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out) @@ -3853,46 +3892,44 @@ class MaskedArray(ndarray): def cumprod(self, axis=None, dtype=None, out=None): """ - Return the cumulative product of the elements along the given axis. - The cumulative product is taken over the flattened array by - default, otherwise over the specified axis. + Return the cumulative product of the elements along the given axis. + The cumulative product is taken over the flattened array by + default, otherwise over the specified axis. - Masked values are set to 1 internally during the computation. - However, their position is saved, and the result will be masked at - the same locations. + Masked values are set to 1 internally during the computation. + However, their position is saved, and the result will be masked at + the same locations. - Parameters - ---------- - axis : {None, -1, int}, optional - Axis along which the product is computed. The default - (`axis` = None) is to compute over the flattened array. - dtype : {None, dtype}, optional - Determines the type of the returned array and of the accumulator - where the elements are multiplied. If ``dtype`` has the value ``None`` and - the type of ``a`` is an integer type of precision less than the default - platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of ``a``. - 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 will be cast if necessary. - - Warnings - -------- - The mask is lost if out is not a valid MaskedArray ! + Parameters + ---------- + axis : {None, -1, int}, optional + Axis along which the product is computed. The default + (`axis` = None) is to compute over the flattened array. + dtype : {None, dtype}, optional + Determines the type of the returned array and of the accumulator + where the elements are multiplied. If ``dtype`` has the value ``None`` + and the type of ``a`` is an integer type of precision less than the + default platform integer, then the default platform integer precision + is used. Otherwise, the dtype is the same as that of ``a``. + 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 will be cast if necessary. - Returns - ------- - cumprod : ndarray - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. + Returns + ------- + cumprod : ndarray + A new array holding the result is returned unless out is specified, + in which case a reference to out is returned. - Notes - ----- - Arithmetic is modular when using integer types, and no error is - raised on overflow. + Notes + ----- + The mask is lost if `out` is not a valid MaskedArray ! - """ + Arithmetic is modular when using integer types, and no error is + raised on overflow. + + """ result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out) if out is not None: if isinstance(out, MaskedArray): diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index 1aa43a222..4454781c3 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -56,11 +56,48 @@ def count_masked(arr, axis=None): """ Count the number of masked elements along the given axis. + Parameters ---------- + arr : array_like + An array with (possibly) masked elements. axis : int, optional - Axis along which to count. - If None (default), a flattened version of the array is used. + Axis along which to count. If None (default), a flattened + version of the array is used. + + Returns + ------- + count : int, ndarray + The total number of masked elements (axis=None) or the number + of masked elements along each slice of the given axis. + + Examples + -------- + >>> import numpy.ma as ma + >>> a = np.arange(9).reshape((3,3)) + >>> a = ma.array(a) + >>> a[1, 0] = ma.masked + >>> a[1, 2] = ma.masked + >>> a[2, 1] = ma.masked + >>> a + masked_array(data = + [[0 1 2] + [-- 4 --] + [6 -- 8]], + mask = + [[False False False] + [ True False True] + [False True False]], + fill_value=999999) + >>> ma.count_masked(a) + 3 + + When the `axis` keyword is used an array is returned. + + >>> ma.count_masked(a, axis=0) + array([1, 1, 1]) + >>> ma.count_masked(a, axis=1) + array([0, 2, 1]) """ m = getmaskarray(arr) |