summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--doc/source/about.rst7
-rw-r--r--doc/source/reference/arrays.classes.rst6
-rw-r--r--doc/source/reference/arrays.interface.rst125
-rw-r--r--doc/source/reference/maskedarray.generic.rst38
-rw-r--r--doc/source/reference/routines.array-creation.rst1
-rw-r--r--doc/source/reference/routines.array-manipulation.rst6
-rw-r--r--doc/source/reference/routines.fft.rst59
-rw-r--r--doc/source/reference/routines.rst1
-rw-r--r--doc/source/reference/ufuncs.rst6
-rw-r--r--doc/source/routines.testing.rst46
-rw-r--r--doc/source/user/c-info.how-to-extend.rst4
-rw-r--r--numpy/add_newdocs.py695
-rw-r--r--numpy/core/code_generators/ufunc_docstrings.py481
-rw-r--r--numpy/core/fromnumeric.py271
-rw-r--r--numpy/core/numeric.py285
-rw-r--r--numpy/doc/constants.py360
-rw-r--r--numpy/doc/misc.py2
-rw-r--r--numpy/fft/__init__.py34
-rw-r--r--numpy/fft/fftpack.py854
-rw-r--r--numpy/fft/info.py183
-rw-r--r--numpy/lib/arraysetops.py22
-rw-r--r--numpy/lib/financial.py1
-rw-r--r--numpy/lib/function_base.py207
-rw-r--r--numpy/lib/index_tricks.py20
-rw-r--r--numpy/lib/io.py43
-rw-r--r--numpy/lib/polynomial.py2
-rw-r--r--numpy/lib/shape_base.py286
-rw-r--r--numpy/lib/twodim_base.py45
-rw-r--r--numpy/lib/type_check.py150
-rw-r--r--numpy/lib/ufunclike.py94
-rw-r--r--numpy/lib/utils.py20
-rw-r--r--numpy/linalg/linalg.py31
-rw-r--r--numpy/ma/core.py1012
-rw-r--r--numpy/ma/extras.py250
-rw-r--r--numpy/random/mtrand/mtrand.pyx81
-rw-r--r--numpy/testing/utils.py309
36 files changed, 4776 insertions, 1261 deletions
diff --git a/doc/source/about.rst b/doc/source/about.rst
index 6b5dfa0f3..bcfbe5323 100644
--- a/doc/source/about.rst
+++ b/doc/source/about.rst
@@ -14,8 +14,8 @@ needed for scientific computing with Python. This package contains:
Besides its obvious scientific uses, *NumPy* can also be used as an
efficient multi-dimensional container of generic data. Arbitrary
-data-types can be defined. This allows *NumPy* to seamlessly and
-speedily integrate with a wide-variety of databases.
+data types can be defined. This allows *NumPy* to seamlessly and
+speedily integrate with a wide variety of databases.
NumPy is a successor for two earlier scientific Python libraries:
NumPy derives from the old *Numeric* code base and can be used
@@ -25,7 +25,7 @@ by *Numarray* and can also be used to replace *Numarray*.
NumPy community
---------------
-Numpy is a distributed, volunteer open-source project. *You* can help
+Numpy is a distributed, volunteer, open-source project. *You* can help
us make it better; if you believe something should be improved either
in functionality or in documentation, don't hesitate to contact us --- or
even better, contact us and participate in fixing the problem.
@@ -63,4 +63,3 @@ examples assume that you have first entered::
>>> import numpy as np
before running the examples.
-
diff --git a/doc/source/reference/arrays.classes.rst b/doc/source/reference/arrays.classes.rst
index 865838699..671c95bbf 100644
--- a/doc/source/reference/arrays.classes.rst
+++ b/doc/source/reference/arrays.classes.rst
@@ -13,7 +13,7 @@ difficult decision, and can be simply a matter of choice. NumPy has
several tools for simplifying how your new object interacts with other
array objects, and so the choice may not be significant in the
end. One way to simplify the question is by asking yourself if the
-object you are interested can be replaced as a single array or does it
+object you are interested in can be replaced as a single array or does it
really require two or more arrays at its core.
Note that :func:`asarray` always returns the base-class ndarray. If
@@ -24,7 +24,7 @@ principal a subclass could redefine any aspect of the array and
therefore, under strict guidelines, :func:`asanyarray` would rarely be
useful. However, most subclasses of the arrayobject will not
redefine certain aspects of the array object such as the buffer
-interface, or the attributes of the array. One of important example,
+interface, or the attributes of the array. One important example,
however, of why your subroutine may not be able to handle an arbitrary
subclass of an array is that matrices redefine the "*" operator to be
matrix-multiplication, rather than element-by-element multiplication.
@@ -77,7 +77,7 @@ Matrix objects
:class:`matrix` objects inherit from the ndarray and therefore, they
have the same attributes and methods of ndarrays. There are six
-important differences of matrix objects, however that may lead to
+important differences of matrix objects, however, that may lead to
unexpected results when you use matrices but expect them to act like
arrays:
diff --git a/doc/source/reference/arrays.interface.rst b/doc/source/reference/arrays.interface.rst
index 4afa3afc1..405e6da0a 100644
--- a/doc/source/reference/arrays.interface.rst
+++ b/doc/source/reference/arrays.interface.rst
@@ -11,16 +11,19 @@ The Array Interface
.. warning::
This page describes the old, deprecated array interface. Everything still
- works as described as of numpy 1.2 and on into the foreseeable future), but
+ works as described as of numpy 1.2 and on into the foreseeable future, but
new development should target :pep:`3118` --
:cfunc:`The Revised Buffer Protocol <PyObject_GetBuffer>`.
:pep:`3118` was incorporated into Python 2.6 and 3.0, and is additionally
- supported by Cython's numpy buffer support. (See the Cython numpy
- tutorial.) Cython provides a way to write code that supports the buffer
+ supported by Cython__'s numpy buffer support. (See the `Cython numpy
+ tutorial`__.) Cython provides a way to write code that supports the buffer
protocol with Python versions older than 2.6 because it has a
backward-compatible implementation utilizing the legacy array interface
described here.
+__ http://cython.org/
+__ http://wiki.cython.org/tutorials/numpy
+
:version: 3
The array interface (sometimes called array protocol) was created in
@@ -206,6 +209,33 @@ array using only one attribute lookup and a well-defined C-structure.
must also not reallocate their memory if other objects are
referencing them.
+The PyArrayInterface structure is defined in ``numpy/ndarrayobject.h``
+as::
+
+ typedef struct {
+ int two; /* contains the integer 2 -- simple sanity check */
+ int nd; /* number of dimensions */
+ char typekind; /* kind in array --- character code of typestr */
+ int itemsize; /* size of each element */
+ int flags; /* flags indicating how the data should be interpreted */
+ /* must set ARR_HAS_DESCR bit to validate descr */
+ Py_intptr_t *shape; /* A length-nd array of shape information */
+ Py_intptr_t *strides; /* A length-nd array of stride information */
+ void *data; /* A pointer to the first element of the array */
+ PyObject *descr; /* NULL or data-description (same as descr key
+ of __array_interface__) -- must set ARR_HAS_DESCR
+ flag or this will be ignored. */
+ } PyArrayInterface;
+
+The flags member may consist of 5 bits showing how the data should be
+interpreted and one bit showing how the Interface should be
+interpreted. The data-bits are :const:`CONTIGUOUS` (0x1),
+:const:`FORTRAN` (0x2), :const:`ALIGNED` (0x100), :const:`NOTSWAPPED`
+(0x200), and :const:`WRITEABLE` (0x400). A final flag
+:const:`ARR_HAS_DESCR` (0x800) indicates whether or not this structure
+has the arrdescr field. The field should not be accessed unless this
+flag is present.
+
.. admonition:: New since June 16, 2006:
In the past most implementations used the "desc" member of the
@@ -215,3 +245,92 @@ array using only one attribute lookup and a well-defined C-structure.
This is now an explicit part of the interface. Be sure to own a
reference to the object when the :ctype:`PyCObject` is created using
:ctype:`PyCObject_FromVoidPtrAndDesc`.
+
+
+Type description examples
+=========================
+
+For clarity it is useful to provide some examples of the type
+description and corresponding :data:`__array_interface__` 'descr'
+entries. Thanks to Scott Gilbert for these examples:
+
+In every case, the 'descr' key is optional, but of course provides
+more information which may be important for various applications::
+
+ * Float data
+ typestr == '>f4'
+ descr == [('','>f4')]
+
+ * Complex double
+ typestr == '>c8'
+ descr == [('real','>f4'), ('imag','>f4')]
+
+ * RGB Pixel data
+ typestr == '|V3'
+ descr == [('r','|u1'), ('g','|u1'), ('b','|u1')]
+
+ * Mixed endian (weird but could happen).
+ typestr == '|V8' (or '>u8')
+ descr == [('big','>i4'), ('little','<i4')]
+
+ * Nested structure
+ struct {
+ int ival;
+ struct {
+ unsigned short sval;
+ unsigned char bval;
+ unsigned char cval;
+ } sub;
+ }
+ typestr == '|V8' (or '<u8' if you want)
+ descr == [('ival','<i4'), ('sub', [('sval','<u2'), ('bval','|u1'), ('cval','|u1') ]) ]
+
+ * Nested array
+ struct {
+ int ival;
+ double data[16*4];
+ }
+ typestr == '|V516'
+ descr == [('ival','>i4'), ('data','>f8',(16,4))]
+
+ * Padded structure
+ struct {
+ int ival;
+ double dval;
+ }
+ typestr == '|V16'
+ descr == [('ival','>i4'),('','|V4'),('dval','>f8')]
+
+It should be clear that any record type could be described using this interface.
+
+Differences with Array interface (Version 2)
+============================================
+
+The version 2 interface was very similar. The differences were
+largely asthetic. In particular:
+
+1. The PyArrayInterface structure had no descr member at the end
+ (and therefore no flag ARR_HAS_DESCR)
+
+2. The desc member of the PyCObject returned from __array_struct__ was
+ not specified. Usually, it was the object exposing the array (so
+ that a reference to it could be kept and destroyed when the
+ C-object was destroyed). Now it must be a tuple whose first
+ element is a string with "PyArrayInterface Version #" and whose
+ second element is the object exposing the array.
+
+3. The tuple returned from __array_interface__['data'] used to be a
+ hex-string (now it is an integer or a long integer).
+
+4. There was no __array_interface__ attribute instead all of the keys
+ (except for version) in the __array_interface__ dictionary were
+ their own attribute: Thus to obtain the Python-side information you
+ had to access separately the attributes:
+
+ * __array_data__
+ * __array_shape__
+ * __array_strides__
+ * __array_typestr__
+ * __array_descr__
+ * __array_offset__
+ * __array_mask__
diff --git a/doc/source/reference/maskedarray.generic.rst b/doc/source/reference/maskedarray.generic.rst
index 580c8a3de..7c998ae63 100644
--- a/doc/source/reference/maskedarray.generic.rst
+++ b/doc/source/reference/maskedarray.generic.rst
@@ -30,6 +30,7 @@ The package ensures that masked entries are not used in computations.
As an illustration, let's consider the following dataset::
>>> import numpy as np
+ >>> import numpy.ma as ma
>>> x = np.array([1, 2, 3, -1, 5])
We wish to mark the fourth entry as invalid. The easiest is to create a masked
@@ -135,7 +136,7 @@ There are several ways to construct a masked array.
Accessing the data
------------------
-The underlying data of a masked array can be accessed through several ways:
+The underlying data of a masked array can be accessed in several ways:
* through the :attr:`~MaskedArray.data` attribute. The output is a view of the array as
a :class:`numpy.ndarray` or one of its subclasses, depending on the type
@@ -148,8 +149,7 @@ The underlying data of a masked array can be accessed through several ways:
* by using the :func:`getdata` function.
-None of these methods is completely satisfactory if some entries have been marked as invalid. As a general rule, invalid data should not be relied on.
-If a representation of the array is needed without any masked entries, it is recommended to fill the array with the :meth:`filled` method.
+None of these methods is completely satisfactory if some entries have been marked as invalid. As a general rule, where a representation of the array is required without any masked entries, it is recommended to fill the array with the :meth:`filled` method.
@@ -264,14 +264,14 @@ To unmask one or several specific entries, we can just assign one or several new
fill_value = 999999)
.. note::
- Unmasking an entry by direct assignment will not work if the masked array
- has a *hard* mask, as shown by the :attr:`~MaskedArray.hardmask` attribute.
- This feature was introduced to prevent the overwriting of the mask.
- To force the unmasking of an entry in such circumstance, the mask has first
- to be softened with the :meth:`soften_mask` method before the allocation,
- and then re-hardened with :meth:`harden_mask`::
-
- >>> x = ma.array([1, 2, 3], mask=[0, 0, 1])
+ Unmasking an entry by direct assignment will silently fail if the masked array
+ has a *hard* mask, as shown by the :attr:`hardmask` attribute.
+ This feature was introduced to prevent overwriting the mask.
+ To force the unmasking of an entry where the array has a hard mask, the mask must first
+ to be softened using the :meth:`soften_mask` method before the allocation. It can be re-hardened
+ with :meth:`harden_mask`::
+
+ >>> x = ma.array([1, 2, 3], mask=[0, 0, 1], hard_mask=True)
>>> x
masked_array(data = [1 2 --],
mask = [False False True],
@@ -287,17 +287,17 @@ To unmask one or several specific entries, we can just assign one or several new
masked_array(data = [1 2 --],
mask = [False False True],
fill_value = 999999)
- >>> x.soften_mask()
+ >>> x.harden_mask()
-To unmask all masked entries of a masked array, the simplest solution is to assign the constant :attr:`nomask` to the mask::
+To unmask all masked entries of a masked array (provided the mask isn't a hard mask), the simplest solution is to assign the constant :attr:`nomask` to the mask::
>>> x = ma.array([1, 2, 3], mask=[0, 0, 1])
>>> x
masked_array(data = [1 2 --],
mask = [False False True],
fill_value = 999999)
- >>> x.mask = nomask
+ >>> x.mask = ma.nomask
>>> x
masked_array(data = [1 2 3],
mask = [False False False],
@@ -364,14 +364,12 @@ Operations on masked arrays
---------------------------
Arithmetic and comparison operations are supported by masked arrays.
-As much as possible, invalid entries of a masked array are not processed,
-meaning that the corresponding :attr:`~MaskedArray.data` entries *should* be
-the same before and after the operation.
+As much as possible, invalid entries of a masked array are not processed, meaning that the
+corresponding :attr:`data` entries *should* be the same before and after the operation.
.. warning::
- We need to stress that this behavior may not be systematic, that invalid
- data may actually be affected by the operation in some cases and once again
- that invalid data should not be relied on.
+ We need to stress that this behavior may not be systematic, that masked data may be affected
+ by the operation in some cases and therefore users should not rely on this data remaining unchanged.
The :mod:`numpy.ma` module comes with a specific implementation of most
ufuncs.
diff --git a/doc/source/reference/routines.array-creation.rst b/doc/source/reference/routines.array-creation.rst
index 25196232a..468ab8aa4 100644
--- a/doc/source/reference/routines.array-creation.rst
+++ b/doc/source/reference/routines.array-creation.rst
@@ -76,6 +76,7 @@ Numerical ranges
logspace
meshgrid
mgrid
+ ogrid
Building matrices
-----------------
diff --git a/doc/source/reference/routines.array-manipulation.rst b/doc/source/reference/routines.array-manipulation.rst
index e5163bcfc..2c1a5b200 100644
--- a/doc/source/reference/routines.array-manipulation.rst
+++ b/doc/source/reference/routines.array-manipulation.rst
@@ -3,8 +3,6 @@ Array manipulation routines
.. currentmodule:: numpy
-.. toctree::
-
Changing array shape
====================
.. autosummary::
@@ -21,7 +19,6 @@ Transpose-like operations
.. autosummary::
:toctree: generated/
-
rollaxis
swapaxes
ndarray.T
@@ -32,7 +29,6 @@ Changing number of dimensions
.. autosummary::
:toctree: generated/
-
atleast_1d
atleast_2d
atleast_3d
@@ -59,7 +55,6 @@ Joining arrays
.. autosummary::
:toctree: generated/
- append
column_stack
concatenate
dstack
@@ -92,6 +87,7 @@ Adding and removing elements
delete
insert
+ append
resize
trim_zeros
unique
diff --git a/doc/source/reference/routines.fft.rst b/doc/source/reference/routines.fft.rst
index e830fcf0d..6c47925ee 100644
--- a/doc/source/reference/routines.fft.rst
+++ b/doc/source/reference/routines.fft.rst
@@ -1,59 +1,2 @@
.. _routines.fft:
-
-Fourier transforms (:mod:`numpy.fft`)
-*************************************
-
-.. currentmodule:: numpy.fft
-
-1-dimensional
--------------
-.. autosummary::
- :toctree: generated/
-
- fft
- ifft
-
-2-dimensional
--------------
-.. autosummary::
- :toctree: generated/
-
- fft2
- ifft2
-
-N-dimensional
--------------
-.. autosummary::
- :toctree: generated/
-
- fftn
- ifftn
-
-Hermite symmetric
------------------
-.. autosummary::
- :toctree: generated/
-
- hfft
- ihfft
-
-Real-valued
------------
-.. autosummary::
- :toctree: generated/
-
- rfft
- irfft
- rfft2
- irfft2
- rfftn
- irfftn
-
-Helper routines
----------------
-.. autosummary::
- :toctree: generated/
-
- fftfreq
- fftshift
- ifftshift
+.. automodule:: numpy.fft
diff --git a/doc/source/reference/routines.rst b/doc/source/reference/routines.rst
index e682f5a57..eb2e9fc4e 100644
--- a/doc/source/reference/routines.rst
+++ b/doc/source/reference/routines.rst
@@ -27,6 +27,7 @@ Routines
routines.ma
routines.help
routines.other
+ routines.testing
routines.emath
routines.matlib
routines.dual
diff --git a/doc/source/reference/ufuncs.rst b/doc/source/reference/ufuncs.rst
index 76b5a97b6..d63486342 100644
--- a/doc/source/reference/ufuncs.rst
+++ b/doc/source/reference/ufuncs.rst
@@ -46,7 +46,7 @@ understood by four rules:
2. The size in each dimension of the output shape is the maximum of all
the input shapes in that dimension.
-3. An input can be used in the calculation if it's shape in a particular
+3. An input can be used in the calculation if its shape in a particular
dimension either matches the output shape or has value exactly 1.
4. If an input has a dimension size of 1 in its shape, the first data
@@ -89,7 +89,7 @@ is true:
to the other rows,
- *c* acts like a (1,6) array and therefore like a (5,6) array
- where ``c[:]` is broadcast to every row, and finally,
+ where ``c[:]`` is broadcast to every row, and finally,
- *d* acts like a (5,6) array where the single value is repeated.
@@ -332,7 +332,7 @@ and a *dtype* keyword, and the arrays must all have dimension >=
1. The *axis* keyword specifies which axis of the array the reduction
will take place over and may be negative, but must be an integer. The
*dtype* keyword allows you to manage a very common problem that arises
-when naively using `{op}.reduce <ufunc.reduce>`. Sometimes you may
+when naively using :ref:`{op}.reduce <ufunc.reduce>`. Sometimes you may
have an array of a certain data type and wish to add up all of its
elements, but the result does not fit into the data type of the
array. This commonly happens if you have an array of single-byte
diff --git a/doc/source/routines.testing.rst b/doc/source/routines.testing.rst
new file mode 100644
index 000000000..5a5f4cb8c
--- /dev/null
+++ b/doc/source/routines.testing.rst
@@ -0,0 +1,46 @@
+Test Support (:mod:`numpy.testing`)
+===================================
+
+.. currentmodule:: numpy.testing
+
+Common test support for all numpy test scripts.
+
+This single module should provide all the common functionality for numpy
+tests in a single location, so that test scripts can just import it and
+work right away.
+
+
+Asserts
+=======
+.. autosummary::
+ :toctree: generated/
+
+ assert_almost_equal
+ assert_approx_equal
+ assert_array_almost_equal
+ assert_array_equal
+ assert_array_less
+ assert_equal
+ assert_raises
+ assert_string_equal
+
+Decorators
+----------
+.. autosummary::
+ :toctree: generated/
+
+ decorators.knownfailureif
+ decorators.setastest
+ decorators.skipif
+ decorators.slow
+ decorate_methods
+
+
+Test Running
+------------
+.. autosummary::
+ :toctree: generated/
+
+ Tester
+ run_module_suite
+ rundocs
diff --git a/doc/source/user/c-info.how-to-extend.rst b/doc/source/user/c-info.how-to-extend.rst
index b2921239e..6c5e25aff 100644
--- a/doc/source/user/c-info.how-to-extend.rst
+++ b/doc/source/user/c-info.how-to-extend.rst
@@ -607,8 +607,8 @@ updates the output array.
PyObject *arg1=NULL, *arg2=NULL, *out=NULL;
PyObject *arr1=NULL, *arr2=NULL, *oarr=NULL;
- if (!PyArg_ParseTuple(args, OOO&, &arg1, *arg2,
- &PyArrayType, *out)) return NULL;
+ if (!PyArg_ParseTuple(args, "OOO!", &arg1, &arg2,
+ &PyArray_Type, &out)) return NULL;
arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_IN_ARRAY);
if (arr1 == NULL) return NULL;
diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py
index e9548d8f5..121b8088f 100644
--- a/numpy/add_newdocs.py
+++ b/numpy/add_newdocs.py
@@ -63,6 +63,43 @@ add_newdoc('numpy.core', 'flatiter', ('copy',
add_newdoc('numpy.core', 'broadcast',
"""
+ Produce an object that mimics broadcasting.
+
+ Parameters
+ ----------
+ in1, in2, ... : array_like
+ Input parameters.
+
+ Returns
+ -------
+ b : broadcast object
+ Broadcast the input parameters against one another, and
+ return an object that encapsulates the result.
+ Amongst others, it has ``shape`` and ``nd`` properties, and
+ may be used as an iterator.
+
+ Examples
+ --------
+ Manually adding two vectors, using broadcasting:
+
+ >>> x = np.array([[1], [2], [3]])
+ >>> y = np.array([4, 5, 6])
+ >>> b = np.broadcast(x, y)
+
+ >>> out = np.empty(b.shape)
+ >>> out.flat = [u+v for (u,v) in b]
+ >>> out
+ array([[ 5., 6., 7.],
+ [ 6., 7., 8.],
+ [ 7., 8., 9.]])
+
+ Compare against built-in broadcasting:
+
+ >>> x + y
+ array([[5, 6, 7],
+ [6, 7, 8],
+ [7, 8, 9]])
+
""")
# attributes
@@ -106,7 +143,7 @@ add_newdoc('numpy.core', 'broadcast', ('size',
add_newdoc('numpy.core.multiarray', 'array',
"""
- array(object, dtype=None, copy=True, order=None, subok=True, ndmin=True)
+ array(object, dtype=None, copy=True, order=None, subok=False, ndmin=True)
Create an array.
@@ -137,7 +174,7 @@ add_newdoc('numpy.core.multiarray', 'array',
discontiguous).
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
- the returned array will be forced to be a base-class array.
+ the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be pre-pended to the shape as
@@ -546,6 +583,9 @@ add_newdoc('numpy.core.multiarray', 'concatenate',
array([[1, 2],
[3, 4],
[5, 6]])
+ >>> np.concatenate((a, b.T), axis=1)
+ array([[1, 2, 5],
+ [3, 4, 6]])
""")
@@ -834,20 +874,22 @@ add_newdoc('numpy.core.multiarray', 'lexsort',
"""
lexsort(keys, axis=-1)
- Perform an indirect sort using a list of keys.
+ Perform an indirect sort using a sequence of keys.
- Imagine three input keys, ``a``, ``b`` and ``c``. These can be seen as
- columns in a spreadsheet. The first row of the spreadsheet would
- therefore be ``a[0], b[0], c[0]``. Lexical sorting orders the different
- rows by first sorting on the on first column (key), then the second,
- and so forth. At each step, the previous ordering is preserved
- when equal keys are encountered.
+ Given multiple sorting keys, which can be interpreted as columns in a
+ spreadsheet, lexsort returns an array of integer indices that describes
+ the sort order by multiple columns. The last key in the sequence is used
+ for the primary sort order, the second-to-last key for the secondary sort
+ order, and so on. The keys argument must be a sequence of objects that
+ can be converted to arrays of the same shape. If a 2D array is provided
+ for the keys argument, it's rows are interpreted as the sorting keys and
+ sorting is according to the last row, second last row etc.
Parameters
----------
keys : (k,N) array or tuple containing k (N,)-shaped sequences
- The `k` different "columns" to be sorted. The last column is the
- primary sort column.
+ The `k` different "columns" to be sorted. The last column (or row if
+ `keys` is a 2D array) is the primary sort key.
axis : int, optional
Axis to be indirectly sorted. By default, sort over the last axis.
@@ -879,22 +921,22 @@ add_newdoc('numpy.core.multiarray', 'lexsort',
>>> a = [1,5,1,4,3,4,4] # First column
>>> b = [9,4,0,4,0,2,1] # Second column
- >>> ind = np.lexsort((b,a)) # Sort by second, then first column
+ >>> ind = np.lexsort((b,a)) # Sort by a, then by b
>>> print ind
[2 0 4 6 5 3 1]
>>> [(a[i],b[i]) for i in ind]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
- Note that the first elements are sorted. For each first element,
- the second elements are also sorted.
+ Note that sorting is first according to the elements of ``a``.
+ Secondary sorting is according to the elements of ``b``.
A normal ``argsort`` would have yielded:
>>> [(a[i],b[i]) for i in np.argsort(a)]
[(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]
- Structured arrays are sorted lexically:
+ Structured arrays are sorted lexically by ``argsort``:
>>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],
... dtype=np.dtype([('x', int), ('y', int)]))
@@ -1158,6 +1200,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray',
nbytes : int
The total number of bytes required to store the array data,
i.e., ``itemsize * size``.
+ ndim : int
+ The number of dimensions that the array has.
shape : tuple of ints
Shape of the array.
strides : tuple of ints
@@ -1383,16 +1427,32 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('flags',
add_newdoc('numpy.core.multiarray', 'ndarray', ('flat',
"""
- A 1-d flat iterator.
+ A 1-D flat iterator over the array.
+
+ This is a `flatiter` instance, which acts similarly to a Python iterator.
+
+ See Also
+ --------
+ flatten : Return a copy of the array collapsed into one dimension.
+ flatiter
Examples
--------
- >>> x = np.arange(3*4*5)
- >>> x.shape = (3,4,5)
- >>> x.flat[19]
- 19
- >>> x.T.flat[19]
- 31
+ >>> x = np.arange(1, 7).reshape(2, 3)
+ >>> x
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> x.flat[3]
+ 4
+ >>> x.T
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+ >>> x.T.flat[3]
+ 5
+
+ >>> type(x.flat)
+ <type 'numpy.flatiter'>
"""))
@@ -1441,6 +1501,10 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('real',
>>> x.real.dtype
dtype('float64')
+ See Also
+ --------
+ numpy.real : equivalent function
+
"""))
@@ -1935,7 +1999,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten',
"""
a.flatten(order='C')
- Collapse an array into one dimension.
+ Return a copy of the array collapsed into one dimension.
Parameters
----------
@@ -1948,6 +2012,11 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten',
y : ndarray
A copy of the input array, flattened to one dimension.
+ See Also
+ --------
+ ravel : Return a flattened array.
+ flat : A 1-D flat iterator over the array.
+
Examples
--------
>>> a = np.array([[1,2], [3,4]])
@@ -2024,36 +2093,44 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('min',
add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder',
- """a.newbyteorder(byteorder)
+ """
+ arr.newbyteorder(new_order='S')
+
+ Return the array with the same data viewed with a different byte order.
+
+ Equivalent to::
+
+ arr.view(arr.dtype.newbytorder(new_order))
- Equivalent to a.view(a.dtype.newbytorder(byteorder))
+ Changes are also made in all fields and sub-arrays of the array data
+ type.
- Return array with dtype changed to interpret array data as
- specified byte order.
- Changes are also made in all fields and sub-arrays of the array
- data type.
Parameters
----------
new_order : string, optional
- Byte order to force; a value from the byte order
- specifications below. The default value ('S') results in
- swapping the current byte order.
- `new_order` codes can be any of:
+ Byte order to force; a value from the byte order specifications
+ above. `new_order` codes can be any of::
+
+ * 'S' - swap dtype from current to opposite endian
* {'<', 'L'} - little endian
* {'>', 'B'} - big endian
* {'=', 'N'} - native order
- * 'S' - swap dtype from current to opposite endian
* {'|', 'I'} - ignore (no change to byte order)
- The code does a case-insensitive check on the first letter of
- `new_order` for these alternatives. For example, any of '>'
- or 'B' or 'b' or 'brian' are valid to specify big-endian.
+
+ The default value ('S') results in swapping the current
+ byte order. The code does a case-insensitive check on the first
+ letter of `new_order` for the alternatives above. For example,
+ any of 'B' or 'b' or 'biggish' are valid to specify big-endian.
+
Returns
-------
new_arr : array
- array with the given change to the dtype byte order.
+ New array object with the dtype reflecting given change to the
+ byte order.
+
"""))
@@ -2123,19 +2200,20 @@ add_newdoc('numpy.core.multiarray', 'putmask',
Changes elements of an array based on conditional and input values.
- Sets `a`.flat[n] = `values`\\[n] for each n where `mask`.flat[n] is true.
+ Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
If `values` is not the same size as `a` and `mask` then it will repeat.
- This gives behavior different from `a[mask] = values`.
+ This gives behavior different from ``a[mask] = values``.
Parameters
----------
a : array_like
- Array to put data into
+ Target array.
mask : array_like
- Boolean mask array
+ Boolean mask array. It has to be the same shape as `a`.
values : array_like
- Values to put
+ Values to put into `a` where `mask` is True. If `values` is smaller
+ than `a` it will be repeated.
See Also
--------
@@ -2143,21 +2221,18 @@ add_newdoc('numpy.core.multiarray', 'putmask',
Examples
--------
- >>> a = np.array([10,20,30,40])
- >>> mask = np.array([True,False,True,True])
- >>> a.putmask([60,70,80,90], mask)
- >>> a
- array([60, 20, 80, 90])
- >>> a = np.array([10,20,30,40])
- >>> a[mask]
- array([60, 80, 90])
- >>> a[mask] = np.array([60,70,80,90])
- >>> a
- array([60, 20, 70, 80])
- >>> a.putmask([10,90], mask)
- >>> a
- array([10, 20, 10, 90])
- >>> np.putmask(a, mask, [60,70,80,90])
+ >>> x = np.arange(6).reshape(2, 3)
+ >>> np.putmask(x, x>2, x**2)
+ >>> x
+ array([[ 0, 1, 2],
+ [ 9, 16, 25]])
+
+ If `values` is smaller than `a` it is repeated:
+
+ >>> x = np.arange(5)
+ >>> np.putmask(x, x>1, [-33, -44])
+ >>> x
+ array([ 0, 1, -33, -44, -33])
""")
@@ -2174,6 +2249,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel',
--------
numpy.ravel : equivalent function
+ ndarray.flat : a flat iterator on the array.
+
"""))
@@ -2471,7 +2548,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist',
Return the array as a possibly nested list.
- Return a copy of the array data as a hierarchical Python list.
+ Return a copy of the array data as a (nested) Python list.
Data items are converted to the nearest compatible Python type.
Parameters
@@ -2531,13 +2608,19 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('trace',
add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose',
- """a.transpose(*axes)
+ """
+ a.transpose(*axes)
Returns a view of 'a' with axes transposed. If no axes are given,
or None is passed, switches the order of the axes. For a 2-d
array, this is the usual matrix transpose. If axes are given,
they describe how the axes are permuted.
+ See Also
+ --------
+ ndarray.T : array property returning the array transposed
+
+
Examples
--------
>>> a = np.array([[1,2],[3,4]])
@@ -2621,14 +2704,80 @@ 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.
+
+ Returns (`out1`, `out2`) from equation `x` = `out1` * ( 2 ** `out2` )
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ 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.
+
+ Examples
+ --------
+ >>> y1,y2 = np.frexp([3.4, 5.7, 1, 10, -100, 0])
+ >>> y1
+ array([ 0.85 , 0.7125 , 0.5 , 0.625 , -0.78125, 0. ])
+ >>> y2
+ array([2, 3, 1, 4, 7, 0], dtype=int32)
+ >>> y1 * 2**y2
+ array([ 3.4, 5.7, 1. , 10. , -100. , 0. ])
+
""")
add_newdoc('numpy.core.umath', 'frompyfunc',
"""
+ frompyfunc(func, nin, nout)
+
+ Takes an arbitrary Python function and returns a ufunc.
+
+ Parameters
+ ----------
+ func : Python function
+ An arbitrary Python function.
+ nin : int
+ The number of input arguments.
+ nout : int
+ The number of objects returned by `func`.
+
+ Returns
+ -------
+ out : ufunc
+ Returns a Numpy universal function (``ufunc`` object).
+
+ Notes
+ -----
+ The returned ufunc always returns PyObject arrays.
+
""")
add_newdoc('numpy.core.umath', 'ldexp',
"""
+ Compute y = x1 * 2**x2.
+
+ Parameters
+ ----------
+ x1 : array_like
+ The significand.
+ x2 : array_like
+ The exponent.
+
+ Returns
+ -------
+ y : array_like
+ y = x1 * 2**x2
+
+ Examples
+ --------
+ >>> np.ldexp(5., 2)
+ 20.
+
""")
add_newdoc('numpy.core.umath','geterrobj',
@@ -2669,29 +2818,66 @@ add_newdoc('numpy.core.umath', 'seterrobj',
add_newdoc('numpy.lib._compiled_base', 'digitize',
"""
- digitize(x,bins)
+ digitize(x, bins)
- Return the index of the bin to which each value of x belongs.
+ Return the indices of the bins to which each value in input array belongs.
- 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.
+ 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.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array to be binned.
+ bins : array_like
+ Array of bins.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of indices of same shape as `x`.
+
+ 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
+ array([1, 4, 3, 2])
+ >>> for n in range(len(x)):
+ ... print bins[d[n]-1], "<=", x[n], "<", bins[d[n]]
+ ...
+ 0.0 <= 0.2 < 1.0
+ 4.0 <= 6.4 < 10.0
+ 2.5 <= 3.0 < 4.0
+ 1.0 <= 1.6 < 2.5
- Beyond the bounds of the bins 0 or len(bins) is returned as appropriate.
""")
add_newdoc('numpy.lib._compiled_base', 'bincount',
"""
- bincount(x,weights=None)
+ bincount(x, weights=None)
+
+ Return the number of occurrences of each value in array of nonnegative
+ integers.
+
+ 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.
- Return the number of occurrences of each value in x.
+ Parameters
+ ----------
+ x : array_like, 1 dimension, nonnegative integers
+ Input array.
+ weights : array_like, same shape as `x`, optional
+ Weights.
- x must be a list of non-negative integers. 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.
+ See Also
+ --------
+ histogram, digitize, unique
- See also: histogram, digitize, unique.
""")
add_newdoc('numpy.lib._compiled_base', 'add_docstring',
@@ -2706,40 +2892,89 @@ add_newdoc('numpy.lib._compiled_base', 'add_docstring',
add_newdoc('numpy.lib._compiled_base', 'packbits',
"""
- out = numpy.packbits(myarray, axis=None)
+ packbits(myarray, axis=None)
+
+ Packs the elements of a binary-valued array into bits in a uint8 array.
- myarray : an integer type array whose elements should be packed to bits
+ The result is padded to full bytes by inserting zero bits at the end.
- This routine packs the elements of a binary-valued dataset into a
- NumPy array of type uint8 ('B') whose bits correspond to
- the logical (0 or nonzero) value of the input elements.
- The dimension over-which bit-packing is done is given by axis.
- The shape of the output has the same number of dimensions as the input
- (unless axis is None, in which case the output is 1-d).
+ Parameters
+ ----------
+ myarray : array_like
+ An integer type array whose elements should be packed to bits.
+ axis : int, optional
+ The dimension over which bit-packing is done.
+ ``None`` implies packing the flattened array.
+
+ Returns
+ -------
+ packed : ndarray
+ Array of type uint8 whose elements represent bits corresponding to the
+ logical (0 or nonzero) value of the input elements. The shape of
+ `packed` has the same number of dimensions as the input (unless `axis`
+ is None, in which case the output is 1-D).
+
+ See Also
+ --------
+ unpackbits: Unpacks elements of a uint8 array into a binary-valued output
+ array.
- Example:
- >>> a = array([[[1,0,1],
- ... [0,1,0]],
- ... [[1,1,0],
- ... [0,0,1]]])
- >>> b = numpy.packbits(a,axis=-1)
+ Examples
+ --------
+ >>> a = np.array([[[1,0,1],
+ ... [0,1,0]],
+ ... [[1,1,0],
+ ... [0,0,1]]])
+ >>> b = np.packbits(a, axis=-1)
>>> b
array([[[160],[64]],[[192],[32]]], dtype=uint8)
- Note that 160 = 128 + 32
- 192 = 128 + 64
+ Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000,
+ and 32 = 0010 0000.
+
""")
add_newdoc('numpy.lib._compiled_base', 'unpackbits',
"""
- out = numpy.unpackbits(myarray, axis=None)
+ unpackbits(myarray, axis=None)
+
+ Unpacks elements of a uint8 array into a binary-valued output array.
+
+ Each element of `myarray` represents a bit-field that should be unpacked
+ into a binary-valued output array. The shape of the output array is either
+ 1-D (if `axis` is None) or the same shape as the input array with unpacking
+ done along the axis specified.
+
+ Parameters
+ ----------
+ myarray : ndarray, uint8 type
+ Input array.
+ axis : int, optional
+ Unpacks along this axis.
+
+ Returns
+ -------
+ unpacked : ndarray, uint8 type
+ The elements are binary-valued (0 or 1).
- myarray - array of uint8 type where each element represents a bit-field
- that should be unpacked into a boolean output array
+ See Also
+ --------
+ packbits : Packs the elements of a binary-valued array into bits in a uint8
+ array.
+
+ Examples
+ --------
+ >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
+ >>> a
+ array([[ 2],
+ [ 7],
+ [23]], dtype=uint8)
+ >>> b = np.unpackbits(a, axis=1)
+ >>> b
+ array([[0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
- The shape of the output array is either 1-d (if axis is None) or
- the same shape as the input array with unpacking done along the
- axis specified.
""")
@@ -3094,22 +3329,30 @@ add_newdoc('numpy.core.multiarray', 'dtype',
add_newdoc('numpy.core.multiarray', 'dtype', ('alignment',
"""
+ The required alignment (bytes) of this data-type according to the compiler.
+
+ More information is available in the C-API section of the manual.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder',
- '''
- byteorder
-
- String giving byteorder of dtype
+ """
+ A character indicating the byte-order of this data-type object.
One of:
- * '=' - native byteorder
- * '<' - little endian
- * '>' - big endian
- * '|' - endian not relevant
+
+ === ==============
+ '=' native
+ '<' little-endian
+ '>' big-endian
+ '|' not applicable
+ === ==============
+
+ All built-in data-type objects have byteorder either '=' or '|'.
Examples
--------
+
>>> dt = np.dtype('i2')
>>> dt.byteorder
'='
@@ -3132,45 +3375,79 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder',
>>> dt = np.dtype(swapped_code + 'i2')
>>> dt.byteorder == swapped_code
True
- '''))
-add_newdoc('numpy.core.multiarray', 'dtype', ('char',
- """
"""))
+add_newdoc('numpy.core.multiarray', 'dtype', ('char',
+ """A unique character code for each of the 21 different built-in types."""))
+
add_newdoc('numpy.core.multiarray', 'dtype', ('descr',
"""
+ Array-interface compliant full description of the data-type.
+
+ The format is that required by the 'descr' key in the
+ `__array_interface__` attribute.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('fields',
"""
+ Dictionary showing any named fields defined for this data type, or None.
+
+ The dictionary is indexed by keys that are the names of the fields.
+ Each entry in the dictionary is a tuple fully describing the field::
+
+ (dtype, offset[, title])
+
+ If present, the optional title can be any object (if it is string
+ or unicode then it will also be a key in the fields dictionary,
+ otherwise it's meta-data). Notice also, that the first two elements
+ of the tuple can be passed directly as arguments to the `ndarray.getfield`
+ and `ndarray.setfield` methods.
+
+ See Also
+ --------
+ ndarray.getfield, ndarray.setfield
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('flags',
"""
+ Bit-flags describing how this data type is to be interpreted.
+
+ Bit-masks are in `numpy.core.multiarray` as the constants
+ `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
+ `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
+ of these flags is in C-API documentation; they are largely useful
+ for user-defined data-types.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('hasobject',
"""
+ Boolean indicating whether this dtype contains any reference-counted
+ objects in any fields or sub-dtypes.
+
+ Recall that what is actually in the ndarray memory representing
+ the Python object is the memory address of that object (a pointer).
+ Special handling may be required, and this attribute is useful for
+ distinguishing data types that may contain arbitrary Python objects
+ and data-types that won't.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin',
"""
- isbuiltin
+ Integer indicating how this dtype relates to the built-in dtypes.
- Value identifying if numpy dtype is a numpy builtin type
-
- Read-only
-
- Returns
- -------
- val : {0,1,2}
- 0 if this is a structured array type, with fields
- 1 if this is a dtype compiled into numpy (such as ints, floats etc)
- 2 if the dtype is for a user-defined numpy type
- A user-defined type uses the numpy C-API machinery to extend
- numpy to handle a new array type. See the Guide to Numpy for
- details.
+ = ========================================================================
+ 0 if this is a structured array type, with fields
+ 1 if this is a dtype compiled into numpy (such as ints, floats etc)
+ 2 if the dtype is for a user-defined numpy type
+ A user-defined type uses the numpy C-API machinery to extend
+ numpy to handle a new array type. See the Guide to Numpy for
+ details.
+ = ========================================================================
Examples
--------
@@ -3183,47 +3460,81 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin',
>>> dt = np.dtype([('field1', 'f8')])
>>> dt.isbuiltin
0
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('isnative',
"""
+ Boolean indicating whether the byte order of this dtype is native
+ to the platform.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize',
"""
+ The element size of this data-type object.
+
+ For 18 of the 21 types this number is fixed by the data-type.
+ For the flexible data-types, this number can be anything.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('kind',
"""
+ A character code (one of 'biufcSUV') identifying the general kind of data.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('name',
"""
+ A bit-width name for this data-type.
+
+ Un-sized flexible data-type objects do not have this attribute.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('names',
"""
+ Ordered list of field names, or ``None`` if there are no fields.
+
+ The names are ordered according to increasing byte offset.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('num',
"""
+ A unique number for each of the 21 different built-in types.
+
+ These are roughly ordered from least-to-most precision.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('shape',
"""
+ Shape tuple of the sub-array if this data type describes a sub-array,
+ and ``()`` otherwise.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('str',
- """
- """))
+ """The array-protocol typestring of this data-type object."""))
add_newdoc('numpy.core.multiarray', 'dtype', ('subdtype',
"""
+ Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
+ None otherwise.
+
+ The *shape* is the fixed shape of the sub-array described by this
+ data type, and *item_dtype* the data type of the array.
+
+ If a field whose dtype object has this attribute is retrieved,
+ then the extra dimensions implied by *shape* are tacked on to
+ the end of the retrieved array.
+
"""))
add_newdoc('numpy.core.multiarray', 'dtype', ('type',
- """
- """))
+ """The type object used to instantiate a scalar of this data-type."""))
##############################################################################
#
@@ -3232,7 +3543,7 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('type',
##############################################################################
add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
- '''
+ """
newbyteorder(new_order='S')
Return a new dtype with a different byte order.
@@ -3245,12 +3556,14 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
Byte order to force; a value from the byte order
specifications below. The default value ('S') results in
swapping the current byte order.
- `new_order` codes can be any of:
+ `new_order` codes can be any of::
+
+ * 'S' - swap dtype from current to opposite endian
* {'<', 'L'} - little endian
* {'>', 'B'} - big endian
* {'=', 'N'} - native order
- * 'S' - swap dtype from current to opposite endian
* {'|', 'I'} - ignore (no change to byte order)
+
The code does a case-insensitive check on the first letter of
`new_order` for these alternatives. For example, any of '>'
or 'B' or 'b' or 'brian' are valid to specify big-endian.
@@ -3260,6 +3573,10 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
new_dtype : dtype
New dtype object with the given change to the byte order.
+ Notes
+ -----
+ Changes are also made in all fields and sub-arrays of the data type.
+
Examples
--------
>>> import sys
@@ -3288,7 +3605,8 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
True
>>> np.dtype('>i2') == native_dt.newbyteorder('B')
True
- '''))
+
+ """))
##############################################################################
@@ -3299,69 +3617,84 @@ add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
add_newdoc('numpy.lib.index_tricks', 'mgrid',
"""
- Construct a multi-dimensional filled "meshgrid".
+ `nd_grid` instance which returns a dense multi-dimensional "meshgrid".
- Returns a mesh-grid when indexed. The dimension and number of the
- output arrays are equal to the number of indexing dimensions. If
- the step length is not a complex number, then the stop is not
- inclusive.
+ An instance of `numpy.lib.index_tricks.nd_grid` which returns an dense
+ (or fleshed out) mesh-grid when indexed, so that each returned argument
+ has the same shape. The dimensions and number of the output arrays are
+ equal to the number of indexing dimensions. If the step length is not a
+ complex number, then the stop is not inclusive.
- However, if the step length is a **complex number** (e.g. 5j),
- then the integer part of its magnitude is interpreted as
- specifying the number of points to create between the start and
- stop values, where the stop value **is inclusive**.
+ However, if the step length is a **complex number** (e.g. 5j), then
+ the integer part of its magnitude is interpreted as specifying the
+ number of points to create between the start and stop values, where
+ the stop value **is inclusive**.
- See also
+ Returns
+ ----------
+ mesh-grid `ndarrays` all of the same dimensions
+
+ See Also
--------
- ogrid
+ numpy.lib.index_tricks.nd_grid : class of `ogrid` and `mgrid` objects
+ ogrid : like mgrid but returns open (not fleshed out) mesh grids
+ r_ : array concatenator
Examples
--------
- >>> np.mgrid[0:5,0:5]
+ >>> mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
- <BLANKLINE>
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
- >>> np.mgrid[-1:1:5j]
+ >>> mgrid[-1:1:5j]
array([-1. , -0.5, 0. , 0.5, 1. ])
+
""")
add_newdoc('numpy.lib.index_tricks', 'ogrid',
"""
- Construct a multi-dimensional open "meshgrid".
+ `nd_grid` instance which returns an open multi-dimensional "meshgrid".
- Returns an 'open' mesh-grid when indexed. The dimension and
- number of the output arrays are equal to the number of indexing
- dimensions. If the step length is not a complex number, then the
- stop is not inclusive.
+ An instance of `numpy.lib.index_tricks.nd_grid` which returns an open
+ (i.e. not fleshed out) mesh-grid when indexed, so that only one dimension
+ of each returned array is greater than 1. The dimension and number of the
+ output arrays are equal to the number of indexing dimensions. If the step
+ length is not a complex number, then the stop is not inclusive.
- The returned mesh-grid is open (or not fleshed out), so that only
- one-dimension of each returned argument is greater than 1
+ However, if the step length is a **complex number** (e.g. 5j), then
+ the integer part of its magnitude is interpreted as specifying the
+ number of points to create between the start and stop values, where
+ the stop value **is inclusive**.
- If the step length is a **complex number** (e.g. 5j), then the
- integer part of its magnitude is interpreted as specifying the
- number of points to create between the start and stop values,
- where the stop value **is inclusive**.
+ Returns
+ ----------
+ mesh-grid `ndarrays` with only one dimension :math:`\\neq 1`
- See also
+ See Also
--------
- mgrid
+ np.lib.index_tricks.nd_grid : class of `ogrid` and `mgrid` objects
+ mgrid : like `ogrid` but returns dense (or fleshed out) mesh grids
+ r_ : array concatenator
Examples
--------
- >>> np.ogrid[0:5,0:5]
+ >>> from numpy import ogrid
+ >>> ogrid[-1:1:5j]
+ array([-1. , -0.5, 0. , 0.5, 1. ])
+ >>> ogrid[0:5,0:5]
[array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]])]
+
""")
@@ -3537,6 +3870,35 @@ add_newdoc('numpy.core.numerictypes', 'generic', ('min',
add_newdoc('numpy.core.numerictypes', 'generic', ('newbyteorder',
"""
+ newbyteorder(new_order='S')
+
+ Return a new dtype with a different byte order.
+
+ Changes are also made in all fields and sub-arrays of the data type.
+
+ The `new_order` code can be any from the following:
+
+ * {'<', 'L'} - little endian
+ * {'>', 'B'} - big endian
+ * {'=', 'N'} - native order
+ * 'S' - swap dtype from current to opposite endian
+ * {'|', 'I'} - ignore (no change to byte order)
+
+ Parameters
+ ----------
+ new_order : string, optional
+ Byte order to force; a value from the byte order specifications
+ above. The default value ('S') results in swapping the current
+ byte order. The code does a case-insensitive check on the first
+ letter of `new_order` for the alternatives above. For example,
+ any of 'B' or 'b' or 'biggish' are valid to specify big-endian.
+
+
+ Returns
+ -------
+ new_dtype : dtype
+ New dtype object with the given change to the byte order.
+
"""))
add_newdoc('numpy.core.numerictypes', 'generic', ('nonzero',
@@ -3647,8 +4009,7 @@ add_newdoc('numpy.core.numerictypes', 'generic', ('view',
##############################################################################
add_newdoc('numpy.core.numerictypes', 'bool_',
- """
- """)
+ """Boolean. Character code ``?``.""")
add_newdoc('numpy.core.numerictypes', 'complex64',
"""
@@ -3663,12 +4024,10 @@ add_newdoc('numpy.core.numerictypes', 'complex256',
""")
add_newdoc('numpy.core.numerictypes', 'float32',
- """
- """)
+ """32-bit floating-point number. Character code ``f``.""")
add_newdoc('numpy.core.numerictypes', 'float64',
- """
- """)
+ """64-bit floating-point number. Character code ``d``.""")
add_newdoc('numpy.core.numerictypes', 'float96',
"""
@@ -3679,20 +4038,16 @@ add_newdoc('numpy.core.numerictypes', 'float128',
""")
add_newdoc('numpy.core.numerictypes', 'int8',
- """
- """)
+ """8-bit integer. Character code ``b``.""")
add_newdoc('numpy.core.numerictypes', 'int16',
- """
- """)
+ """16-bit integer. Character code ``h``.""")
add_newdoc('numpy.core.numerictypes', 'int32',
- """
- """)
+ """32-bit integer. Character code ``i4``.""")
add_newdoc('numpy.core.numerictypes', 'int64',
- """
- """)
+ """64-bit integer. Character code ``i8``.""")
add_newdoc('numpy.core.numerictypes', 'object_',
"""
diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py
index 08f131c23..e880f21a2 100644
--- a/numpy/core/code_generators/ufunc_docstrings.py
+++ b/numpy/core/code_generators/ufunc_docstrings.py
@@ -468,26 +468,11 @@ add_newdoc('numpy.core.umath', 'arctanh',
add_newdoc('numpy.core.umath', 'bitwise_and',
"""
- Compute bit-wise AND of two arrays, element-wise.
+ Compute the bit-wise AND of two arrays element-wise.
- When calculating the bit-wise AND between two elements, ``x`` and ``y``,
- each element is first converted to its binary representation (which works
- just like the decimal system, only now we're using 2 instead of 10):
-
- .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i\\\\
- y = \\sum_{i=0}^{W-1} b_i \\cdot 2^i,
-
- where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
- and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
- is represented as ``00001101``, which translates to
- :math:`2^4 + 2^3 + 2`.
-
- The bit-wise operator is the result of
-
- .. math:: z = \\sum_{i=0}^{i=W-1} (a_i \\wedge b_i) \\cdot 2^i,
-
- where :math:`\\wedge` is the AND operator, which yields one whenever
- both :math:`a_i` and :math:`b_i` are 1.
+ Computes the bit-wise AND of the underlying binary representation of
+ the integers in the input arrays. This ufunc implements the C/Python
+ operator ``&``.
Parameters
----------
@@ -501,14 +486,15 @@ add_newdoc('numpy.core.umath', 'bitwise_and',
See Also
--------
- bitwise_or, bitwise_xor
logical_and
+ bitwise_or
+ bitwise_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
- We have seen that 13 is represented by ``00001101``. Similary, 17 is
+ The number 13 is represented by ``00001101``. Likewise, 17 is
represented by ``00010001``. The bit-wise AND of 13 and 17 is
therefore ``000000001``, or 1:
@@ -533,26 +519,11 @@ add_newdoc('numpy.core.umath', 'bitwise_and',
add_newdoc('numpy.core.umath', 'bitwise_or',
"""
- Compute bit-wise OR of two arrays, element-wise.
-
- When calculating the bit-wise OR between two elements, ``x`` and ``y``,
- each element is first converted to its binary representation (which works
- just like the decimal system, only now we are using 2 instead of 10):
-
- .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i\\\\
- y = \\sum_{i=0}^{W-1} b_i \\cdot 2^i,
+ Compute the bit-wise OR of two arrays element-wise.
- where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
- and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
- is represented as ``00001101``, which translates to
- :math:`2^4 + 2^3 + 2`.
-
- The bit-wise operator is the result of
-
- .. math:: z = \\sum_{i=0}^{i=W-1} (a_i \\vee b_i) \\cdot 2^i,
-
- where :math:`\\vee` is the OR operator, which yields one whenever
- either :math:`a_i` or :math:`b_i` is 1.
+ Computes the bit-wise OR of the underlying binary representation of
+ the integers in the input arrays. This ufunc implements the C/Python
+ operator ``|``.
Parameters
----------
@@ -566,16 +537,17 @@ add_newdoc('numpy.core.umath', 'bitwise_or',
See Also
--------
- bitwise_and, bitwise_xor
logical_or
+ bitwise_and
+ bitwise_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
- We've seen that 13 is represented by ``00001101``. Similary, 16 is
- represented by ``00010000``. The bit-wise OR of 13 and 16 is
- therefore ``000111011``, or 29:
+ The number 13 has the binaray representation ``00001101``. Likewise,
+ 16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is
+ then ``000111011``, or 29:
>>> np.bitwise_or(13, 16)
29
@@ -601,26 +573,11 @@ add_newdoc('numpy.core.umath', 'bitwise_or',
add_newdoc('numpy.core.umath', 'bitwise_xor',
"""
- Compute bit-wise XOR of two arrays, element-wise.
-
- When calculating the bit-wise XOR between two elements, ``x`` and ``y``,
- each element is first converted to its binary representation (which works
- just like the decimal system, only now we are using 2 instead of 10):
-
- .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i\\\\
- y = \\sum_{i=0}^{W-1} b_i \\cdot 2^i,
-
- where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
- and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
- is represented as ``00001101``, which translates to
- :math:`2^4 + 2^3 + 2`.
-
- The bit-wise operator is the result of
+ Compute the bit-wise XOR of two arrays element-wise.
- .. math:: z = \\sum_{i=0}^{i=W-1} (a_i \\oplus b_i) \\cdot 2^i,
-
- where :math:`\\oplus` is the XOR operator, which yields one whenever
- either :math:`a_i` or :math:`b_i` is 1, but not both.
+ Computes the bit-wise XOR of the underlying binary representation of
+ the integers in the input arrays. This ufunc implements the C/Python
+ operator ``^``.
Parameters
----------
@@ -629,19 +586,20 @@ add_newdoc('numpy.core.umath', 'bitwise_xor',
Returns
-------
- out : ndarray
+ out : array_like
Result.
See Also
--------
- bitwise_and, bitwise_or
logical_xor
+ bitwise_and
+ bitwise_or
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
- We've seen that 13 is represented by ``00001101``. Similary, 17 is
+ The number 13 is represented by ``00001101``. Likewise, 17 is
represented by ``00010001``. The bit-wise XOR of 13 and 17 is
therefore ``00011100``, or 28:
@@ -679,6 +637,10 @@ add_newdoc('numpy.core.umath', 'ceil',
y : {ndarray, scalar}
The ceiling of each element in `x`.
+ See Also
+ --------
+ floor, trunc, rint
+
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
@@ -705,10 +667,14 @@ add_newdoc('numpy.core.umath', 'trunc',
y : {ndarray, scalar}
The truncated value of each element in `x`.
+ See Also
+ --------
+ ceil, floor, rint
+
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
- >>> np.ceil(a)
+ >>> np.trunc(a)
array([-1., -1., -0., 0., 1., 1., 2.])
Notes
@@ -804,26 +770,21 @@ add_newdoc('numpy.core.umath', 'degrees',
add_newdoc('numpy.core.umath', 'rad2deg',
"""
- Convert angles from radians to degrees. This is the same
- function as degrees but is preferred because its more
- descriptive name.
+ Convert angles from radians to degrees.
Parameters
----------
x : array_like
- Angle in radians.
+ Angle in radians.
Returns
-------
y : ndarray
- The corresponding angle in degrees.
-
+ The corresponding angle in degrees.
See Also
--------
- degrees : Convert angles from radians to degrees.
deg2rad : Convert angles from degrees to radians.
- radians : Convert angles from degrees to radians.
unwrap : Remove large jumps in angle by wrapping.
Notes
@@ -911,7 +872,7 @@ add_newdoc('numpy.core.umath', 'divide',
add_newdoc('numpy.core.umath', 'equal',
"""
- Returns elementwise x1 == x2 in a bool array.
+ Return (x1 == x2) element-wise.
Parameters
----------
@@ -920,8 +881,23 @@ add_newdoc('numpy.core.umath', 'equal',
Returns
-------
- out : boolean
- The elementwise test `x1` == `x2`.
+ out : {ndarray, bool}
+ Output array of bools, or a single bool if x1 and x2 are scalars.
+
+ See Also
+ --------
+ not_equal, greater_equal, less_equal, greater, less
+
+ Examples
+ --------
+ >>> np.equal([0, 1, 3], np.arange(3))
+ array([ True, True, False], dtype=bool)
+
+ What is compared are values, not types. So an int (1) and an array of
+ length one can evaluate as True:
+
+ >>> np.equal(1, np.ones(1))
+ array([ True], dtype=bool)
""")
@@ -1005,32 +981,33 @@ add_newdoc('numpy.core.umath', 'exp2',
add_newdoc('numpy.core.umath', 'expm1',
"""
- Return the exponential of the elements in the array minus one.
+ Compute ``exp(x) - 1`` for all elements in the array.
Parameters
----------
x : array_like
- Input values.
+ Input values.
Returns
-------
out : ndarray
- Element-wise exponential minus one: ``out=exp(x)-1``.
+ Element-wise exponential minus one: ``out = exp(x) - 1``.
See Also
--------
- log1p : ``log(1+x)``, the inverse of expm1.
+ log1p : ``log(1 + x)``, the inverse of expm1.
Notes
-----
- This function provides greater precision than using ``exp(x)-1``
- for small values of `x`.
+ This function provides greater precision than the formula ``exp(x) - 1``
+ for small values of ``x``.
Examples
--------
- Since the series expansion of ``e**x = 1 + x + x**2/2! + x**3/3! + ...``,
- for very small `x` we expect that ``e**x -1 ~ x + x**2/2``:
+ The true value of ``exp(1e-10) - 1`` is ``1.00000000005e-10`` to
+ about 32 significant digits. This example shows the superiority of
+ expm1 in this case.
>>> np.expm1(1e-10)
1.00000000005e-10
@@ -1088,11 +1065,15 @@ add_newdoc('numpy.core.umath', 'floor',
y : {ndarray, scalar}
The floor of each element in `x`.
+ See Also
+ --------
+ ceil, trunc, rint
+
Notes
-----
Some spreadsheet programs calculate the "floor-towards-zero", in other
words ``floor(-2.5) == -2``. NumPy, however, uses the a definition of
- `floor` such that `floor(-2.5) == -3``.
+ `floor` such that `floor(-2.5) == -3`.
Examples
--------
@@ -1206,7 +1187,7 @@ add_newdoc('numpy.core.umath', 'greater',
add_newdoc('numpy.core.umath', 'greater_equal',
"""
- Element-wise True if first array is greater or equal than second array.
+ Return (x1 >= x2) element-wise.
Parameters
----------
@@ -1215,17 +1196,17 @@ add_newdoc('numpy.core.umath', 'greater_equal',
Returns
-------
- out : ndarray, bool
- Output array.
+ out : {ndarray, bool}
+ Output array of bools, or a single bool if x1 and x2 are scalars.
See Also
--------
- greater, less, less_equal, equal
+ greater, less, less_equal, equal, not_equal
Examples
--------
- >>> np.greater_equal([4,2],[2,2])
- array([ True, True], dtype=bool)
+ >>> np.greater_equal([4, 2, 1], [2, 2, 2])
+ array([ True, True, False], dtype=bool)
""")
@@ -1256,22 +1237,9 @@ add_newdoc('numpy.core.umath', 'invert',
"""
Compute bit-wise inversion, or bit-wise NOT, element-wise.
- When calculating the bit-wise NOT of an element ``x``, each element is
- first converted to its binary representation (which works
- just like the decimal system, only now we're using 2 instead of 10):
-
- .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i
-
- where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
- and each :math:`a_i` is either 0 or 1. For example, 13 is represented
- as ``00001101``, which translates to :math:`2^4 + 2^3 + 2`.
-
- The bit-wise operator is the result of
-
- .. math:: z = \\sum_{i=0}^{i=W-1} (\\lnot a_i) \\cdot 2^i,
-
- where :math:`\\lnot` is the NOT operator, which yields 1 whenever
- :math:`a_i` is 0 and yields 0 whenever :math:`a_i` is 1.
+ Computes the bit-wise NOT of the underlying binary representation of
+ the integers in the input arrays. This ufunc implements the C/Python
+ operator ``~``.
For signed integer inputs, the two's complement is returned.
In a two's-complement system negative numbers are represented by the two's
@@ -1282,12 +1250,12 @@ add_newdoc('numpy.core.umath', 'invert',
Parameters
----------
- x1 : ndarray
+ x1 : array_like
Only integer types are handled (including booleans).
Returns
-------
- out : ndarray
+ out : array_like
Result.
See Also
@@ -1347,39 +1315,36 @@ add_newdoc('numpy.core.umath', 'invert',
add_newdoc('numpy.core.umath', 'isfinite',
"""
- Returns True for each element that is a finite number.
-
- Shows which elements of the input are finite (not infinity or not
- Not a Number).
+ Test element-wise for finite-ness (not infinity or not Not a Number),
+ return result as bool array.
Parameters
----------
x : array_like
- Input values.
+ Input values.
y : array_like, optional
- A boolean array with the same shape and type as `x` to store the result.
+ A boolean array with the same shape and type as `x` to store the
+ result.
Returns
-------
y : ndarray, bool
- For scalar input data, the result is a new numpy boolean with value True
- if the input data is finite; otherwise the value is False (input is
- either positive infinity, negative infinity or Not a Number).
-
- For array input data, the result is an numpy boolean array with the same
- dimensions as the input and the values are True if the corresponding
- element of the input is finite; otherwise the values are False (element
- is either positive infinity, negative infinity or Not a Number). If the
- second argument is supplied then an numpy integer array is returned with
- values 0 or 1 corresponding to False and True, respectively.
+ For scalar input, the result is a new boolean with value True
+ if the input is finite; otherwise the value is False (input is
+ either positive infinity, negative infinity or Not a Number).
+
+ For array input, the result is a boolean array with the same
+ dimensions as the input and the values are True if the corresponding
+ element of the input is finite; otherwise the values are False (element
+ is either positive infinity, negative infinity or Not a Number). If a
+ second argument is supplied the result is stored there. If the type of
+ that array is a numeric type the result is represented as zeros and
+ ones, if the type is boolean then as False and True. The return value
+ `y` is then a reference to that array.
See Also
--------
- isinf : Shows which elements are negative or negative infinity.
- isneginf : Shows which elements are negative infinity.
- isposinf : Shows which elements are positive infinity.
- isnan : Shows which elements are Not a Number (NaN).
-
+ isinf, isneginf, isposinf, isnan
Notes
-----
@@ -1390,9 +1355,8 @@ add_newdoc('numpy.core.umath', 'isfinite',
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Also that positive infinity is not equivalent to negative infinity. But
infinity is equivalent to positive infinity.
-
- Errors result if second argument is also supplied with scalar input or
- if first and second arguments have different shapes.
+ Errors result if the second argument is also supplied when `x` is a scalar
+ input, or if first and second arguments have different shapes.
Examples
--------
@@ -1408,9 +1372,10 @@ add_newdoc('numpy.core.umath', 'isfinite',
False
>>> np.isfinite([np.log(-1.),1.,np.log(0)])
array([False, True, False], dtype=bool)
- >>> x=np.array([-np.inf, 0., np.inf])
- >>> y=np.array([2,2,2])
- >>> np.isfinite(x,y)
+
+ >>> x = np.array([-np.inf, 0., np.inf])
+ >>> y = np.array([2, 2, 2])
+ >>> np.isfinite(x, y)
array([0, 1, 0])
>>> y
array([0, 1, 0])
@@ -1419,45 +1384,39 @@ add_newdoc('numpy.core.umath', 'isfinite',
add_newdoc('numpy.core.umath', 'isinf',
"""
- Shows which elements of the input are positive or negative infinity.
- Returns a numpy boolean scalar or array resulting from an element-wise test
- for positive or negative infinity.
+ Test element-wise for positive or negative infinity, return result as bool
+ array.
Parameters
----------
x : array_like
- input values
+ Input values
y : array_like, optional
- An array with the same shape as `x` to store the result.
+ An array with the same shape as `x` to store the result.
Returns
-------
y : {ndarray, bool}
- For scalar input data, the result is a new numpy boolean with value True
- if the input data is positive or negative infinity; otherwise the value
- is False.
-
- For array input data, the result is an numpy boolean array with the same
- dimensions as the input and the values are True if the corresponding
- element of the input is positive or negative infinity; otherwise the
- values are False. If the second argument is supplied then an numpy
- integer array is returned with values 0 or 1 corresponding to False and
- True, respectively.
+ For scalar input, the result is a new boolean with value True
+ if the input is positive or negative infinity; otherwise the value
+ is False.
+
+ For array input, the result is a boolean array with the same
+ dimensions as the input and the values are True if the corresponding
+ element of the input is positive or negative infinity; otherwise the
+ values are False. If a second argument is supplied the result is
+ stored there. If the type of that array is a numeric type the result
+ is represented as zeros and ones, if the type is boolean then as
+ False and True. The return value `y` is then a reference to that array.
See Also
--------
- isneginf : Shows which elements are negative infinity.
- isposinf : Shows which elements are positive infinity.
- isnan : Shows which elements are Not a Number (NaN).
- isfinite: Shows which elements are not: Not a number, positive and
- negative infinity
+ isneginf, isposinf, isnan, isfinite
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
- (IEEE 754). This means that Not a Number is not equivalent to infinity.
- Also that positive infinity is not equivalent to negative infinity. But
- infinity is equivalent to positive infinity.
+ (IEEE 754).
Errors result if second argument is also supplied with scalar input or
if first and second arguments have different shapes.
@@ -1472,9 +1431,10 @@ add_newdoc('numpy.core.umath', 'isinf',
True
>>> np.isinf([np.inf, -np.inf, 1.0, np.nan])
array([ True, True, False, False], dtype=bool)
- >>> x=np.array([-np.inf, 0., np.inf])
- >>> y=np.array([2,2,2])
- >>> np.isinf(x,y)
+
+ >>> x = np.array([-np.inf, 0., np.inf])
+ >>> y = np.array([2, 2, 2])
+ >>> np.isinf(x, y)
array([1, 0, 1])
>>> y
array([1, 0, 1])
@@ -1483,31 +1443,26 @@ add_newdoc('numpy.core.umath', 'isinf',
add_newdoc('numpy.core.umath', 'isnan',
"""
- Returns a numpy boolean scalar or array resulting from an element-wise test
- for Not a Number (NaN).
+ Test element-wise for Not a Number (NaN), return result as a bool array.
Parameters
----------
x : array_like
- input data.
+ Input array.
Returns
-------
y : {ndarray, bool}
- For scalar input data, the result is a new numpy boolean with value True
- if the input data is NaN; otherwise the value is False.
+ For scalar input, the result is a new boolean with value True
+ if the input is NaN; otherwise the value is False.
- For array input data, the result is an numpy boolean array with the same
- dimensions as the input and the values are True if the corresponding
- element of the input is Not a Number; otherwise the values are False.
+ For array input, the result is a boolean array with the same
+ dimensions as the input and the values are True if the corresponding
+ element of the input is NaN; otherwise the values are False.
See Also
--------
- isinf : Tests for infinity.
- isneginf : Tests for negative infinity.
- isposinf : Tests for positive infinity.
- isfinite : Shows which elements are not: Not a number, positive infinity
- and negative infinity
+ isinf, isneginf, isposinf, isfinite
Notes
-----
@@ -1553,6 +1508,13 @@ add_newdoc('numpy.core.umath', 'left_shift',
Examples
--------
+ >>> np.binary_repr(5)
+ '101'
+ >>> np.left_shift(5, 2)
+ 20
+ >>> np.binary_repr(20)
+ '10100'
+
>>> np.left_shift(5, [1,2,3])
array([10, 20, 40])
@@ -1560,7 +1522,7 @@ add_newdoc('numpy.core.umath', 'left_shift',
add_newdoc('numpy.core.umath', 'less',
"""
- Returns (x1 < x2) element-wise.
+ Return (x1 < x2) element-wise.
Parameters
----------
@@ -1574,18 +1536,18 @@ add_newdoc('numpy.core.umath', 'less',
See Also
--------
- less_equal
+ less_equal, greater, greater_equal, equal, not_equal
Examples
--------
- >>> np.less([1,2],[2,2])
+ >>> np.less([1, 2], [2, 2])
array([ True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'less_equal',
"""
- Returns (x1 <= x2) element-wise.
+ Return (x1 <= x2) element-wise.
Parameters
----------
@@ -1599,11 +1561,11 @@ add_newdoc('numpy.core.umath', 'less_equal',
See Also
--------
- less
+ less, greater_equal, greater, equal, not_equal
Examples
--------
- >>> np.less_equal([1,2,3],[2,2,2])
+ >>> np.less_equal([1, 2, 3], [2, 2, 2])
array([ True, True, False], dtype=bool)
""")
@@ -1841,15 +1803,14 @@ add_newdoc('numpy.core.umath', 'logical_and',
Parameters
----------
x1, x2 : array_like
- Logical AND is applied to the elements of `x1` and `x2`.
- They have to be of the same shape.
+ Input arrays. `x1` and `x2` must be of the same shape.
Returns
-------
y : {ndarray, bool}
Boolean result with the same shape as `x1` and `x2` of the logical
- AND operation on elements of `x1` and `x2`.
+ AND operation on corresponding elements of `x1` and `x2`.
See Also
--------
@@ -2012,13 +1973,18 @@ add_newdoc('numpy.core.umath', 'minimum',
"""
Element-wise minimum of array elements.
- Compare two arrays and returns a new array containing
- the element-wise minima.
+ Compare two arrays and returns a new array containing the element-wise
+ minima. If one of the elements being compared is a nan, then that element
+ is returned. If both elements are nans then the first is returned. The
+ latter distinction is important for complex nans, which are defined as at
+ least one of the real or imaginary parts being a nan. The net effect is
+ that nans are propagated.
Parameters
----------
x1, x2 : array_like
- The arrays holding the elements to be compared.
+ The arrays holding the elements to be compared. They must have
+ the same shape.
Returns
-------
@@ -2029,12 +1995,16 @@ add_newdoc('numpy.core.umath', 'minimum',
See Also
--------
maximum :
- element-wise maximum
+ element-wise minimum that propagates nans.
+ fmax :
+ element-wise maximum that ignores nans unless both inputs are nans.
+ fmin :
+ element-wise minimum that ignores nans unless both inputs are nans.
Notes
-----
- Equivalent to ``np.where(x1 < x2, x1, x2)`` but faster and does proper
- broadcasting.
+ The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither
+ x1 nor x2 are nans, but it is faster and does proper broadcasting.
Examples
--------
@@ -2045,18 +2015,119 @@ add_newdoc('numpy.core.umath', 'minimum',
array([[ 0.5, 0. ],
[ 0. , 1. ]])
+ >>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])
+ array([ NaN, NaN, NaN])
+
""")
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
+ maxima. If one of the elements being compared is a nan, then the non-nan
+ element is returned. If both elements are nans then the first is returned.
+ The latter distinction is important for complex nans, which are defined as
+ at least one of the real or imaginary parts being a nan. The net effect is
+ that nans are ignored when possible.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ The arrays holding the elements to be compared. They must have
+ the same shape.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The minimum of `x1` and `x2`, element-wise. Returns scalar if
+ both `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ fmin :
+ element-wise minimum that ignores nans unless both inputs are nans.
+ maximum :
+ element-wise maximum that propagates nans.
+ minimum :
+ element-wise minimum that propagates nans.
+
+ Notes
+ -----
.. versionadded:: 1.3.0
+ The fmax is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither
+ x1 nor x2 are nans, but it is faster and does proper broadcasting.
+
+ Examples
+ --------
+ >>> np.fmax([2, 3, 4], [1, 5, 2])
+ array([ 2., 5., 4.])
+
+ >>> np.fmax(np.eye(2), [0.5, 2])
+ array([[ 1. , 2. ],
+ [ 0.5, 2. ]])
+
+ >>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan])
+ array([ 0., 0., NaN])
+
""")
add_newdoc('numpy.core.umath', 'fmin',
"""
+ fmin(x1, x2[, out])
+
+ Element-wise minimum of array elements.
+
+ Compare two arrays and returns a new array containing the element-wise
+ minima. If one of the elements being compared is a nan, then the non-nan
+ element is returned. If both elements are nans then the first is returned.
+ The latter distinction is important for complex nans, which are defined as
+ at least one of the real or imaginary parts being a nan. The net effect is
+ that nans are ignored when possible.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ The arrays holding the elements to be compared. They must have
+ the same shape.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The minimum of `x1` and `x2`, element-wise. Returns scalar if
+ both `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ fmax :
+ element-wise maximum that ignores nans unless both inputs are nans.
+ maximum :
+ element-wise maximum that propagates nans.
+ minimum :
+ element-wise minimum that propagates nans.
+
+ Notes
+ -----
.. versionadded:: 1.3.0
+ The fmin is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither
+ x1 nor x2 are nans, but it is faster and does proper broadcasting.
+
+ Examples
+ --------
+ >>> np.fmin([2, 3, 4], [1, 5, 2])
+ array([2, 5, 4])
+
+ >>> np.fmin(np.eye(2), [0.5, 2])
+ array([[ 1. , 2. ],
+ [ 0.5, 2. ]])
+
+ >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan])
+ array([ 0., 0., NaN])
+
""")
add_newdoc('numpy.core.umath', 'modf',
@@ -2250,24 +2321,21 @@ add_newdoc('numpy.core.umath', 'radians',
add_newdoc('numpy.core.umath', 'deg2rad',
"""
- Convert angles from degrees to radians. This is the same
- function as radians, but deg2rad is a more descriptive name.
+ Convert angles from degrees to radians.
Parameters
----------
x : array_like
- Angles in degrees.
+ Angles in degrees.
Returns
-------
y : ndarray
- The corresponding angle in radians.
+ The corresponding angle in radians.
See Also
--------
- radians : Convert angles from degrees to radians.
rad2deg : Convert angles from radians to degrees.
- degrees : Convert angles from radians to degrees.
unwrap : Remove large jumps in angle by wrapping.
Notes
@@ -2369,6 +2437,13 @@ add_newdoc('numpy.core.umath', 'right_shift',
Examples
--------
+ >>> np.binary_repr(10)
+ '1010'
+ >>> np.right_shift(10, 1)
+ 5
+ >>> np.binary_repr(5)
+ '101'
+
>>> np.right_shift(10, [1,2,3])
array([5, 2, 1])
@@ -2385,14 +2460,18 @@ add_newdoc('numpy.core.umath', 'rint',
Returns
-------
- out : ndarray
+ out : {ndarray, scalar}
Output array is same shape and type as `x`.
+ See Also
+ --------
+ ceil, floor, trunc
+
Examples
--------
- >>> a = [-4.1, -3.6, -2.5, 0.1, 2.5, 3.1, 3.9]
+ >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.rint(a)
- array([-4., -4., -2., 0., 2., 3., 4.])
+ array([-2., -2., -0., 0., 2., 2., 2.])
""")
diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py
index 2dfabd80e..99b837ba2 100644
--- a/numpy/core/fromnumeric.py
+++ b/numpy/core/fromnumeric.py
@@ -54,19 +54,24 @@ def take(a, indices, axis=None, out=None, mode='raise'):
----------
a : array_like
The source array.
- indices : array_like, int
+ indices : array_like
The indices of the values to extract.
axis : int, optional
- The axis over which to select values. By default, the
- flattened input array is used.
+ The axis over which to select values. By default, the flattened
+ input array is used.
out : ndarray, optional
If provided, the result will be placed in this array. It should
be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
- 'raise' -- raise an error
- 'wrap' -- wrap around
- 'clip' -- clip to the range
+
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
+
+ 'clip' mode means that all indices that are too large are replaced
+ by the index that addresses the last element along that axis. Note
+ that this disables indexing with negative numbers.
Returns
-------
@@ -84,7 +89,8 @@ def take(a, indices, axis=None, out=None, mode='raise'):
>>> np.take(a, indices)
array([4, 3, 6])
- In this example if `a` is a ndarray, "fancy" indexing can be used.
+ In this example if `a` is an ndarray, "fancy" indexing can be used.
+
>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])
@@ -132,6 +138,7 @@ def reshape(a, newshape, order='C'):
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])
+
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
@@ -251,42 +258,49 @@ def put(a, ind, v, mode='raise'):
"""
Changes specific elements of one array by replacing from another array.
- Set `a`.flat[n] = `v`\\[n] for all n in `ind`. If `v` is shorter than
- `ind`, it will repeat which is different than `a[ind]` = `v`.
+ The indexing works on the flattened target array, `put` is roughly
+ equivalent to:
+
+ ::
+
+ for i, val in zip(ind, v):
+ x.flat[i] = val
Parameters
----------
- a : array_like (contiguous)
+ a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
- Values to place in `a` at target indices.
+ Values to place in `a` at target indices. If `v` is shorter than
+ `ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
- * 'raise' -- raise an error
- * 'wrap' -- wrap around
- * 'clip' -- clip to the range
+ * 'raise' -- raise an error (default)
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
- Notes
- -----
- If `v` is shorter than `mask` it will be repeated as necessary. In
- particular `v` can be a scalar or length 1 array. The routine put
- is the equivalent of the following (although the loop is in C for
- speed):
- ::
+ 'clip' mode means that all indices that are too large are replaced
+ by the index that addresses the last element along that axis. Note
+ that this disables indexing with negative numbers.
- ind = array(indices, copy=False)
- v = array(values, copy=False).astype(a.dtype)
- for i in ind: a.flat[i] = v[i]
+ See Also
+ --------
+ putmask, place
Examples
--------
>>> x = np.arange(5)
- >>> np.put(x,[0,2,4],[-1,-2,-3])
- >>> print x
- [-1 1 -2 3 -3]
+ >>> np.put(x, [0, 2], [-44, -55])
+ >>> x
+ array([-44, 1, -55, 3, 4])
+
+ >>> x = np.arange(5)
+ >>> np.put(x, 22, -5, mode='clip')
+ >>> x
+ array([ 0, 1, 2, 3, -5])
"""
return a.put(ind, v, mode)
@@ -323,14 +337,12 @@ def swapaxes(a, axis1, axis2):
>>> x
array([[[0, 1],
[2, 3]],
- <BLANKLINE>
[[4, 5],
[6, 7]]])
>>> np.swapaxes(x,0,2)
array([[[0, 4],
[2, 6]],
- <BLANKLINE>
[[1, 5],
[3, 7]]])
@@ -491,8 +503,9 @@ def argsort(a, axis=-1, kind='quicksort', order=None):
----------
a : array_like
Array to sort.
- axis : int, optional
- Axis along which to sort. If not given, the flattened array is used.
+ axis : int or None, optional
+ Axis along which to sort. The default is -1 (the last axis). If None,
+ the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
@@ -629,7 +642,7 @@ def searchsorted(a, v, side='left'):
Parameters
----------
- a : 1-D array_like of shape (N,)
+ a : 1-D array_like
Input array, sorted in ascending order.
v : array_like
Values to insert into `a`.
@@ -645,7 +658,7 @@ def searchsorted(a, v, side='left'):
See Also
--------
- sort : In-place sort.
+ sort : Return a sorted copy of an array.
histogram : Produce histogram from 1-D data.
Notes
@@ -833,43 +846,44 @@ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""
Return the sum along diagonals of the array.
- If a is 2-d, returns the sum along the diagonal of self with the given
- offset, i.e., the collection of elements of the form a[i,i+offset]. If
- a has more than two dimensions, then the axes specified by axis1 and
- axis2 are used to determine the 2-d subarray whose trace is returned.
- The shape of the resulting array can be determined by removing axis1
- and axis2 and appending an index to the right equal to the size of the
- resulting diagonals.
+ If `a` is 2-D, the sum along its diagonal with the given offset
+ is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
+
+ If `a` has more than two dimensions, then the axes specified by axis1 and
+ axis2 are used to determine the 2-D sub-arrays whose traces are returned.
+ The shape of the resulting array is the same as that of `a` with `axis1`
+ and `axis2` removed.
Parameters
----------
a : array_like
- Array from whis the diagonals are taken.
- offset : integer, optional
+ Input array, from which the diagonals are taken.
+ offset : int, optional
Offset of the diagonal from the main diagonal. Can be both positive
- and negative. Defaults to main diagonal.
- axis1 : integer, optional
- Axis to be used as the first axis of the 2-d subarrays from which
- the diagonals should be taken. Defaults to first axis.
- axis2 : integer, optional
- Axis to be used as the second axis of the 2-d subarrays from which
- the diagonals should be taken. Defaults to second axis.
+ and negative. Defaults to 0.
+ axis1, axis2 : int, optional
+ Axes to be used as the first and second axis of the 2-D sub-arrays
+ from which the diagonals should be taken. Defaults are the first two
+ axes of `a`.
dtype : dtype, optional
- Determines the type of the returned array and of the accumulator
- where the elements are summed. If dtype has the value None and a is
+ Determines the data-type of the returned array and of the accumulator
+ where the elements are summed. If dtype has the value None and `a` is
of integer type of precision less than the default integer
precision, then the default integer precision is used. Otherwise,
- the precision is the same as that of a.
- out : array, optional
- Array into which the sum can be placed. Its type is preserved and
+ the precision is the same as that of `a`.
+ out : ndarray, optional
+ Array into which the output is placed. Its type is preserved and
it must be of the right shape to hold the output.
Returns
-------
sum_along_diagonals : ndarray
- If a is 2-d, a 0-d array containing the diagonal is
- returned. If a has larger dimensions, then an array of
- diagonals is returned.
+ If `a` is 2-D, the sum along the diagonal is returned. If `a` has
+ larger dimensions, then an array of sums along diagonals is returned.
+
+ See Also
+ --------
+ diag, diagonal, diagflat
Examples
--------
@@ -879,6 +893,10 @@ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
>>> np.trace(a)
array([6, 8])
+ >>> a = np.arange(24).reshape((2,2,2,3))
+ >>> np.trace(a).shape
+ (2, 3)
+
"""
return asarray(a).trace(offset, axis1, axis2, dtype, out)
@@ -886,14 +904,14 @@ def ravel(a, order='C'):
"""
Return a flattened array.
- A 1-d array, containing the elements of the input, is returned. A copy is
+ A 1-D array, containing the elements of the input, is returned. A copy is
made only if needed.
Parameters
----------
a : array_like
Input array. The elements in `a` are read in the order specified by
- `order`, and packed as a 1-dimensional array.
+ `order`, and packed as a 1-D array.
order : {'C','F'}, optional
The elements of `a` are read in this order. It can be either
'C' for row-major order, or `F` for column-major order.
@@ -902,8 +920,7 @@ def ravel(a, order='C'):
Returns
-------
1d_array : ndarray
- Output of the same dtype as `a`, and of shape ``(a.size(),)`` (or
- ``(np.prod(a.shape),)``).
+ Output of the same dtype as `a`, and of shape ``(a.size(),)``.
See Also
--------
@@ -914,7 +931,7 @@ def ravel(a, order='C'):
Notes
-----
In row-major order, the row index varies the slowest, and the column
- index the quickest. This can be generalised to multiple dimensions,
+ index the quickest. This can be generalized to multiple dimensions,
where row-major order implies that the index along the first axis
varies slowest, and the index along the last quickest. The opposite holds
for Fortran-, or column-major, mode.
@@ -992,6 +1009,24 @@ def nonzero(a):
[1, 1],
[2, 2]])
+ A common use for ``nonzero`` is to find the indices of an array, where
+ a condition is True. Given an array `a`, the condition `a` > 3 is a
+ boolean array and since False is interpreted as 0, np.nonzero(a > 3)
+ yields the indices of the `a` where the condition is true.
+
+ >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
+ >>> a > 3
+ array([[False, False, False],
+ [ True, True, True],
+ [ True, True, True]], dtype=bool)
+ >>> np.nonzero(a > 3)
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
+ The ``nonzero`` method of the boolean array can also be called.
+
+ >>> (a > 3).nonzero()
+ (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
+
"""
try:
nonzero = a.nonzero
@@ -1269,24 +1304,27 @@ def alltrue (a, axis=None, out=None):
def any(a,axis=None, out=None):
"""
- Test whether any elements of an array evaluate to True along an axis.
+ Test whether any array element along a given axis evaluates to True.
Parameters
----------
a : array_like
- Input array.
+ Input array or object that can be converted to an array.
axis : int, optional
- Axis over which to perform the operation.
- If None, use a flattened input array and return a bool.
+ Axis along which an logical OR is performed.
+ The default (`axis` = `None`) is to perform a logical OR
+ over a flattened input array. `axis` may be negative, in which
+ case it counts from the last to the first axis.
out : ndarray, optional
- Array into which the result is placed. Its type is preserved
- and it must be of the right shape to hold the output.
+ Alternative output array in which to place the result.
+ It must have the same shape as the expected output and
+ the type is preserved.
Returns
-------
- out : ndarray
- A logical OR is performed along `axis`, and the result placed
- in `out`. If `out` was not specified, a new output array is created.
+ any : ndarray, bool
+ A new boolean or array is returned unless `out` is
+ specified, in which case a reference to `out` is returned.
See Also
--------
@@ -1294,7 +1332,8 @@ def any(a,axis=None, out=None):
Notes
-----
- Since NaN is not equal to zero, NaN evaluates to True.
+ Not a Number (NaN), positive infinity and negative infinity
+ evaluate to `True` because these are not equal to zero.
Examples
--------
@@ -1310,6 +1349,11 @@ def any(a,axis=None, out=None):
>>> np.any(np.nan)
True
+ >>> o=np.array([False])
+ >>> z=np.any([-1, 4, 5], out=o)
+ >>> id(z), id(o), z
+ (28224368, 28224368, array([ True], dtype=bool))
+
"""
try:
any = a.any
@@ -1320,24 +1364,27 @@ def any(a,axis=None, out=None):
def all(a,axis=None, out=None):
"""
- Returns True if all elements evaluate to True.
+ Test whether all array elements along a given axis evaluate to True.
Parameters
----------
a : array_like
- Input array.
+ Input array or object that can be converted to an array.
axis : int, optional
- Axis over which to perform the operation.
- If None, use a flattened input array and return a bool.
+ Axis along which an logical AND is performed.
+ The default (`axis` = `None`) is to perform a logical AND
+ over a flattened input array. `axis` may be negative, in which
+ case it counts from the last to the first axis.
out : ndarray, optional
- Array into which the result is placed. Its type is preserved
- and it must be of the right shape to hold the output.
+ Alternative output array in which to place the result.
+ It must have the same shape as the expected output and
+ the type is preserved.
Returns
-------
- out : ndarray, bool
- A logical AND is performed along `axis`, and the result placed
- in `out`. If `out` was not specified, a new output array is created.
+ all : ndarray, bool
+ A new boolean or array is returned unless `out` is
+ specified, in which case a reference to `out` is returned.
See Also
--------
@@ -1345,7 +1392,8 @@ def all(a,axis=None, out=None):
Notes
-----
- Since NaN is not equal to zero, NaN evaluates to True.
+ Not a Number (NaN), positive infinity and negative infinity
+ evaluate to `True` because these are not equal to zero.
Examples
--------
@@ -1361,6 +1409,11 @@ def all(a,axis=None, out=None):
>>> np.all([1.0, np.nan])
True
+ >>> o=np.array([False])
+ >>> z=np.all([-1, 4, 5], out=o)
+ >>> id(z), id(o), z
+ (28293632, 28293632, array([ True], dtype=bool))
+
"""
try:
all = a.all
@@ -1508,6 +1561,17 @@ def amax(a, axis=None, out=None):
A new array or a scalar with the result, or a reference to `out`
if it was specified.
+ See Also
+ --------
+ nanmax: nan values are ignored instead of being propagated
+ fmax: same behavior as the C99 fmax function
+
+ Notes
+ -----
+ NaN values are propagated, that is if at least one item is nan, the
+ corresponding max value will be nan as well. To ignore NaN values (matlab
+ behavior), please use nanmax.
+
Examples
--------
>>> a = np.arange(4).reshape((2,2))
@@ -1519,17 +1583,6 @@ def amax(a, axis=None, out=None):
>>> np.amax(a, axis=1)
array([1, 3])
- Notes
- -----
- NaN values are propagated, that is if at least one item is nan, the
- corresponding max value will be nan as well. To ignore NaN values (matlab
- behavior), please use nanmax.
-
- See Also
- --------
- nanmax: nan values are ignored instead of being propagated
- fmax: same behavior as the C99 fmax function
-
"""
try:
amax = a.max
@@ -1558,6 +1611,17 @@ def amin(a, axis=None, out=None):
A new array or a scalar with the result, or a reference to `out` if it
was specified.
+ See Also
+ --------
+ nanmin: nan values are ignored instead of being propagated
+ fmin: same behavior as the C99 fmin function
+
+ Notes
+ -----
+ NaN values are propagated, that is if at least one item is nan, the
+ corresponding min value will be nan as well. To ignore NaN values (matlab
+ behavior), please use nanmin.
+
Examples
--------
>>> a = np.arange(4).reshape((2,2))
@@ -1571,16 +1635,6 @@ def amin(a, axis=None, out=None):
>>> np.amin(a, axis=1) # Minima along the second axis
array([0, 2])
- Notes
- -----
- NaN values are propagated, that is if at least one item is nan, the
- corresponding min value will be nan as well. To ignore NaN values (matlab
- behavior), please use nanmin.
-
- See Also
- --------
- nanmin: nan values are ignored instead of being propagated
- fmin: same behavior as the C99 fmin function
"""
try:
amin = a.min
@@ -2064,7 +2118,7 @@ def std(a, axis=None, dtype=None, out=None, ddof=0):
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
- By default `ddof` is zero (biased estimate).
+ By default `ddof` is zero.
Returns
-------
@@ -2080,11 +2134,16 @@ def std(a, axis=None, dtype=None, out=None, ddof=0):
Notes
-----
The standard deviation is the square root of the average of the squared
- deviations from the mean, i.e., ``var = sqrt(mean(abs(x - x.mean())**2))``.
+ deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``.
The mean is normally calculated as ``x.sum() / N``, where
``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof``
- is used instead.
+ is used instead. In standard statistical practice, ``ddof=1`` provides an
+ unbiased estimator of the variance of the infinite population. ``ddof=0``
+ provides a maximum likelihood estimate of the variance for normally
+ distributed variables. The standard deviation computed in this function
+ 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
value before squaring, so that the result is always real and nonnegative.
diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py
index 57f36cfad..26ef27dc9 100644
--- a/numpy/core/numeric.py
+++ b/numpy/core/numeric.py
@@ -288,44 +288,66 @@ def ascontiguousarray(a, dtype=None):
----------
a : array_like
Input array.
- dtype : string
- Type code of returned array.
+ dtype : str or dtype object, optional
+ Data-type of returned array.
Returns
-------
out : ndarray
- Contiguous array of same shape and content as `a` with type `dtype`.
+ Contiguous array of same shape and content as `a`, with type `dtype`
+ if specified.
+
+ See Also
+ --------
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ require : Return an ndarray that satisfies requirements.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Examples
+ --------
+ >>> x = np.arange(6).reshape(2,3)
+ >>> np.ascontiguousarray(x, dtype=np.float32)
+ array([[ 0., 1., 2.],
+ [ 3., 4., 5.]], dtype=float32)
+ >>> x.flags['C_CONTIGUOUS']
+ True
"""
return array(a, dtype, copy=False, order='C', ndmin=1)
def asfortranarray(a, dtype=None):
"""
- Return an array laid out in Fortran-order in memory.
+ Return an array laid out in Fortran order in memory.
Parameters
----------
a : array_like
Input array.
- dtype : data-type, optional
+ dtype : str or dtype object, optional
By default, the data-type is inferred from the input data.
Returns
-------
out : ndarray
- Array interpretation of `a` in Fortran (column-order).
+ The input `a` in Fortran, or column-major, order.
See Also
--------
- asarray : Similar function which always returns ndarrays.
- ascontiguousarray : Convert input to a contiguous array.
- asfarray : Convert input to a floating point ndarray.
+ ascontiguousarray : Convert input to a contiguous (C order) array.
asanyarray : Convert input to an ndarray with either row or
column-major memory order.
- asarray_chkfinite : Similar function which checks input for NaNs and Infs.
- fromiter : Create an array from an iterator.
- fromfunction : Construct an array by executing a function on grid
- positions.
+ require : Return an ndarray that satisfies requirements.
+ ndarray.flags : Information about the memory layout of the array.
+
+ Examples
+ --------
+ >>> x = np.arange(6).reshape(2,3)
+ >>> y = np.asfortranarray(x)
+ >>> x.flags['F_CONTIGUOUS']
+ False
+ >>> y.flags['F_CONTIGUOUS']
+ True
"""
return array(a, dtype, copy=False, order='F', ndmin=1)
@@ -392,12 +414,57 @@ def require(a, dtype=None, requirements=None):
def isfortran(a):
"""
- Returns True if array is arranged in Fortran-order and dimension > 1.
+ Returns True if array is arranged in Fortran-order in memory
+ and dimension > 1.
Parameters
----------
a : ndarray
- Input array to test.
+ Input array.
+
+
+ Examples
+ --------
+
+ np.array allows to specify whether the array is written in C-contiguous
+ order (last index varies the fastest), or FORTRAN-contiguous order in
+ memory (first index varies the fastest).
+
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(a)
+ False
+
+ >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='FORTRAN')
+ >>> b
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(b)
+ True
+
+
+ The transpose of a C-ordered array is a FORTRAN-ordered array.
+
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
+ >>> a
+ array([[1, 2, 3],
+ [4, 5, 6]])
+ >>> np.isfortran(a)
+ False
+ >>> b = a.T
+ >>> b
+ array([[1, 4],
+ [2, 5],
+ [3, 6]])
+ >>> np.isfortran(b)
+ True
+
+ 1-D arrays always evaluate as False.
+
+ >>> np.isfortran(np.array([1, 2], order='FORTRAN'))
+ False
"""
return a.flags.fnc
@@ -472,6 +539,9 @@ def flatnonzero(a):
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
+ Use the indices of the non-zero elements as an index array to extract
+ these elements:
+
>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1, 1, 2])
@@ -908,12 +978,110 @@ def _move_axis_to_0(a, axis):
return rollaxis(a, axis, 0)
def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
- """Return the cross product of two (arrays of) vectors.
+ """
+ Return the cross product of two (arrays of) vectors.
+
+ The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
+ to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
+ are defined by the last axis of `a` and `b` by default, and these axes
+ can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
+ 2, the third component of the input vector is assumed to be zero and the
+ cross product calculated accordingly. In cases where both input vectors
+ have dimension 2, the z-component of the cross product is returned.
+
+ Parameters
+ ----------
+ a : array_like
+ Components of the first vector(s).
+ b : array_like
+ Components of the second vector(s).
+ axisa : int, optional
+ Axis of `a` that defines the vector(s). By default, the last axis.
+ axisb : int, optional
+ Axis of `b` that defines the vector(s). By default, the last axis.
+ axisc : int, optional
+ Axis of `c` containing the cross product vector(s). By default, the
+ last axis.
+ axis : int, optional
+ If defined, the axis of `a`, `b` and `c` that defines the vector(s)
+ and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
+
+ Returns
+ -------
+ c : ndarray
+ Vector cross product(s).
+
+ Raises
+ ------
+ ValueError
+ When the dimension of the vector(s) in `a` and/or `b` does not
+ equal 2 or 3.
+
+ See Also
+ --------
+ inner : Inner product
+ outer : Outer product.
+ ix_ : Construct index arrays.
+
+ Examples
+ --------
+ Vector cross-product.
+
+ >>> x = [1, 2, 3]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([-3, 6, -3])
+
+ One vector with dimension 2.
+
+ >>> x = [1, 2]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([12, -6, -3])
+
+ Equivalently:
+
+ >>> x = [1, 2, 0]
+ >>> y = [4, 5, 6]
+ >>> np.cross(x, y)
+ array([12, -6, -3])
+
+ Both vectors with dimension 2.
+
+ >>> x = [1,2]
+ >>> y = [4,5]
+ >>> np.cross(x, y)
+ -3
+
+ Multiple vector cross-products. Note that the direction of the cross
+ product vector is defined by the `right-hand rule`.
+
+ >>> x = np.array([[1,2,3], [4,5,6]])
+ >>> y = np.array([[4,5,6], [1,2,3]])
+ >>> np.cross(x, y)
+ array([[-3, 6, -3],
+ [ 3, -6, 3]])
+
+ The orientation of `c` can be changed using the `axisc` keyword.
+
+ >>> np.cross(x, y, axisc=0)
+ array([[-3, 3],
+ [ 6, -6],
+ [-3, 3]])
+
+ Change the vector definition of `x` and `y` using `axisa` and `axisb`.
+
+ >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
+ >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
+ >>> np.cross(x, y)
+ array([[ -6, 12, -6],
+ [ 0, 0, 0],
+ [ 6, -12, 6]])
+ >>> np.cross(x, y, axisa=0, axisb=0)
+ array([[-24, 48, -24],
+ [-30, 60, -30],
+ [-36, 72, -36]])
- The cross product is performed over the last axis of a and b by default,
- and can handle axes with dimensions 2 and 3. For a dimension of 2,
- the z-component of the equivalent three-dimensional cross product is
- returned.
"""
if axis is not None:
axisa,axisb,axisc=(axis,)*3
@@ -1027,7 +1195,7 @@ 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 loating point precision.
+ If `a` is float, `precision` sets floating point precision.
suppress_small : boolean, optional
Represent very small numbers as zero.
@@ -1162,12 +1330,12 @@ def fromfunction(function, shape, **kwargs):
def isscalar(num):
"""
- Returns True if the type of num is a scalar type.
+ Returns True if the type of `num` is a scalar type.
Parameters
----------
num : any
- Input argument.
+ Input argument, can be of any type and shape.
Returns
-------
@@ -1243,7 +1411,8 @@ def binary_repr(num, width=None):
See Also
--------
- base_repr
+ base_repr: Return a string representation of a number in the given base
+ system.
Notes
-----
@@ -1318,7 +1487,7 @@ def base_repr (number, base=2, padding=0):
'3'
>>> np.base_repr(6, 5)
'11'
- >>> np.base_repr(7, 5, padding=3)
+ >>> np.base_repr(7, base=5, padding=3)
'00012'
"""
@@ -1449,18 +1618,18 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8):
Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The
- relative difference (`rtol` * `b`) and the absolute difference (`atol`)
- are added together to compare against the absolute difference between `a`
- and `b`.
+ relative difference (`rtol` * abs(`b`)) and the absolute difference
+ `atol` are added together to compare against the absolute difference
+ between `a` and `b`.
Parameters
----------
a, b : array_like
Input arrays to compare.
- rtol : Relative tolerance
- The relative difference is equal to `rtol` * `b`.
- atol : Absolute tolerance
- The absolute difference is equal to `atol`.
+ rtol : float
+ The relative tolerance parameter (see Notes).
+ atol : float
+ The absolute tolerance parameter (see Notes).
Returns
-------
@@ -1511,25 +1680,30 @@ def array_equal(a1, a2):
Parameters
----------
- a1 : array_like
- First input array.
- a2 : array_like
- Second input array.
+ a1, a2 : array_like
+ Input arrays.
Returns
-------
- b : {True, False}
+ b : bool
Returns True if the arrays are equal.
+ See Also
+ --------
+ allclose: Returns True if two arrays are element-wise equal within a
+ tolerance.
+ array_equiv: Returns True if input arrays are shape consistent and all
+ elements equal.
+
Examples
--------
- >>> np.array_equal([1,2],[1,2])
+ >>> np.array_equal([1, 2], [1, 2])
True
- >>> np.array_equal(np.array([1,2]),np.array([1,2]))
+ >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
- >>> np.array_equal([1,2],[1,2,3])
+ >>> np.array_equal([1, 2], [1, 2, 3])
False
- >>> np.array_equal([1,2],[1,4])
+ >>> np.array_equal([1, 2], [1, 4])
False
"""
@@ -1545,12 +1719,13 @@ def array_equiv(a1, a2):
"""
Returns True if input arrays are shape consistent and all elements equal.
+ Shape consistent means they are either the same shape, or one input array
+ can be broadcasted to create the same shape as the other one.
+
Parameters
----------
- a1 : array_like
- Input array.
- a2 : array_like
- Input array.
+ a1, a2 : array_like
+ Input arrays.
Returns
-------
@@ -1559,13 +1734,19 @@ def array_equiv(a1, a2):
Examples
--------
- >>> np.array_equiv([1,2],[1,2])
+ >>> np.array_equiv([1, 2], [1, 2])
>>> True
- >>> np.array_equiv([1,2],[1,3])
+ >>> np.array_equiv([1, 2], [1, 3])
>>> False
- >>> np.array_equiv([1,2], [[1,2],[1,2]])
+
+ Showing the shape equivalence:
+
+ >>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
>>> True
- >>> np.array_equiv([1,2], [[1,2],[1,3]])
+ >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
+ >>> False
+
+ >>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
>>> False
"""
@@ -1595,7 +1776,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None):
"""
Set how floating-point errors are handled.
- Note that operations on integer scalar types (such as int16) are
+ Note that operations on integer scalar types (such as `int16`) are
handled like floating point, and are affected by these settings.
Parameters
@@ -1604,8 +1785,8 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None):
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
+ - warn: Print a `RuntimeWarning` (via the Python `warnings` module)
+ - raise: Raise a `FloatingPointError`
- call: Call a function specified using the `seterrcall` function.
The default is not to change the current behavior.
diff --git a/numpy/doc/constants.py b/numpy/doc/constants.py
index 8240aab8e..22e353b0e 100644
--- a/numpy/doc/constants.py
+++ b/numpy/doc/constants.py
@@ -16,54 +16,414 @@ def add_newdoc(module, name, doc):
add_newdoc('numpy', 'Inf',
"""
+ IEEE 754 floating point representation of (positive) infinity.
+
+ Returns
+ -------
+ y : A floating point representation of positive infinity.
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+ Also that positive infinity is not equivalent to negative infinity. But
+ infinity is equivalent to positive infinity.
+
+ Use numpy.inf because Inf, Infinity, PINF, infty are equivalent
+ definitions of numpy.inf.
+
""")
add_newdoc('numpy', 'Infinity',
"""
+ IEEE 754 floating point representation of (positive) infinity.
+
+ Returns
+ -------
+ y : A floating point representation of positive infinity.
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+ Also that positive infinity is not equivalent to negative infinity. But
+ infinity is equivalent to positive infinity.
+
+ Use numpy.inf because Inf, Infinity, PINF, infty are equivalent
+ definitions of numpy.inf.
+
""")
add_newdoc('numpy', 'NAN',
"""
+ IEEE 754 floating point representation of Not a Number (NaN).
+
+ Returns
+ -------
+ y : A floating point representation of Not a Number.
+
+ 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)
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+
+ NaN and NAN are equivalent definitions of numpy.nan. Please use
+ numpy.nan instead of numpy.NAN.
+
+
+ Examples
+ --------
+ >>> np.NAN
+ nan
+ >>> np.log(-1)
+ nan
+ >>> np.log([-1, 1, 2])
+ array([ NaN, 0. , 0.69314718])
+
""")
add_newdoc('numpy', 'NINF',
"""
+ IEEE 754 floating point representation of negative infinity.
+
+ Returns
+ -------
+ y : A floating point representation of negative infinity.
+
+ See Also
+ --------
+ isinf : Shows which elements are positive or negative infinity
+
+ isposinf : Shows which elements are positive infinity
+
+ isneginf : Shows which elements are 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
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+ Also that positive infinity is not equivalent to negative infinity. But
+ infinity is equivalent to positive infinity.
+
+
+ Examples
+ --------
+ >>> np.NINF
+ -inf
+ >>> np.log(0)
+ -inf
+
""")
add_newdoc('numpy', 'NZERO',
"""
+ IEEE 754 floating point representation of negative zero.
+
+ Returns
+ -------
+ y : A floating point representation of negative zero.
+
+ See Also
+ --------
+ PZERO : Defines positive zero.
+
+ isinf : Shows which elements are positive or negative infinity.
+
+ isposinf : Shows which elements are positive infinity.
+
+ isneginf : Shows which elements are 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
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). Negative zero is considered to be a finite number.
+
+
+ Examples
+ --------
+ >>> np.NZERO
+ -0.0
+ >>> np.PZERO
+ 0.0
+ >>> np.isfinite([np.NZERO])
+ array([ True], dtype=bool)
+ >>> np.isnan([np.NZERO])
+ array([False], dtype=bool)
+ >>> np.isinf([np.NZERO])
+ array([False], dtype=bool)
+
""")
add_newdoc('numpy', 'NaN',
"""
+ IEEE 754 floating point representation of Not a Number (NaN).
+
+ Returns
+ -------
+ y : A floating point representation of Not a Number.
+
+ 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)
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+
+ NaN and NAN are equivalent definitions of numpy.nan. Please use
+ numpy.nan instead of numpy.NaN.
+
+
+ Examples
+ --------
+ >>> np.NaN
+ nan
+ >>> np.log(-1)
+ nan
+ >>> np.log([-1, 1, 2])
+ array([ NaN, 0. , 0.69314718])
+
""")
add_newdoc('numpy', 'PINF',
"""
+ IEEE 754 floating point representation of (positive) infinity.
+
+ Returns
+ -------
+ y : A floating point representation of positive infinity.
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+ Also that positive infinity is not equivalent to negative infinity. But
+ infinity is equivalent to positive infinity.
+
+ Use numpy.inf because Inf, Infinity, PINF, infty are equivalent
+ definitions of numpy.inf.
+
""")
add_newdoc('numpy', 'PZERO',
"""
+ IEEE 754 floating point representation of positive zero.
+
+ Returns
+ -------
+ y : A floating point representation of positive zero.
+
+ See Also
+ --------
+ NZERO : Defines negative zero.
+
+ isinf : Shows which elements are positive or negative infinity.
+
+ isposinf : Shows which elements are positive infinity.
+
+ isneginf : Shows which elements are 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
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754).
+
+
+ Examples
+ --------
+ >>> np.PZERO
+ 0.0
+ >>> np.NZERO
+ -0.0
+ >>> np.isfinite([np.PZERO])
+ array([ True], dtype=bool)
+ >>> np.isnan([np.PZERO])
+ array([False], dtype=bool)
+ >>> np.isinf([np.PZERO])
+ array([False], dtype=bool)
+
""")
add_newdoc('numpy', 'e',
"""
+ Euler's constant, base of natural logarithms, Napier's constant.
+
+ `e = 2.71828182845904523536028747135266249775724709369995...`
+
+ See Also
+ --------
+ exp : Exponential function
+ log : Natural logarithm
+
+ References
+ ----------
+ .. [1] http://en.wikipedia.org/wiki/Napier_constant
+
""")
add_newdoc('numpy', 'inf',
"""
+ IEEE 754 floating point representation of (positive) infinity.
+
+ Returns
+ -------
+ y : A floating point representation of positive infinity.
+
+ See Also
+ --------
+ isinf : Shows which elements are positive or negative infinity
+
+ isposinf : Shows which elements are positive infinity
+
+ isneginf : Shows which elements are 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
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+ Also that positive infinity is not equivalent to negative infinity. But
+ infinity is equivalent to positive infinity.
+
+ Inf, Infinity, PINF, infty are equivalent definitions of numpy.inf.
+
+
+ Examples
+ --------
+ >>> np.inf
+ inf
+ >>> np.array([1])/0.
+ array([ Inf])
+
""")
add_newdoc('numpy', 'infty',
"""
+ IEEE 754 floating point representation of (positive) infinity.
+
+ Returns
+ -------
+ y : A floating point representation of positive infinity.
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+ Also that positive infinity is not equivalent to negative infinity. But
+ infinity is equivalent to positive infinity.
+
+ Use numpy.inf because Inf, Infinity, PINF, infty are equivalent
+ definitions of numpy.inf.
+
""")
add_newdoc('numpy', 'nan',
"""
+ IEEE 754 floating point representation of Not a Number (NaN).
+
+ Returns
+ -------
+ y : A floating point representation of Not a Number.
+
+ 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)
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+
+ NaN and NAN are equivalent definitions of numpy.nan.
+
+
+ Examples
+ --------
+ >>> np.nan
+ nan
+ >>> np.log(-1)
+ nan
+ >>> np.log([-1, 1, 2])
+ array([ NaN, 0. , 0.69314718])
+
""")
add_newdoc('numpy', 'newaxis',
"""
+ See Also
+ --------
+ `numpy.doc.indexing`
+
+ Examples
+ --------
+ >>> newaxis is None
+ True
+ >>> x = np.arange(3)
+ >>> x
+ array([0, 1, 2])
+ >>> x[:,newaxis]
+ array([[0],
+ [1],
+ [2]])
+ >>> x[:,newaxis,newaxis]
+ array([[[0]],
+ [[1]],
+ [[2]]])
+ >>> x[:,newaxis] * x
+ array([[0, 0, 0],
+ [0, 1, 2],
+ [0, 2, 4]])
+
+ Outer product, same as outer(x,y):
+
+ >>> y = np.arange(3,6)
+ >>> x[:,newaxis] * y
+ array([[ 0, 0, 0],
+ [ 3, 4, 5],
+ [ 6, 8, 10]])
+
+ x[newaxis,:] is equivalent to x[newaxis] and x[None]:
+
+ >>> x[newaxis,:].shape
+ (1, 3)
+ >>> x[newaxis].shape
+ (1, 3)
+ >>> x[None].shape
+ (1, 3)
+ >>> x[:,newaxis].shape
+ (3, 1)
+
""")
if __doc__:
diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py
index 1e43f312a..eb2dc4395 100644
--- a/numpy/doc/misc.py
+++ b/numpy/doc/misc.py
@@ -95,7 +95,7 @@ Examples:
Interfacing to C:
-----------------
-Only a survey the choices. Little detail on how each works.
+Only a survey of the choices. Little detail on how each works.
1) Bare metal, wrap your own C-code manually.
diff --git a/numpy/fft/__init__.py b/numpy/fft/__init__.py
index 1171a6026..324e39f4d 100644
--- a/numpy/fft/__init__.py
+++ b/numpy/fft/__init__.py
@@ -1,37 +1,3 @@
-"""
-Discrete Fast Fourier Transform (FFT)
-=====================================
-
-========= =========================================================
-Standard FFTs
-===================================================================
-fft Discrete Fourier transform.
-ifft Inverse discrete Fourier transform.
-fft2 Discrete Fourier transform in two dimensions.
-ifft2 Inverse discrete Fourier transform in two dimensions.
-fftn Discrete Fourier transform in N-dimensions.
-ifftn Inverse discrete Fourier transform in N dimensions.
-========= =========================================================
-
-========= ==========================================================
-Real FFTs
-====================================================================
-rfft Real discrete Fourier transform.
-irfft Inverse real discrete Fourier transform.
-rfft2 Real discrete Fourier transform in two dimensions.
-irfft2 Inverse real discrete Fourier transform in two dimensions.
-rfftn Real discrete Fourier transform in N dimensions.
-irfftn Inverse real discrete Fourier transform in N dimensions.
-========= ==========================================================
-
-========= =========================================================
-Hermite FFTs
-===================================================================
-hfft Hermite discrete Fourier transform.
-ihfft Inverse hermite discrete Fourier transform.
-========= =========================================================
-
-"""
# To get sub-modules
from info import __doc__
diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py
index 0af1cdc79..af2d5e934 100644
--- a/numpy/fft/fftpack.py
+++ b/numpy/fft/fftpack.py
@@ -71,36 +71,88 @@ def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti,
def fft(a, n=None, axis=-1):
"""
- Compute the one dimensional fft on a given axis.
+ Compute the one-dimensional discrete Fourier Transform
- Return the n point discrete Fourier transform of a. n defaults to the
- length of a. If n is larger than the length of a, then a will be
- zero-padded to make up the difference. If n is smaller than the length of
- a, only the first n items in a will be used.
+ This function computes the one-dimensional *n*-point discrete Fourier
+ Transform (DFT) with the efficient Fast Fourier Transform (FFT) algorithm. [CT]
Parameters
----------
+ a : array_like
+ Input array, can be complex
+ n : int, optional
+ Length of the transformed axis of the output.
+ If `n` is smaller than the length of the input, the input is cropped.
+ If it is larger, the input is padded with zeros. If `n` is not given,
+ the length of the input (along the axis specified by `axis`) is used.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
- a : array
- input array
- n : int
- length of the fft
- axis : int
- axis over which to compute the fft
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axis
+ indicated by `axis`, or the last one if `axis` is not specified.
+
+ Raises
+ ------
+ IndexError
+ if `axes` is larger than the last axis of `a`
+
+ See Also
+ --------
+ numpy.fft : for definition of the DFT and conventions used
+ ifft : The inverse of `fft`.
+ fft2 : The two-dimensional FFT.
+ fftn : The *n*-dimensional FFT.
+ rfftn : The *n*-dimensional FFT of real input.
+ fftfreq : Frequency bins for given FFT parameters.
Notes
-----
- The packing of the result is "standard": If A = fft(a, n), then A[0]
- contains the zero-frequency term, A[1:n/2+1] contains the
- positive-frequency terms, and A[n/2+1:] contains the negative-frequency
- terms, in order of decreasingly negative frequency. So for an 8-point
- transform, the frequencies of the result are [ 0, 1, 2, 3, 4, -3, -2, -1].
+ FFT (Fast Fourier Transform) refers to a way the discrete Fourier
+ Transform (DFT) can be calculated efficiently, by using symmetries in the
+ calculated terms. The symmetry is highest when `n` is a power of 2, and
+ the transform is therefore most efficient for these sizes.
- This is most efficient for n a power of two. This also stores a cache of
- working memory for different sizes of fft's, so you could theoretically
- run into memory problems if you call this too many times with too many
- different n's.
+ The DFT is defined, with the conventions used in this implementation, in
+ the documentation for the `numpy.fft` module.
+
+ References
+ ----------
+ .. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+ machine calculation of complex Fourier series," *Math. Comput.*
+ 19: 297-301.
+
+ Examples
+ --------
+
+ >>> from numpy import arange, pi, exp
+ >>> from numpy.fft import fft
+ >>> fft(exp(2j*pi*arange(8)/8))
+ array([ -3.44505240e-16 +1.14383329e-17j,
+ 8.00000000e+00 -5.71092652e-15j,
+ 2.33482938e-16 +1.22460635e-16j,
+ 1.64863782e-15 +1.77635684e-15j,
+ 9.95839695e-17 +2.33482938e-16j,
+ 0.00000000e+00 +1.66837030e-15j,
+ 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)
+ >>> sp = fft(np.sin(t))
+ >>> freq = fftfreq(t.shape[-1])
+ >>> plt.plot(freq, sp.real, freq, sp.imag)
+ >>> plt.show()
+
+ In this example, real input has an FFT which is Hermitian, i.e., symmetric
+ in the real part and anti-symmetric in the imaginary part, as described in
+ the `numpy.fft` documentation.
"""
@@ -109,39 +161,78 @@ def fft(a, n=None, axis=-1):
def ifft(a, n=None, axis=-1):
"""
- Compute the one-dimensonal inverse fft along an axis.
+ Compute the one-dimensional inverse discrete Fourier Transform
+
+ This function computes the inverse of the one-dimensional *n*-point
+ discrete Fourier transform computed by `fft`. In other words,
+ `ifft(fft(a)) == a` to within numerical accuracy.
+ For a general description of the algorithm and definitions,
+ see `numpy.fft`.
- Return the `n` point inverse discrete Fourier transform of `a`. The length
- `n` defaults to the length of `a`. If `n` is larger than the length of `a`,
- then `a` will be zero-padded to make up the difference. If `n` is smaller
- than the length of `a`, then `a` will be truncated to reduce its size.
+ The input should be ordered in the same way as is returned by `fft`,
+ i.e., `a[0]` should contain the zero frequency term,
+ `a[1:n/2+1]` should contain the positive-frequency terms, and
+ `a[n/2+1:]` should contain the negative-frequency terms, in order of
+ decreasingly negative frequency. See `numpy.fft` for details.
Parameters
----------
-
a : array_like
- Input array.
+ Input array, can be complex
n : int, optional
- Length of the fft.
+ Length of the transformed axis of the output.
+ If `n` is smaller than the length of the input, the input is cropped.
+ If it is larger, the input is padded with zeros. If `n` is not given,
+ the length of the input (along the axis specified by `axis`) is used.
+ See notes about padding issues.
axis : int, optional
- Axis over which to compute the inverse fft.
+ Axis over which to compute the inverse DFT. If not given, the last
+ axis is used.
+
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axis
+ indicated by `axis`, or the last one if `axis` is not specified.
+
+ Raises
+ ------
+ IndexError
+ if `axes` is larger than the last axis of `a`
See Also
--------
- fft
+ numpy.fft : An introduction, with definitions and general explanations
+ fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse
+ ifft2 : The two-dimensional inverse FFT
+ ifftn : The n-dimensional inverse FFT
Notes
-----
- The input array is expected to be packed the same way as the output of
- fft, as discussed in the fft documentation.
- This is the inverse of fft: ifft(fft(a)) == a within numerical
- accuracy.
+ If the input parameter `n` is larger than the size of the input, the input
+ is padded by appending zeros at the end. Even though this is the common
+ approach, it might lead to surprising results. If a different padding is
+ desired, it must be performed before calling `ifft`.
- This is most efficient for `n` a power of two. This also stores a cache of
- working memory for different sizes of fft's, so you could theoretically
- run into memory problems if you call this too many times with too many
- different `n` values.
+ Examples
+ --------
+
+ >>> from numpy.fft import ifft
+ >>> ifft([0, 4, 0, 0])
+ array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j])
+
+ >>> from numpy import exp, pi, arange, zeros
+ >>> import matplotlib.pyplot as plt
+ >>> t = arange(400)
+ >>> n = zeros((400,), dtype=complex)
+ >>> n[40:60] = exp(1j*np.random.uniform(0, 2*pi, (20,)))
+ >>> s = np.fft.ifft(n)
+ >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
+ >>> plt.legend(('real', 'imaginary'))
+ >>> plt.show()
+
+ Creates and plots a band-limited signal with random phases.
"""
@@ -153,34 +244,76 @@ def ifft(a, n=None, axis=-1):
def rfft(a, n=None, axis=-1):
"""
- Compute the one-dimensional fft for real input.
+ Compute the one-dimensional discrete Fourier Transform for real input.
- Return the n point discrete Fourier transform of the real valued
- array a. n defaults to the length of a. n is the length of the
- input, not the output.
+ This function computes the one-dimensional *n*-point discrete Fourier
+ Transform (DFT) of a real-valued array by means of an efficient algorithm
+ called the Fast Fourier Transform (FFT).
Parameters
----------
+ a : array_like
+ Input array
+ n : int, optional
+ Number of points along transformation axis in the input to use.
+ If `n` is smaller than the length of the input, the input is cropped.
+ If it is larger, the input is padded with zeros. If `n` is not given,
+ the length of the input (along the axis specified by `axis`) is used.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
- a : array
- input array with real data type
- n : int
- length of the fft
- axis : int
- axis over which to compute the fft
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axis
+ indicated by `axis`, or the last one if `axis` is not specified.
+ The length of the transformed axis is `n/2+1`.
+
+ Raises
+ ------
+ IndexError
+ if `axis` is larger than the last axis of `a`
+
+ See Also
+ --------
+ numpy.fft : for definition of the DFT and conventions used
+ irfft : The inverse of `rfft`
+ fft : The one-dimensional FFT of general (complex) input
+ fftn : The *n*-dimensional FFT.
+ rfftn : The *n*-dimensional FFT of real input.
Notes
-----
- The returned array will be the nonnegative frequency terms of the
- Hermite-symmetric, complex transform of the real array. So for an 8-point
- transform, the frequencies in the result are [ 0, 1, 2, 3, 4]. The first
- term will be real, as will the last if n is even. The negative frequency
- terms are not needed because they are the complex conjugates of the
- positive frequency terms. (This is what I mean when I say
- Hermite-symmetric.)
+ When the DFT is computed for purely real input, the output is
+ Hermite-symmetric, i.e. the negative frequency terms are just the complex
+ conjugates of the corresponding positive-frequency terms, and the
+ negative-frequency terms are therefore redundant. This function does not
+ compute the negative frequency terms, and the length of the transformed
+ axis of the output is therefore `n/2+1`.
+
+ When `A = rfft(a)`, `A[0]` contains the zero-frequency term, which must be
+ purely real due to the Hermite symmetry.
+
+ If `n` is even, `A[-1]` contains the term for frequencies `n/2` and `-n/2`,
+ and must also be purely real. If `n` is odd, `A[-1]` contains the term
+ for frequency `A[(n-1)/2]`, and is complex in the general case.
- This is most efficient for n a power of two.
+ If the input `a` contains an imaginary part, it is silently discarded.
+
+ Examples
+ --------
+
+ >>> from numpy.fft import fft, rfft
+ >>> fft([0, 1, 0, 0])
+ array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j])
+ >>> rfft([0, 1, 0, 0])
+ array([ 1.+0.j, 0.-1.j, -1.+0.j])
+
+ Notice how the final element of the `fft` output is the complex conjugate
+ of the second element, for real input. For `rfft`, this symmetry is
+ exploited to compute only the nonnegative frequency terms.
"""
@@ -190,37 +323,82 @@ def rfft(a, n=None, axis=-1):
def irfft(a, n=None, axis=-1):
"""
- Compute the one-dimensional inverse fft for real input.
+ Compute the inverse of the n-point DFT for real input.
+
+ This function computes the inverse of the one-dimensional *n*-point
+ discrete Fourier Transform of real input computed by `rfft`.
+ In other words, `irfft(rfft(a), len(a)) == a` to within numerical accuracy.
+ (See Notes below for why `len(a)` is necessary here.)
+
+ The input is expected to be in the form returned by `rfft`, i.e. the
+ real zero-frequency term followed by the complex positive frequency terms
+ in order of increasing frequency. Since the discrete Fourier Transform of
+ real input is Hermite-symmetric, the negative frequency terms are taken
+ to be the complex conjugates of the corresponding positive frequency terms.
Parameters
----------
- a : array
- Input array with real data type.
- n : int
- Length of the fft.
- axis : int
- Axis over which to compute the fft.
+ a : array_like
+ Input array
+ n : int, optional
+ Length of the transformed axis of the output.
+ For `n` output points, `n/2+1` input points are necessary. If the
+ input is longer than this, it is cropped. If it is shorter than this,
+ it is padded with zeros. If `n` is not given, it is determined from
+ the length of the input (along the axis specified by `axis`)
+ as explained below.
+ axis : int, optional
+ Axis over which to compute the inverse FFT.
+
+ Returns
+ -------
+ out : real ndarray
+ The truncated or zero-padded input, transformed along the axis
+ indicated by `axis`, or the last one if `axis` is not specified.
+ The length of the transformed axis is `n`, or, if `n` is not given,
+ `2*(m-1)` where `m` is the length of the transformed axis of the input.
+ To get an odd number of output points, `n` must be specified.
+
+ Raises
+ ------
+ IndexError
+ if `axis` is larger than the last axis of `a`
See Also
--------
- rfft
+ numpy.fft : for definition of the DFT and conventions used
+ rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
+ fft : The one-dimensional FFT
+ irfft2 : The inverse of the two-dimensional FFT of real input.
+ irfftn : The inverse of the *n*-dimensional FFT of real input.
Notes
-----
- Return the real valued `n` point inverse discrete Fourier transform
+
+ Returns the real valued `n`-point inverse discrete Fourier transform
of `a`, where `a` contains the nonnegative frequency terms of a
Hermite-symmetric sequence. `n` is the length of the result, not the
- input. If `n` is not supplied, the default is 2*(len(`a`)-1). If you
- want the length of the result to be odd, you have to say so.
+ input.
If you specify an `n` such that `a` must be zero-padded or truncated, the
extra/removed values will be added/removed at high frequencies. One can
- thus resample a series to m points via Fourier interpolation by: a_resamp
- = irfft(rfft(a), m).
+ thus resample a series to `m` points via Fourier interpolation by:
+ `a_resamp = irfft(rfft(a), m)`.
- Within numerical accuracy ``irfft`` is the inverse of ``rfft``::
- irfft(rfft(a), len(a)) == a
+ Examples
+ --------
+
+ >>> from numpy.fft import ifft, irfft
+ >>> ifft([1, -1j, -1, 1j])
+ array([ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j])
+ >>> irfft([1, -1j, -1])
+ array([ 0., 1., 0., 0.])
+
+ Notice how the last term in the input to the ordinary `ifft` is the
+ complex conjugate of the second term, and the output has zero imaginary
+ part everywhere. When calling `irfft`, the negative frequencies are not
+ specified, and the output array is purely real.
"""
@@ -333,31 +511,95 @@ def _raw_fftnd(a, s=None, axes=None, function=fft):
def fftn(a, s=None, axes=None):
"""
- Compute the N-dimensional Fast Fourier Transform.
+ Compute the N-dimensional discrete Fourier Transform
+
+ This function computes the *N*-dimensional discrete Fourier Transform over
+ any number of axes in an *M*-dimensional array by means of the Fast Fourier
+ Transform (FFT).
Parameters
----------
a : array_like
- Input array.
- s : sequence of ints
- Shape of each axis of the input (s[0] refers to axis 0, s[1] to
- axis 1, etc.). This corresponds to `n` for `fft(x, n)`.
+ Input array, can be complex
+ s : sequence of ints, optional
+ Shape (length of each transformed axis) of the output
+ (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.).
+ This corresponds to `n` for `fft(x, n)`.
Along any axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
- axes : tuple of int
- Axes over which to compute the FFT.
+ if `s` is not given, the shape of the input (along the axes specified
+ by `axes`) is used.
+ axes : sequence of ints, optional
+ Axes over which to compute the FFT. If not given, the last `len(s)`
+ axes are used, or all axes if `s` is also not specified.
+ Repeated indices in `axes` means that the transform over that axis is
+ performed multiple times.
+
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axes
+ indicated by `axes`, or by a combination of `s` and `a`,
+ as explained in the parameters section above.
+
+ Raises
+ ------
+ ValueError
+ if `s` and `axes` have different length.
+ IndexError
+ if an element of `axes` is larger than than the number of axes of `a`.
+
+ See Also
+ --------
+ numpy.fft : Overall view of discrete Fourier transforms, with definitions
+ and conventions used.
+ ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT.
+ fft : The one-dimensional FFT, with definitions and conventions used.
+ rfftn : The *n*-dimensional FFT of real input.
+ fft2 : The two-dimensional FFT.
+ fftshift : shifts zero-frequency terms to centre of array
Notes
-----
- Analogously to `fft`, the term for zero frequency in all axes is in the
- low-order corner, while the term for the Nyquist frequency in all axes is
- in the middle.
- If neither `s` nor `axes` is specified, the transform is taken along all
- axes. If `s` is specified and `axes` is not, the last ``len(s)`` axes are
- used. If `axes` is specified and `s` is not, the input shape along the
- specified axes is used. If `s` and `axes` are both specified and are not
- the same length, an exception is raised.
+ The output, analogously to `fft`, contains the term for zero frequency in
+ the low-order corner of all axes, the positive frequency terms in the
+ first half of all axes, the term for the Nyquist frequency in the middle
+ of all axes and the negative frequency terms in the second half of all
+ axes, in order of decreasingly negative frequency.
+
+ See `numpy.fft` for details, definitions and conventions used.
+
+ Examples
+ --------
+ >>> from numpy import mgrid
+ >>> from numpy.fft import fftn
+ >>> a = mgrid[:3,:3,:3][0]
+ >>> fftn(a, axes=(1,2))
+ array([[[ 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j]],
+ [[ 9.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j]],
+ [[ 18.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j]]])
+ >>> fftn(a, (2,2), axes=(0,1))
+ array([[[ 2.+0.j, 2.+0.j, 2.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j]],
+ [[-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
+ >>> [X, Y] = np.meshgrid(2*pi*arange(200)/12, 2*pi*arange(200)/34)
+ >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)
+ >>> FS = np.fft.fftn(S)
+ >>> plt.imshow(np.log(np.abs(fftshift(FS))**2))
+ >>> plt.show()
"""
@@ -365,30 +607,95 @@ def fftn(a, s=None, axes=None):
def ifftn(a, s=None, axes=None):
"""
- Compute the inverse of fftn.
+ Compute the N-dimensional inverse discrete Fourier Transform
+
+ This function computes the inverse of the N-dimensional discrete
+ Fourier Transform over any number of axes in an M-dimensional array by
+ means of the Fast Fourier Transform (FFT). In other words,
+ `ifftn(fftn(a)) == a` to within numerical accuracy.
+ For a description of the definitions and conventions used, see `numpy.fft`.
+
+ The input, analogously to `ifft`, should be ordered in the same way as is
+ returned by `fftn`, i.e. it should have the term for zero frequency
+ in all axes in the low-order corner, the positive frequency terms in the
+ first half of all axes, the term for the Nyquist frequency in the middle
+ of all axes and the negative frequency terms in the second half of all
+ axes, in order of decreasingly negative frequency.
Parameters
----------
- a : array
- input array
- s : sequence (int)
- shape of the ifft
- axis : int
- axis over which to compute the ifft
+ a : array_like
+ Input array, can be complex
+ s : sequence of ints, optional
+ Shape (length of each transformed axis) of the output
+ (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.).
+ This corresponds to `n` for `ifft(x, n)`.
+ Along any axis, if the given shape is smaller than that of the input,
+ the input is cropped. If it is larger, the input is padded with zeros.
+ if `s` is not given, the shape of the input (along the axes specified
+ by `axes`) is used. See notes for issue on ifft zero padding.
+ axes : sequence of ints, optional
+ Axes over which to compute the IFFT. If not given, the last `len(s)`
+ axes are used, or all axes if `s` is also not specified.
+ Repeated indices in `axes` means that the inverse transform over that
+ axis is performed multiple times.
+
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axes
+ indicated by `axes`, or by a combination of `s` or `a`,
+ as explained in the parameters section above.
+
+ Raises
+ ------
+ ValueError
+ if `s` and `axes` have different length.
+ IndexError
+ if an element of `axes` is larger than than the number of axes of `a`.
+
+ See Also
+ --------
+ numpy.fft : Overall view of discrete Fourier transforms, with definitions
+ and conventions used.
+ fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.
+ ifft : The one-dimensional inverse FFT.
+ ifft2 : The two-dimensional inverse FFT.
+ ifftshift : undoes `fftshift`, shifts zero-frequency terms to beginning
+ of array
Notes
-----
- The n-dimensional ifft of a. s is a sequence giving the shape of the input
- an result along the transformed axes, as n for fft. Results are packed
- analogously to fft: the term for zero frequency in all axes is in the
- low-order corner, while the term for the Nyquist frequency in all axes is
- in the middle.
-
- If neither s nor axes is specified, the transform is taken along all
- axes. If s is specified and axes is not, the last len(s) axes are used.
- If axes are specified and s is not, the input shape along the specified
- axes is used. If s and axes are both specified and are not the same
- length, an exception is raised.
+
+ See `numpy.fft` for definitions and conventions used.
+
+ Zero-padding, analogously with `ifft`, is performed by appending zeros to
+ the input along the specified dimension. Although this is the common
+ approach, it might lead to surprising results. If another form of zero
+ padding is desired, it must be performed before `ifftn` is called.
+
+ Examples
+ --------
+ >>> from numpy import eye
+ >>> from numpy.fft import ifftn, fftn
+ >>> a = eye(4)
+ >>> ifftn(fftn(a, axes=(0,)),axes=(1,))
+ array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
+
+ >>> from numpy import zeros, exp
+ >>> from numpy.random import uniform
+ >>> from numpy.fft import ifftn
+ >>> import matplotlib.pyplot as plt
+ >>> n = np.zeros((200,200), dtype=complex)
+ >>> n[60:80,20:40] = exp(1j*uniform(0, 2*pi, (20,20)))
+ >>> im = np.fft.ifftn(n).real
+ >>> plt.imshow(im)
+ >>> plt.show()
+
+ Creates and plots an image with band-limited frequency content
"""
@@ -397,21 +704,82 @@ def ifftn(a, s=None, axes=None):
def fft2(a, s=None, axes=(-2,-1)):
"""
- Compute the 2-D FFT of an array.
+ Compute the 2-dimensional discrete Fourier Transform
+
+ This function computes the *n*-dimensional discrete Fourier Transform
+ over any axes in an *M*-dimensional array by means of the
+ Fast Fourier Transform (FFT). By default, the transform is computed over
+ the last two axes of the input array, i.e., a 2-dimensional FFT.
Parameters
----------
a : array_like
- Input array. The rank (dimensions) of `a` must be 2 or greater.
- s : shape tuple
- Shape of the FFT.
- axes : sequence of 2 ints
- The 2 axes over which to compute the FFT. The default is the last two
- axes (-2, -1).
+ Input array, can be complex
+ s : sequence of ints, optional
+ Shape (length of each transformed axis) of the output
+ (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.).
+ This corresponds to `n` for `fft(x, n)`.
+ Along each axis, if the given shape is smaller than that of the input,
+ the input is cropped. If it is larger, the input is padded with zeros.
+ if `s` is not given, the shape of the input (along the axes specified
+ by `axes`) is used.
+ axes : sequence of ints, optional
+ Axes over which to compute the FFT. If not given, the last 2
+ axes are used. A repeated index in `axes` means the transform over
+ that axis is performed multiple times. A one-element sequence means
+ that a one-dimensional FFT is performed.
+
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axes
+ indicated by `axes`, or the last two axes if `axes` is not given.
+
+ Raises
+ ------
+ ValueError
+ if `s` and `axes` have different length, or
+ `axes` not given and `len(s) != 2`
+ IndexError
+ if an element of `axes` is larger than than the number of axes of `a`.
+
+ See Also
+ --------
+ numpy.fft : Overall view of discrete Fourier transforms, with definitions
+ and conventions used.
+ ifft2 : The inverse two-dimensional FFT
+ fft : The one-dimensional FFT
+ fftn : The *n*-dimensional FFT
+ fftshift : shifts zero-frequency terms to centre of array.
+ For two-dimensional input, swaps first and third quadrants, and second
+ and fourth quadrants.
Notes
-----
- This is really just ``fftn`` with different default behavior.
+
+ `fft2` is just `fftn` with a different default for `axes`.
+
+ The output, analogously to `fft`, contains the term for zero frequency in
+ the low-order corner of the transformed axes, the positive frequency terms
+ in the first half of these axes, the term for the Nyquist frequency in the
+ middle of the axes and the negative frequency terms in the second half of
+ the axes, in order of decreasingly negative frequency.
+
+ See `fftn` for details and a plotting example, and `numpy.fft` for
+ definitions and conventions used.
+
+
+ Examples
+ --------
+ >>> from numpy import mgrid
+ >>> from numpy.fft import fft2
+ >>> a = mgrid[:5, :5][0]
+ >>> fft2(a)
+ array([[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 5.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 10.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 15.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 20.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]])
"""
@@ -420,20 +788,84 @@ def fft2(a, s=None, axes=(-2,-1)):
def ifft2(a, s=None, axes=(-2,-1)):
"""
- Compute the inverse 2d fft of an array.
+ Compute the 2-dimensional inverse discrete Fourier Transform
+
+ This function computes the inverse of the 2-dimensional discrete Fourier
+ Transform over any number of axes in an M-dimensional array by means of
+ the Fast Fourier Transform (FFT). In other words, `ifft2(fft2(a)) == a`
+ to within numerical accuracy. By default, the inverse transform is
+ computed over the last two axes of the input array.
+
+ The input, analogously to `ifft`, should be ordered in the same way as is
+ returned by `fft2`, i.e. it should have the term for zero frequency
+ in the low-order corner of the two axes, the positive frequency terms in
+ the first half of these axes, the term for the Nyquist frequency in the
+ middle of the axes and the negative frequency terms in the second half of
+ both axes, in order of decreasingly negative frequency.
Parameters
----------
- a : array
- input array
- s : sequence (int)
- shape of the ifft
- axis : int
- axis over which to compute the ifft
+ a : array_like
+ Input array, can be complex
+ s : sequence of ints, optional
+ Shape (length of each axis) of the output (`s[0]` refers to axis 0,
+ `s[1]` to axis 1, etc.). This corresponds to `n` for `ifft(x, n)`.
+ Along each axis, if the given shape is smaller than that of the input,
+ the input is cropped. If it is larger, the input is padded with zeros.
+ if `s` is not given, the shape of the input (along the axes specified
+ by `axes`) is used. See notes for issue on ifft zero padding.
+ axes : sequence of ints, optional
+ Axes over which to compute the FFT. If not given, the last 2
+ axes are used. A repeated index in `axes` means the transform over
+ that axis is performed multiple times. A one-element sequence means
+ that a one-dimensional FFT is performed.
+
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axes
+ indicated by `axes`, or the last two axes if `axes` is not given.
+
+ Raises
+ ------
+ ValueError
+ if `s` and `axes` have different length, or
+ `axes` not given and `len(s) != 2`
+ IndexError
+ if an element of `axes` is larger than than the number of axes of `a`.
+
+ See Also
+ --------
+ numpy.fft : Overall view of discrete Fourier transforms, with definitions
+ and conventions used.
+ fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse.
+ ifftn : The inverse of the *n*-dimensional FFT.
+ fft : The one-dimensional FFT
+ ifft : The one-dimensional inverse FFT.
Notes
-----
- This is really just ifftn with different default behavior.
+
+ `ifft2` is just `ifftn` with a different default for `axes`.
+
+ See `ifftn` for details and a plotting example, and `numpy.fft` for
+ definition and conventions used.
+
+ Zero-padding, analogously with `ifft`, is performed by appending zeros to
+ the input along the specified dimension. Although this is the common
+ approach, it might lead to surprising results. If another form of zero
+ padding is desired, it must be performed before `ifft2` is called.
+
+ Examples
+ --------
+ >>> from numpy import eye
+ >>> from numpy.fft import ifft2
+ >>> a = 4*eye(4)
+ >>> ifft2(a)
+ array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
+ [ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
+ [ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
"""
@@ -442,22 +874,90 @@ def ifft2(a, s=None, axes=(-2,-1)):
def rfftn(a, s=None, axes=None):
"""
- Compute the n-dimensional fft of a real array.
+ Compute the N-dimensional discrete Fourier Transform for real input.
+
+ This function computes the N-dimensional discrete Fourier Transform over
+ any number of axes in an M-dimensional real array by means of the Fast
+ Fourier Transform (FFT). By default, all axes are transformed, with the
+ real transform performed over the last axis, while the remaining
+ transforms are complex.
Parameters
----------
- a : array (real)
- input array
- s : sequence (int)
- shape of the fft
- axis : int
- axis over which to compute the fft
+ a : array_like
+ Input array, taken to be real
+ s : sequence of ints, optional
+ Shape (length along each transformed axis) to use from the input.
+ (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.).
+ The final element of `s` corresponds to `n` for `rfft(x, n)`, while
+ for the remaining axes, it corresponds to `n` for `fft(x, n)`.
+ Along any axis, if the given shape is smaller than that of the input,
+ the input is cropped. If it is larger, the input is padded with zeros.
+ if `s` is not given, the shape of the input (along the axes specified
+ by `axes`) is used.
+ axes : sequence of ints, optional
+ Axes over which to compute the FFT. If not given, the last `len(s)`
+ axes are used, or all axes if `s` is also not specified.
+
+ Returns
+ -------
+ out : complex ndarray
+ The truncated or zero-padded input, transformed along the axes
+ indicated by `axes`, or by a combination of `s` and `a`,
+ as explained in the parameters section above.
+ The length of the last axis transformed will be `s[-1]//2+1`,
+ while the remaining transformed axes will have lengths according to
+ `s`, or unchanged from the input.
+
+ Raises
+ ------
+ ValueError
+ if `s` and `axes` have different length.
+ IndexError
+ if an element of `axes` is larger than than the number of axes of `a`.
+
+ See Also
+ --------
+ irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT
+ of real input.
+ fft : The one-dimensional FFT, with definitions and conventions used.
+ rfft : The one-dimensional FFT of real input.
+ fftn : The n-dimensional FFT.
+ rfft2 : The two-dimensional FFT of real input.
Notes
-----
- A real transform as rfft is performed along the axis specified by the last
- element of axes, then complex transforms as fft are performed along the
- other axes.
+
+ The transform for real input is performed over the last transformation
+ axis, as by `rfft`, then the transform over the remaining axes is
+ performed as by `fftn`. The order of the output is as for `rfft` for the
+ final transformation axis, and as for `fftn` for the remaining
+ transformation axes.
+
+ See `fft` for details, definitions and conventions used.
+
+ Examples
+ --------
+ >>> from numpy import ones
+ >>> from numpy.fft import rfftn
+ >>> a = ones((3,3,3))
+ >>> rfftn(a)
+ array([[[ 27.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j]],
+ [[ 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j]],
+ [[ 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j]]])
+ >>> rfftn(a, axes=(2,0))
+ array([[[ 9.+0.j, 0.+0.j, 0.+0.j],
+ [ 9.+0.j, 0.+0.j, 0.+0.j],
+ [ 9.+0.j, 0.+0.j, 0.+0.j]],
+ [[ 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j]]])
"""
@@ -492,23 +992,95 @@ def rfft2(a, s=None, axes=(-2,-1)):
def irfftn(a, s=None, axes=None):
"""
- Compute the n-dimensional inverse fft of a real array.
+ Compute the inverse of the N-dimensional FFT of real input.
+
+ This function computes the inverse of the N-dimensional discrete
+ Fourier Transform for real input over any number of axes in an
+ M-dimensional array by means of the Fast Fourier Transform (FFT). In
+ other words, `irfftn(rfftn(a), a.shape) == a` to within numerical accuracy.
+ (The `a.shape` is necessary like `len(a)` is for `irfft`, and for the same
+ reason.)
+
+ The input should be ordered in the same way as is returned by `rfftn`,
+ i.e. as for `irfft` for the final transformation axis, and as for `ifftn`
+ along all the other axes.
Parameters
----------
- a : array (real)
- input array
- s : sequence (int)
- shape of the inverse fft
- axis : int
- axis over which to compute the inverse fft
+ a : array_like
+ Input array.
+ s : sequence of ints, optional
+ Shape (length of each transformed axis) of the output
+ (`s[0]` refers to axis 0, `s[1]` to axis 1, etc.). `s` is also the
+ number of input points used along this axis, except for the last axis,
+ where `s[-1]//2+1` points of the input are used.
+ Along any axis, if the shape indicated by `s` is smaller than that of
+ the input, the input is cropped. If it is larger, the input is padded
+ with zeros. if `s` is not given, the shape of the input (along the
+ axes specified by `axes`) is used.
+ axes : sequence of ints, optional
+ Axes over which to compute the inverse FFT. If not given, the last
+ `len(s)` axes are used, or all axes if `s` is also not specified.
+ Repeated indices in `axes` means that the inverse transform over that
+ axis is performed multiple times.
+
+ Returns
+ -------
+ out : real ndarray
+ The truncated or zero-padded input, transformed along the axes
+ indicated by `axes`, or by a combination of `s` or `a`,
+ as explained in the parameters section above.
+ The length of each transformed axis is as given by the corresponding
+ element of `s`, or the length of the input in every axis except for the
+ last one if `s` is not given. In the final transformed axis the length
+ of the output when `s` is not given is `2*(m-1)` where `m` is the
+ length of the final transformed axis of the input. To get an odd
+ number of output points in the final axis, `s` must be specified.
+
+ Raises
+ ------
+ ValueError
+ if `s` and `axes` have different length.
+ IndexError
+ if an element of `axes` is larger than than the number of axes of `a`.
+
+ See Also
+ --------
+ rfftn : The forward n-dimensional FFT of real input,
+ of which `ifftn` is the inverse.
+ fft : The one-dimensional FFT, with definitions and conventions used.
+ irfft : The inverse of the one-dimensional FFT of real input.
+ irfft2 : The inverse of the two-dimensional FFT of real input.
Notes
-----
- The transform implemented in ifftn is applied along
- all axes but the last, then the transform implemented in irfft is performed
- along the last axis. As with irfft, the length of the result along that
- axis must be specified if it is to be odd.
+
+ See `fft` for definitions and conventions used.
+
+ See `rfft` for definitions and conventions used for real input.
+
+ Examples
+ --------
+ >>> from numpy import zeros
+ >>> from numpy.fft import irfftn, zeros
+ >>> a = zeros((4,4,3); a[0,0,0] = 64;
+ >>> irfftn(a)
+ array([[[ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.]],
+ [[ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.]],
+ [[ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.]],
+ [[ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.],
+ [ 1., 1., 1., 1.]]])
"""
diff --git a/numpy/fft/info.py b/numpy/fft/info.py
index c9ab599a4..77630e92b 100644
--- a/numpy/fft/info.py
+++ b/numpy/fft/info.py
@@ -1,29 +1,172 @@
-"""\
-Core FFT routines
-==================
+"""
+Discrete Fourier Transform (:mod:`numpy.fft`)
+=============================================
+
+.. currentmodule:: numpy.fft
+
+
+Standard FFTs
+-------------
+
+.. autosummary::
+ :toctree: generated/
+
+ fft Discrete Fourier transform.
+ ifft Inverse discrete Fourier transform.
+ fft2 Discrete Fourier transform in two dimensions.
+ ifft2 Inverse discrete Fourier transform in two dimensions.
+ fftn Discrete Fourier transform in N-dimensions.
+ ifftn Inverse discrete Fourier transform in N dimensions.
+
+Real FFTs
+---------
+
+.. autosummary::
+ :toctree: generated/
+
+ rfft Real discrete Fourier transform.
+ irfft Inverse real discrete Fourier transform.
+ rfft2 Real discrete Fourier transform in two dimensions.
+ irfft2 Inverse real discrete Fourier transform in two dimensions.
+ rfftn Real discrete Fourier transform in N dimensions.
+ irfftn Inverse real discrete Fourier transform in N dimensions.
+
+
+Hermitian FFTs
+--------------
+
+.. autosummary::
+ :toctree: generated/
+
+ hfft Hermitian discrete Fourier transform.
+ ihfft Inverse Hermitian discrete Fourier transform.
+
+
+Helper routines
+---------------
+
+.. autosummary::
+ :toctree: generated/
+
+ fftfreq Discrete Fourier Transform sample frequencies.
+ fftshift Shift zero-frequency component to center of spectrum.
+ ifftshift Inverse of fftshift.
+
+Background information
+----------------------
+
+Fourier analysis is fundamentally a method for expressing a function as a
+sum of periodic components, and for recovering the signal from those
+components. When both the function and its Fourier transform are
+replaced with discretized counterparts, it is called the discrete Fourier
+transform (DFT). The DFT has become a mainstay of numerical computing in
+part because of a very fast algorithm for computing it, called the Fast
+Fourier Transform (FFT), which was known to Gauss (1805) and was brought
+to light in its current form by Cooley and Tukey [CT]_. Press et al. [NR]_
+provide an accessible introduction to Fourier analysis and its
+applications.
+
+Because the discrete Fourier transform separates its input into
+components that contribute at discrete frequencies, it has a great number
+of applications in digital signal processing, e.g., for filtering, and in
+this context the discretized input to the transform is customarily
+referred to as a *signal*, which exists in the *time domain*. The output
+is called a *spectrum* or *transform* and exists in the *frequency
+domain*.
+
+There are many ways to define the DFT, varying in the sign of the
+exponent, normalization, etc. In this implementation, the DFT is defined
+as
+
+.. math::
+ A_k = \\sum_{m=0}^{n-1} a_m \\exp\\left\\{-2\\pi i{mk \\over n}\\right\\}
+ \\qquad k = 0,\\ldots,n-1.
+
+The DFT is in general defined for complex inputs and outputs, and a
+single-frequency component at linear frequency :math:`f` is
+represented by a complex exponential
+:math:`a_m = \\exp\\{2\\pi i\\,f m\\Delta t\\}`, where :math:`\\Delta t`
+is the sampling interval.
+
+The values in the result follow so-called "standard" order: If `A =
+fft(a, n)`, then `A[0]` contains the zero-frequency term (the mean of the
+signal), which is always purely real for real inputs. Then `A[1:n/2]`
+contains the positive-frequency terms, and `A[n/2+1:]` contains the
+negative-frequency terms, in order of decreasingly negative frequency.
+For an even number of input points, `A[n/2]` represents both positive and
+negative Nyquist frequency, and is also purely real for real input. For
+an odd number of input points, `A[(n-1)/2]` contains the largest positive
+frequency, while `A[(n+1)/2]` contains the largest negative frequency.
+The routine `np.fft.fftfreq(A)` returns an array giving the frequencies
+of corresponding elements in the output. The routine
+`np.fft.fftshift(A)` shifts transforms and their frequencies to put the
+zero-frequency components in the middle, and `np.fft.ifftshift(A)` undoes
+that shift.
+
+When the input `a` is a time-domain signal and `A = fft(a)`, `np.abs(A)`
+is its amplitude spectrum and `np.abs(A)**2` is its power spectrum.
+The phase spectrum is obtained by `np.angle(A)`.
+
+The inverse DFT is defined as
+
+.. math::
+ a_m = \\frac{1}{n}\\sum_{k=0}^{n-1}A_k\\exp\\left\\{2\\pi i{mk\\over n}\\right\\}
+ \\qquad n = 0,\\ldots,n-1.
+
+It differs from the forward transform by the sign of the exponential
+argument and the normalization by :math:`1/n`.
+
+Real and Hermitian transforms
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+When the input is purely real, its transform is Hermitian, i.e., the
+component at frequency :math:`f_k` is the complex conjugate of the
+component at frequency :math:`-f_k`, which means that for real
+inputs there is no information in the negative frequency components that
+is not already available from the positive frequency components.
+The family of `rfft` functions is
+designed to operate on real inputs, and exploits this symmetry by
+computing only the positive frequency components, up to and including the
+Nyquist frequency. Thus, `n` input points produce `n/2+1` complex
+output points. The inverses of this family assumes the same symmetry of
+its input, and for an output of `n` points uses `n/2+1` input points.
+
+Correspondingly, when the spectrum is purely real, the signal is
+Hermitian. The `hfft` family of functions exploits this symmetry by
+using `n/2+1` complex points in the input (time) domain for `n` real
+points in the frequency domain.
+
+In higher dimensions, FFTs are used, e.g., for image analysis and
+filtering. The computational efficiency of the FFT means that it can
+also be a faster way to compute large convolutions, using the property
+that a convolution in the time domain is equivalent to a point-by-point
+multiplication in the frequency domain.
+
+In two dimensions, the DFT is defined as
+
+.. math::
+ A_{kl} = \\sum_{m=0}^{M-1} \\sum_{n=0}^{N-1}
+ a_{mn}\\exp\\left\\{-2\\pi i \\left({mk\\over M}+{nl\\over N}\\right)\\right\\}
+ \\qquad k = 0, \\ldots, N-1;\\quad l = 0, \\ldots, M-1,
- Standard FFTs
+which extends in the obvious way to higher dimensions, and the inverses
+in higher dimensions also extend in the same way.
- fft
- ifft
- fft2
- ifft2
- fftn
- ifftn
+References
+^^^^^^^^^^
+.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+ machine calculation of complex Fourier series," *Math. Comput.*
+ 19: 297-301.
- Real FFTs
+.. [NR] Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P.,
+ 2007, *Numerical Recipes: The Art of Scientific Computing*, ch.
+ 12-13. Cambridge Univ. Press, Cambridge, UK.
- rfft
- irfft
- rfft2
- irfft2
- rfftn
- irfftn
+Examples
+^^^^^^^^
- Hermite FFTs
+For examples, see the various functions.
- hfft
- ihfft
"""
depends = ['core']
diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py
index f023f6027..9afb00f29 100644
--- a/numpy/lib/arraysetops.py
+++ b/numpy/lib/arraysetops.py
@@ -52,17 +52,16 @@ def ediff1d(ary, to_end=None, to_begin=None):
If provided, this number will be taked onto the beginning of the
returned differences.
- Notes
- -----
- When applied to masked arrays, this function drops the mask information
- if the `to_begin` and/or `to_end` parameters are used
-
-
Returns
-------
ed : array
The differences. Loosely, this will be (ary[1:] - ary[:-1]).
+ Notes
+ -----
+ When applied to masked arrays, this function drops the mask information
+ if the `to_begin` and/or `to_end` parameters are used
+
"""
ary = np.asanyarray(ary).flat
ed = ary[1:] - ary[:-1]
@@ -285,11 +284,22 @@ def setmember1d(ar1, ar2):
mask : ndarray, bool
The values `ar1[mask]` are in `ar2`.
+
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
+ Examples
+ --------
+ >>> test = np.arange(5)
+ >>> states = [0, 2]
+ >>> mask = np.setmember1d(test,states)
+ >>> mask
+ array([ True, False, True, False, False], dtype=bool)
+ >>> test[mask]
+ array([0, 2])
+
"""
ar1 = np.asarray( ar1 )
ar2 = np.asarray( ar2 )
diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py
index f53a77631..0cef1c4d2 100644
--- a/numpy/lib/financial.py
+++ b/numpy/lib/financial.py
@@ -190,7 +190,6 @@ def nper(rate, pmt, pv, fv=0, when='end'):
>>> np.nper(*(np.ogrid[0.06/12:0.071/12:0.01/12, -200:-99:100, 6000:7001:1000]))
array([[[ 32.58497782, 38.57048452],
[ 71.51317802, 86.37179563]],
- <BLANKLINE>
[[ 33.07413144, 39.26244268],
[ 74.06368256, 90.22989997]]])
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
index b7b1552b0..f76bf2a78 100644
--- a/numpy/lib/function_base.py
+++ b/numpy/lib/function_base.py
@@ -242,7 +242,6 @@ def histogram(a, bins=10, range=None, normed=False, weights=None, new=None):
Return the bin edges ``(length(hist)+1)``.
With ``new=False``, return the left bin edges (``length(hist)``).
-
See Also
--------
histogramdd
@@ -1241,8 +1240,9 @@ def sort_complex(a):
--------
>>> np.sort_complex([5, 3, 6, 2, 1])
array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
- >>> np.sort_complex([5 + 2j, 3 - 1j, 6 - 2j, 2 - 3j, 1 - 5j])
- array([ 1.-5.j, 2.-3.j, 3.-1.j, 5.+2.j, 6.-2.j])
+
+ >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
+ array([ 1.+2.j, 2.-1.j, 3.-5.j, 3.-3.j, 3.+2.j])
"""
b = array(a,copy=True)
@@ -1259,21 +1259,35 @@ def sort_complex(a):
def trim_zeros(filt, trim='fb'):
"""
- Trim the leading and trailing zeros from a 1D array.
+ Trim the leading and/or trailing zeros from a 1-D array or sequence.
Parameters
----------
- filt : array_like
+ filt : 1-D array or sequence
Input array.
- trim : string, optional
+ trim : str, optional
A string with 'f' representing trim from front and 'b' to trim from
- back.
+ back. Default is 'fb', trim zeros from both front and back of the
+ array.
+
+ Returns
+ -------
+ trimmed : 1-D array or sequence
+ The result of trimming the input. The input data type is preserved.
Examples
--------
- >>> a = np.array((0, 0, 0, 1, 2, 3, 2, 1, 0))
+ >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
>>> np.trim_zeros(a)
- array([1, 2, 3, 2, 1])
+ array([1, 2, 3, 0, 2, 1])
+
+ >>> np.trim_zeros(a, 'b')
+ array([0, 0, 0, 1, 2, 3, 0, 2, 1])
+
+ The input data type is preserved, list/tuple in means list/tuple out.
+
+ >>> np.trim_zeros([0, 1, 2, 0])
+ [1, 2]
"""
first = 0
@@ -1299,7 +1313,7 @@ def unique(x):
Parameters
----------
- x : array_like
+ x : ndarray or sequence
Input array.
Returns
@@ -1315,6 +1329,9 @@ def unique(x):
>>> np.unique(a)
array([1, 2, 3])
+ >>> np.unique([True, True, False])
+ array([False, True], dtype=bool)
+
"""
try:
tmp = x.flatten()
@@ -1719,40 +1736,65 @@ def _get_nargs(obj):
class vectorize(object):
"""
- vectorize(somefunction, otypes=None, doc=None)
+ vectorize(pyfunc, otypes='', doc=None)
Generalized function class.
- Define a vectorized function which takes nested sequence
+ Define a vectorized function which takes a nested sequence
of objects or numpy arrays as inputs and returns a
- numpy array as output, evaluating the function over successive
- tuples of the input arrays like the python map function except it uses
- the broadcasting rules of numpy.
+ numpy array as output. The vectorized function evaluates `pyfunc` over
+ successive tuples of the input arrays like the python map function,
+ except it uses the broadcasting rules of numpy.
- Data-type of output of vectorized is determined by calling the function
- with the first element of the input. This can be avoided by specifying
- the otypes argument as either a string of typecode characters or a list
- of data-types specifiers. There should be one data-type specifier for
- each output.
+ The data type of the output of `vectorized` is determined by calling
+ the function with the first element of the input. This can be avoided
+ by specifying the `otypes` argument.
Parameters
----------
- f : callable
- A Python function or method.
+ pyfunc : callable
+ A python function or method.
+ otypes : str or list of dtypes, optional
+ The output data type. It must be specified as either a string of
+ typecode characters or a list of data type specifiers. There should
+ be one data type specifier for each output.
+ doc : str, optional
+ The docstring for the function. If None, the docstring will be the
+ `pyfunc` one.
Examples
--------
>>> def myfunc(a, b):
- ... if a > b:
- ... return a-b
- ... else:
- ... return a+b
+ ... \"\"\"Return a-b if a>b, otherwise return a+b\"\"\"
+ ... if a > b:
+ ... return a - b
+ ... else:
+ ... return a + b
>>> vfunc = np.vectorize(myfunc)
-
>>> vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])
+ The docstring is taken from the input function to `vectorize` unless it
+ is specified
+
+ >>> vfunc.__doc__
+ 'Return a-b if a>b, otherwise return a+b'
+ >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
+ >>> vfunc.__doc__
+ 'Vectorized `myfunc`'
+
+ The output type is determined by evaluating the first element of the input,
+ unless it is specified
+
+ >>> out = vfunc([1, 2, 3, 4], 2)
+ >>> type(out[0])
+ <type 'numpy.int32'>
+ >>> vfunc = np.vectorize(myfunc, otypes=[np.float])
+ >>> out = vfunc([1, 2, 3, 4], 2)
+ >>> type(out[0])
+ <type 'numpy.float64'>
+
"""
def __init__(self, pyfunc, otypes='', doc=None):
self.thefunc = pyfunc
@@ -2675,8 +2717,8 @@ def median(a, axis=None, out=None, overwrite_input=False):
a : array_like
Input array or object that can be converted to an array.
axis : {None, int}, optional
- Axis along which the medians are computed. The default (axis=None) is to
- compute the median along a flattened version of the array.
+ Axis along which the medians are computed. The default (axis=None)
+ is to compute the median along a flattened version of the array.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
@@ -2840,30 +2882,29 @@ def meshgrid(x,y):
"""
Return coordinate matrices from two coordinate vectors.
-
-
-
Parameters
----------
x, y : ndarray
- Two 1D arrays representing the x and y coordinates
+ Two 1-D arrays representing the x and y coordinates of a grid.
Returns
-------
X, Y : ndarray
- For vectors `x`, `y` with lengths Nx=len(`x`) and Ny=len(`y`),
- return `X`, `Y` where `X` and `Y` are (Ny, Nx) shaped arrays
+ For vectors `x`, `y` with lengths ``Nx=len(x)`` and ``Ny=len(y)``,
+ return `X`, `Y` where `X` and `Y` are ``(Ny, Nx)`` shaped arrays
with the elements of `x` and y repeated to fill the matrix along
the first dimension for `x`, the second for `y`.
See Also
--------
- numpy.mgrid : Construct a multi-dimensional "meshgrid"
- using indexing notation.
+ index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
+ using indexing notation.
+ index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
+ using indexing notation.
Examples
--------
- >>> X, Y = numpy.meshgrid([1,2,3], [4,5,6,7])
+ >>> X, Y = np.meshgrid([1,2,3], [4,5,6,7])
>>> X
array([[1, 2, 3],
[1, 2, 3],
@@ -2875,6 +2916,13 @@ def meshgrid(x,y):
[6, 6, 6],
[7, 7, 7]])
+ `meshgrid` is very useful to evaluate functions on a grid.
+
+ >>> x = np.arange(-5, 5, 0.1)
+ >>> y = np.arange(-5, 5, 0.1)
+ >>> xx, yy = np.meshgrid(x, y)
+ >>> z = np.sin(xx**2+yy**2)/(xx**2+yy**2)
+
"""
x = asarray(x)
y = asarray(y)
@@ -2894,20 +2942,27 @@ def delete(arr, obj, axis=None):
----------
arr : array_like
Input array.
- obj : slice, integer or an array of integers
+ obj : slice, int or array of ints
Indicate which sub-arrays to remove.
- axis : integer, optional
+ axis : int, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
+ Returns
+ -------
+ out : ndarray
+ A copy of `arr` with the elements specified by `obj` removed. Note
+ that `delete` does not occur in-place. If `axis` is None, `out` is
+ a flattened array.
+
See Also
--------
- insert : Insert values into an array.
- append : Append values at the end of an array.
+ insert : Insert elements into an array.
+ append : Append elements at the end of an array.
Examples
--------
- >>> arr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
+ >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
@@ -2915,6 +2970,7 @@ def delete(arr, obj, axis=None):
>>> np.delete(arr, 1, 0)
array([[ 1, 2, 3, 4],
[ 9, 10, 11, 12]])
+
>>> np.delete(arr, np.s_[::2], 1)
array([[ 2, 4],
[ 6, 8],
@@ -3012,25 +3068,52 @@ def insert(arr, obj, values, axis=None):
----------
arr : array_like
Input array.
- obj : {integer, slice, integer array_like}
+ obj : int, slice, or array of ints
Insert `values` before `obj` indices.
- values :
- Values to insert into `arr`.
+ values : array_like
+ Values to insert into `arr`. If the type of `values` is different
+ from that of `arr`, `values` is converted to the type of `arr`.
axis : int, optional
- Axis along which to insert `values`. If `axis` is None then ravel
- `arr` first.
+ Axis along which to insert `values`. If `axis` is None then `arr`
+ is flattened first.
+
+ Returns
+ -------
+ out : ndarray
+ A copy of `arr` with `values` inserted. Note that `insert`
+ does not occur in-place: a new array is returned. If
+ `axis` is None, `out` is a flattened array.
+
+ See Also
+ --------
+ append : Append elements at the end of an array.
+ delete : Delete elements from an array.
Examples
--------
- >>> a = np.array([[1,2,3],
- ... [4,5,6],
- ... [7,8,9]])
- >>> np.insert(a, [1,2], [[4],[5]], axis=0)
- array([[1, 2, 3],
- [4, 4, 4],
- [4, 5, 6],
- [5, 5, 5],
- [7, 8, 9]])
+ >>> a = np.array([[1, 1], [2, 2], [3, 3]])
+ >>> a
+ array([[1, 1],
+ [2, 2],
+ [3, 3]])
+ >>> np.insert(a, 1, 5)
+ array([1, 5, 1, 2, 2, 3, 3])
+ >>> np.insert(a, 1, 5, axis=1)
+ array([[1, 5, 1],
+ [2, 5, 2],
+ [3, 5, 3]])
+
+ >>> b = a.flatten()
+ >>> b
+ array([1, 1, 2, 2, 3, 3])
+ >>> np.insert(b, [2, 2], [5, 6])
+ array([1, 1, 5, 6, 2, 2, 3, 3])
+
+ >>> np.insert(b, slice(2, 4), [5, 6])
+ array([1, 1, 5, 2, 6, 2, 3, 3])
+
+ >>> np.insert(b, [2, 2], [7.13, False])
+ array([1, 1, 7, 0, 2, 2, 3, 3])
"""
wrap = None
@@ -3121,13 +3204,21 @@ def append(arr, values, axis=None):
-------
out : ndarray
A copy of `arr` with `values` appended to `axis`. Note that `append`
- does not occur in-place: a new array is allocated and filled.
+ does not occur in-place: a new array is allocated and filled. If
+ `axis` is None, `out` is a flattened array.
+
+ See Also
+ --------
+ insert : Insert elements into an array.
+ delete : Delete elements from an array.
Examples
--------
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
+ When `axis` is specified, `values` must have the correct shape.
+
>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
[4, 5, 6],
diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py
index fcd3909af..b8add9ed7 100644
--- a/numpy/lib/index_tricks.py
+++ b/numpy/lib/index_tricks.py
@@ -34,7 +34,7 @@ def unravel_index(x,dims):
Examples
--------
- >>> arr = np.ones((5,4))
+ >>> arr = np.arange(20).reshape(5,4)
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
@@ -130,7 +130,6 @@ class nd_grid(object):
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
- <BLANKLINE>
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
@@ -396,11 +395,20 @@ class ndenumerate(object):
class ndindex(object):
- """Pass in a sequence of integers corresponding
- to the number of dimensions in the counter. This iterator
- will then return an N-dimensional counter.
+ """
+ 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.
- Example:
+ Parameters
+ ----------
+ `*args` : integers
+ The size of each dimension in the counter.
+
+ Examples
+ --------
>>> for index in np.ndindex(3,2,1):
... print index
(0, 0, 0)
diff --git a/numpy/lib/io.py b/numpy/lib/io.py
index a4bd7f9ee..84790ac42 100644
--- a/numpy/lib/io.py
+++ b/numpy/lib/io.py
@@ -212,6 +212,11 @@ def save(file, arr):
x : array_like
Array data.
+ See Also
+ --------
+ savez : Save several arrays into an .npz compressed archive
+ savetxt : Save an array to a file as plain text
+
Examples
--------
>>> from tempfile import TemporaryFile
@@ -237,21 +242,36 @@ def save(file, arr):
def savez(file, *args, **kwds):
"""
- Save several arrays into an .npz file format which is a zipped-archive
- of arrays
+ Save several arrays into a single, compressed file with extension ".npz"
- If keyword arguments are given, then filenames are taken from the keywords.
- If arguments are passed in with no keywords, then stored file names are
- arr_0, arr_1, etc.
+ If keyword arguments are given, the names for variables assigned to the
+ keywords are the keyword names (not the variable names in the caller).
+ If arguments are passed in with no keywords, the corresponding variable
+ names are arr_0, arr_1, etc.
Parameters
----------
- file : string
- File name of .npz file.
+ file : Either the filename (string) or an open file (file-like object)
+ If file is a string, it names the output file. ".npz" will be appended
+ if it is not already there.
args : Arguments
- Function arguments.
+ Any function arguments other than the file name are variables to save.
+ Since it is not possible for Python to know their names outside the
+ savez function, they will be saved with names "arr_0", "arr_1", and so
+ on. These arguments can be any expression.
kwds : Keyword arguments
- Keywords.
+ All keyword=value pairs cause the value to be saved with the name of
+ the keyword.
+
+ See Also
+ --------
+ save : Save a single array to a binary file in NumPy format
+ savetxt : Save an array to a file as plain text
+
+ Notes
+ -----
+ The .npz file format is a zipped archive of files named after the variables
+ they contain. Each file contains one variable in .npy format.
"""
@@ -510,6 +530,11 @@ def savetxt(fname, X, fmt='%.18e',delimiter=' '):
delimiter : str
Character separating columns.
+ See Also
+ --------
+ save : Save an array to a binary file in NumPy format
+ savez : Save several arrays into an .npz compressed archive
+
Notes
-----
Further explanation of the `fmt` parameter
diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py
index 10fd6dd6c..5c3d146f8 100644
--- a/numpy/lib/polynomial.py
+++ b/numpy/lib/polynomial.py
@@ -621,7 +621,7 @@ def polysub(a1, a2):
Examples
--------
- .. math:: (2 x^2 + 10x - 2) - (3 x^2 + 10x -4) = (-x^2 + 2)
+ .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)
>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1, 0, 2])
diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py
index a890a8a2b..19dd54f7a 100644
--- a/numpy/lib/shape_base.py
+++ b/numpy/lib/shape_base.py
@@ -10,30 +10,30 @@ from numpy.core.fromnumeric import product, reshape
def apply_along_axis(func1d,axis,arr,*args):
"""
- Apply function to 1-D slices along the given axis.
+ Apply a function to 1-D slices along the given axis.
- Execute `func1d(a[i],*args)` where `func1d` takes 1-D arrays, `a` is
- the input array, and `i` is an integer that varies in order to apply the
- function along the given axis for each 1-D subarray in `a`.
+ Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a`
+ is a 1-D slice of `arr` along `axis`.
Parameters
----------
func1d : function
- This function should be able to take 1-D arrays. It is applied to 1-D
- slices of `a` along the specified axis.
+ This function should accept 1-D arrays. It is applied to 1-D
+ slices of `arr` along the specified axis.
axis : integer
- Axis along which `func1d` is applied.
- a : ndarray
+ Axis along which `arr` is sliced.
+ arr : ndarray
Input array.
args : any
Additional arguments to `func1d`.
Returns
-------
- out : ndarray
- The output array. The shape of `out` is identical to the shape of `a`,
- except along the `axis` dimension, whose length is equal to the size
- of the return value of `func1d`.
+ outarr : ndarray
+ The output array. The shape of `outarr` is identical to the shape of
+ `arr`, except along the `axis` dimension, where the length of `outarr`
+ is equal to the size of the return value of `func1d`. If `func1d`
+ returns a scalar `outarr` will have one fewer dimensions than `arr`.
See Also
--------
@@ -50,6 +50,18 @@ def apply_along_axis(func1d,axis,arr,*args):
>>> np.apply_along_axis(my_func, 1, b)
array([2., 5., 8.])
+ For a function that doesn't return a scalar, the number of dimensions in
+ `outarr` is the same as `arr`.
+
+ >>> def new_func(a):
+ ... \"\"\"Divide elements of a by 2.\"\"\"
+ ... return a * 0.5
+ >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
+ >>> np.apply_along_axis(new_func, 0, b)
+ array([[ 0.5, 1. , 1.5],
+ [ 2. , 2.5, 3. ],
+ [ 3.5, 4. , 4.5]])
+
"""
arr = asarray(arr)
nd = arr.ndim
@@ -148,7 +160,6 @@ def apply_over_axes(func, a, axes):
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
- <BLANKLINE>
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
@@ -310,13 +321,13 @@ def atleast_2d(*arys):
Examples
--------
- >>> numpy.atleast_2d(3.0)
+ >>> np.atleast_2d(3.0)
array([[ 3.]])
- >>> x = numpy.arange(3.0)
- >>> numpy.atleast_2d(x)
+ >>> x = np.arange(3.0)
+ >>> np.atleast_2d(x)
array([[ 0., 1., 2.]])
- >>> numpy.atleast_2d(x).base is x
+ >>> np.atleast_2d(x).base is x
True
>>> np.atleast_2d(1, [1, 2], [[1, 2]])
@@ -347,38 +358,37 @@ def atleast_3d(*arys):
res1, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 3``.
Copies are avoided where possible, and views with three or more
- dimensions are returned. For example, a one-dimensional array of
- shape ``N`` becomes a view of shape ``(1, N, 1)``. An ``(M, N)``
- array becomes a view of shape ``(N, M, 1)``.
+ dimensions are returned. For example, a 1-D array of shape ``N``
+ becomes a view of shape ``(1, N, 1)``. A 2-D array of shape ``(M, N)``
+ becomes a view of shape ``(M, N, 1)``.
See Also
--------
- numpy.atleast_1d, numpy.atleast_2d
+ atleast_1d, atleast_2d
Examples
--------
- >>> numpy.atleast_3d(3.0)
+ >>> np.atleast_3d(3.0)
array([[[ 3.]]])
- >>> x = numpy.arange(3.0)
- >>> numpy.atleast_3d(x).shape
+ >>> x = np.arange(3.0)
+ >>> np.atleast_3d(x).shape
(1, 3, 1)
- >>> x = numpy.arange(12.0).reshape(4,3)
- >>> numpy.atleast_3d(x).shape
+ >>> x = np.arange(12.0).reshape(4,3)
+ >>> np.atleast_3d(x).shape
(4, 3, 1)
- >>> numpy.atleast_3d(x).base is x
+ >>> np.atleast_3d(x).base is x
True
- >>> for arr in np.atleast_3d(1, [1, 2], [[1, 2]]): print arr, "\\n"
+ >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
+ ... print arr, arr.shape
...
- [[[1]]]
-
[[[1]
- [2]]]
-
+ [2]]] (1, 2, 1)
[[[1]
- [2]]]
+ [2]]] (1, 2, 1)
+ [[[1 2]]] (1, 1, 2)
"""
res = []
@@ -401,27 +411,33 @@ def atleast_3d(*arys):
def vstack(tup):
"""
- Stack arrays vertically.
+ Stack arrays in sequence vertically (row wise).
- `vstack` can be used to rebuild arrays divided by `vsplit`.
+ Take a sequence of arrays and stack them vertically to make a single
+ array. Rebuild arrays divided by `vsplit`.
Parameters
----------
- tup : sequence of arrays
- Tuple containing arrays to be stacked. The arrays must have the same
+ tup : sequence of ndarrays
+ Tuple containing arrays to be stacked. The arrays must have the same
shape along all but the first axis.
+ Returns
+ -------
+ stacked : ndarray
+ The array formed by stacking the given arrays.
+
See Also
--------
- array_split : Split an array into a list of multiple sub-arrays of
- near-equal size.
- split : Split array into a list of multiple sub-arrays of equal size.
- vsplit : Split array into a list of multiple sub-arrays vertically.
- dsplit : Split array into a list of multiple sub-arrays along the 3rd axis
- (depth).
- concatenate : Join arrays together.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
+ concatenate : Join a sequence of arrays together.
+ vsplit : Split array into a list of multiple sub-arrays vertically.
+
+
+ Notes
+ -----
+ Equivalent to ``np.concatenate(tup, axis=0)``
Examples
--------
@@ -430,6 +446,7 @@ def vstack(tup):
>>> np.vstack((a,b))
array([[1, 2, 3],
[2, 3, 4]])
+
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a,b))
@@ -445,7 +462,7 @@ def vstack(tup):
def hstack(tup):
"""
- Stack arrays in sequence horizontally (column wise)
+ Stack arrays in sequence horizontally (column wise).
Take a sequence of arrays and stack them horizontally to make
a single array. Rebuild arrays divided by ``hsplit``.
@@ -462,9 +479,9 @@ def hstack(tup):
See Also
--------
- vstack : Stack along first axis.
- dstack : Stack along third axis.
- concatenate : Join arrays.
+ vstack : Stack arrays in sequence vertically (row wise).
+ dstack : Stack arrays in sequence depth wise (along third axis).
+ concatenate : Join a sequence of arrays together.
hsplit : Split array along second axis.
Notes
@@ -491,11 +508,11 @@ row_stack = vstack
def column_stack(tup):
"""
- Stack 1-D arrays as columns into a 2-D array
+ Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
- just like with hstack. 1-D arrays are turned into 2-D columns
+ just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
@@ -503,6 +520,19 @@ def column_stack(tup):
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
+ Returns
+ -------
+ stacked : 2-D array
+ The array formed by stacking the given arrays.
+
+ See Also
+ --------
+ hstack, vstack, concatenate
+
+ Notes
+ -----
+ This function is equivalent to ``np.vstack(tup).T``.
+
Examples
--------
>>> a = np.array((1,2,3))
@@ -523,7 +553,7 @@ def column_stack(tup):
def dstack(tup):
"""
- Stack arrays in sequence depth wise (along third axis)
+ Stack arrays in sequence depth wise (along third axis).
Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by ``dsplit``.
@@ -560,13 +590,12 @@ def dstack(tup):
array([[[1, 2],
[2, 3],
[3, 4]]])
+
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
- <BLANKLINE>
[[2, 3]],
- <BLANKLINE>
[[3, 4]]])
"""
@@ -584,13 +613,14 @@ def array_split(ary,indices_or_sections,axis = 0):
"""
Split an array into multiple sub-arrays of equal or near-equal size.
- Please refer to the `numpy.split` documentation. The only difference
- between these functions is that `array_split` allows `indices_or_sections`
- to be an integer that does *not* equally divide the axis.
+ Please refer to the ``split`` documentation. The only difference
+ between these functions is that ``array_split`` allows
+ `indices_or_sections` to be an integer that does *not* equally
+ divide the axis.
See Also
--------
- numpy.split : Split array into multiple sub-arrays.
+ split : Split array into multiple sub-arrays of equal size.
Examples
--------
@@ -638,12 +668,12 @@ def split(ary,indices_or_sections,axis=0):
----------
ary : ndarray
Array to be divided into sub-arrays.
- indices_or_sections: integer or 1D array
+ indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
- If `indices_or_sections` is a 1D array of sorted integers, the entries
+ If `indices_or_sections` is a 1-D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis = 0``, result in
@@ -653,12 +683,12 @@ def split(ary,indices_or_sections,axis=0):
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
- axis : integer, optional
- The axis along which to split. Default is 0.
+ axis : int, optional
+ The axis along which to split, default is 0.
Returns
-------
- sub-arrays : list
+ sub-arrays : list of ndarrays
A list of sub-arrays.
Raises
@@ -688,7 +718,6 @@ def split(ary,indices_or_sections,axis=0):
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
- <BLANKLINE>
[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
@@ -707,20 +736,25 @@ def split(ary,indices_or_sections,axis=0):
def hsplit(ary,indices_or_sections):
"""
- Split array into multiple sub-arrays horizontally.
+ Split an array into multiple sub-arrays horizontally (column-wise).
- Please refer to the `numpy.split` documentation. `hsplit` is
- equivalent to `numpy.split` with ``axis = 1``.
+ Please refer to the ``split`` documentation. ``hsplit`` is equivalent
+ to ``split`` with `axis=1`, the array is always split along the second
+ axis regardless of the array dimension.
See Also
--------
- split : Split array into multiple sub-arrays.
+ split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
+ >>> x
+ array([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [ 12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
- <BLANKLINE>
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
@@ -729,9 +763,7 @@ def hsplit(ary,indices_or_sections):
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
-
- >>> np.hsplit(x, array([3, 6]))
- <BLANKLINE>
+ >>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
@@ -742,6 +774,20 @@ def hsplit(ary,indices_or_sections):
[ 15.]]),
array([], dtype=float64)]
+ With a higher dimensional array the split is still along the second axis.
+
+ >>> x = np.arange(8.0).reshape(2, 2, 2)
+ >>> x
+ array([[[ 0., 1.],
+ [ 2., 3.]],
+ [[ 4., 5.],
+ [ 6., 7.]]])
+ >>> np.hsplit(x, 2)
+ [array([[[ 0., 1.]],
+ [[ 4., 5.]]]),
+ array([[[ 2., 3.]],
+ [[ 6., 7.]]])]
+
"""
if len(_nx.shape(ary)) == 0:
raise ValueError, 'hsplit only works on arrays of 1 or more dimensions'
@@ -752,14 +798,49 @@ def hsplit(ary,indices_or_sections):
def vsplit(ary,indices_or_sections):
"""
- Split array into multiple sub-arrays vertically.
+ Split an array into multiple sub-arrays vertically (row-wise).
- Please refer to the `numpy.split` documentation.
+ Please refer to the ``split`` documentation. ``vsplit`` is equivalent
+ to ``split`` with `axis=0` (default), the array is always split along the
+ first axis regardless of the array dimension.
See Also
--------
- numpy.split : The default behaviour of this function implements
- `vsplit`.
+ split : Split an array into multiple sub-arrays of equal size.
+
+ Examples
+ --------
+ >>> x = np.arange(16.0).reshape(4, 4)
+ >>> x
+ array([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [ 12., 13., 14., 15.]])
+ >>> np.vsplit(x, 2)
+ [array([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.]]),
+ array([[ 8., 9., 10., 11.],
+ [ 12., 13., 14., 15.]])]
+ >>> np.vsplit(x, np.array([3, 6]))
+ [array([[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]]),
+ array([[ 12., 13., 14., 15.]]),
+ array([], dtype=float64)]
+
+ With a higher dimensional array the split is still along the first axis.
+
+ >>> x = np.arange(8.0).reshape(2, 2, 2)
+ >>> x
+ array([[[ 0., 1.],
+ [ 2., 3.]],
+ [[ 4., 5.],
+ [ 6., 7.]]])
+ >>> np.vsplit(x, 2)
+ [array([[[ 0., 1.],
+ [ 2., 3.]]]),
+ array([[[ 4., 5.],
+ [ 6., 7.]]])]
"""
if len(_nx.shape(ary)) < 2:
@@ -770,73 +851,38 @@ def dsplit(ary,indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
- Parameters
- ----------
- ary : ndarray
- An array, with at least 3 dimensions, to be divided into sub-arrays
- depth-wise, or along the third axis.
- indices_or_sections: integer or 1D array
- If `indices_or_sections` is an integer, N, the array will be divided
- into N equal arrays along `axis`. If an equal split is not possible,
- a ValueError is raised.
-
- if `indices_or_sections` is a 1D array of sorted integers representing
- indices along `axis`, the array will be divided such that each index
- marks the start of each sub-array. If an index exceeds the dimension of
- the array along `axis`, and empty sub-array is returned for that index.
- axis : integer, optional
- the axis along which to split. Default is 0.
-
- Returns
- -------
- sub-arrays : list
- A list of sub-arrays.
+ Please refer to the ``split`` documentation. ``dsplit`` is equivalent
+ to ``split`` with `axis=2`, the array is always split along the third
+ axis provided the array dimension is greater than or equal to 3.
See Also
--------
- array_split : Split an array into a list of multiple sub-arrays
- of near-equal size.
- split : Split array into a list of multiple sub-arrays of equal size.
- hsplit : Split array into a list of multiple sub-arrays horizontally
- vsplit : Split array into a list of multiple sub-arrays vertically
- concatenate : Join arrays together.
- hstack : Stack arrays in sequence horizontally (column wise)
- vstack : Stack arrays in sequence vertically (row wise)
- dstack : Stack arrays in sequence depth wise (along third dimension)
-
- Notes
- -----
- `dsplit` requires that sub-arrays are of equal shape, whereas
- `array_split` allows for sub-arrays to have nearly-equal shape.
- Equivalent to `split` with `axis` = 2.
+ split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
+ >>> x
+ array([[[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.]],
+ [[ 8., 9., 10., 11.],
+ [ 12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
- <BLANKLINE>
[array([[[ 0., 1.],
[ 4., 5.]],
- <BLANKLINE>
[[ 8., 9.],
[ 12., 13.]]]),
array([[[ 2., 3.],
[ 6., 7.]],
- <BLANKLINE>
[[ 10., 11.],
[ 14., 15.]]])]
- <BLANKLINE>
- >>> x = np.arange(16.0).reshape(2, 2, 4)
- >>> np.dsplit(x, array([3, 6]))
- <BLANKLINE>
+ >>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
- <BLANKLINE>
[[ 8., 9., 10.],
[ 12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
- <BLANKLINE>
[[ 11.],
[ 15.]]]),
array([], dtype=float64)]
diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py
index e796a065a..f0abf3122 100644
--- a/numpy/lib/twodim_base.py
+++ b/numpy/lib/twodim_base.py
@@ -10,7 +10,7 @@ from numpy.core.numeric import asanyarray, equal, subtract, arange, \
def fliplr(m):
"""
- Left-right flip.
+ Flip array in the left/right direction.
Flip the entries in each row in the left/right direction.
Columns are preserved, but appear in a different order than before.
@@ -33,7 +33,7 @@ def fliplr(m):
Notes
-----
- Equivalent to A[::-1,...]. Does not require the array to be
+ Equivalent to A[:,::-1]. Does not require the array to be
two-dimensional.
Examples
@@ -60,7 +60,7 @@ def fliplr(m):
def flipud(m):
"""
- Up-down flip.
+ Flip array in the up/down direction.
Flip the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
@@ -76,6 +76,11 @@ def flipud(m):
A view of `m` with the rows reversed. Since a view is
returned, this operation is :math:`\\mathcal O(1)`.
+ See Also
+ --------
+ fliplr : Flip array in the left/right direction.
+ rot90 : Rotate array counterclockwise.
+
Notes
-----
Equivalent to ``A[::-1,...]``.
@@ -203,11 +208,22 @@ def diag(v, k=0):
Parameters
----------
v : array_like
- If `v` is a 2-dimensional array, return a copy of
- its `k`-th diagonal. If `v` is a 1-dimensional array,
- return a 2-dimensional array with `v` on the `k`-th diagonal.
+ If `v` is a 2-D array, return a copy of its `k`-th diagonal.
+ If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
+ diagonal.
k : int, optional
- Diagonal in question. The defaults is 0.
+ Diagonal in question. The default is 0.
+
+ Returns
+ -------
+ out : ndarray
+ The extracted diagonal or constructed diagonal array.
+
+ See Also
+ --------
+ diagonal : Return specified diagonals.
+ diagflat : Create a 2-D array with the flattened input as a diagonal.
+ trace : Sum along diagonals.
Examples
--------
@@ -255,7 +271,7 @@ def diag(v, k=0):
def diagflat(v,k=0):
"""
- Create a 2-dimensional array with the flattened input as a diagonal.
+ Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
@@ -265,9 +281,20 @@ def diagflat(v,k=0):
k : int, optional
Diagonal to set. The default is 0.
+ Returns
+ -------
+ out : ndarray
+ The 2-D output array.
+
+ See Also
+ --------
+ diag : Matlab workalike for 1-D and 2-D arrays.
+ diagonal : Return specified diagonals.
+ trace : Sum along diagonals.
+
Examples
--------
- >>> np.diagflat([[1,2],[3,4]])
+ >>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py
index 6f37326cc..113cec682 100644
--- a/numpy/lib/type_check.py
+++ b/numpy/lib/type_check.py
@@ -43,20 +43,20 @@ def mintypecode(typechars,typeset='GDFgdf',default='d'):
def asfarray(a, dtype=_nx.float_):
"""
- Return an array converted to float type.
+ Return an array converted to a float type.
Parameters
----------
a : array_like
- Input array.
- dtype : string or dtype object, optional
- Float type code to coerce input array `a`. If one of the 'int' dtype,
- it is replaced with float64.
+ The input array.
+ dtype : str or dtype object, optional
+ Float type code to coerce input array `a`. If `dtype` is one of the
+ 'int' dtypes, it is replaced with float64.
Returns
-------
- out : ndarray, float
- Input `a` as a float ndarray.
+ out : ndarray
+ The input `a` as a float ndarray.
Examples
--------
@@ -126,9 +126,10 @@ def imag(val):
def iscomplex(x):
"""
- Return a bool array, True if element is complex (non-zero imaginary part).
+ Returns a bool array, where True if input element is complex.
- For scalars, return a boolean.
+ What is tested is whether the input has a non-zero imaginary part, not if
+ the input type is complex.
Parameters
----------
@@ -140,11 +141,16 @@ def iscomplex(x):
out : ndarray, bool
Output array.
+ See Also
+ --------
+ isreal: Returns a bool array, where True if input element is real.
+ iscomplexobj: Return True if x is a complex type or an array of complex
+ numbers.
+
Examples
--------
- >>> x = np.array([1,2,3.j])
- >>> np.iscomplex(x)
- array([False, False, True], dtype=bool)
+ >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j])
+ array([ True, False, False, False, False, True], dtype=bool)
"""
ax = asanyarray(x)
@@ -155,9 +161,10 @@ def iscomplex(x):
def isreal(x):
"""
- Returns a bool array where True if the corresponding input element is real.
+ Returns a bool array, where True if input element is real.
- True if complex part is zero.
+ If the input value has a complex type but with complex part zero, the
+ return value is True.
Parameters
----------
@@ -169,6 +176,12 @@ def isreal(x):
out : ndarray, bool
Boolean array of same shape as `x`.
+ See Also
+ --------
+ iscomplex: Return a bool array, where True if input element is complex
+ (non-zero imaginary part).
+ isrealobj: Return True if x is not a complex type.
+
Examples
--------
>>> np.isreal([1+1j, 1+0j, 4.5, 3, 2, 2j])
@@ -178,16 +191,70 @@ def isreal(x):
return imag(x) == 0
def iscomplexobj(x):
- """Return True if x is a complex type or an array of complex numbers.
+ """
+ Return True if x is a complex type or an array of complex numbers.
+
+ The type of the input is checked, not the value. So even if the input
+ has an imaginary part equal to zero, `iscomplexobj` evaluates to True
+ if the data type is complex.
+
+ Parameters
+ ----------
+ x : any
+ The input can be of any type and shape.
+
+ Returns
+ -------
+ y : bool
+ The return value, True if `x` is of a complex type.
+
+ See Also
+ --------
+ isrealobj, iscomplex
+
+ Examples
+ --------
+ >>> np.iscomplexobj(1)
+ False
+ >>> np.iscomplexobj(1+0j)
+ True
+ np.iscomplexobj([3, 1+0j, True])
+ True
- Unlike iscomplex(x), complex(3.0) is considered a complex object.
"""
return issubclass( asarray(x).dtype.type, _nx.complexfloating)
def isrealobj(x):
- """Return True if x is not a complex type.
+ """
+ Return True if x is a not complex type or an array of complex numbers.
+
+ The type of the input is checked, not the value. So even if the input
+ has an imaginary part equal to zero, `isrealobj` evaluates to False
+ if the data type is complex.
+
+ Parameters
+ ----------
+ x : any
+ The input can be of any type and shape.
+
+ Returns
+ -------
+ y : bool
+ The return value, False if `x` is of a complex type.
+
+ See Also
+ --------
+ iscomplexobj, isreal
+
+ Examples
+ --------
+ >>> np.isrealobj(1)
+ True
+ >>> np.isrealobj(1+0j)
+ False
+ >>> np.isrealobj([3, 1+0j, True])
+ False
- Unlike isreal(x), complex(3.0) is considered a complex object.
"""
return not issubclass( asarray(x).dtype.type, _nx.complexfloating)
@@ -200,7 +267,11 @@ def _getmaxmin(t):
def nan_to_num(x):
"""
- Replace nan with zero and inf with large numbers.
+ Replace nan with zero and inf with finite numbers.
+
+ Returns an array or scalar replacing Not a Number (NaN) with zero,
+ (positive) infinity with a very large number and negative infinity
+ with a very small (or negative) number.
Parameters
----------
@@ -209,10 +280,26 @@ def nan_to_num(x):
Returns
-------
- out : ndarray
- Array with the same shape and dtype as `x`. Nan is replaced
- by zero, and inf (-inf) is replaced by the largest (smallest)
- floating point value that fits in the output dtype.
+ out : ndarray, float
+ Array with the same shape as `x` and dtype of the element in `x` with
+ the greatest precision. NaN is replaced by zero, and infinity
+ (-infinity) is replaced by the largest (smallest or most negative)
+ floating point value that fits in the output dtype. All finite numbers
+ are upcast to the output dtype (default float64).
+
+ See Also
+ --------
+ isinf : Shows which elements are negative or negative infinity.
+ isneginf : Shows which elements are negative infinity.
+ isposinf : Shows which elements are positive infinity.
+ isnan : Shows which elements are Not a Number (NaN).
+ isfinite : Shows which elements are finite (not NaN, not infinity)
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
+
Examples
--------
@@ -263,8 +350,9 @@ def real_if_close(a,tol=100):
----------
a : array_like
Input array.
- tol : scalar
- Tolerance for the complex part of the elements in the array.
+ tol : float
+ Tolerance in machine epsilons for the complex part of the elements
+ in the array.
Returns
-------
@@ -285,12 +373,12 @@ def real_if_close(a,tol=100):
Examples
--------
- >>> np.finfo(np.float).eps # DOCTEST +skip
+ >>> np.finfo(np.float).eps
2.2204460492503131e-16
- >>> np.real_if_close([2.1 + 4e-14j], tol = 1000)
+ >>> np.real_if_close([2.1 + 4e-14j], tol=1000)
array([ 2.1])
- >>> np.real_if_close([2.1 + 4e-13j], tol = 1000)
+ >>> np.real_if_close([2.1 + 4e-13j], tol=1000)
array([ 2.1 +4.00000000e-13j])
"""
@@ -313,17 +401,17 @@ def asscalar(a):
Parameters
----------
a : ndarray
- Input array.
+ Input array of size 1.
Returns
-------
out : scalar
- Scalar of size 1 array.
+ Scalar representation of `a`. The input data type is preserved.
Examples
--------
>>> np.asscalar(np.array([24]))
- >>> 24
+ 24
"""
return a.item()
diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py
index 8ea7c6662..5dbc3f225 100644
--- a/numpy/lib/ufunclike.py
+++ b/numpy/lib/ufunclike.py
@@ -27,7 +27,7 @@ def fix(x, y=None):
See Also
--------
- floor : Round downwards
+ trunc, floor, ceil
around : Round to given number of decimals
Examples
@@ -50,48 +50,40 @@ def fix(x, y=None):
def isposinf(x, y=None):
"""
- Shows which elements of the input are positive infinity.
-
- Returns a numpy array resulting from an element-wise test for positive
- infinity.
+ Test element-wise for positive infinity, return result as bool array.
Parameters
----------
x : array_like
- The input array.
- y : array_like
- A boolean array with the same shape as `x` to store the result.
+ The input array.
+ y : array_like, optional
+ A boolean array with the same shape as `x` to store the result.
Returns
-------
y : ndarray
- A numpy boolean array with the same dimensions as the input.
- If second argument is not supplied then a numpy boolean array is returned
- with values True where the corresponding element of the input is positive
- infinity and values False where the element of the input is not positive
- infinity.
+ A boolean array with the same dimensions as the input.
+ If second argument is not supplied then a boolean array is returned
+ with values True where the corresponding element of the input is
+ positive infinity and values False where the element of the input is
+ not positive infinity.
- If second argument is supplied then an numpy integer array is returned
- with values 1 where the corresponding element of the input is positive
- positive infinity.
+ If a second argument is supplied the result is stored there. If the
+ type of that array is a numeric type the result is represented as zeros
+ and ones, if the type is boolean then as False and True.
+ The return value `y` is then a reference to that array.
See Also
--------
- isinf : Shows which elements are negative or positive infinity.
- isneginf : Shows which elements are negative infinity.
- isnan : Shows which elements are Not a Number (NaN).
- isfinite: Shows which elements are not: Not a number, positive and
- negative infinity
+ isinf, isneginf, isfinite, isnan
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
- (IEEE 754). This means that Not a Number is not equivalent to infinity.
- Also that positive infinity is not equivalent to negative infinity. But
- infinity is equivalent to positive infinity.
+ (IEEE 754).
- Errors result if second argument is also supplied with scalar input or
- if first and second arguments have different shapes.
+ Errors result if the second argument is also supplied when `x` is a
+ scalar input, or if first and second arguments have different shapes.
Examples
--------
@@ -103,9 +95,10 @@ def isposinf(x, y=None):
array(False, dtype=bool)
>>> np.isposinf([-np.inf, 0., np.inf])
array([False, False, True], dtype=bool)
- >>> x=np.array([-np.inf, 0., np.inf])
- >>> y=np.array([2,2,2])
- >>> np.isposinf(x,y)
+
+ >>> x = np.array([-np.inf, 0., np.inf])
+ >>> y = np.array([2, 2, 2])
+ >>> np.isposinf(x, y)
array([1, 0, 0])
>>> y
array([1, 0, 0])
@@ -119,29 +112,60 @@ def isposinf(x, y=None):
def isneginf(x, y=None):
"""
- Return True where x is -infinity, and False otherwise.
+ Test element-wise for negative infinity, return result as bool array.
Parameters
----------
x : array_like
- The input array.
- y : array_like
- A boolean array with the same shape as `x` to store the result.
+ The input array.
+ y : array_like, optional
+ A boolean array with the same shape and type as `x` to store the
+ result.
Returns
-------
y : ndarray
- A boolean array where y[i] = True only if x[i] = -Inf.
+ A boolean array with the same dimensions as the input.
+ If second argument is not supplied then a numpy boolean array is
+ returned with values True where the corresponding element of the
+ input is negative infinity and values False where the element of
+ the input is not negative infinity.
+
+ If a second argument is supplied the result is stored there. If the
+ type of that array is a numeric type the result is represented as
+ zeros and ones, if the type is boolean then as False and True. The
+ return value `y` is then a reference to that array.
See Also
--------
- isposinf, isfinite
+ isinf, isposinf, isnan, isfinite
+
+ Notes
+ -----
+ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+ (IEEE 754).
+
+ Errors result if the second argument is also supplied when x is a scalar
+ input, or if first and second arguments have different shapes.
Examples
--------
+ >>> np.isneginf(np.NINF)
+ array(True, dtype=bool)
+ >>> np.isneginf(np.inf)
+ array(False, dtype=bool)
+ >>> np.isneginf(np.PINF)
+ array(False, dtype=bool)
>>> np.isneginf([-np.inf, 0., np.inf])
array([ True, False, False], dtype=bool)
+ >>> x = np.array([-np.inf, 0., np.inf])
+ >>> y = np.array([2, 2, 2])
+ >>> np.isneginf(x, y)
+ array([1, 0, 0])
+ >>> y
+ array([1, 0, 0])
+
"""
if y is None:
x = nx.asarray(x)
diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py
index 9717a7a8f..3de0579df 100644
--- a/numpy/lib/utils.py
+++ b/numpy/lib/utils.py
@@ -149,15 +149,21 @@ get_numpy_include = deprecate(get_include, 'get_numpy_include', 'get_include')
#--------------------------------------------
def byte_bounds(a):
- """(low, high) are pointers to the end-points of an array
+ """
+ Returns pointers to the end-points of an array.
- low is the first byte
- high is just *past* the last byte
+ Parameters
+ ----------
+ a : ndarray
+ Input array. It must conform to the Python-side of the array interface.
- If the array is not single-segment, then it may not actually
- use every byte between these bounds.
+ Returns
+ -------
+ (low, high) : tuple of 2 integers
+ The first integer is the first byte of the array, the second integer is
+ just past the last byte of the array. If `a` is not contiguous it
+ would not use every byte between the (`low`, `high`) values.
- The array provided must conform to the Python-side of the array interface
"""
ai = a.__array_interface__
a_data = ai['data'][0]
@@ -228,10 +234,8 @@ def who(vardict=None):
>>> np.whos(d)
Name Shape Bytes Type
===========================================================
- <BLANKLINE>
y 3 24 float64
x 2 16 float64
- <BLANKLINE>
Upper bound on total bytes = 40
"""
diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py
index 1570407ff..dcf7fde26 100644
--- a/numpy/linalg/linalg.py
+++ b/numpy/linalg/linalg.py
@@ -202,6 +202,18 @@ def solve(a, b):
LinAlgError
If `a` is singular or not square.
+ Notes
+ -----
+
+ ``linalg.solve`` is a wrapper to the LAPACK http://www.netlib.org/lapack
+ routines `dgesv`_ and `zgesv`_. The solution to the system of linear
+ equations is computed using an LU decomposition with partial pivoting and
+ row interchanges.
+
+ .. _dgesv: http://www.netlib.org/lapack/double/dgesv.f
+
+ .. _zgesv: http://www.netlib.org/lapack/complex16/zgesv.f
+
Examples
--------
Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``:
@@ -756,16 +768,17 @@ def eig(a):
complex arrays respectively.
The number `w` is an eigenvalue of a if there exists a vector `v`
- satisfying the equation ``dot(a,v) = w*v``. Alternately, if `w` is a root of
- the characteristic equation ``det(a - w[i]*I) = 0``, where `det` is the
- determinant and `I` is the identity matrix. The arrays `a`, `w`, and `v`
- satisfy the equation ``dot(a,v[i]) = w[i]*v[:,i]``.
+ satisfying the equation ``dot(a,v) = w*v``. Alternately, if `w` is
+ a root of the characteristic equation ``det(a - w[i]*I) = 0``, where
+ `det` is the determinant and `I` is the identity matrix. The arrays
+ `a`, `w`, and `v` satisfy the equation ``dot(a,v[i]) = w[i]*v[:,i]``.
The array `v` of eigenvectors may not be of maximum rank, that is, some
- of the columns may be dependent, although roundoff error may obscure
- that fact. If the eigenvalues are all different, then theoretically the
- eigenvectors are independent. Likewise, the matrix of eigenvectors is
- unitary if the matrix `a` is normal, i.e., if ``dot(a, a.H) = dot(a.H, a)``.
+ of the columns may be dependent, although roundoff error may
+ obscure that fact. If the eigenvalues are all different, then theoretically
+ the eigenvectors are independent. Likewise, the matrix of eigenvectors
+ is unitary if the matrix `a` is normal, i.e., if
+ ``dot(a, a.H) = dot(a.H, a)``.
The left and right eigenvectors are not necessarily the (Hermitian)
transposes of each other.
@@ -1332,7 +1345,7 @@ def norm(x, ord=None):
----------
x : array_like, shape (M,) or (M, N)
Input array.
- ord : {int, 1, -1, 2, -2, inf, -inf, 'fro'}
+ ord : {2, int, inf, -inf, 'fro'}
Order of the norm (see table under ``Notes``).
Returns
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index 811ce5f19..29dc82815 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -296,20 +296,61 @@ def _check_fill_value(fill_value, ndtype):
def set_fill_value(a, fill_value):
"""
- Set the filling value of a, if a is a masked array. Otherwise,
- do nothing.
+ Set the filling value of a, if a is a masked array.
+
+ This function changes the fill value of the masked array `a` in place.
+ If `a` is not a masked array, the function returns silently, without
+ doing anything.
Parameters
----------
- a : ndarray
- Input array
- fill_value : var
+ a : array_like
+ Input array.
+ fill_value : dtype
Filling value. A consistency test is performed to make sure
- the value is compatible with the dtype of a.
+ the value is compatible with the dtype of `a`.
Returns
-------
None
+ Nothing returned by this function.
+
+ See Also
+ --------
+ maximum_fill_value : Return the default fill value for a dtype.
+ MaskedArray.fill_value : Return current fill value.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(5)
+ >>> a
+ array([0, 1, 2, 3, 4])
+ >>> a = ma.masked_where(a < 3, a)
+ >>> a
+ masked_array(data = [-- -- -- 3 4],
+ mask = [ True True True False False],
+ fill_value=999999)
+ >>> ma.set_fill_value(a, -999)
+ >>> a
+ masked_array(data = [-- -- -- 3 4],
+ mask = [ True True True False False],
+ fill_value=-999)
+
+ Nothing happens if `a` is not a masked array.
+
+ >>> a = range(5)
+ >>> a
+ [0, 1, 2, 3, 4]
+ >>> ma.set_fill_value(a, 100)
+ >>> a
+ [0, 1, 2, 3, 4]
+ >>> a = np.arange(5)
+ >>> a
+ array([0, 1, 2, 3, 4])
+ >>> ma.set_fill_value(a, 100)
+ >>> a
+ array([0, 1, 2, 3, 4])
"""
if isinstance(a, MaskedArray):
@@ -399,15 +440,46 @@ def get_masked_subclass(*arrays):
#####--------------------------------------------------------------------------
def getdata(a, subok=True):
"""
- Return the `_data` part of `a` if `a` is a MaskedArray, or `a` itself.
+ Return the data of a masked array as an ndarray.
+
+ Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
+ else return `a` as a ndarray or subclass (depending on `subok`) if not.
Parameters
----------
a : array_like
- A ndarray or a subclass of.
- subok : {True, False}, optional
- Whether to force the output to a 'pure' ndarray (False) or to
- return a subclass of ndarray if approriate (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).
+
+ See Also
+ --------
+ getmask : Return the mask of a masked array, or nomask.
+ getmaskarray : Return the mask of a masked array, or full array of False.
+
+ Examples
+ --------
+
+ >>> import numpy.ma as ma
+ >>> a = ma.masked_equal([[1,2],[3,4]], 2)
+ >>> a
+ masked_array(data =
+ [[1 --]
+ [3 4]],
+ mask =
+ [[False True]
+ [False False]],
+ fill_value=999999)
+ >>> ma.getdata(a)
+ array([[1, 2],
+ [3, 4]])
+
+ Equivalently use the ``MaskedArray`` `data` attribute.
+
+ >>> a.data
+ array([[1, 2],
+ [3, 4]])
"""
data = getattr(a, '_data', np.array(a, subok=subok))
@@ -893,8 +965,33 @@ def _recursive_make_descr(datatype, newtype=bool_):
return newtype
def make_mask_descr(ndtype):
- """Constructs a dtype description list from a given dtype.
- Each field is set to a bool.
+ """
+ Construct a dtype description list from a given dtype.
+
+ Returns a new dtype object, with the type of all fields in `ndtype` to a
+ boolean type. Field names are not altered.
+
+ Parameters
+ ----------
+ ndtype : dtype
+ The dtype to convert.
+
+ Returns
+ -------
+ result : dtype
+ A dtype that looks like `ndtype`, the type of all fields is boolean.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> dtype = np.dtype({'names':['foo', 'bar'],
+ 'formats':[np.float32, np.int]})
+ >>> dtype
+ dtype([('foo', '<f4'), ('bar', '<i4')])
+ >>> ma.make_mask_descr(dtype)
+ dtype([('foo', '|b1'), ('bar', '|b1')])
+ >>> ma.make_mask_descr(np.float32)
+ <type 'numpy.bool_'>
"""
# Make sure we do have a dtype
@@ -903,18 +1000,115 @@ def make_mask_descr(ndtype):
return np.dtype(_recursive_make_descr(ndtype, np.bool))
def getmask(a):
- """Return the mask of a, if any, or nomask.
+ """
+ Return the mask of a masked array, or nomask.
+
+ Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
+ mask is not `nomask`, else return `nomask`. To guarantee a full array
+ of booleans of the same shape as a, use `getmaskarray`.
+
+ Parameters
+ ----------
+ a : array_like
+ Input `MaskedArray` for which the mask is required.
+
+ See Also
+ --------
+ getdata : Return the data of a masked array as an ndarray.
+ getmaskarray : Return the mask of a masked array, or full array of False.
- To get a full array of booleans of the same shape as a, use
- getmaskarray.
+ Examples
+ --------
+
+ >>> import numpy.ma as ma
+ >>> a = ma.masked_equal([[1,2],[3,4]], 2)
+ >>> a
+ masked_array(data =
+ [[1 --]
+ [3 4]],
+ mask =
+ [[False True]
+ [False False]],
+ fill_value=999999)
+ >>> ma.getmask(a)
+ array([[False, True],
+ [False, False]], dtype=bool)
+
+ Equivalently use the `MaskedArray` `mask` attribute.
+
+ >>> a.mask
+ array([[False, True],
+ [False, False]], dtype=bool)
+
+ Result when mask == `nomask`
+
+ >>> b = ma.masked_array([[1,2],[3,4]])
+ >>> b
+ masked_array(data =
+ [[1 2]
+ [3 4]],
+ mask =
+ False,
+ fill_value=999999)
+ >>> ma.nomask
+ False
+ >>> ma.getmask(b) == ma.nomask
+ True
+ >>> b.mask == ma.nomask
+ True
"""
return getattr(a, '_mask', nomask)
get_mask = getmask
def getmaskarray(arr):
- """Return the mask of arr, if any, or a boolean array of the shape
- of a, full of False.
+ """
+ Return the mask of a masked array, or full boolean array of False.
+
+ Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and
+ the mask is not `nomask`, else return a full boolean array of False of
+ the same shape as `arr`.
+
+ Parameters
+ ----------
+ arr : array_like
+ Input `MaskedArray` for which the mask is required.
+
+ See Also
+ --------
+ getmask : Return the mask of a masked array, or nomask.
+ getdata : Return the data of a masked array as an ndarray.
+
+ Examples
+ --------
+
+ >>> import numpy.ma as ma
+ >>> a = ma.masked_equal([[1,2],[3,4]], 2)
+ >>> a
+ masked_array(data =
+ [[1 --]
+ [3 4]],
+ mask =
+ [[False True]
+ [False False]],
+ fill_value=999999)
+ >>> ma.getmaskarray(a)
+ array([[False, True],
+ [False, False]], dtype=bool)
+
+ Result when mask == ``nomask``
+
+ >>> b = ma.masked_array([[1,2],[3,4]])
+ >>> b
+ masked_array(data =
+ [[1 2]
+ [3 4]],
+ mask =
+ False,
+ fill_value=999999)
+ >>> >ma.getmaskarray(b)
+ array([[False, False],
+ [False, False]], dtype=bool)
"""
mask = getmask(arr)
@@ -926,10 +1120,62 @@ def is_mask(m):
"""
Return True if m is a valid, standard mask.
- Notes
- -----
- This function does not check contents, only the type. In particular,
- this function returns False if the mask has a flexible dtype.
+ This function does not check the contents of the input, only that the
+ type is MaskType. In particular, this function returns False if the
+ mask has a flexible dtype.
+
+ Parameters
+ ----------
+ m : array_like
+ Array to test.
+
+ Returns
+ -------
+ result : bool
+ True if `m.dtype.type` is MaskType, False otherwise.
+
+ See Also
+ --------
+ isMaskedArray : Test whether input is an instance of MaskedArray.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0)
+ >>> m
+ masked_array(data = [-- 1 -- 2 3],
+ mask = [ True False True False False],
+ fill_value=999999)
+ >>> ma.is_mask(m)
+ False
+ >>> ma.is_mask(m.mask)
+ True
+
+ Input must be an ndarray (or have similar attributes)
+ for it to be considered a valid mask.
+
+ >>> m = [False, True, False]
+ >>> ma.is_mask(m)
+ False
+ >>> m = np.array([False, True, False])
+ >>> m
+ array([False, True, False], dtype=bool)
+ >>> ma.is_mask(m)
+ True
+
+ Arrays with complex dtypes don't return True.
+
+ >>> dtype = np.dtype({'names':['monty', 'pithon'],
+ 'formats':[np.bool, np.bool]})
+ >>> dtype
+ dtype([('monty', '|b1'), ('pithon', '|b1')])
+ >>> m = np.array([(True, False), (False, True), (True, False)],
+ dtype=dtype)
+ >>> m
+ array([(True, False), (False, True), (True, False)],
+ dtype=[('monty', '|b1'), ('pithon', '|b1')])
+ >>> ma.is_mask(m)
+ False
"""
try:
@@ -939,24 +1185,75 @@ def is_mask(m):
def make_mask(m, copy=False, shrink=True, flag=None, dtype=MaskType):
"""
- Return m as a mask, creating a copy if necessary or requested.
+ Create a boolean mask from an array.
- The function can accept any sequence of integers or nomask. Does
- not check that contents must be 0s and 1s.
+ Return `m` as a boolean mask, creating a copy if necessary or requested.
+ The function can accept any sequence that is convertible to integers,
+ or ``nomask``. Does not require that contents must be 0s and 1s, values
+ of 0 are interepreted as False, everything else as True.
Parameters
----------
m : array_like
Potential mask.
copy : bool
- Whether to return a copy of m (True) or m itself (False).
+ Whether to return a copy of `m` (True) or `m` itself (False).
shrink : bool
- Whether to shrink m to nomask if all its values are False.
+ Whether to shrink `m` to ``nomask`` if all its values are False.
+ flag : bool
+ Deprecated equivalent of `shrink`.
dtype : dtype
Data-type of the output mask. By default, the output mask has
a dtype of MaskType (bool). If the dtype is flexible, each field
has a boolean dtype.
+ Returns
+ -------
+ result : ndarray
+ A boolean mask derived from `m`.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> m = [True, False, True, True]
+ >>> ma.make_mask(m)
+ array([ True, False, True, True], dtype=bool)
+ >>> m = [1, 0, 1, 1]
+ >>> ma.make_mask(m)
+ array([ True, False, True, True], dtype=bool)
+ >>> m = [1, 0, 2, -3]
+ >>> ma.make_mask(m)
+ array([ True, False, True, True], dtype=bool)
+
+ Effect of the `shrink` parameter.
+
+ >>> m = np.zeros(4)
+ >>> m
+ array([ 0., 0., 0., 0.])
+ >>> ma.make_mask(m)
+ False
+ >>> ma.make_mask(m, shrink=False)
+ array([False, False, False, False], dtype=bool)
+
+ Using a flexible `dtype`.
+
+ >>> m = [1, 0, 1, 1]
+ >>> n = [0, 1, 0, 0]
+ >>> arr = []
+ >>> for man, mouse in zip(m, n):
+ ... arr.append((man, mouse))
+ >>> arr
+ [(1, 0), (0, 1), (1, 0), (1, 0)]
+ >>> dtype = np.dtype({'names':['man', 'mouse'],
+ 'formats':[np.int, np.int]})
+ >>> arr = np.array(arr, dtype=dtype)
+ >>> arr
+ array([(1, 0), (0, 1), (1, 0), (1, 0)],
+ dtype=[('man', '<i4'), ('mouse', '<i4')])
+ >>> ma.make_mask(arr, dtype=dtype)
+ array([(True, False), (False, True), (True, False), (True, False)],
+ dtype=[('man', '|b1'), ('mouse', '|b1')])
+
"""
if flag is not None:
warnings.warn("The flag 'flag' is now called 'shrink'!",
@@ -988,15 +1285,45 @@ def make_mask(m, copy=False, shrink=True, flag=None, dtype=MaskType):
def make_mask_none(newshape, dtype=None):
"""
- Return a mask of shape s, filled with False.
+ Return a boolean mask of the given shape, filled with False.
+
+ This function returns a boolean ndarray with all entries False, that can
+ be used in common mask manipulations. If a complex dtype is specified, the
+ type of each field is converted to a boolean type.
Parameters
----------
- news : tuple
- A tuple indicating the shape of the final mask.
+ newshape : tuple
+ A tuple indicating the shape of the mask.
dtype: {None, dtype}, optional
- If None, use MaskType. Otherwise, use a new datatype with the same fields
- as `dtype` with boolean type.
+ If None, use a MaskType instance. Otherwise, use a new datatype with
+ the same fields as `dtype`, converted to boolean types.
+
+ Returns
+ -------
+ result : ndarray
+ An ndarray of appropriate shape and dtype, filled with False.
+
+ See Also
+ --------
+ make_mask : Create a boolean mask from an array.
+ make_mask_descr : Construct a dtype description list from a given dtype.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> ma.make_mask_none((3,))
+ array([False, False, False], dtype=bool)
+
+ Defining a more complex dtype.
+
+ >>> dtype = np.dtype({'names':['foo', 'bar'],
+ 'formats':[np.float32, np.int]})
+ >>> dtype
+ dtype([('foo', '<f4'), ('bar', '<i4')])
+ >>> ma.make_mask_none((3,), dtype=dtype)
+ array([(False, False), (False, False), (False, False)],
+ dtype=[('foo', '|b1'), ('bar', '|b1')])
"""
if dtype is None:
@@ -1119,17 +1446,100 @@ def flatten_mask(mask):
def masked_where(condition, a, copy=True):
"""
- Return ``a`` as an array masked where ``condition`` is ``True``.
- Masked values of ``a`` or ``condition`` are kept.
+ Mask an array where a condition is met.
+
+ Return `a` as an array masked where `condition` is True.
+ Any masked values of `a` or `condition` are also masked in the output.
Parameters
----------
condition : array_like
- Masking condition.
+ Masking condition. When `condition` tests floating point values for
+ equality, consider using ``masked_values`` instead.
a : array_like
Array to mask.
copy : bool
- Whether to return a copy of ``a`` (True) or modify ``a`` in place (False).
+ If True (default) make a copy of `a` in the result. If False modify
+ `a` in place and return a view.
+
+ Returns
+ -------
+ result : MaskedArray
+ The result of masking `a` where `condition` is True.
+
+ See Also
+ --------
+ masked_values : Mask using floating point equality.
+ masked_equal : Mask where equal to a given value.
+ masked_not_equal : Mask where `not` equal to a given value.
+ masked_less_equal : Mask where less than or equal to a given value.
+ masked_greater_equal : Mask where greater than or equal to a given value.
+ masked_less : Mask where less than a given value.
+ masked_greater : Mask where greater than a given value.
+ masked_inside : Mask inside a given interval.
+ masked_outside : Mask outside a given interval.
+ masked_invalid : Mask invalid values (NaNs or infs).
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_where(a <= 2, a)
+ masked_array(data = [-- -- -- 3],
+ mask = [ True True True False],
+ fill_value=999999)
+
+ Mask array `b` conditional on `a`.
+
+ >>> b = ['a', 'b', 'c', 'd']
+ >>> ma.masked_where(a == 2, b)
+ masked_array(data = [a b -- d],
+ mask = [False False True False],
+ fill_value=N/A)
+
+ Effect of the `copy` argument.
+
+ >>> c = ma.masked_where(a <= 2, a)
+ >>> c
+ masked_array(data = [-- -- -- 3],
+ mask = [ True True True False],
+ fill_value=999999)
+ >>> c[0] = 99
+ >>> c
+ masked_array(data = [99 -- -- 3],
+ mask = [False True True False],
+ fill_value=999999)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> c = ma.masked_where(a <= 2, a, copy=False)
+ >>> c[0] = 99
+ >>> c
+ masked_array(data = [99 -- -- 3],
+ mask = [False True True False],
+ fill_value=999999)
+ >>> a
+ array([99, 1, 2, 3])
+
+ When `condition` or `a` contain masked values.
+
+ >>> a = np.arange(4)
+ >>> a = ma.masked_where(a == 2, a)
+ >>> a
+ masked_array(data = [0 1 -- 3],
+ mask = [False False True False],
+ fill_value=999999)
+ >>> b = np.arange(4)
+ >>> b = ma.masked_where(b == 0, b)
+ >>> b
+ masked_array(data = [-- 1 2 3],
+ mask = [ True False False False],
+ fill_value=999999)
+ >>> ma.masked_where(a == 3, b)
+ masked_array(data = [-- 1 -- --],
+ mask = [ True False True True],
+ fill_value=999999)
"""
# Make sure that condition is a valid standard-type mask.
@@ -1152,41 +1562,157 @@ def masked_where(condition, a, copy=True):
def masked_greater(x, value, copy=True):
"""
- Return the array `x` masked where ``(x > value)``.
- Any value of mask already masked is kept masked.
+ Mask an array where greater than a given value.
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = (x > value).
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_greater(a, 2)
+ masked_array(data = [0 1 2 --],
+ mask = [False False False True],
+ fill_value=999999)
"""
return masked_where(greater(x, value), x, copy=copy)
def masked_greater_equal(x, value, copy=True):
- "Shortcut to masked_where, with condition ``(x >= value)``."
+ """
+ Mask an array where greater than or equal to a given value.
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = (x >= value).
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_greater_equal(a, 2)
+ masked_array(data = [0 1 -- --],
+ mask = [False False True True],
+ fill_value=999999)
+
+ """
return masked_where(greater_equal(x, value), x, copy=copy)
def masked_less(x, value, copy=True):
- "Shortcut to masked_where, with condition ``(x < value)``."
+ """
+ Mask an array where less than a given value.
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = (x < value).
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_less(a, 2)
+ masked_array(data = [-- -- 2 3],
+ mask = [ True True False False],
+ fill_value=999999)
+
+ """
return masked_where(less(x, value), x, copy=copy)
def masked_less_equal(x, value, copy=True):
- "Shortcut to masked_where, with condition ``(x <= value)``."
+ """
+ Mask an array where less than or equal to a given value.
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = (x <= value).
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_less_equal(a, 2)
+ masked_array(data = [-- -- -- 3],
+ mask = [ True True True False],
+ fill_value=999999)
+
+ """
return masked_where(less_equal(x, value), x, copy=copy)
def masked_not_equal(x, value, copy=True):
- "Shortcut to masked_where, with condition ``(x != value)``."
+ """
+ Mask an array where `not` equal to a given value.
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = (x != value).
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_not_equal(a, 2)
+ masked_array(data = [-- -- 2 --],
+ mask = [ True True False True],
+ fill_value=999999)
+
+ """
return masked_where(not_equal(x, value), x, copy=copy)
def masked_equal(x, value, copy=True):
"""
- Shortcut to masked_where, with condition ``(x == value)``.
+ Mask an array where equal to a given value.
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = (x == value). For floating point arrays,
+ consider using ``masked_values(x, value)``.
See Also
--------
- masked_where : base function
- masked_values : equivalent function for floats.
+ masked_where : Mask where a condition is met.
+ masked_values : Mask using floating point equality.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(4)
+ >>> a
+ array([0, 1, 2, 3])
+ >>> ma.masked_equal(a, 2)
+ masked_array(data = [0 1 -- 3],
+ mask = [False False True False],
+ fill_value=999999)
"""
# An alternative implementation relies on filling first: probably not needed.
@@ -1199,13 +1725,35 @@ def masked_equal(x, value, copy=True):
def masked_inside(x, v1, v2, copy=True):
"""
- Shortcut to masked_where, where ``condition`` is True for x inside
- the interval [v1,v2] (v1 <= x <= v2). The boundaries v1 and v2
+ Mask an array inside a given interval.
+
+ Shortcut to ``masked_where``, where `condition` is True for `x` inside
+ the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2`
can be given in either order.
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
Notes
-----
- The array x is prefilled with its filling value.
+ The array `x` is prefilled with its filling value.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
+ >>> ma.masked_inside(x, -0.3, 0.3)
+ masked_array(data = [0.31 1.2 -- -- -0.4 -1.1],
+ mask = [False False True True False False],
+ fill_value=1e+20)
+
+ The order of `v1` and `v2` doesn't matter.
+
+ >>> ma.masked_inside(x, 0.3, -0.3)
+ masked_array(data = [0.31 1.2 -- -- -0.4 -1.1],
+ mask = [False False True True False False],
+ fill_value=1e+20)
"""
if v2 < v1:
@@ -1217,13 +1765,35 @@ def masked_inside(x, v1, v2, copy=True):
def masked_outside(x, v1, v2, copy=True):
"""
- Shortcut to ``masked_where``, where ``condition`` is True for x outside
+ Mask an array outside a given interval.
+
+ Shortcut to ``masked_where``, where `condition` is True for `x` outside
the interval [v1,v2] (x < v1)|(x > v2).
- The boundaries v1 and v2 can be given in either order.
+ The boundaries `v1` and `v2` can be given in either order.
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
Notes
-----
- The array x is prefilled with its filling value.
+ The array `x` is prefilled with its filling value.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
+ >>> ma.masked_outside(x, -0.3, 0.3)
+ masked_array(data = [-- -- 0.01 0.2 -- --],
+ mask = [ True True False False True True],
+ fill_value=1e+20)
+
+ The order of `v1` and `v2` doesn't matter.
+
+ >>> ma.masked_outside(x, 0.3, -0.3)
+ masked_array(data = [-- -- 0.01 0.2 -- --],
+ mask = [ True True False False True True],
+ fill_value=1e+20)
"""
if v2 < v1:
@@ -1237,20 +1807,52 @@ def masked_object(x, value, copy=True, shrink=True):
"""
Mask the array `x` where the data are exactly equal to value.
- This function is suitable only for object arrays: for floating
- point, please use `masked_values`_ instead.
+ This function is similar to `masked_values`, but only suitable
+ for object arrays: for floating point, use `masked_values` instead.
Parameters
----------
x : array_like
Array to mask
- value : var
+ value : object
Comparison value
copy : {True, False}, optional
- Whether to return a copy of x.
+ Whether to return a copy of `x`.
shrink : {True, False}, optional
Whether to collapse a mask full of False to nomask
+ Returns
+ -------
+ result : MaskedArray
+ The result of masking `x` where equal to `value`.
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+ masked_equal : Mask where equal to a given value (integers).
+ masked_values : Mask using floating point equality.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> food = np.array(['green_eggs', 'ham'], dtype=object)
+ >>> # don't eat spoiled food
+ >>> eat = ma.masked_object(food, 'green_eggs')
+ >>> print eat
+ [-- ham]
+ >>> # plain ol` ham is boring
+ >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
+ >>> eat = ma.masked_object(fresh_food, 'green_eggs')
+ >>> print eat
+ [cheese ham pineapple]
+
+ Note that `mask` is set to ``nomask`` if possible.
+
+ >>> eat
+ masked_array(data = [cheese ham pineapple],
+ mask = False,
+ fill_value=?)
+
"""
if isMaskedArray(x):
condition = umath.equal(x._data, value)
@@ -1264,26 +1866,71 @@ def masked_object(x, value, copy=True, shrink=True):
def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True, shrink=True):
"""
- Mask the array x where the data are approximately equal in
- value, i.e. ``(abs(x - value) <= atol+rtol*abs(value))``
+ Mask using floating point equality.
+
+ Return a MaskedArray, masked where the data in array `x` are approximately
+ equal to `value`, i.e. where the following condition is True
- Suitable only for floating points. For integers, please use
- :func:`masked_equal`. The mask is set to ``nomask`` if posible.
+ (abs(x - value) <= atol+rtol*abs(value))
+
+ The fill_value is set to `value` and the mask is set to ``nomask`` if
+ possible. For integers, consider using ``masked_equal``.
Parameters
----------
x : array_like
- Array to fill.
+ Array to mask.
value : float
Masking value.
- rtol : {float}, optional
+ rtol : float, optional
Tolerance parameter.
- atol : {float}, optional
+ atol : float, optional
Tolerance parameter (1e-8).
copy : {True, False}, optional
- Whether to return a copy of x.
+ Whether to return a copy of `x`.
shrink : {True, False}, optional
- Whether to collapse a mask full of False to nomask
+ Whether to collapse a mask full of False to ``nomask``
+
+ Returns
+ -------
+ result : MaskedArray
+ The result of masking `x` where approximately equal to `value`.
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+ masked_equal : Mask where equal to a given value (integers).
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> x = np.array([1, 1.1, 2, 1.1, 3])
+ >>> ma.masked_values(x, 1.1)
+ masked_array(data = [1.0 -- 2.0 -- 3.0],
+ mask = [False True False True False],
+ fill_value=1.1)
+
+ Note that `mask` is set to ``nomask`` if possible.
+
+ >>> ma.masked_values(x, 1.5)
+ masked_array(data = [ 1. 1.1 2. 1.1 3. ],
+ mask = False,
+ fill_value=1.5)
+
+ For integers, the fill value will be different in general to the
+ result of ``masked_equal``.
+
+ >>> x = np.arange(5)
+ >>> x
+ array([0, 1, 2, 3, 4])
+ >>> ma.masked_values(x, 2)
+ masked_array(data = [0 1 -- 3 4],
+ mask = [False False True False False],
+ fill_value=2)
+ >>> ma.masked_equal(x, 2)
+ masked_array(data = [0 1 -- 3 4],
+ mask = [False False True False False],
+ fill_value=999999)
"""
mabs = umath.absolute
@@ -1300,8 +1947,29 @@ def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True, shrink=True):
def masked_invalid(a, copy=True):
"""
- Mask the array for invalid values (NaNs or infs).
- Any preexisting mask is conserved.
+ Mask an array where invalid values occur (NaNs or infs).
+
+ This function is a shortcut to ``masked_where``, with
+ `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
+ Only applies to arrays with a dtype where NaNs or infs make sense
+ (i.e. floating point types), but accepts any array_like object.
+
+ See Also
+ --------
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.arange(5, dtype=np.float)
+ >>> a[2] = np.NaN
+ >>> a[3] = np.PINF
+ >>> a
+ array([ 0., 1., NaN, Inf, 4.])
+ >>> ma.masked_invalid(a)
+ masked_array(data = [0.0 1.0 -- -- 4.0],
+ mask = [False False True True False],
+ fill_value=1e+20)
"""
a = np.array(a, copy=copy, subok=True)
@@ -2305,31 +2973,57 @@ class MaskedArray(ndarray):
def compress(self, condition, axis=None, out=None):
"""
- Return `a` where condition is ``True``.
- If condition is a `MaskedArray`, missing values are considered as ``False``.
+ Return `a` where condition is ``True``.
- Parameters
- ----------
- condition : var
- Boolean 1-d array selecting which entries to return. If len(condition)
- is less than the size of a along the axis, then output is truncated
- to length of condition array.
- axis : {None, int}, optional
- Axis along which the operation must be performed.
- out : {None, ndarray}, optional
- Alternative output array in which to place the result. It must have
- the same shape as the expected output but the type will be cast if
- necessary.
+ If condition is a `MaskedArray`, missing values are considered
+ as ``False``.
- Returns
- -------
- result : MaskedArray
- A :class:`MaskedArray` object.
+ Parameters
+ ----------
+ condition : var
+ Boolean 1-d array selecting which entries to return. If len(condition)
+ is less than the size of a along the axis, then output is truncated
+ to length of condition array.
+ axis : {None, int}, optional
+ Axis along which the operation must be performed.
+ out : {None, ndarray}, optional
+ Alternative output array in which to place the result. It must have
+ the same shape as the expected output but the type will be cast if
+ necessary.
- Warnings
- --------
- Please note the difference with :meth:`compressed` !
- The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not.
+ Returns
+ -------
+ result : MaskedArray
+ A :class:`MaskedArray` object.
+
+ Notes
+ -----
+ Please note the difference with :meth:`compressed` !
+ The output of :meth:`compress` has a mask, the output of
+ :meth:`compressed` does not.
+
+ Examples
+ --------
+ >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
+ >>> print x
+ [[1 -- 3]
+ [-- 5 --]
+ [7 -- 9]]
+ >>> x.compress([1, 0, 1])
+ masked_array(data = [1 3],
+ mask = [False False],
+ fill_value=999999)
+
+ >>> x.compress([1, 0, 1], axis=1)
+ masked_array(data =
+ [[1 3]
+ [-- --]
+ [7 9]],
+ mask =
+ [[False False]
+ [ True True]
+ [False False]],
+ fill_value=999999)
"""
# Get the basic components
@@ -3792,7 +4486,7 @@ class MaskedArray(ndarray):
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
- >>> print x.torecords()
+ >>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
@@ -3880,7 +4574,54 @@ def _mareconstruct(subtype, baseclass, baseshape, basetype,):
#---- --- Shortcuts ---
#####---------------------------------------------------------------------------
def isMaskedArray(x):
- "Is x a masked array, that is, an instance of MaskedArray?"
+ """
+ Test whether input is an instance of MaskedArray.
+
+ This function returns True if `x` is an instance of MaskedArray
+ and returns False otherwise. Any object is accepted as input.
+
+ Parameters
+ ----------
+ x : object
+ Object to test.
+
+ Returns
+ -------
+ result : bool
+ True if `x` is a MaskedArray.
+
+ See Also
+ --------
+ isMA : Alias to isMaskedArray.
+ isarray : Alias to isMaskedArray.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.eye(3, 3)
+ >>> a
+ array([[ 1., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]])
+ >>> m = ma.masked_values(a, 0)
+ >>> m
+ masked_array(data =
+ [[1.0 -- --]
+ [-- 1.0 --]
+ [-- -- 1.0]],
+ mask =
+ [[False True True]
+ [ True False True]
+ [ True True False]],
+ fill_value=0.0)
+ >>> ma.isMaskedArray(a)
+ False
+ >>> ma.isMaskedArray(m)
+ True
+ >>> ma.isMaskedArray([0, 1, 2])
+ False
+
+ """
return isinstance(x, MaskedArray)
isarray = isMaskedArray
isMA = isMaskedArray #backward compatibility
@@ -3910,7 +4651,50 @@ def array(data, dtype=None, copy=False, order=False,
array.__doc__ = masked_array.__doc__
def is_masked(x):
- """Does x have masked values?"""
+ """
+ Determine whether input has masked values.
+
+ Accepts any object as input, but always returns False unless the
+ input is a MaskedArray containing masked values.
+
+ Parameters
+ ----------
+ x : array_like
+ Array to check for masked values.
+
+ Returns
+ -------
+ result : bool
+ True if `x` is a MaskedArray with masked values, False otherwise.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
+ >>> x
+ masked_array(data = [-- 1 -- 2 3],
+ mask = [ True False True False False],
+ fill_value=999999)
+ >>> ma.is_masked(x)
+ True
+ >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
+ >>> x
+ masked_array(data = [0 1 0 2 3],
+ mask = False,
+ fill_value=999999)
+ >>> ma.is_masked(x)
+ False
+
+ Always returns False if `x` isn't a MaskedArray.
+
+ >>> x = [False, True, False]
+ >>> ma.is_masked(x)
+ False
+ >>> x = 'a string'
+ >>> ma.is_masked(x)
+ False
+
+ """
m = getmask(x)
if m is nomask:
return False
@@ -4629,23 +5413,24 @@ def allclose (a, b, masked_equal=True, rtol=1.e-5, atol=1.e-8, fill_value=None):
"""
Returns True if two arrays are element-wise equal within a tolerance.
- The tolerance values are positive, typically very small numbers. The
- relative difference (`rtol` * `b`) and the absolute difference (`atol`)
- are added together to compare against the absolute difference between `a`
- and `b`.
+ This function is equivalent to `allclose` except that masked values
+ are treated as equal (default) or unequal, depending on the `masked_equal`
+ argument.
Parameters
----------
a, b : array_like
Input arrays to compare.
- fill_value : boolean, optional
- Whether masked values in a or b are considered equal (True) or not
- (False).
-
+ masked_equal : boolean, optional
+ Whether masked values in `a` and `b` are considered equal (True) or not
+ (False). They are considered equal by default.
rtol : Relative tolerance
The relative difference is equal to `rtol` * `b`.
atol : Absolute tolerance
The absolute difference is equal to `atol`.
+ fill_value : boolean, optional
+ *Deprecated* - Whether masked values in a or b are considered equal
+ (True) or not (False).
Returns
-------
@@ -4656,7 +5441,8 @@ def allclose (a, b, masked_equal=True, rtol=1.e-5, atol=1.e-8, fill_value=None):
See Also
--------
- all, any, alltrue, sometrue
+ all, any
+ numpy.allclose : the non-masked allclose
Notes
-----
@@ -4668,6 +5454,32 @@ def allclose (a, b, masked_equal=True, rtol=1.e-5, atol=1.e-8, fill_value=None):
Return True if all elements of a and b are equal subject to
given tolerances.
+ Examples
+ --------
+ >>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
+ >>> a
+ masked_array(data = [10000000000.0 1e-07 --],
+ mask = [False False True],
+ fill_value = 1e+20)
+ >>> b = ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
+ >>> ma.allclose(a, b)
+ False
+ >>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
+ >>> b = ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
+ >>> ma.allclose(a, b)
+ True
+ >>> ma.allclose(a, b, masked_equal=False)
+ False
+
+ Masked values are not compared directly.
+
+ >>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
+ >>> b = ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
+ >>> ma.allclose(a, b)
+ True
+ >>> ma.allclose(a, b, masked_equal=False)
+ False
+
"""
if fill_value is not None:
warnings.warn("The use of fill_value is deprecated."\
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
index b2f06ea6c..f30f73ab3 100644
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -67,13 +67,50 @@ def count_masked(arr, axis=None):
return m.sum(axis)
def masked_all(shape, dtype=float):
- """Return an empty masked array of the given shape and dtype,
- where all the data are masked.
+ """
+ Empty masked array with all elements masked.
+
+ Return an empty masked array of the given shape and dtype, where all the
+ data are masked.
Parameters
----------
- dtype : dtype, optional
- Data type of the output.
+ shape : tuple
+ Shape of the required MaskedArray.
+ dtype : dtype, optional
+ Data type of the output.
+
+ Returns
+ -------
+ a : MaskedArray
+ A masked array with all data masked.
+
+ See Also
+ --------
+ masked_all_like : Empty masked array modelled on an existing array.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> ma.masked_all((3, 3))
+ masked_array(data =
+ [[-- -- --]
+ [-- -- --]
+ [-- -- --]],
+ mask =
+ [[ True True True]
+ [ True True True]
+ [ True True True]],
+ fill_value=1e+20)
+
+ The `dtype` parameter defines the underlying data type.
+
+ >>> a = ma.masked_all((3, 3))
+ >>> a.dtype
+ dtype('float64')
+ >>> a = ma.masked_all((3, 3), dtype=np.int32)
+ >>> a.dtype
+ dtype('int32')
"""
a = masked_array(np.empty(shape, dtype),
@@ -81,8 +118,53 @@ def masked_all(shape, dtype=float):
return a
def masked_all_like(arr):
- """Return an empty masked array of the same shape and dtype as
- the array `a`, where all the data are masked.
+ """
+ Empty masked array with the properties of an existing array.
+
+ Return an empty masked array of the same shape and dtype as
+ the array `arr`, where all the data are masked.
+
+ Parameters
+ ----------
+ arr : ndarray
+ An array describing the shape and dtype of the required MaskedArray.
+
+ Returns
+ -------
+ a : MaskedArray
+ A masked array with all data masked.
+
+ Raises
+ ------
+ AttributeError
+ If `arr` doesn't have a shape attribute (i.e. not an ndarray)
+
+ See Also
+ --------
+ masked_all : Empty masked array with all elements masked.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> arr = np.zeros((2, 3), dtype=np.float32)
+ >>> arr
+ array([[ 0., 0., 0.],
+ [ 0., 0., 0.]], dtype=float32)
+ >>> ma.masked_all_like(arr)
+ masked_array(data =
+ [[-- -- --]
+ [-- -- --]],
+ mask =
+ [[ True True True]
+ [ True True True]],
+ fill_value=1e+20)
+
+ The dtype of the masked array matches the dtype of `arr`.
+
+ >>> arr.dtype
+ dtype('float32')
+ >>> ma.masked_all_like(arr).dtype
+ dtype('float32')
"""
a = np.empty_like(arr).view(MaskedArray)
@@ -501,23 +583,77 @@ def compress_cols(a):
def mask_rowcols(a, axis=None):
"""
+ Mask rows and/or columns of a 2D array that contain masked values.
+
Mask whole rows and/or columns of a 2D array that contain
- masked values. The masking behavior is selected with the
+ masked values. The masking behavior is selected using the
`axis` parameter.
- - If axis is None, rows and columns are masked.
- - If axis is 0, only rows are masked.
- - If axis is 1 or -1, only columns are masked.
+ - If `axis` is None, rows *and* columns are masked.
+ - If `axis` is 0, only rows are masked.
+ - If `axis` is 1 or -1, only columns are masked.
Parameters
----------
+ a : array_like, MaskedArray
+ The array to mask. If not a MaskedArray instance (or if no array
+ elements are masked). The result is a MaskedArray with `mask` set
+ to `nomask` (False). Must be a 2D array.
axis : int, optional
- Axis along which to perform the operation.
- If None, applies to a flattened version of the array.
+ Axis along which to perform the operation. If None, applies to a
+ flattened version of the array.
Returns
-------
- a *pure* ndarray.
+ a : MaskedArray
+ A modified version of the input array, masked depending on the value
+ of the `axis` parameter.
+
+ Raises
+ ------
+ NotImplementedError
+ If input array `a` is not 2D.
+
+ See Also
+ --------
+ mask_rows : Mask rows of a 2D array that contain masked values.
+ mask_cols : Mask cols of a 2D array that contain masked values.
+ masked_where : Mask where a condition is met.
+
+ Notes
+ -----
+ The input array's mask is modified by this function.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.zeros((3, 3), dtype=np.int)
+ >>> a[1, 1] = 1
+ >>> a
+ array([[0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]])
+ >>> a = ma.masked_equal(a, 1)
+ >>> a
+ masked_array(data =
+ [[0 0 0]
+ [0 -- 0]
+ [0 0 0]],
+ mask =
+ [[False False False]
+ [False True False]
+ [False False False]],
+ fill_value=999999)
+ >>> ma.mask_rowcols(a)
+ masked_array(data =
+ [[0 -- 0]
+ [-- -- --]
+ [0 -- 0]],
+ mask =
+ [[False True False]
+ [ True True True]
+ [False True False]],
+ fill_value=999999)
"""
a = asarray(a)
@@ -537,26 +673,90 @@ def mask_rowcols(a, axis=None):
def mask_rows(a, axis=None):
"""
- Mask whole rows of a 2D array that contain masked values.
+ Mask rows of a 2D array that contain masked values.
- Parameters
- ----------
- axis : int, optional
- Axis along which to perform the operation.
- If None, applies to a flattened version of the array.
+ This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0.
+
+ See Also
+ --------
+ mask_rowcols : Mask rows and/or columns of a 2D array.
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.zeros((3, 3), dtype=np.int)
+ >>> a[1, 1] = 1
+ >>> a
+ array([[0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]])
+ >>> a = ma.masked_equal(a, 1)
+ >>> a
+ masked_array(data =
+ [[0 0 0]
+ [0 -- 0]
+ [0 0 0]],
+ mask =
+ [[False False False]
+ [False True False]
+ [False False False]],
+ fill_value=999999)
+ >>> ma.mask_rows(a)
+ masked_array(data =
+ [[0 0 0]
+ [-- -- --]
+ [0 0 0]],
+ mask =
+ [[False False False]
+ [ True True True]
+ [False False False]],
+ fill_value=999999)
"""
return mask_rowcols(a, 0)
def mask_cols(a, axis=None):
"""
- Mask whole columns of a 2D array that contain masked values.
+ Mask columns of a 2D array that contain masked values.
- Parameters
- ----------
- axis : int, optional
- Axis along which to perform the operation.
- If None, applies to a flattened version of the array.
+ This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.
+
+ See Also
+ --------
+ mask_rowcols : Mask rows and/or columns of a 2D array.
+ masked_where : Mask where a condition is met.
+
+ Examples
+ --------
+ >>> import numpy.ma as ma
+ >>> a = np.zeros((3, 3), dtype=np.int)
+ >>> a[1, 1] = 1
+ >>> a
+ array([[0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]])
+ >>> a = ma.masked_equal(a, 1)
+ >>> a
+ masked_array(data =
+ [[0 0 0]
+ [0 -- 0]
+ [0 0 0]],
+ mask =
+ [[False False False]
+ [False True False]
+ [False False False]],
+ fill_value=999999)
+ >>> ma.mask_cols(a)
+ masked_array(data =
+ [[0 -- 0]
+ [0 -- 0]
+ [0 -- 0]],
+ mask =
+ [[False True False]
+ [False True False]
+ [False True False]],
+ fill_value=999999)
"""
return mask_rowcols(a, 1)
diff --git a/numpy/random/mtrand/mtrand.pyx b/numpy/random/mtrand/mtrand.pyx
index 7ac9fc12c..b3b676b9c 100644
--- a/numpy/random/mtrand/mtrand.pyx
+++ b/numpy/random/mtrand/mtrand.pyx
@@ -583,9 +583,22 @@ cdef class RandomState:
"""
get_state()
- Return a tuple representing the internal state of the generator::
+ Return a tuple representing the internal state of the generator.
- ('MT19937', int key[624], int pos, int has_gauss, float cached_gaussian)
+ Returns
+ -------
+ out : tuple(string, list of 624 integers, int, int, float)
+ The returned tuple has the following items:
+
+ 1. the string 'MT19937'
+ 2. a list of 624 integer keys
+ 3. an integer pos
+ 4. an integer has_gauss
+ 5. and a float cached_gaussian
+
+ See Also
+ --------
+ set_state
"""
cdef ndarray state "arrayObject_state"
@@ -601,8 +614,28 @@ cdef class RandomState:
Set the state from a tuple.
- state = ('MT19937', int key[624], int pos, int has_gauss, float cached_gaussian)
+ Parameters
+ ----------
+ state : tuple(string, list of 624 ints, int, int, float)
+ The `state` tuple is made up of
+
+ 1. the string 'MT19937'
+ 2. a list of 624 integer keys
+ 3. an integer pos
+ 4. an integer has_gauss
+ 5. and a float for the cached_gaussian
+
+ Returns
+ -------
+ out : None
+ Returns 'None' on success.
+
+ See Also
+ --------
+ get_state
+ Notes
+ -----
For backwards compatibility, the following form is also accepted
although it is missing some information about the cached Gaussian value.
@@ -649,6 +682,16 @@ cdef class RandomState:
Return random floats in the half-open interval [0.0, 1.0).
+ Parameters
+ ----------
+ size : shape tuple, optional
+ Defines the shape of the returned array of random floats.
+
+ Returns
+ -------
+ out : ndarray, floats
+ Array of random of floats with shape of `size`.
+
"""
return cont0_array(self.internal_state, rk_double, size)
@@ -911,7 +954,19 @@ cdef class RandomState:
"""
standard_normal(size=None)
- Standard Normal distribution (mean=0, stdev=1).
+ Returns samples from a Standard Normal distribution (mean=0, stdev=1).
+
+ Parameters
+ ----------
+ size : int, shape tuple, optional
+ Returns the number of samples required to satisfy the `size` parameter.
+ If not given or 'None' indicates to return one sample.
+
+ Returns
+ -------
+ out : float, ndarray
+ Samples the Standard Normal distribution with a shape satisfying the
+ `size` parameter.
"""
return cont0_array(self.internal_state, rk_gauss, size)
@@ -1083,10 +1138,12 @@ cdef class RandomState:
Its probability density function is
- .. math:: f(x; \\lambda) = \\lambda \\exp(-\\lambda x),
+ .. math:: f(x; \\frac{1}{\\beta}) = \\frac{1}{\\beta} \\exp(-\\frac{x}{\\beta}),
- for ``x > 0`` and 0 elsewhere. :math:`lambda` is
- known as the rate parameter.
+ for ``x > 0`` and 0 elsewhere. :math:`\\beta` is the scale parameter,
+ which is the inverse of the rate parameter :math:`\\lambda = 1/\\beta`.
+ The rate parameter is an alternative, widely used parameterization
+ of the exponential distribution [3]_.
The exponential distribution is a continuous analogue of the
geometric distribution. It describes many common situations, such as
@@ -1096,7 +1153,7 @@ cdef class RandomState:
Parameters
----------
scale : float
- The rate parameter, :math:`\\lambda`.
+ The scale parameter, :math:`\\beta = 1/\\lambda`.
size : tuple of ints
Number of samples to draw. The output is shaped
according to `size`.
@@ -1107,6 +1164,8 @@ cdef class RandomState:
Random Signal Principles", 4th ed, 2001, p. 57.
.. [2] "Poisson Process", Wikipedia,
http://en.wikipedia.org/wiki/Poisson_process
+ .. [3] "Exponential Distribution, Wikipedia,
+ http://en.wikipedia.org/wiki/Exponential_distribution
"""
cdef ndarray oscale
@@ -1800,11 +1859,11 @@ cdef class RandomState:
>>> import matplotlib.pyplot as plt
>>> def weib(x,n,a):
- ... return (a/n)*(x/n)**(a-1)*exp(-(x/n)**a)
+ ... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
- >>> count, bins, ignored = plt.hist(numpy.random.weibull(5.,1000))
+ >>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
+ >>> x = np.arange(1,100.)/50.
>>> scale = count.max()/weib(x, 1., 5.).max()
- >>> x = arange(1,100.)/50.
>>> plt.plot(x, weib(x, 1., 5.)*scale)
>>> plt.show()
diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py
index 4489881eb..4f46e76b3 100644
--- a/numpy/testing/utils.py
+++ b/numpy/testing/utils.py
@@ -158,12 +158,11 @@ def assert_equal(actual,desired,err_msg='',verbose=True):
Examples
--------
- >>> np.testing.assert_equal([4,5], [4,6]) # doctest:+ELLIPSIS
+ >>> np.testing.assert_equal([4,5], [4,6])
...
<type 'exceptions.AssertionError'>:
Items are not equal:
item=1
- <BLANKLINE>
ACTUAL: 5
DESIRED: 6
@@ -204,11 +203,59 @@ def print_assert_equal(test_string,actual,desired):
raise AssertionError(msg.getvalue())
def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
- """ Raise an assertion if two items are not equal.
-
- I think this should be part of unittest.py
+ """
+ Raise an assertion if two items are not equal up to desired precision.
The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal)
+
+ Given two objects (numbers or ndarrays), check that all elements of these
+ objects are almost equal. An exception is raised at conflicting values.
+ For ndarrays this delegates to assert_array_almost_equal
+
+ Parameters
+ ----------
+ actual : number or ndarray
+ The object to check.
+ desired : number or ndarray
+ The expected object.
+ decimal : integer (decimal=7)
+ desired precision
+ err_msg : string
+ The error message to be printed in case of failure.
+ verbose : bool
+ If True, the conflicting values are appended to the error message.
+
+ Raises
+ ------
+ AssertionError
+ If actual and desired are not equal up to specified precision.
+
+ See Also
+ --------
+ assert_array_almost_equal: compares array_like objects
+ assert_equal: tests objects for equality
+
+
+ Examples
+ --------
+ >>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
+ >>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
+ ...
+ <type 'exceptions.AssertionError'>:
+ Items are not equal:
+ ACTUAL: 2.3333333333333002
+ DESIRED: 2.3333333399999998
+
+ >>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
+ \t\t\tnp.array([1.0,2.33333334]), decimal=9)
+ ...
+ <type 'exceptions.AssertionError'>:
+ Arrays are not almost equal
+ <BLANKLINE>
+ (mismatch 50.0%)
+ x: array([ 1. , 2.33333333])
+ y: array([ 1. , 2.33333334])
+
"""
from numpy.core import ndarray
if isinstance(actual, ndarray) or isinstance(desired, ndarray):
@@ -219,10 +266,56 @@ def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
- """ Raise an assertion if two items are not
- equal. I think this should be part of unittest.py
- Approximately equal is defined as the number of significant digits
- correct
+ """
+ Raise an assertion if two items are not equal up to significant digits.
+
+ Given two numbers, check that they are approximately equal.
+ Approximately equal is defined as the number of significant digits
+ that agree.
+
+ Parameters
+ ----------
+ actual : number
+ The object to check.
+ desired : number
+ The expected object.
+ significant : integer (significant=7)
+ desired precision
+ err_msg : string
+ The error message to be printed in case of failure.
+ verbose : bool
+ If True, the conflicting values are appended to the error message.
+
+ Raises
+ ------
+ AssertionError
+ If actual and desired are not equal up to specified precision.
+
+ See Also
+ --------
+ assert_almost_equal: compares objects by decimals
+ assert_array_almost_equal: compares array_like objects by decimals
+ assert_equal: tests objects for equality
+
+
+ Examples
+ --------
+ >>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
+ >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
+ significant=8)
+ >>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
+ significant=8)
+ ...
+ <type 'exceptions.AssertionError'>:
+ Items are not equal to 8 significant digits:
+ ACTUAL: 1.234567e-021
+ DESIRED: 1.2345672000000001e-021
+
+ the evaluated condition that raises the exception is
+
+ >>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
+ True
+
"""
import math
actual, desired = map(float, (actual, desired))
@@ -306,10 +399,133 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True,
raise ValueError(msg)
def assert_array_equal(x, y, err_msg='', verbose=True):
+ """
+ Raise an assertion if two array_like objects are not equal.
+
+ Given two array_like objects, check that the shape is equal and all
+ elements of these objects are equal. An exception is raised at
+ shape mismatch or conflicting values. In contrast to the standard usage
+ in numpy, NaNs are compared like numbers, no assertion is raised if
+ both objects have NaNs in the same positions.
+
+ The usual caution for verifying equality with floating point numbers is
+ advised.
+
+ Parameters
+ ----------
+ x : array_like
+ The actual object to check.
+ y : array_like
+ The desired, expected object.
+ err_msg : string
+ The error message to be printed in case of failure.
+ verbose : bool
+ If True, the conflicting values are appended to the error message.
+
+ Raises
+ ------
+ AssertionError
+ If actual and desired objects are not equal.
+
+ See Also
+ --------
+ assert_array_almost_equal: test objects for equality up to precision
+ assert_equal: tests objects for equality
+
+
+ Examples
+ --------
+ the first assert does not raise an exception
+
+ >>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
+ \t\t\t[np.exp(0),2.33333, np.nan])
+
+ assert fails with numerical inprecision with floats
+
+ >>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
+ \t\t\t[1, np.sqrt(np.pi)**2, np.nan])
+ ...
+ <type 'exceptions.ValueError'>:
+ AssertionError:
+ Arrays are not equal
+ <BLANKLINE>
+ (mismatch 50.0%)
+ x: array([ 1. , 3.14159265, NaN])
+ y: array([ 1. , 3.14159265, NaN])
+
+ use assert_array_almost_equal for these cases instead
+
+ >>> np.testing.assert_array_almost_equal([1.0,np.pi,np.nan],
+ \t\t\t[1, np.sqrt(np.pi)**2, np.nan], decimal=15)
+
+ """
assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
verbose=verbose, header='Arrays are not equal')
def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
+ """
+ Raise an assertion if two objects are not equal up to desired precision.
+
+ The test verifies identical shapes and verifies values with
+ abs(desired-actual) < 0.5 * 10**(-decimal)
+
+ Given two array_like objects, check that the shape is equal and all
+ elements of these objects are almost equal. An exception is raised at
+ shape mismatch or conflicting values. In contrast to the standard usage
+ in numpy, NaNs are compared like numbers, no assertion is raised if
+ both objects have NaNs in the same positions.
+
+ Parameters
+ ----------
+ x : array_like
+ The actual object to check.
+ y : array_like
+ The desired, expected object.
+ decimal : integer (decimal=6)
+ desired precision
+ err_msg : string
+ The error message to be printed in case of failure.
+ verbose : bool
+ If True, the conflicting values are appended to the error message.
+
+ Raises
+ ------
+ AssertionError
+ If actual and desired are not equal up to specified precision.
+
+ See Also
+ --------
+ assert_almost_equal: simple version for comparing numbers
+ assert_array_equal: tests objects for equality
+
+
+ Examples
+ --------
+ the first assert does not raise an exception
+
+ >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
+ [1.0,2.333,np.nan])
+
+ >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
+ \t\t\t[1.0,2.33339,np.nan], decimal=5)
+ ...
+ <type 'exceptions.AssertionError'>:
+ AssertionError:
+ Arrays are not almost equal
+ <BLANKLINE>
+ (mismatch 50.0%)
+ x: array([ 1. , 2.33333, NaN])
+ y: array([ 1. , 2.33339, NaN])
+
+ >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
+ \t\t\t[1.0,2.33333, 5], decimal=5)
+ <type 'exceptions.ValueError'>:
+ ValueError:
+ Arrays are not almost equal
+ x: array([ 1. , 2.33333, NaN])
+ y: array([ 1. , 2.33333, 5. ])
+
+ """
from numpy.core import around, number, float_
from numpy.lib import issubdtype
def compare(x, y):
@@ -321,6 +537,70 @@ def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
header='Arrays are not almost equal')
def assert_array_less(x, y, err_msg='', verbose=True):
+ """
+ Raise an assertion if two array_like objects are not ordered by less than.
+
+ Given two array_like objects, check that the shape is equal and all
+ elements of the first object are strictly smaller than those of the
+ second object. An exception is raised at shape mismatch or incorrectly
+ ordered values. Shape mismatch does not raise if an object has zero
+ dimension. In contrast to the standard usage in numpy, NaNs are
+ compared, no assertion is raised if both objects have NaNs in the same
+ positions.
+
+
+
+ Parameters
+ ----------
+ x : array_like
+ The smaller object to check.
+ y : array_like
+ The larger object to compare.
+ err_msg : string
+ The error message to be printed in case of failure.
+ verbose : bool
+ If True, the conflicting values are appended to the error message.
+
+ Raises
+ ------
+ AssertionError
+ If actual and desired objects are not equal.
+
+ See Also
+ --------
+ assert_array_equal: tests objects for equality
+ assert_array_almost_equal: test objects for equality up to precision
+
+
+
+ Examples
+ --------
+ >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
+ >>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
+ ...
+ <type 'exceptions.ValueError'>:
+ Arrays are not less-ordered
+ (mismatch 50.0%)
+ x: array([ 1., 1., NaN])
+ y: array([ 1., 2., NaN])
+
+ >>> np.testing.assert_array_less([1.0, 4.0], 3)
+ ...
+ <type 'exceptions.ValueError'>:
+ Arrays are not less-ordered
+ (mismatch 50.0%)
+ x: array([ 1., 4.])
+ y: array(3)
+
+ >>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
+ ...
+ <type 'exceptions.ValueError'>:
+ Arrays are not less-ordered
+ (shapes (3,), (1,) mismatch)
+ x: array([ 1., 2., 3.])
+ y: array([4])
+
+ """
assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,
verbose=verbose,
header='Arrays are not less-ordered')
@@ -398,6 +678,17 @@ def raises(*args,**kwargs):
return nose.tools.raises(*args,**kwargs)
def assert_raises(*args,**kwargs):
+ """
+ assert_raises(excecption_class, callable, *args, **kwargs)
+
+ Fail unless an exception of class exception_class is thrown
+ by callable when invoked with arguments args and keyword
+ arguments kwargs. If a different type of exception is
+ thrown, it will not be caught, and the test case will be
+ deemed to have suffered an error, exactly as for an
+ unexpected exception.
+
+ """
nose = import_nose()
return nose.tools.assert_raises(*args,**kwargs)