diff options
Diffstat (limited to 'numpy')
35 files changed, 3544 insertions, 993 deletions
diff --git a/numpy/__init__.py b/numpy/__init__.py index 119cb44cf..90f9e687c 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -30,13 +30,18 @@ Use the built-in ``help`` function to view a function's docstring:: >>> help(np.sort) -For some objects, ``np.info(obj)`` may provide additional help. +For some objects, ``np.info(obj)`` may provide additional help. This is +particularly true if you see the line "Help on ufunc object:" at the top +of the help() page. Ufuncs are implemented in C, not Python, for speed. +The native Python help() does not know how to view their help, but our +np.info() function does. -To search for objects of which the documentation contains keywords, do:: +To search for documents containing a keyword, do:: >>> np.lookfor('keyword') -Topical documentation is available under the ``doc`` sub-module:: +General-purpose documents like a glossary and help on the basic concepts +of numpy are available under the ``doc`` sub-module:: >>> from numpy import doc >>> help(doc) @@ -87,10 +92,10 @@ the source code). Copies vs. in-place operation ----------------------------- -Most of the methods in `numpy` return a copy of the array argument (e.g., -`sort`). In-place versions of these methods are often available as -array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. Exceptions to -this rule are documented. +Most of the functions in `numpy` return a copy of the array argument +(e.g., `sort`). In-place versions of these functions are often +available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. +Exceptions to this rule are documented. """ diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 5826f6c70..cff9e5e03 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -65,11 +65,25 @@ dtype([('surname', '|S25'), ('age', '|u1')]) add_newdoc('numpy.core', 'dtype', """ - Create a data type. + dtype(obj, align=False, copy=False) + + Create a data type object. A numpy array is homogeneous, and contains elements described by a - dtype. A dtype can be constructed from different combinations of - fundamental numeric types, as illustrated below. + dtype object. A dtype object can be constructed from different + combinations of fundamental numeric types. + + Parameters + ---------- + obj + Object to be converted to a data type object. + align : bool, optional + Add padding to the fields to match what a C compiler would output + for a similar C-struct. Can be ``True`` only if `obj` is a dictionary + or a comma-separated string. + copy : bool, optional + Make a new copy of the data-type object. If ``False``, the result + may just be a reference to a built-in data-type object. Examples -------- @@ -228,7 +242,7 @@ add_newdoc('numpy.core.multiarray', 'array', Parameters ---------- - object : array-like + object : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. @@ -752,15 +766,16 @@ add_newdoc('numpy.core.multiarray', 'arange', Values are generated within the half-open interval ``[start, stop)`` (in other words, the interval including `start` but excluding `stop`). - For integer arguments, the function is equivalent to ``range`` - (but returns an array). + For integer arguments the function is equivalent to the Python built-in + `range <http://docs.python.org/lib/built-in-funcs.html>`_ function, + but returns a ndarray rather than a list. Parameters ---------- start : number, optional Start of interval. The interval includes this value. The default start value is 0. - end : number + stop : number End of interval. The interval does not include this value. step : number, optional Spacing between values. For any output `out`, this is the distance @@ -782,7 +797,6 @@ add_newdoc('numpy.core.multiarray', 'arange', See Also -------- - range : The Python equivalent for integers linspace : Evenly spaced numbers with careful handling of endpoints. ogrid: Arrays of evenly spaced numbers in N-dimensions mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions @@ -913,7 +927,7 @@ add_newdoc('numpy.core.multiarray', 'where', See Also -------- - nonzero + nonzero, choose Notes ----- @@ -964,18 +978,19 @@ add_newdoc('numpy.core.multiarray', 'lexsort', 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. - axis : integer, optional + axis : int, optional Axis to be indirectly sorted. By default, sort over the last axis. Returns ------- - indices : (N,) integer array + indices : (N,) ndarray of ints Array of indices that sort the keys along the specified axis. See Also -------- argsort : Indirect sort. - sort : In-place sort. + ndarray.sort : In-place sort. + sort : Return a sorted copy of an array. Examples -------- @@ -1255,7 +1270,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype', add_newdoc('numpy.core.multiarray', 'ndarray', ('imag', """ - Imaginary part of the array. + The imaginary part of the array. Examples -------- @@ -1285,7 +1300,52 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize', add_newdoc('numpy.core.multiarray', 'ndarray', ('flags', - """Special object providing array flags. + """ + Information about the memory layout of the array. + + Attributes + ---------- + C_CONTIGUOUS (C) + The data is in a single, C-style contiguous segment. + F_CONTIGUOUS (F) + The data is in a single, Fortran-style contiguous segment. + OWNDATA (O) + The array owns the memory it uses or borrows it from another object. + WRITEABLE (W) + The data area can be written to. + ALIGNED (A) + The data and strides are aligned appropriately for the hardware. + UPDATEIFCOPY (U) + This array is a copy of some other array. When this array is + deallocated, the base array will be updated with the contents of + this array. + + FNC + F_CONTIGUOUS and not C_CONTIGUOUS. + FORC + F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). + BEHAVED (B) + ALIGNED and WRITEABLE. + CARRAY (CA) + BEHAVED and C_CONTIGUOUS. + FARRAY (FA) + BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. + + Notes + ----- + The `flags` object can be also accessed dictionary-like, and using + lowercased attribute names. Short flag names are only supported in + dictionary access. + + Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by + the user, via assigning to ``flags['FLAGNAME']`` or `ndarray.setflags`. + The array flags cannot be set arbitrarily: + + - UPDATEIFCOPY can only be set ``False``. + - ALIGNED can only be set ``True`` if the data is truly aligned. + - WRITEABLE can only be set ``True`` if the array owns its own memory + or the ultimate owner of the memory exposes a writeable buffer + interface or is a string. """)) @@ -1340,7 +1400,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim', add_newdoc('numpy.core.multiarray', 'ndarray', ('real', """ - Real part of the array. + The real part of the array. Examples -------- @@ -1500,7 +1560,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('all', """ a.all(axis=None, out=None) - Check if all of the elements of `a` are true. + Returns True if all elements evaluate to True. Refer to `numpy.all` for full documentation. @@ -1542,7 +1602,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax', Returns ------- - index_array : {ndarray, int} + index_array : ndarray An array of indices or single index value, or a reference to `out` if it was specified. @@ -1609,10 +1669,41 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('astype', add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap', - """a.byteswap(False) -> View or copy. Swap the bytes in the array. + """ + a.byteswap(inplace) + + Swap the bytes of the array elements + + Toggle between low-endian and big-endian data representation by + returning a byteswapped array, optionally swapped in-place. + + Parameters + ---------- + inplace: bool, optional + If ``True``, swap bytes in-place, default is ``False``. - Swap the bytes in the array. Return the byteswapped array. If the first - argument is True, byteswap in-place and return a reference to self. + Returns + ------- + out: ndarray + The byteswapped array. If `inplace` is ``True``, this is + a view to self. + + Examples + -------- + >>> A = np.array([1, 256, 8755], dtype=np.int16) + >>> map(hex, A) + ['0x1', '0x100', '0x2233'] + >>> A.byteswap(True) + array([ 256, 1, 13090], dtype=int16) + >>> map(hex, A) + ['0x100', '0x1', '0x3322'] + + Arrays of strings are not swapped + + >>> A = np.array(['ceg', 'fac']) + >>> A.byteswap() + array(['ceg', 'fac'], + dtype='|S3') """)) @@ -1680,7 +1771,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate', add_newdoc('numpy.core.multiarray', 'ndarray', ('copy', """ - a.copy([order]) + a.copy(order='C') Return a copy of the array. @@ -1795,10 +1886,6 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('fill', value : scalar All elements of `a` will be assigned this value. - Returns - ------- - None - Examples -------- >>> a = np.array([1, 2]) @@ -1917,7 +2004,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero', """ a.nonzero() - Return the indices of the elements of a which are not zero. + Return the indices of the elements that are non-zero. Refer to `numpy.nonzero` for full documentation. @@ -1977,10 +2064,12 @@ add_newdoc('numpy.core.multiarray', 'putmask', """ putmask(a, mask, values) - Sets a.flat[n] = values[n] for each n where mask.flat[n] is true. + 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. 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 ---------- @@ -1993,7 +2082,7 @@ add_newdoc('numpy.core.multiarray', 'putmask', See Also -------- - put, take + place, put, take Examples -------- @@ -2050,7 +2139,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape', """ a.reshape(shape, order='C') - Returns an array containing the data of a, but with a new shape. + Returns an array containing the same data with a new shape. Refer to `numpy.reshape` for full documentation. @@ -2167,41 +2256,47 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', Parameters ---------- - axis : integer - Axis to be sorted along. None indicates that the flattened array - should be used. Default is -1. - kind : string - Sorting algorithm to use. Possible values are 'quicksort', - 'mergesort', or 'heapsort'. Default is 'quicksort'. - order : list type or None - When a is an array with fields defined, this argument specifies + axis : int, optional + Axis along which to sort. Default is -1, which means sort along the + last axis. + kind : {'quicksort', 'mergesort', 'heapsort'}, optional + Sorting algorithm. Default is 'quicksort'. + order : list, optional + When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified. See Also -------- - argsort : indirect sort - lexsort : indirect stable sort on multiple keys - searchsorted : find keys in sorted array + numpy.sort : Return a sorted copy of an array. + argsort : Indirect sort. + lexsort : Indirect stable sort on multiple keys. + searchsorted : Find elements in sorted array. Notes ----- - The various sorts are characterized by average speed, worst case - performance, need for work space, and whether they are stable. A stable - sort keeps items with the same key in the same relative order. The three - available algorithms have the following properties: + See ``sort`` for notes on the different sorting algorithms. - =========== ======= ============= ============ ======= - kind speed worst case work space stable - =========== ======= ============= ============ ======= - 'quicksort' 1 O(n^2) 0 no - 'mergesort' 2 O(n*log(n)) ~n/2 yes - 'heapsort' 3 O(n*log(n)) 0 no - =========== ======= ============= ============ ======= + Examples + -------- + >>> a = np.array([[1,4], [3,1]]) + >>> a.sort(axis=1) + >>> a + array([[1, 4], + [1, 3]]) + >>> a.sort(axis=0) + >>> a + array([[1, 3], + [1, 4]]) - All the sort algorithms make temporary copies of the data when the sort is - not along the last axis. Consequently, sorts along the last axis are faster - and use less space than sorts along other axis. + Use the `order` keyword to specify a field to use when sorting a + structured array: + + >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) + >>> a.sort(order='y') + >>> a + array([('c', 1), ('a', 2)], + dtype=[('x', '|S1'), ('y', '<i4')]) """)) @@ -2282,9 +2377,10 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('take', add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile', - """a.tofile(fid, sep="", format="%s") + """ + a.tofile(fid, sep="", format="%s") - Write the data to a file. + Write array to a file as text or binary. Data is always written in 'C' order, independently of the order of `a`. The data produced by this method can be recovered by using the function @@ -2316,19 +2412,23 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', """ a.tolist() - Return the array as a list or nested lists. + Return the array as a possibly nested list. + + Return a copy of the array data as a hierarchical Python list. + Data items are converted to the nearest compatible Python type. Parameters ---------- - a : ndarray - Input array. + none Returns ------- y : list - Copy the data portion of the array to a hierarchical Python list and - return that list. Data items are converted to the nearest compatible - Python type. + The possibly nested list of array elements. + + Notes + ----- + The array may be recreated, ``a = np.array(a.tolist())``. Examples -------- @@ -2336,6 +2436,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', >>> a.tolist() [1, 2] >>> a = np.array([[1, 2], [3, 4]]) + >>> list(a) + [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]] @@ -2465,8 +2567,9 @@ add_newdoc('numpy.core.umath','geterrobj', """) -add_newdoc('numpy.core.umath','seterrobj', - """seterrobj() +add_newdoc('numpy.core.umath', 'seterrobj', + """ + seterrobj(errobj) Used internally by `seterr`. @@ -2481,8 +2584,9 @@ add_newdoc('numpy.core.umath','seterrobj', """) -add_newdoc("numpy.core","ufunc", - """Functions that operate element by element on whole arrays. +add_newdoc('numpy.core', 'ufunc', + """ + Functions that operate element by element on whole arrays. Unary ufuncs: ============= @@ -2492,13 +2596,14 @@ add_newdoc("numpy.core","ufunc", Parameters ---------- - X : array-like - out : array-like + X : array_like + Input array + out : array_like An array to store the output. Must be the same shape as X. Returns ------- - r : array-like + r : array_like r will have the same shape as X; if out is provided, r will be equal to out. @@ -2515,8 +2620,10 @@ add_newdoc("numpy.core","ufunc", Parameters ---------- - X : array-like - Y : array-like + X : array_like + First input array + Y : array_like + Second input array out : array-like An array to store the output. Must be the same shape as the output would have. @@ -2547,21 +2654,21 @@ add_newdoc('numpy.core', 'ufunc', ('reduce', Parameters ---------- - array : array-like + array : array_like The array to act on. - axis : integer + axis : integer, optional The axis along which to apply the reduction. - dtype : {data-type-code, None} + dtype : data-type-code, optional The type used to represent the intermediate results. Defaults to the data type of the output array if this is provided, or the data type of the input array if no output array is provided. - out : {array-like, None} + out : array_like, optional A location into which the result is stored. If not provided a freshly-allocated array is returned. Returns ------- - r : {array, scalar} + r : ndarray The reduced values. If out was supplied, r is equal to out. Examples @@ -2690,14 +2797,14 @@ add_newdoc('numpy.core', 'ufunc', ('outer', Parameters ---------- - A : array-like + A : array_like First term - B : array-like + B : array_like Second term Returns ------- - r : array + r : ndarray Output array Examples diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 8400802f7..98df924e7 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -42,23 +42,23 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, Parameters ---------- - precision : int + precision : int, optional Number of digits of precision for floating point output (default 8). - threshold : int + threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). - edgeitems : int + edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). - linewidth : int + linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). - suppress : bool + suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). - nanstr : string + nanstr : string, optional String representation of floating point not-a-number (default nan). - infstr : string + infstr : string, optional String representation of floating point infinity (default inf). Examples @@ -242,7 +242,8 @@ def array2string(a, max_line_width = None, precision = None, The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements. precision : int, optional - Floating point precision. + Floating point precision. Default is the current printing + precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent very small numbers as zero. separator : string, optional @@ -259,7 +260,7 @@ def array2string(a, max_line_width = None, precision = None, See Also -------- - array_str, array_repr + array_str, array_repr, set_printoptions Examples -------- diff --git a/numpy/core/code_generators/docstrings.py b/numpy/core/code_generators/docstrings.py index 5360d3bc2..882a781a8 100644 --- a/numpy/core/code_generators/docstrings.py +++ b/numpy/core/code_generators/docstrings.py @@ -95,7 +95,7 @@ add_newdoc('numpy.core.umath', 'arccos', Returns ------- - angle : {ndarray, scalar} + angle : ndarray The angle of the ray intersecting the unit circle at the given `x`-coordinate in radians [0, pi]. If `x` is a scalar then a scalar is returned, otherwise an array of the same shape as `x` @@ -156,7 +156,7 @@ add_newdoc('numpy.core.umath', 'arccosh', Returns ------- - out : {ndarray, scalar} + out : ndarray Array of the same shape and dtype as `x`. Notes @@ -198,7 +198,7 @@ add_newdoc('numpy.core.umath', 'arcsin', Returns ------- - angle : {ndarray, scalar} + angle : ndarray The angle of the ray intersecting the unit circle at the given `y`-coordinate in radians ``[-pi, pi]``. If `x` is a scalar then a scalar is returned, otherwise an array is returned. @@ -263,7 +263,7 @@ add_newdoc('numpy.core.umath', 'arcsinh', For real-valued input data types, `arcsinh` always returns real output. For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + returns ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccos` is a complex analytical function that has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from @@ -294,12 +294,12 @@ add_newdoc('numpy.core.umath', 'arctan', Parameters ---------- - x : {array_like, scalar} + x : array_like Input values. `arctan` is applied to each element of `x`. Returns ------- - out : {ndarray, scalar} + out : ndarray Out has the same shape as `x`. Its real part is in ``[-pi/2, pi/2]``. It is a scalar if `x` is a scalar. @@ -363,15 +363,15 @@ add_newdoc('numpy.core.umath', 'arctan2', Parameters ---------- - x1 : array-like, real-valued + x1 : array_like, real-valued y-coordinates. - x2 : array-like, real-valued + x2 : array_like, real-valued x-coordinates. `x2` must be broadcastable to match the shape of `x1`, or vice versa. Returns ------- - angle : array-like + angle : ndarray Array of angles in radians, in the range ``[-pi, pi]``. See Also @@ -726,7 +726,7 @@ add_newdoc('numpy.core.umath', 'conjugate', Returns ------- - y : {ndarray, scalar} + y : ndarray The complex conjugate of `x`, with same dtype as `y`. Examples @@ -793,12 +793,12 @@ add_newdoc('numpy.core.umath', 'degrees', Parameters ---------- - x : array-like + x : array_like Angle in radians. Returns ------- - y : {ndarray, scalar} + y : ndarray The corresponding angle in degrees. @@ -964,7 +964,37 @@ add_newdoc('numpy.core.umath', 'exp', add_newdoc('numpy.core.umath', 'expm1', """ - e**x-1 elementwise. + Return the exponential of the elements in the array minus one. + + Parameters + ---------- + x : array_like + Input values. + + Returns + ------- + out : ndarray + Element-wise exponential minus one: ``out=exp(x)-1``. + + See Also + -------- + log1p : ``log(1+x)``, the inverse of expm1. + + + Notes + ----- + This function provides greater precision than using ``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``: + + >>> np.expm1(1e-10) + 1.00000000005e-10 + >>> np.exp(1e-10) - 1 + 1.000000082740371e-10 """) @@ -1135,7 +1165,7 @@ add_newdoc('numpy.core.umath', 'greater', add_newdoc('numpy.core.umath', 'greater_equal', """ - Returns (x1 >= x2) element-wise. + Element-wise True if first array is greater or equal than second array. Parameters ---------- @@ -1144,12 +1174,12 @@ add_newdoc('numpy.core.umath', 'greater_equal', Returns ------- - Out : {ndarray, bool} - Output array of bools, or a single bool if `x1` and `x2` are scalars. + out : ndarray, bool + Output array. See Also -------- - greater + greater, less, less_equal, equal Examples -------- @@ -1164,17 +1194,16 @@ add_newdoc('numpy.core.umath', 'hypot', Parameters ---------- - x : array-like + x : array_like Base of the triangle. - y : array-like + y : array_like Height of the triangle. Returns ------- - z : {ndarray, scalar} + z : ndarray Hypotenuse of the triangle: sqrt(x**2 + y**2) - Examples -------- >>> np.hypot(3,4) @@ -1277,66 +1306,182 @@ add_newdoc('numpy.core.umath', 'invert', add_newdoc('numpy.core.umath', 'isfinite', """ - Returns True where x is finite, False otherwise. + 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). 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. Returns ------- - y : {ndarray, bool} - array of bools + 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. + + 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). + Notes ----- - `Nan` is considered as non-finite. + Not a Number, positive infinity and negative infinity are considered + to be non-finite. + + 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. + + Errors result if second argument is also supplied with scalar input or + if first and second arguments have different shapes. Examples -------- + >>> np.isfinite(1) + True + >>> np.isfinite(0) + True + >>> np.isfinite(np.nan) + False + >>> np.isfinite(np.inf) + False + >>> np.isfinite(np.NINF) + 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) + array([0, 1, 0]) + >>> y + array([0, 1, 0]) """) add_newdoc('numpy.core.umath', 'isinf', """ - Returns True where x is +inf or -inf, False otherwise. + 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. Parameters ---------- x : array_like input values + y : array_like, optional + An array with the same shape as `x` to store the result. Returns ------- y : {ndarray, bool} - array of bools + 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. + + 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 + + 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. + + Errors result if second argument is also supplied with scalar input or + if first and second arguments have different shapes. + + Numpy's definitions for positive infinity (PINF) and negative infinity + (NINF) may be change in the future versions. Examples -------- + >>> np.isinf(np.inf) + True + >>> np.isinf(np.nan) + False + >>> np.isinf(np.NINF) + 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) + array([1, 0, 1]) + >>> y + array([1, 0, 1]) """) add_newdoc('numpy.core.umath', 'isnan', """ - Returns True where elements are Not-A-Number, False otherwise. + Returns a numpy boolean scalar or array resulting from an element-wise test + for Not a Number (NaN). Parameters ---------- x : array_like - input values. + input data. Returns ------- y : {ndarray, bool} - array of bools + 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 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. + + 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 + + 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 -------- + >>> np.isnan(np.nan) + True + >>> np.isnan(np.inf) + False >>> np.isnan([np.log(-1.),1.,np.log(0)]) array([ True, False, False], dtype=bool) @@ -1344,7 +1489,34 @@ add_newdoc('numpy.core.umath', 'isnan', add_newdoc('numpy.core.umath', 'left_shift', """ - Computes x1 << x2 (x1 shifted to left by x2 bits) elementwise. + Shift the bits of an integer to the left. + + Bits are shifted to the left by appending `x2` 0s at the right of `x1`. + Since the internal representation of numbers is in binary format, this + operation is equivalent to multiplying `x1` by ``2**x2``. + + Parameters + ---------- + x1 : array_like of integer type + Input values. + x2 : array_like of integer type + Number of zeros to append to `x1`. + + Returns + ------- + out : array of integer type + Return `x1` with bits shifted `x2` times to the left. + + See Also + -------- + right_shift : Shift the bits of an integer to the right. + binary_repr : Return the binary representation of the input number + as a string. + + Examples + -------- + >>> np.left_shift(5, [1,2,3]) + array([10, 20, 40]) """) @@ -1354,7 +1526,7 @@ add_newdoc('numpy.core.umath', 'less', Parameters ---------- - x1, x2 : array-like + x1, x2 : array_like Input arrays. Returns @@ -1408,12 +1580,12 @@ add_newdoc('numpy.core.umath', 'log', Parameters ---------- x : array_like - Input value. + Input value. Returns ------- - y : {ndarray, scalar} - The natural logarithm of `x`, element-wise. + y : ndarray + The natural logarithm of `x`, element-wise. See Also -------- @@ -1449,18 +1621,17 @@ add_newdoc('numpy.core.umath', 'log', add_newdoc('numpy.core.umath', 'log10', """ - Compute the logarithm in base 10 elementwise. + Compute the logarithm in base 10 element-wise. Parameters ---------- x : array_like - input values. + Input values. Returns ------- - y : {ndarray, scalar} - base-10 logarithm of `x`. - + y : ndarray + Base-10 logarithm of `x`. Notes ----- @@ -1501,7 +1672,7 @@ add_newdoc('numpy.core.umath', 'log1p', Returns ------- - y : {ndarray, scalar} + y : ndarray Natural logarithm of `1 + x`, elementwise. Notes @@ -1674,13 +1845,79 @@ add_newdoc('numpy.core.umath', 'logical_xor', add_newdoc('numpy.core.umath', 'maximum', """ - Returns maximum (if x1 > x2: x1; else: x2) elementwise. + Element-wise maximum of array elements. + + Compare two arrays and returns a new array containing + the element-wise maxima. + + Parameters + ---------- + x1, x2 : array_like + The arrays holding the elements to be compared. + + Returns + ------- + y : {ndarray, scalar} + The maximum of `x1` and `x2`, element-wise. Returns scalar if + both `x1` and `x2` are scalars. + + See Also + -------- + minimum : + element-wise minimum + + Notes + ----- + Equivalent to ``np.where(x1 > x2, x1, x2)`` but faster and does proper + broadcasting. + + Examples + -------- + >>> np.maximum([2, 3, 4], [1, 5, 2]) + array([2, 5, 4]) + + >>> np.maximum(np.eye(2), [0.5, 2]) + array([[ 1. , 2. ], + [ 0.5, 2. ]]) """) add_newdoc('numpy.core.umath', 'minimum', """ - Returns minimum (if x1 < x2: x1; else: x2) elementwise + Element-wise minimum of array elements. + + Compare two arrays and returns a new array containing + the element-wise minima. + + Parameters + ---------- + x1, x2 : array_like + The arrays holding the elements to be compared. + + Returns + ------- + y : {ndarray, scalar} + The minimum of `x1` and `x2`, element-wise. Returns scalar if + both `x1` and `x2` are scalars. + + See Also + -------- + maximum : + element-wise maximum + + Notes + ----- + Equivalent to ``np.where(x1 < x2, x1, x2)`` but faster and does proper + broadcasting. + + Examples + -------- + >>> np.minimum([2, 3, 4], [1, 5, 2]) + array([1, 3, 2]) + + >>> np.minimum(np.eye(2), [0.5, 2]) + array([[ 0.5, 0. ], + [ 0. , 1. ]]) """) @@ -1718,12 +1955,12 @@ add_newdoc('numpy.core.umath', 'multiply', Parameters ---------- - x1, x2 : array-like + x1, x2 : array_like The arrays to be multiplied. Returns ------- - y : {ndarray, scalar} + y : ndarray The product of `x1` and `x2`, elementwise. Returns a scalar if both `x1` and `x2` are scalars. @@ -1797,7 +2034,7 @@ add_newdoc('numpy.core.umath', 'not_equal', add_newdoc('numpy.core.umath', 'ones_like', """ - Returns an array of zeros with the same shape and type as a given array. + Returns an array of ones with the same shape and type as a given array. Equivalent to ``a.copy().fill(1)``. @@ -1818,7 +2055,7 @@ add_newdoc('numpy.core.umath', 'ones_like', add_newdoc('numpy.core.umath', 'power', """ - Computes `x1` ** `x2` elementwise. + Returns element-wise base array raised to power from second array. Raise each base in `x1` to the power of the exponents in `x2`. This requires that `x1` and `x2` must be broadcastable to the same shape. @@ -1874,7 +2111,7 @@ add_newdoc('numpy.core.umath', 'radians', Returns ------- - y : {ndarray, scalar} + y : ndarray The corresponding angle in radians. See Also @@ -1895,7 +2132,7 @@ add_newdoc('numpy.core.umath', 'radians', add_newdoc('numpy.core.umath', 'reciprocal', """ - Compute 1/x. + Return element-wise reciprocal. Parameters ---------- @@ -1904,7 +2141,7 @@ add_newdoc('numpy.core.umath', 'reciprocal', Returns ------- - y : {ndarray, scalar} + y : ndarray Return value. Examples @@ -1918,7 +2155,9 @@ add_newdoc('numpy.core.umath', 'reciprocal', add_newdoc('numpy.core.umath', 'remainder', """ - Computes x1-n*x2 where n is floor(x1 / x2) + Returns element-wise remainder of division. + + Computes `x1 - floor(x1/x2)*x2`. Parameters ---------- @@ -1929,9 +2168,9 @@ add_newdoc('numpy.core.umath', 'remainder', Returns ------- - y : {ndarray, scalar} - The quotient `x1/x2`, element-wise. Returns a scalar if - both `x1` and `x2` are scalars. + y : ndarray + The remainder of the quotient `x1/x2`, element-wise. Returns a scalar + if both `x1` and `x2` are scalars. See Also -------- @@ -1951,7 +2190,34 @@ add_newdoc('numpy.core.umath', 'remainder', add_newdoc('numpy.core.umath', 'right_shift', """ - Computes x1 >> x2 (x1 shifted to right by x2 bits) elementwise. + Shift the bits of an integer to the right. + + Bits are shifted to the right by removing `x2` bits at the right of `x1`. + Since the internal representation of numbers is in binary format, this + operation is equivalent to dividing `x1` by ``2**x2``. + + Parameters + ---------- + x1 : array_like, int + Input values. + x2 : array_like, int + Number of bits to remove at the right of `x1`. + + Returns + ------- + out : ndarray, int + Return `x1` with bits shifted `x2` times to the right. + + See Also + -------- + left_shift : Shift the bits of an integer to the left. + binary_repr : Return the binary representation of the input number + as a string. + + Examples + -------- + >>> np.right_shift(10, [1,2,3]) + array([5, 2, 1]) """) @@ -1979,9 +2245,9 @@ add_newdoc('numpy.core.umath', 'rint', add_newdoc('numpy.core.umath', 'sign', """ - Return the sign of a number. + Returns an element-wise indication of the sign of a number. - -1 if x < 0, 0 if x==0, 1 if x > 0. + The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Parameters ---------- @@ -1990,7 +2256,7 @@ add_newdoc('numpy.core.umath', 'sign', Returns ------- - y : {ndarray, scalar} + y : ndarray The sign of `x`. Examples @@ -2004,20 +2270,23 @@ add_newdoc('numpy.core.umath', 'sign', add_newdoc('numpy.core.umath', 'signbit', """ - Returns True where `signbit` of `x` is set (`x<0`). + Returns element-wise True where signbit is set (less than zero). Parameters ---------- - x: array-like or scalar - the input value(s). - output : array-like or scalar - the returned boolean(s) + x: array_like + The input value(s). + + Returns + ------- + out : array_like, bool + Output. Examples -------- >>> np.signbit(-1.2) True - >>> np.signbit(np.array([1,-2.3,2.1])) + >>> np.signbit(np.array([1, -2.3, 2.1])) array([False, True, False], dtype=bool) """) @@ -2138,18 +2407,18 @@ add_newdoc('numpy.core.umath', 'sqrt', add_newdoc('numpy.core.umath', 'square', """ - Compute `x` squared, or `x` to the power of two. + Return the element-wise square of the input. Parameters ---------- - x : array_like or scalar + x : array_like Input data. Returns ------- - out : ndarray or scalar + out : ndarray Element-wise `x*x`, of the same shape and dtype as `x`. - `out` is a scalar if `x` is a scalar. + Returns scalar if `x` is a scalar. See Also -------- @@ -2166,18 +2435,18 @@ add_newdoc('numpy.core.umath', 'square', add_newdoc('numpy.core.umath', 'subtract', """ - Subtract arguments elementwise. + Subtract arguments element-wise. Parameters ---------- - x1, x2 : {array_like, scalar} + x1, x2 : array_like The arrays to be subtracted from each other. If type is 'array_like' the `x1` and `x2` shapes must be identical. Returns ------- - y : {ndarray, scalar} - The difference of `x1` and `x2`, elementwise. Returns a scalar if + y : ndarray + The difference of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes @@ -2200,7 +2469,7 @@ add_newdoc('numpy.core.umath', 'subtract', add_newdoc('numpy.core.umath', 'tan', """ - Compute tangent elementwise. + Compute tangent element-wise. Parameters ---------- @@ -2209,7 +2478,7 @@ add_newdoc('numpy.core.umath', 'tan', Returns ------- - y : ndarray or scalar + y : ndarray The corresponding tangent values. @@ -2223,7 +2492,7 @@ add_newdoc('numpy.core.umath', 'tan', add_newdoc('numpy.core.umath', 'tanh', """ - Hyperbolic tangent elementwise. + Hyperbolic tangent element-wise. Parameters ---------- @@ -2232,14 +2501,14 @@ add_newdoc('numpy.core.umath', 'tanh', Returns ------- - y : ndarray or scalar + y : ndarray The corresponding hyperbolic tangent values. """) add_newdoc('numpy.core.umath', 'true_divide', """ - Returns an elementwise, true division of the inputs. + Returns an element-wise, true division of the inputs. Instead of the Python traditional 'floor division', this returns a true division. True division adjusts the output type to present the best @@ -2254,7 +2523,7 @@ add_newdoc('numpy.core.umath', 'true_divide', Returns ------- - out : {ndarray, scalar} + out : ndarray Result is scalar if both inputs are scalar, ndarray otherwise. Notes diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 33e90c965..2dec5634e 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -16,6 +16,20 @@ _unicode = unicode # comparisons class chararray(ndarray): + """ + chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, + strides=None, order=None) + + A character array of string or unicode type. + + The array items will be `itemsize` characters long. + + Create the array using buffer (with offset and strides) if it is + not None. If buffer is None, then construct a new array with strides + in Fortran order if len(shape) >=2 and order is 'Fortran' (otherwise + the strides will be in 'C' order). + + """ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C'): global _globalvar diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index a6f4203be..0023c99f0 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -44,17 +44,17 @@ def _wrapit(obj, method, *args, **kwds): def take(a, indices, axis=None, out=None, mode='raise'): """ - Take elements from an array along a given axis. + Take elements from an array along an axis. This function does the same thing as "fancy" indexing (indexing arrays - using arrays); however, it can be easier to use if you need to specify - a given axis. + using arrays); however, it can be easier to use if you need elements + along a given axis. Parameters ---------- - a : ndarray + a : array_like The source array. - indices : int array + indices : array_like, int The indices of the values to extract. axis : int, optional The axis over which to select values. By default, the @@ -77,6 +77,18 @@ def take(a, indices, axis=None, out=None, mode='raise'): -------- ndarray.take : equivalent method + Examples + -------- + >>> a = [4, 3, 5, 7, 6, 8] + >>> indices = [0, 1, 4] + >>> np.take(a, indices) + array([4, 3, 6]) + + In this example if `a` is a ndarray, "fancy" indexing can be used. + >>> a = np.array(a) + >>> a[indices] + array([4, 3, 6]) + """ try: take = a.take @@ -88,15 +100,17 @@ def take(a, indices, axis=None, out=None, mode='raise'): # not deprecated --- copy if necessary, view otherwise def reshape(a, newshape, order='C'): """ - Returns an array containing the data of a, but with a new shape. + Gives a new shape to an array without changing its data. Parameters ---------- - a : ndarray + a : array_like Array to be reshaped. newshape : {tuple, int} - The new shape should be compatible with the original shape. If an - integer, then the result will be a 1-D array of that length. + The new shape should be compatible with the original shape. If + an integer, then the result will be a 1-D array of that length. + One shape dimension can be -1. In this case, the value is inferred + from the length of the array and remaining dimensions. order : {'C', 'F'}, optional Determines whether the array data should be viewed as in C (row-major) order or FORTRAN (column-major) order. @@ -113,16 +127,15 @@ def reshape(a, newshape, order='C'): Examples -------- - >>> a = np.array([[1,2], [3,4]]) - >>> a.reshape(4) - array([1, 2, 3, 4]) - >>> a.reshape(4, order='F') - array([1, 3, 2, 4]) - >>> a.reshape((4,1)) - array([[1], - [2], - [3], - [4]]) + >>> a = np.array([[1,2,3], [4,5,6]]) + >>> np.reshape(a, 6) + 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], + [5, 6]]) """ try: @@ -236,9 +249,10 @@ def repeat(a, repeats, axis=None): def put(a, ind, v, mode='raise'): """ - Set a.flat[n] = v[n] for all n in ind. + Changes specific elements of one array by replacing from another array. - If `v` is shorter than `ind`, it will repeat. + 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`. Parameters ---------- @@ -379,28 +393,29 @@ def sort(a, axis=-1, kind='quicksort', order=None): Parameters ---------- - a : array-like + a : array_like Array to be sorted. - axis : int, optional - Axis along which to sort. If not specified, the flattened array - is used. + axis : int or None, optional + Axis along which to sort. If None, the array is flattened before + sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional - Sorting algorithm. + Sorting algorithm. Default is 'quicksort'. order : list, optional - When `a` is an ndarray with fields defined, this argument specifies - which fields to compare first, second, etc. Not all fields need be - specified. + When `a` is a structured array, this argument specifies which fields + to compare first, second, and so on. This list does not need to + include all of the fields. Returns ------- sorted_array : ndarray - Array of same type and shape as `a`. + Array of the same type and shape as `a`. See Also -------- + ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. - searchsorted : Find keys in sorted array. + searchsorted : Find elements in a sorted array. Notes ----- @@ -425,15 +440,34 @@ def sort(a, axis=-1, kind='quicksort', order=None): Examples -------- - >>> a=np.array([[1,4],[3,1]]) - >>> a.sort(1) - >>> a + >>> a = np.array([[1,4],[3,1]]) + >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) - >>> a.sort(0) - >>> a - array([[1, 3], - [1, 4]]) + >>> np.sort(a, axis=None) # sort the flattened array + array([1, 1, 3, 4]) + >>> np.sort(a, axis=0) # sort along the first axis + array([[1, 1], + [3, 4]]) + + Use the `order` keyword to specify a field to use when sorting a + structured array: + + >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] + >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), + ... ('Galahad', 1.7, 38)] + >>> a = np.array(values, dtype=dtype) # create a structured array + >>> np.sort(a, order='height') # doctest: +SKIP + array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), + ('Lancelot', 1.8999999999999999, 38)], + dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) + + Sort by age, then height if ages are equal: + + >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP + array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38), + ('Arthur', 1.8, 41)], + dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) """ if axis is None: @@ -468,7 +502,7 @@ def argsort(a, axis=-1, kind='quicksort', order=None): Returns ------- - index_array : ndarray of ints + index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. @@ -528,7 +562,7 @@ def argsort(a, axis=-1, kind='quicksort', order=None): def argmax(a, axis=None): """ - Indices of the maximum values along a given axis. + Indices of the maximum values along an axis. Parameters ---------- @@ -540,13 +574,14 @@ def argmax(a, axis=None): Returns ------- - index_array : ndarray of ints - Array of indices into the array. It has the same shape `a`, + index_array : ndarray, int + Array of indices into the array. It has the same shape as `a`, except with `axis` removed. See Also -------- - amax : The maximum along a given axis. + argmin : Indices of the minimum values along an axis. + amax : The maximum value along a given axis. unravel_index : Convert a flat index into an index tuple. Examples @@ -569,9 +604,12 @@ def argmax(a, axis=None): def argmin(a, axis=None): """ - Return the indices of the minimum values along the given axis of `a`. + Return the indices of the minimum values along an axis. - Refer to `numpy.argmax` for detailed documentation. + See Also + -------- + argmax : Similar function. Please refer to `numpy.argmax` for detailed + documentation. """ try: @@ -697,7 +735,7 @@ def squeeze(a): Parameters ---------- - a : array-like + a : array_like Input data. Returns @@ -726,7 +764,7 @@ def diagonal(a, offset=0, axis1=0, axis2=1): """ Return specified diagonals. - If `a` is 2-D, returns the diagonal of self with the given offset, + If `a` is 2-D, returns the diagonal of `a` 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 @@ -829,7 +867,7 @@ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): Returns ------- - sum_along_diagonals : array + 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. @@ -935,6 +973,8 @@ def nonzero(a): flatnonzero : Return indices that are non-zero in the flattened version of the input array. + ndarray.nonzero : + Equivalent ndarray method. Examples -------- @@ -980,6 +1020,7 @@ def shape(a): See Also -------- + alen, ndarray.shape : array method Examples @@ -993,10 +1034,10 @@ def shape(a): >>> np.shape(0) () - >>> x = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')]) - >>> np.shape(x) + >>> a = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')]) + >>> np.shape(a) (2,) - >>> x.shape + >>> a.shape (2,) """ @@ -1013,24 +1054,29 @@ def compress(condition, a, axis=None, out=None): Parameters ---------- - condition : {array} - 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. - a : {array_type} + condition : array_like + Boolean 1-D array selecting which entries to return. If len(condition) + is less than the size of `a` along the given axis, then output is + truncated to the length of the condition array. + a : array_like Array from which to extract a part. - axis : {None, integer} - Axis along which to take slices. If None, work on the flattened array. - out : array, optional + axis : int, optional + Axis along which to take slices. If None (default), work on the + flattened array. + out : ndarray, optional Output array. Its type is preserved and it must be of the right shape to hold the output. Returns ------- - compressed_array : array + compressed_array : ndarray A copy of `a` without the slices along axis for which `condition` is false. + See Also + -------- + ndarray.compress: Equivalent method. + Examples -------- >>> a = np.array([[1, 2], [3, 4]]) @@ -1127,7 +1173,7 @@ def sum(a, axis=None, dtype=None, out=None): Returns ------- - sum_along_axis : ndarray or scalar + sum_along_axis : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar is returned. If an output array is specified, a reference to @@ -1208,14 +1254,11 @@ def sometrue(a, axis=None, out=None): def alltrue (a, axis=None, out=None): """ - Check if all of the elements of `a` are true. - - Please refer to the `numpy.all` documentation. `numpy.all` is - the same function. + Check if all elements of input array are true. See Also -------- - numpy.all : equivalent function + numpy.all : Equivalent function; see for details. """ try: @@ -1227,7 +1270,7 @@ 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 a given axis. + Test whether any elements of an array evaluate to True along an axis. Parameters ---------- @@ -1278,7 +1321,7 @@ def any(a,axis=None, out=None): def all(a,axis=None, out=None): """ - Test whether all elements of an array evaluate to true along a given axis. + Returns True if all elements evaluate to True. Parameters ---------- @@ -1293,7 +1336,7 @@ def all(a,axis=None, out=None): Returns ------- - out : ndarray + 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. @@ -1333,7 +1376,7 @@ def cumsum (a, axis=None, dtype=None, out=None): Parameters ---------- - a : array-like + a : array_like Input array or object that can be converted to an array. axis : int, optional Axis along which the cumulative sum is computed. The default @@ -1403,7 +1446,9 @@ def cumproduct(a, axis=None, dtype=None, out=None): def ptp(a, axis=None, out=None): """ - Peak to peak (maximum - minimum) value along a given axis. + Range of values (maximum - minimum) along an axis. + + The name of the function comes from the acronym for 'peak to peak'. Parameters ---------- @@ -1526,7 +1571,7 @@ def amin(a, axis=None, out=None): def alen(a): """ - Return the length of an array_like as an array of at least 1 dimension. + Return the length of the first dimension of the input array. Parameters ---------- @@ -1538,12 +1583,16 @@ def alen(a): alen : int Length of the first dimension of `a`. + See Also + -------- + shape + Examples -------- - >>> z = np.zeros((7,4,5)) - >>> z.shape[0] + >>> a = np.zeros((7,4,5)) + >>> a.shape[0] 7 - >>> np.alen(z) + >>> np.alen(a) 7 """ @@ -1567,8 +1616,8 @@ def prod(a, axis=None, dtype=None, out=None): dtype : data-type, optional The data-type of the returned array, as well as of the accumulator in which the elements are multiplied. By default, if `a` is of - integer type, `dtype` is the default platform integer (note: if - the type of `a` is unsigned, then so is `dtype`). Otherwise, + integer type, `dtype` is the default platform integer. (Note: if + the type of `a` is unsigned, then so is `dtype`.) Otherwise, the dtype is the same as that of `a`. out : ndarray, optional Alternative output array in which to place the result. It must have @@ -1577,7 +1626,7 @@ def prod(a, axis=None, dtype=None, out=None): Returns ------- - product_along_axis : {ndarray, scalar}, see `dtype` parameter above. + product_along_axis : ndarray, see `dtype` parameter above. An array shaped as `a` but with the specified axis removed. Returns a reference to `out` if specified. @@ -1846,9 +1895,9 @@ def around(a, decimals=0, out=None): Returns ------- - rounded_array : {array} + rounded_array : ndarray An array of the same type as `a`, containing the rounded values. - Unless `a` was specified, a new array is created. A reference to + Unless `out` was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index c27a0ea45..ff2eb6ca9 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -305,7 +305,7 @@ def asfortranarray(a, dtype=None): Parameters ---------- - a : array-like + a : array_like Input array. dtype : data-type, optional By default, the data-type is inferred from the input data. @@ -339,7 +339,7 @@ def require(a, dtype=None, requirements=None): Parameters ---------- - a : array-like + a : array_like The object to be converted to a type-and-requirement satisfying array dtype : data-type The required data-type (None is the default data-type -- float64) @@ -403,15 +403,42 @@ def isfortran(a): return a.flags.fnc def argwhere(a): - """Return a 2-d array of shape N x a.ndim where each row - is a sequence of indices into a. This sequence must be - converted to a tuple in order to be used to index into a. + """ + Find the indices of array elements that are non-zero, grouped by element. + + Parameters + ---------- + a : array_like + Input data. + + Returns + ------- + index_array : ndarray + Indices of elements that are non-zero. Indices are grouped by element. + + See Also + -------- + where, nonzero + + Notes + ----- + ``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``. + + The output of ``argwhere`` is not suitable for indexing arrays. + For this purpose use ``where(a)`` instead. - >>> np.argwhere(np.ones((2, 2))) - array([[0, 0], - [0, 1], + Examples + -------- + >>> x = np.arange(6).reshape(2,3) + >>> x + array([[0, 1, 2], + [3, 4, 5]]) + >>> np.argwhere(x>1) + array([[0, 2], [1, 0], - [1, 1]]) + [1, 1], + [1, 2]]) + """ return asarray(a.nonzero()).T @@ -635,6 +662,13 @@ def vdot(a, b): dot(`a`, `b`). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. + For 2-D arrays it is equivalent to matrix multiplication, and for 1-D + arrays to inner product of vectors (with complex conjugation of `a`). + For N dimensions it is a sum product over the last axis of `a` and + the second-to-last of `b`:: + + dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) + Parameters ---------- a : array_like @@ -645,7 +679,7 @@ def vdot(a, b): Returns ------- - output : scalar + output : ndarray Returns dot product of `a` and `b`. Can be an int, float, or complex depending on the types of `a` and `b`. @@ -726,7 +760,7 @@ except ImportError: def tensordot(a, b, axes=2): """ - Returns the tensor dot product for (ndim >= 1) arrays along specified axes. + Returns the tensor dot product for (ndim >= 1) arrays along an axes. The first element of the sequence determines the axis or axes in `a` to sum over, and the second element in `axes` argument sequence @@ -1109,40 +1143,52 @@ little_endian = (sys.byteorder == 'little') def indices(dimensions, dtype=int): """ - Return an array representing the coordinates of a grid. + Return an array representing the indices of a grid. + + Compute an array where the subarrays contain index values 0,1,... + varying only along the corresponding axis. Parameters ---------- - shape : (N,) tuple of ints + dimensions : sequence of ints + The shape of the grid. + dtype : optional + Data_type of the result. Returns ------- grid : ndarray - The output shape is ``(N,) + shape``. I.e., if `shape` is ``(2,4,5)``, - the output shape is ``(3, 2, 4, 5)``. Each subarray, ``grid[i,...]`` - contains values that vary only along the ``i-th`` axis. + The array of grid indices, + ``grid.shape = (len(dimensions),) + tuple(dimensions)``. - Examples + See Also -------- - >>> grid = np.indices((2,3)) + mgrid, meshgrid - The row-positions are given by: + Notes + ----- + The output shape is obtained by prepending the number of dimensions + in front of the tuple of dimensions, i.e. if `dimensions` is a tuple + ``(r0, ..., rN-1)`` of length ``N``, the output shape is + ``(N,r0,...,rN-1)``. - >>> grid[0] - array([[0, 0, 0], - [1, 1, 1]]) + The subarrays ``grid[k]`` contains the N-D array of indices along the + ``k-th`` axis. Explicitly:: - and the column-positions by + grid[k,i0,i1,...,iN-1] = ik - >>> grid[1] + Examples + -------- + >>> grid = np.indices((2,3)) + >>> grid.shape + (2,2,3) + >>> grid[0] # row indices + array([[0, 0, 0], + [1, 1, 1]]) + >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]]) - - See Also - -------- - mgrid, meshgrid, ndindex - """ dimensions = tuple(dimensions) N = len(dimensions) @@ -1491,7 +1537,7 @@ def identity(n, dtype=None): def allclose(a, b, rtol=1.e-5, atol=1.e-8): """ - Returns True if all elements are equal subject to given tolerances. + 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`) @@ -1507,17 +1553,33 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8): atol : Absolute tolerance The absolute difference is equal to `atol`. + Returns + ------- + y : bool + Returns True if the two arrays are equal within the given + tolerance; False otherwise. If either array contains NaN, then + False is returned. + See Also -------- all, any, alltrue, sometrue + Notes + ----- + If the following equation is element-wise True, then allclose returns + True. + + absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) + Examples -------- - >>> allclose(array([1e10,1e-7]), array([1.00001e10,1e-8])) + >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False - >>> allclose(array([1e10,1e-8]), array([1.00001e10,1e-9])) + >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True - >>> allclose(array([1e10,1e-8]), array([1.0001e10,1e-9])) + >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) + False + >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False """ @@ -1540,9 +1602,9 @@ def array_equal(a1, a2): Parameters ---------- - a1 : array-like + a1 : array_like First input array. - a2 : array-like + a2 : array_like Second input array. Returns @@ -1571,9 +1633,32 @@ def array_equal(a1, a2): return bool(logical_and.reduce(equal(a1,a2).ravel())) def array_equiv(a1, a2): - """Returns True if a1 and a2 are shape consistent - (mutually broadcastable) and have all elements equal and False - otherwise. + """ + Returns True if input arrays are shape consistent and all elements equal. + + Parameters + ---------- + a1 : array_like + Input array. + a2 : array_like + Input array. + + Returns + ------- + out : bool + True if equivalent, False otherwise. + + Examples + -------- + >>> np.array_equiv([1,2],[1,2]) + >>> True + >>> np.array_equiv([1,2],[1,3]) + >>> False + >>> np.array_equiv([1,2], [[1,2],[1,2]]) + >>> True + >>> np.array_equiv([1,2], [[1,2],[1,3]]) + >>> False + """ try: a1, a2 = asarray(a1), asarray(a2) @@ -1598,31 +1683,73 @@ for key in _errdict.keys(): del key def seterr(all=None, divide=None, over=None, under=None, invalid=None): - """Set how floating-point errors are handled. - - Valid values for each type of error are the strings - "ignore", "warn", "raise", and "call". Returns the old settings. - If 'all' is specified, values that are not otherwise specified - will be set to 'all', otherwise they will retain their old - values. + """ + Set how floating-point errors are handled. Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings. - Example: + Parameters + ---------- + all : {'ignore', 'warn', 'raise', 'call'}, optional + Set treatment for all types of floating-point errors at once: + + - ignore: Take no action when the exception occurs + - warn: Print a RuntimeWarning (via the Python `warnings` module) + - raise: Raise a FloatingPointError + - call: Call a function specified using the `seterrcall` function. + + The default is not to change the current behavior. + divide : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for division by zero. + over : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for floating-point overflow. + under : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for floating-point underflow. + invalid : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for invalid floating-point operation. + + Returns + ------- + old_settings : dict + Dictionary containing the old settings. + + See also + -------- + seterrcall : set a callback function for the 'call' mode. + geterr, geterrcall + + Notes + ----- + The floating-point exceptions are defined in the IEEE 754 standard [1]: + + - Division by zero: infinite result obtained from finite numbers. + - Overflow: result too large to be expressed. + - Underflow: result so close to zero that some precision + was lost. + - Invalid operation: result is not an expressible number, typically + indicates that a NaN was produced. + + .. [1] http://en.wikipedia.org/wiki/IEEE_754 + + Examples + -------- + + Set mode: >>> seterr(over='raise') # doctest: +SKIP - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} - >>> seterr(all='warn', over='raise') # doctest: +SKIP - {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + >>> old_settings = seterr(all='warn', over='raise') # doctest: +SKIP >>> int16(32000) * int16(3) # doctest: +SKIP Traceback (most recent call last): File "<stdin>", line 1, in ? FloatingPointError: overflow encountered in short_scalars >>> seterr(all='ignore') # doctest: +SKIP - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} """ @@ -1665,7 +1792,14 @@ def geterr(): return res def setbufsize(size): - """Set the size of the buffer used in ufuncs. + """ + Set the size of the buffer used in ufuncs. + + Parameters + ---------- + size : int + Size of buffer. + """ if size > 10e6: raise ValueError, "Buffer size, %s, is too big." % size diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 8a89f40c6..3d34ceb7f 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -662,7 +662,8 @@ def _find_common_coerce(a, b): def find_common_type(array_types, scalar_types): - """Determine common type following standard coercion rules + """ + Determine common type following standard coercion rules Parameters ---------- @@ -679,6 +680,11 @@ def find_common_type(array_types, scalar_types): is of a different kind. If the kinds is not understood, then None is returned. + + See Also + -------- + dtype + """ array_types = [dtype(x) for x in array_types] scalar_types = [dtype(x) for x in scalar_types] diff --git a/numpy/doc/basics.py b/numpy/doc/basics.py index dfb8fe74d..d34c1f303 100644 --- a/numpy/doc/basics.py +++ b/numpy/doc/basics.py @@ -132,6 +132,4 @@ identical behaviour between arrays and scalars, irrespective of whether the value is inside an array or not. NumPy scalars also have many of the same methods arrays do. -See xxx for details. - """ diff --git a/numpy/doc/creation.py b/numpy/doc/creation.py index 1e80e5115..133765678 100644 --- a/numpy/doc/creation.py +++ b/numpy/doc/creation.py @@ -1,6 +1,6 @@ """ ============== -Array creation +Array Creation ============== Introduction @@ -18,17 +18,15 @@ This section will not cover means of replicating, joining, or otherwise expanding or mutating existing arrays. Nor will it cover creating object arrays or record arrays. Both of those are covered in their own sections. -Converting Python array-like objects to numpy arrays +Converting Python array_like Objects to Numpy Arrays ==================================================== In general, numerical data arranged in an array-like structure in Python can be converted to arrays through the use of the array() function. The most obvious examples are lists and tuples. See the documentation for array() for details for -its use. Some -objects may support the array-protocol and allow conversion to arrays this -way. A simple way to find out if the object can be converted to a numpy array -using array() is simply to try it interactively and see if it works! (The -Python Way). +its use. Some objects may support the array-protocol and allow conversion to arrays +this way. A simple way to find out if the object can be converted to a numpy array +using array() is simply to try it interactively and see if it works! (The Python Way). Examples: :: @@ -37,7 +35,7 @@ Examples: :: >>> x = np.array([[1,2.0],[0,0],(1+1j,3.)]) # note mix of tuple and lists, and types >>> x = np.array([[ 1.+0.j, 2.+0.j], [ 0.+0.j, 0.+0.j], [ 1.+1.j, 3.+0.j]]) -Intrinsic numpy array creation +Intrinsic Numpy Array Creation ============================== Numpy has built-in functions for creating arrays from scratch: @@ -65,6 +63,17 @@ examples will be given here: :: Note that there are some subtleties regarding the last usage that the user should be aware of that are described in the arange docstring. +linspace() will create arrays with a specified number of elements, and +spaced equally between the specified beginning and end values. For +example: :: + + >>> np.linspace(1., 4., 6) + array([ 1. , 1.6, 2.2, 2.8, 3.4, 4. ]) + +The advantage of this creation function is that one can guarantee the +number of elements and the starting and end point, which arange() +generally will not do for arbitrary start, stop, and step values. + indices() will create a set of arrays (stacked as a one-higher dimensioned array), one per dimension with each representing variation in that dimension. An examples illustrates much better than a verbal description: :: @@ -75,41 +84,41 @@ An examples illustrates much better than a verbal description: :: This is particularly useful for evaluating functions of multiple dimensions on a regular grid. -Reading arrays from disk +Reading Arrays From Disk ======================== This is presumably the most common case of large array creation. The details, of course, depend greatly on the format of data on disk and so this section can only give general pointers on how to handle various formats. -Standard binary formats +Standard Binary Formats ----------------------- Various fields have standard formats for array data. The following lists the ones with known python libraries to read them and return numpy arrays (there may be others for which it is possible to read and convert to numpy arrays so check the last section as well) +:: -HDF5: PyTables -FITS: PyFITS -Others? xxx + HDF5: PyTables + FITS: PyFITS + Others? xxx Examples of formats that cannot be read directly but for which it is not hard to convert are libraries like PIL (able to read and write many image formats such as jpg, png, etc). -Common ascii formats --------------------- +Common ASCII Formats +------------------------ Comma Separated Value files (CSV) are widely used (and an export and import option for programs like Excel). There are a number of ways of reading these -files in Python. The most convenient ways of reading these are found in pylab -(part of matplotlib) in the xxx function. (list alternatives xxx) +files in Python. There are CSV functions in Python and functions in pylab +(part of matplotlib). -More generic ascii files can be read using the io package in scipy. xxx a few -more details needed... +More generic ascii files can be read using the io package in scipy. -Custom binary formats +Custom Binary Formats --------------------- There are a variety of approaches one can use. If the file has a relatively @@ -120,13 +129,13 @@ read the data, one can wrap that library with a variety of techniques (see xxx) though that certainly is much more work and requires significantly more advanced knowledge to interface with C or C++. -Use of special libraries +Use of Special Libraries ------------------------ There are libraries that can be used to generate arrays for special purposes and it isn't possible to enumerate all of them. The most common uses are use of the many array generation functions in random that can generate arrays of random values, and some utility functions to generate special matrices (e.g. -diagonal, see xxx) +diagonal) """ diff --git a/numpy/doc/glossary.py b/numpy/doc/glossary.py index 6a182adf4..f591a5424 100644 --- a/numpy/doc/glossary.py +++ b/numpy/doc/glossary.py @@ -1,7 +1,7 @@ """ -================= +======== Glossary -================= +======== along an axis Axes are defined for arrays with more than one dimension. A @@ -23,7 +23,7 @@ along an axis >>> x.sum(axis=1) array([ 6, 22, 38]) -array or ndarray +array A homogeneous container of numerical elements. Each element in the array occupies a fixed amount of memory (hence homogeneous), and can be a numerical element of a single type (such as float, int @@ -60,6 +60,9 @@ attribute >>> x.shape (3,) +BLAS + `Basic Linear Algebra Subprograms <http://en.wikipedia.org/wiki/BLAS>`_ + broadcast NumPy can do operations on arrays whose shapes are mismatched:: @@ -79,6 +82,24 @@ broadcast See `doc.broadcasting`_ for more information. +C order + See `row-major` + +column-major + A way to represent items in a N-dimensional array in the 1-dimensional + computer memory. In column-major order, the leftmost index "varies the + fastest": for example the array:: + + [[1, 2, 3], + [4, 5, 6]] + + is represented in the column-major order as:: + + [1, 4, 2, 5, 3, 6] + + Column-major order is also known as the Fortran order, as the Fortran + programming language uses it. + decorator An operator that transforms a function. For example, a ``log`` decorator may be defined to print debugging information upon @@ -128,6 +149,12 @@ dictionary For more information on dictionaries, read the `Python tutorial <http://docs.python.org/tut>`_. +Fortran order + See `column-major` + +flattened + Collapsed to a one-dimensional array. See `ndarray.flatten`_ for details. + immutable An object that cannot be modified after execution is called immutable. Two common examples are strings and tuples. @@ -250,10 +277,28 @@ method >>> x.repeat(2) array([1, 1, 2, 2, 3, 3]) +ndarray + See *array*. + reference If ``a`` is a reference to ``b``, then ``(a is b) == True``. Therefore, ``a`` and ``b`` are different names for the same Python object. +row-major + A way to represent items in a N-dimensional array in the 1-dimensional + computer memory. In row-major order, the rightmost index "varies + the fastest": for example the array:: + + [[1, 2, 3], + [4, 5, 6]] + + is represented in the row-major order as:: + + [1, 2, 3, 4, 5, 6] + + Row-major order is also known as the C order, as the C programming + language uses it. New Numpy arrays are by default in row-major order. + self Often seen in method signatures, ``self`` refers to the instance of the associated class. For example: diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py index e978100bf..1e43f312a 100644 --- a/numpy/doc/misc.py +++ b/numpy/doc/misc.py @@ -1,9 +1,223 @@ """ - ============= Miscellaneous ============= -Placeholder for other tips. +IEEE 754 Floating Point Special Values: +----------------------------------------------- + +Special values defined in numpy: nan, inf, + +NaNs can be used as a poor-man's mask (if you don't care what the +original value was) + +Note: cannot use equality to test NaNs. E.g.: :: + + >>> np.where(myarr == np.nan) + >>> nan == nan # is always False! Use special numpy functions instead. + + >>> np.nan == np.nan + False + >>> myarr = np.array([1., 0., np.nan, 3.]) + >>> myarr[myarr == np.nan] = 0. # doesn't work + >>> myarr + array([ 1., 0., NaN, 3.]) + >>> myarr[np.isnan(myarr)] = 0. # use this instead find + >>> myarr + array([ 1., 0., 0., 3.]) + +Other related special value functions: :: + + isinf(): True if value is inf + isfinite(): True if not nan or inf + nan_to_num(): Map nan to 0, inf to max float, -inf to min float + +The following corresponds to the usual functions except that nans are excluded from +the results: :: + + nansum() + nanmax() + nanmin() + nanargmax() + nanargmin() + + >>> x = np.arange(10.) + >>> x[3] = np.nan + >>> x.sum() + nan + >>> np.nansum(x) + 42.0 + +How numpy handles numerical exceptions + +Default is to "warn" +But this can be changed, and it can be set individually for different kinds +of exceptions. The different behaviors are: :: + + 'ignore' : ignore completely + 'warn' : print a warning (once only) + 'raise' : raise an exception + 'call' : call a user-supplied function (set using seterrcall()) + +These behaviors can be set for all kinds of errors or specific ones: :: + + all: apply to all numeric exceptions + invalid: when NaNs are generated + divide: divide by zero (for integers as well!) + overflow: floating point overflows + underflow: floating point underflows + +Note that integer divide-by-zero is handled by the same machinery. +These behaviors are set on a per-thead basis. + +Examples: +------------ + +:: + + >>> oldsettings = np.seterr(all='warn') + >>> np.zeros(5,dtype=np.float32)/0. + invalid value encountered in divide + >>> j = np.seterr(under='ignore') + >>> np.array([1.e-100])**10 + >>> j = np.seterr(invalid='raise') + >>> np.sqrt(np.array([-1.])) + FloatingPointError: invalid value encountered in sqrt + >>> def errorhandler(errstr, errflag): + ... print "saw stupid error!" + >>> np.seterrcall(errorhandler) + >>> j = np.seterr(all='call') + >>> np.zeros(5, dtype=np.int32)/0 + FloatingPointError: invalid value encountered in divide + saw stupid error! + >>> j = np.seterr(**oldsettings) # restore previous + # error-handling settings + +Interfacing to C: +----------------- +Only a survey the choices. Little detail on how each works. + +1) Bare metal, wrap your own C-code manually. + + - Plusses: + + - Efficient + - No dependencies on other tools + + - Minuses: + + - Lots of learning overhead: + + - need to learn basics of Python C API + - need to learn basics of numpy C API + - need to learn how to handle reference counting and love it. + + - Reference counting often difficult to get right. + + - getting it wrong leads to memory leaks, and worse, segfaults + + - API will change for Python 3.0! + +2) pyrex + + - Plusses: + + - avoid learning C API's + - no dealing with reference counting + - can code in psuedo python and generate C code + - can also interface to existing C code + - should shield you from changes to Python C api + - become pretty popular within Python community + + - Minuses: + + - Can write code in non-standard form which may become obsolete + - Not as flexible as manual wrapping + - Maintainers not easily adaptable to new features + +Thus: + +3) cython - fork of pyrex to allow needed features for SAGE + + - being considered as the standard scipy/numpy wrapping tool + - fast indexing support for arrays + +4) ctypes + + - Plusses: + + - part of Python standard library + - good for interfacing to existing sharable libraries, particularly + Windows DLLs + - avoids API/reference counting issues + - good numpy support: arrays have all these in their ctypes + attribute: :: + + a.ctypes.data a.ctypes.get_strides + a.ctypes.data_as a.ctypes.shape + a.ctypes.get_as_parameter a.ctypes.shape_as + a.ctypes.get_data a.ctypes.strides + a.ctypes.get_shape a.ctypes.strides_as + + - Minuses: + + - can't use for writing code to be turned into C extensions, only a wrapper tool. + +5) SWIG (automatic wrapper generator) + + - Plusses: + + - around a long time + - multiple scripting language support + - C++ support + - Good for wrapping large (many functions) existing C libraries + + - Minuses: + + - generates lots of code between Python and the C code + + - can cause performance problems that are nearly impossible to optimize out + + - interface files can be hard to write + - doesn't necessarily avoid reference counting issues or needing to know API's + +7) Weave + + - Plusses: + + - Phenomenal tool + - can turn many numpy expressions into C code + - dynamic compiling and loading of generated C code + - can embed pure C code in Python module and have weave extract, generate interfaces + and compile, etc. + + - Minuses: + + - Future uncertain--lacks a champion + +8) Psyco + + - Plusses: + + - Turns pure python into efficient machine code through jit-like optimizations + - very fast when it optimizes well + + - Minuses: + + - Only on intel (windows?) + - Doesn't do much for numpy? + +Interfacing to Fortran: +----------------------- +Fortran: Clear choice is f2py. (Pyfort is an older alternative, but not supported +any longer) + +Interfacing to C++: +------------------- +1) CXX +2) Boost.python +3) SWIG +4) Sage has used cython to wrap C++ (not pretty, but it can be done) +5) SIP (used mainly in PyQT) """ diff --git a/numpy/doc/subclassing.py b/numpy/doc/subclassing.py index 859ab32f9..bbd44f8ee 100644 --- a/numpy/doc/subclassing.py +++ b/numpy/doc/subclassing.py @@ -20,17 +20,17 @@ why subclassing works as it does. ndarrays and object creation ============================ The creation of ndarrays is complicated by the need to return views of -ndarrays, that are also ndarrays. For example:: - - >>> import numpy as np - >>> arr = np.zeros((3,)) - >>> type(arr) - <type 'numpy.ndarray'> - >>> v = arr[1:] - >>> type(v) - <type 'numpy.ndarray'> - >>> v is arr - False +ndarrays, that are also ndarrays. For example: + +>>> import numpy as np +>>> arr = np.zeros((3,)) +>>> type(arr) +<type 'numpy.ndarray'> +>>> v = arr[1:] +>>> type(v) +<type 'numpy.ndarray'> +>>> v is arr +False So, when we take a view (here a slice) from the ndarray, we return a new ndarray, that points to the data in the original. When we @@ -148,6 +148,7 @@ Simple example - adding an extra attribute to ndarray ----------------------------------------------------- :: + import numpy as np class InfoArray(np.ndarray): diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index 12c207cb0..0af1cdc79 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -109,23 +109,26 @@ def fft(a, n=None, axis=-1): def ifft(a, n=None, axis=-1): """ - Compute the one-dimensonal inverse fft on a given axis. + Compute the one-dimensonal inverse fft along an axis. - Return the n point inverse 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, then a will be truncated to reduce - its size. + 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. Parameters ---------- - a : array - input array - n : int - length of the fft - axis : int - axis over which to compute the inverse fft + a : array_like + Input array. + n : int, optional + Length of the fft. + axis : int, optional + Axis over which to compute the inverse fft. + + See Also + -------- + fft Notes ----- @@ -135,10 +138,10 @@ def ifft(a, n=None, axis=-1): This is the inverse of fft: ifft(fft(a)) == a within numerical accuracy. - This is most efficient for n a power of two. This also stores a cache of + 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. + different `n` values. """ @@ -189,34 +192,35 @@ def irfft(a, n=None, axis=-1): """ Compute the one-dimensional inverse fft for real input. - Notes - ----- - - Return 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. - Parameters ---------- - a : array - input array with real data type + Input array with real data type. n : int - length of the fft + Length of the fft. axis : int - axis over which to compute the fft + Axis over which to compute the fft. + + See Also + -------- + rfft Notes ----- + Return 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. - If you specify an n such that a must be zero-padded or truncated, the + 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). - This is the inverse of rfft: irfft(rfft(a), len(a)) == a within numerical accuracy. + Within numerical accuracy ``irfft`` is the inverse of ``rfft``:: + + irfft(rfft(a), len(a)) == a """ @@ -240,6 +244,11 @@ def hfft(a, n=None, axis=-1): axis : int axis over which to compute the hfft + See also + -------- + rfft + ihfft + Notes ----- These are a pair analogous to rfft/irfft, but for the @@ -250,11 +259,6 @@ def hfft(a, n=None, axis=-1): ihfft(hfft(a), len(a)) == a within numerical accuracy. - See also - -------- - rfft - ihfft - """ a = asarray(a).astype(complex) @@ -265,17 +269,20 @@ def hfft(a, n=None, axis=-1): def ihfft(a, n=None, axis=-1): """ - Compute the inverse fft of a signal which spectrum has Hermitian - symmetry. + Compute the inverse fft of a signal whose spectrum has Hermitian symmetry. Parameters ---------- - a : array - input array - n : int - length of the ihfft - axis : int - axis over which to compute the ihfft + a : array_like + Input array. + n : int, optional + Length of the ihfft. + axis : int, optional + Axis over which to compute the ihfft. + + See also + -------- + rfft, hfft Notes ----- @@ -287,11 +294,6 @@ def ihfft(a, n=None, axis=-1): ihfft(hfft(a), len(a)) == a within numerical accuracy. - See also - -------- - rfft - hfft - """ a = asarray(a).astype(float) @@ -395,20 +397,21 @@ def ifftn(a, s=None, axes=None): def fft2(a, s=None, axes=(-2,-1)): """ - Compute the 2d fft of an array. + Compute the 2-D FFT of an array. Parameters ---------- - a : array - input array - s : sequence (int) - shape of the fft - axis : int - axis over which to compute the fft + 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). Notes ----- - This is really just fftn with different default behavior. + This is really just ``fftn`` with different default behavior. """ diff --git a/numpy/fft/helper.py b/numpy/fft/helper.py index 74f4e363b..e2e36c323 100644 --- a/numpy/fft/helper.py +++ b/numpy/fft/helper.py @@ -10,14 +10,23 @@ from numpy.core import asarray, concatenate, arange, take, \ import types def fftshift(x,axes=None): - """ fftshift(x, axes=None) -> y - + """ Shift zero-frequency component to center of spectrum. This function swaps half-spaces for all axes listed (defaults to all). + If len(x) is even then the Nyquist component is y[0]. + + Parameters + ---------- + x : array_like + Input array. + axes : int or shape tuple, optional + Axes over which to shift. Default is None which shifts all axes. + + See Also + -------- + ifftshift - Notes: - If len(x) is even then the Nyquist component is y[0]. """ tmp = asarray(x) ndim = len(tmp.shape) @@ -33,9 +42,20 @@ def fftshift(x,axes=None): def ifftshift(x,axes=None): - """ ifftshift(x,axes=None) - > y - + """ Inverse of fftshift. + + Parameters + ---------- + x : array_like + Input array. + axes : int or shape tuple, optional + Axes over which to calculate. Defaults to None which is over all axes. + + See Also + -------- + fftshift + """ tmp = asarray(x) ndim = len(tmp.shape) @@ -50,16 +70,39 @@ def ifftshift(x,axes=None): return y def fftfreq(n,d=1.0): - """ fftfreq(n, d=1.0) -> f - - DFT sample frequencies + """ + Discrete Fourier Transform sample frequencies. The returned float array contains the frequency bins in - cycles/unit (with zero at the start) given a window length n and a - sample spacing d: + cycles/unit (with zero at the start) given a window length `n` and a + sample spacing `d`. + :: f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd + + Parameters + ---------- + n : int + Window length. + d : scalar + Sample spacing. + + Returns + ------- + out : ndarray, shape(`n`,) + Sample frequencies. + + Examples + -------- + >>> signal = np.array([-2., 8., -6., 4., 1., 0., 3., 5.]) + >>> fourier = np.fft.fft(signal) + >>> n = len(signal) + >>> timestep = 0.1 + >>> freq = np.fft.fftfreq(n, d=timestep) + >>> freq + array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25]) + """ assert isinstance(n,types.IntType) or isinstance(n, integer) val = 1.0/(n*d) diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 07f6d5c27..296ca7135 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -1,3 +1,151 @@ +""" +Basic functions used by several sub-packages and +useful to have in the main name-space. + +Type Handling +------------- +================ =================== +iscomplexobj Test for complex object, scalar result +isrealobj Test for real object, scalar result +iscomplex Test for complex elements, array result +isreal Test for real elements, array result +imag Imaginary part +real Real part +real_if_close Turns complex number with tiny imaginary part to real +isneginf Tests for negative infinity, array result +isposinf Tests for positive infinity, array result +isnan Tests for nans, array result +isinf Tests for infinity, array result +isfinite Tests for finite numbers, array result +isscalar True if argument is a scalar +nan_to_num Replaces NaN's with 0 and infinities with large numbers +cast Dictionary of functions to force cast to each type +common_type Determine the minimum common type code for a group + of arrays +mintypecode Return minimal allowed common typecode. +================ =================== + +Index Tricks +------------ +================ =================== +mgrid Method which allows easy construction of N-d + 'mesh-grids' +``r_`` Append and construct arrays: turns slice objects into + ranges and concatenates them, for 2d arrays appends rows. +index_exp Konrad Hinsen's index_expression class instance which + can be useful for building complicated slicing syntax. +================ =================== + +Useful Functions +---------------- +================ =================== +select Extension of where to multiple conditions and choices +extract Extract 1d array from flattened array according to mask +insert Insert 1d array of values into Nd array according to mask +linspace Evenly spaced samples in linear space +logspace Evenly spaced samples in logarithmic space +fix Round x to nearest integer towards zero +mod Modulo mod(x,y) = x % y except keeps sign of y +amax Array maximum along axis +amin Array minimum along axis +ptp Array max-min along axis +cumsum Cumulative sum along axis +prod Product of elements along axis +cumprod Cumluative product along axis +diff Discrete differences along axis +angle Returns angle of complex argument +unwrap Unwrap phase along given axis (1-d algorithm) +sort_complex Sort a complex-array (based on real, then imaginary) +trim_zeros Trim the leading and trailing zeros from 1D array. +vectorize A class that wraps a Python function taking scalar + arguments into a generalized function which can handle + arrays of arguments using the broadcast rules of + numerix Python. +================ =================== + +Shape Manipulation +------------------ +================ =================== +squeeze Return a with length-one dimensions removed. +atleast_1d Force arrays to be > 1D +atleast_2d Force arrays to be > 2D +atleast_3d Force arrays to be > 3D +vstack Stack arrays vertically (row on row) +hstack Stack arrays horizontally (column on column) +column_stack Stack 1D arrays as columns into 2D array +dstack Stack arrays depthwise (along third dimension) +split Divide array into a list of sub-arrays +hsplit Split into columns +vsplit Split into rows +dsplit Split along third dimension +================ =================== + +Matrix (2D Array) Manipulations +------------------------------- +================ =================== +fliplr 2D array with columns flipped +flipud 2D array with rows flipped +rot90 Rotate a 2D array a multiple of 90 degrees +eye Return a 2D array with ones down a given diagonal +diag Construct a 2D array from a vector, or return a given + diagonal from a 2D array. +mat Construct a Matrix +bmat Build a Matrix from blocks +================ =================== + +Polynomials +----------- +================ =================== +poly1d A one-dimensional polynomial class +poly Return polynomial coefficients from roots +roots Find roots of polynomial given coefficients +polyint Integrate polynomial +polyder Differentiate polynomial +polyadd Add polynomials +polysub Substract polynomials +polymul Multiply polynomials +polydiv Divide polynomials +polyval Evaluate polynomial at given argument +================ =================== + +Import Tricks +------------- +================ =================== +ppimport Postpone module import until trying to use it +ppimport_attr Postpone module import until trying to use its attribute +ppresolve Import postponed module and return it. +================ =================== + +Machine Arithmetics +------------------- +================ =================== +machar_single Single precision floating point arithmetic parameters +machar_double Double precision floating point arithmetic parameters +================ =================== + +Threading Tricks +---------------- +================ =================== +ParallelExec Execute commands in parallel thread. +================ =================== + +1D Array Set Operations +----------------------- +Set operations for 1D numeric arrays based on sort() function. + +================ =================== +ediff1d Array difference (auxiliary function). +unique1d Unique elements of 1D array. +intersect1d Intersection of 1D arrays with unique elements. +intersect1d_nu Intersection of 1D arrays with any elements. +setxor1d Set exclusive-or of 1D arrays with unique elements. +setmember1d Return an array of shape of ar1 containing 1 where + the elements of ar1 are in ar2 and 0 otherwise. +union1d Union of 1D arrays with unique elements. +setdiff1d Set difference of 1D arrays with unique elements. +================ =================== + +""" from info import __doc__ from numpy.version import version as __version__ diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index 7e760b416..0fe594ac3 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -275,26 +275,28 @@ class DataSource (object): return None def abspath(self, path): - """Return absolute path of ``path`` in the DataSource directory. + """ + Return absolute path of file in the DataSource directory. - If ``path`` is an URL, the ``abspath`` will be either the location + If `path` is an URL, the ``abspath`` will be either the location the file exists locally or the location it would exist when opened using the ``open`` method. The functionality is idential to os.path.abspath. - *Parameters*: - - path : {string} - Can be a local file or a remote URL. - - *Returns*: + Parameters + ---------- + path : string + Can be a local file or a remote URL. + Returns + ------- + out : string Complete path, rooted in the DataSource destination directory. - *See Also*: - - `open` : Method that downloads and opens files. + See Also + -------- + open """ # We do this here to reduce the 'import numpy' initial import time. @@ -332,9 +334,10 @@ class DataSource (object): return path def exists(self, path): - """Test if ``path`` exists. + """ + Test if path exists. - Test if ``path`` exists as (and in this order): + Test if `path` exists as (and in this order): - a local file. - a remote URL that have been downloaded and stored locally in the @@ -342,25 +345,26 @@ class DataSource (object): - a remote URL that has not been downloaded, but is valid and accessible. - *Parameters*: + Parameters + ---------- + path : string + Can be a local file or a remote URL. - path : {string} - Can be a local file or a remote URL. - - *Returns*: + Returns + ------- + out : bool + True if `path` exists. - boolean + See Also + -------- + abspath - *See Also*: - - `abspath` - - *Notes* - - When ``path`` is an URL, ``exist`` will return True if it's either - stored locally in the DataSource directory, or is a valid remote - URL. DataSource does not discriminate between to two, the file - is accessible if it exists in either location. + Notes + ----- + When `path` is an URL, ``exist`` will return True if it's either stored + locally in the DataSource directory, or is a valid remote URL. DataSource + does not discriminate between to two, the file is accessible if it exists + in either location. """ # We import this here because importing urllib2 is slow and @@ -387,21 +391,25 @@ class DataSource (object): return False def open(self, path, mode='r'): - """Open ``path`` with ``mode`` and return the file object. + """ + Open and return file-like object. If ``path`` is an URL, it will be downloaded, stored in the DataSource directory and opened from there. - *Parameters*: + Parameters + ---------- + path : string + Local file path or URL to open + mode : {'r', 'w', 'a'}, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to + append. Available modes depend on the type of object specified by + `path`. - path : {string} - - mode : {string}, optional - - - *Returns*: - - file object + Returns + ------- + out : file object + File object. """ @@ -476,19 +484,106 @@ class Repository (DataSource): return DataSource._findfile(self, self._fullpath(path)) def abspath(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" + """ + Return absolute path of file in the Repository directory. + + If `path` is an URL, the ``abspath`` will be either the location + the file exists locally or the location it would exist when opened + using the ``open`` method. + + The functionality is idential to os.path.abspath. + + Parameters + ---------- + path : string + Can be a local file or a remote URL. + + Returns + ------- + out : string + Complete path, rooted in the DataSource destination directory. + + See Also + -------- + open + + """ return DataSource.abspath(self, self._fullpath(path)) def exists(self, path): - """Extend DataSource method to prepend baseurl to ``path``.""" + """ + Test if path exists prepending Repository base URL to path. + + Test if `path` exists as (and in this order): + + - a local file. + - a remote URL that have been downloaded and stored locally in the + DataSource directory. + - a remote URL that has not been downloaded, but is valid and + accessible. + + Parameters + ---------- + path : string + Can be a local file or a remote URL. + + Returns + ------- + out : bool + True if `path` exists. + + See Also + -------- + abspath + + Notes + ----- + When `path` is an URL, ``exist`` will return True if it's either stored + locally in the DataSource directory, or is a valid remote URL. DataSource + does not discriminate between to two, the file is accessible if it exists + in either location. + + """ return DataSource.exists(self, self._fullpath(path)) def open(self, path, mode='r'): - """Extend DataSource method to prepend baseurl to ``path``.""" + """ + Open and return file-like object prepending Repository base URL. + + If `path` is an URL, it will be downloaded, stored in the DataSource + directory and opened from there. + + Parameters + ---------- + path : string + Local file path or URL to open + mode : {'r', 'w', 'a'}, optional + Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to + append. Available modes depend on the type of object specified by + `path`. + + Returns + ------- + out : file object + File object. + + """ return DataSource.open(self, self._fullpath(path), mode) def listdir(self): - '''List files in the source Repository.''' + """ + List files in the source Repository. + + Returns + ------- + files : list of str + List of file names (not containing a directory part). + + Notes + ----- + Does not currently work for remote repositories. + + """ if self._isurl(self._baseurl): raise NotImplementedError, \ "Directory listing of URLs, not supported yet." diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index 270927321..49a1d3e89 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -79,7 +79,7 @@ def unique1d(ar1, return_index=False, return_inverse=False): Parameters ---------- - ar1 : array-like + ar1 : array_like This array will be flattened if it is not already 1-D. return_index : bool, optional If True, also return the indices against `ar1` that result in the @@ -101,8 +101,8 @@ def unique1d(ar1, return_index=False, return_inverse=False): See Also -------- - numpy.lib.arraysetops : Module with a number of other functions - for performing set operations on arrays. + numpy.lib.arraysetops : Module with a number of other functions + for performing set operations on arrays. Examples -------- @@ -230,14 +230,14 @@ def setxor1d(ar1, ar2): Parameters ---------- - ar1 : array + ar1 : array_like Input array. - ar2 : array + ar2 : array_like Input array. Returns ------- - xor : array + xor : ndarray The values that are only in one, but not both, of the input arrays. See Also @@ -269,15 +269,15 @@ def setmember1d(ar1, ar2): Parameters ---------- - ar1 : array + ar1 : array_like Input array. - ar2 : array + ar2 : array_like Input array. Returns ------- - mask : bool-array - The values ar1[mask] are in ar2. + mask : ndarray, bool + The values `ar1[mask]` are in `ar2`. See Also -------- @@ -325,7 +325,7 @@ def union1d(ar1, ar2): Returns ------- - union : array + union : ndarray Unique union of input arrays. See also @@ -345,14 +345,14 @@ def setdiff1d(ar1, ar2): Parameters ---------- - ar1 : array + ar1 : array_like Input array. - ar2 : array + ar2 : array_like Input comparison array. Returns ------- - difference : array + difference : ndarray The values in ar1 that are not in ar2. See Also diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index ded809c4d..f53a77631 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -30,26 +30,36 @@ def fv(rate, nper, pmt, pv, when='end'): Parameters ---------- - rate : array-like - Rate of interest (per period) - nper : array-like + rate : scalar or array_like of shape(M, ) + Rate of interest as decimal (not per cent) per period + nper : scalar or array_like of shape(M, ) Number of compounding periods - pmt : array-like + pmt : scalar or array_like of shape(M, ) Payment - pv : array-like + pv : scalar or array_like of shape(M, ) Present value - when : array-like - When payments are due ('begin' (1) or 'end' (0)) + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional + When payments are due ('begin' (1) or 'end' (0)). + Defaults to {'end', 0}. + + Returns + ------- + out : ndarray + Future values. If all input is scalar, returns a scalar float. If + any input is array_like, returns future values for each input element. + If multiple inputs are array_like, they all must have the same shape. Notes ----- The future value is computed by solving the equation:: - fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) == 0 + fv + + pv*(1+rate)**nper + + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: - fv + pv + pmt * nper == 0 + fv + pv + pmt * nper == 0 Examples -------- @@ -64,6 +74,13 @@ def fv(rate, nper, pmt, pv, when='end'): available today). Thus, saving $100 a month at 5% annual interest leads to $15,692.93 available to spend in 10 years. + If any input is array_like, returns an array of equal shape. Let's + compare different interest rates from the example above. + + >>> a = np.array((0.05, 0.06, 0.07))/12 + >>> np.fv(a, 10*12, -100, -100) + array([ 15692.92889434, 16569.87435405, 17509.44688102]) + """ when = _convert_when(when) rate, nper, pmt, pv, when = map(np.asarray, [rate, nper, pmt, pv, when]) @@ -75,26 +92,36 @@ def fv(rate, nper, pmt, pv, when='end'): def pmt(rate, nper, pv, fv=0, when='end'): """ - Compute the payment. + Compute the payment against loan principal plus interest. Parameters ---------- - rate : array-like + rate : array_like Rate of interest (per period) - nper : array-like + nper : array_like Number of compounding periods - pv : array-like + pv : array_like Present value - fv : array-like + fv : array_like Future value - when : array-like + when : {{'begin', 1}, {'end', 0}}, {string, int} When payments are due ('begin' (1) or 'end' (0)) + Returns + ------- + out : ndarray + Payment against loan plus interest. If all input is scalar, returns a + scalar float. If any input is array_like, returns payment for each + input element. If multiple inputs are array_like, they all must have + the same shape. + Notes ----- The payment ``pmt`` is computed by solving the equation:: - fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) == 0 + fv + + pv*(1 + rate)**nper + + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0 or, when ``rate == 0``:: @@ -132,9 +159,9 @@ def nper(rate, pmt, pv, fv=0, when='end'): Payment pv : array_like Present value - fv : array_like + fv : array_like, optional Future value - when : array_like + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) Notes @@ -157,8 +184,8 @@ def nper(rate, pmt, pv, fv=0, when='end'): So, over 64 months would be required to pay off the loan. - The same analysis could be done with several different interest rates and/or - payments and/or total amounts to produce an entire table. + The same analysis could be done with several different interest rates + and/or payments and/or total amounts to produce an entire table. >>> np.nper(*(np.ogrid[0.06/12:0.071/12:0.01/12, -200:-99:100, 6000:7001:1000])) array([[[ 32.58497782, 38.57048452], @@ -182,7 +209,42 @@ def nper(rate, pmt, pv, fv=0, when='end'): def ipmt(rate, per, nper, pv, fv=0.0, when='end'): """ - Not implemented. + Not implemented. Compute the payment portion for loan interest. + + Parameters + ---------- + rate : scalar or array_like of shape(M, ) + Rate of interest as decimal (not per cent) per period + per : scalar or array_like of shape(M, ) + Interest paid against the loan changes during the life or the loan. + The `per` is the payment period to calculate the interest amount. + nper : scalar or array_like of shape(M, ) + Number of compounding periods + pv : scalar or array_like of shape(M, ) + Present value + fv : scalar or array_like of shape(M, ), optional + Future value + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional + When payments are due ('begin' (1) or 'end' (0)). + Defaults to {'end', 0}. + + Returns + ------- + out : ndarray + Interest portion of payment. If all input is scalar, returns a scalar + float. If any input is array_like, returns interest payment for each + input element. If multiple inputs are array_like, they all must have + the same shape. + + See Also + -------- + ppmt, pmt, pv + + Notes + ----- + The total payment is made up of payment against principal plus interest. + + ``pmt = ppmt + ipmt`` """ total = pmt(rate, nper, pv, fv, when) @@ -190,6 +252,30 @@ def ipmt(rate, per, nper, pv, fv=0.0, when='end'): raise NotImplementedError def ppmt(rate, per, nper, pv, fv=0.0, when='end'): + """ + Not implemented. Compute the payment against loan principal. + + Parameters + ---------- + rate : array_like + Rate of interest (per period) + per : array_like, int + Amount paid against the loan changes. The `per` is the period of + interest. + nper : array_like + Number of compounding periods + pv : array_like + Present value + fv : array_like, optional + Future value + when : {{'begin', 1}, {'end', 0}}, {string, int} + When payments are due ('begin' (1) or 'end' (0)) + + See Also + -------- + pmt, pv, ipmt + + """ total = pmt(rate, nper, pv, fv, when) return total - ipmt(rate, per, nper, pv, fv, when) @@ -199,22 +285,29 @@ def pv(rate, nper, pmt, fv=0.0, when='end'): Parameters ---------- - rate : array-like + rate : array_like Rate of interest (per period) - nper : array-like + nper : array_like Number of compounding periods - pmt : array-like + pmt : array_like Payment - fv : array-like + fv : array_like, optional Future value - when : array-like + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) + Returns + ------- + out : ndarray, float + Present value of a series of payments or investments. + Notes ----- The present value ``pv`` is computed by solving the equation:: - fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0 + fv + + pv*(1 + rate)**nper + + pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0 or, when ``rate = 0``:: @@ -258,7 +351,7 @@ def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): Present value fv : array_like Future value - when : array_like, optional + when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)) guess : float, optional Starting guess for solving the rate of interest @@ -296,11 +389,27 @@ def rate(nper, pmt, pv, fv, when='end', guess=0.10, tol=1e-6, maxiter=100): return rn def irr(values): - """Internal Rate of Return + """ + Return the Internal Rate of Return (IRR). + + This is the rate of return that gives a net present value of 0.0. - This is the rate of return that gives a net present value of 0.0 + Parameters + ---------- + values : array_like, shape(N,) + Input cash flows per time period. At least the first value would be + negative to represent the investment in the project. + + Returns + ------- + out : float + Internal Rate of Return for periodic input values. + + Examples + -------- + >>> np.irr([-100, 39, 59, 55, 20]) + 0.2809484211599611 - npv(irr(values), values) == 0.0 """ res = np.roots(values[::-1]) # Find the root(s) between 0 and 1 @@ -314,25 +423,51 @@ def irr(values): return rate def npv(rate, values): - """Net Present Value + """ + Returns the NPV (Net Present Value) of a cash flow series. + + Parameters + ---------- + rate : scalar + The discount rate. + values : array_like, shape(M, ) + The values of the time series of cash flows. Must be the same + increment as the `rate`. + + Returns + ------- + out : float + The NPV of the input cash flow series `values` at the discount `rate`. + + Notes + ----- + Returns the result of: + + .. math :: \\sum_{t=1}^M{\\frac{values_t}{(1+rate)^{t}}} - sum ( values_k / (1+rate)**k, k = 1..n) """ values = np.asarray(values) return (values / (1+rate)**np.arange(1,len(values)+1)).sum(axis=0) def mirr(values, finance_rate, reinvest_rate): - """Modified internal rate of return + """ + Modified internal rate of return. Parameters ---------- - values: + values : array_like Cash flows (must contain at least one positive and one negative value) or nan is returned. - finance_rate : + finance_rate : scalar Interest rate paid on the cash flows - reinvest_rate : + reinvest_rate : scalar Interest rate received on the cash flows upon reinvestment + + Returns + ------- + out : float + Modified internal rate of return + """ values = np.asarray(values) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 19037d975..0654fad01 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -34,34 +34,35 @@ import numpy as np def linspace(start, stop, num=50, endpoint=True, retstep=False): """ - Return evenly spaced numbers. + Return evenly spaced numbers over a specified interval. - `linspace` returns `num` evenly spaced samples, calculated over the - interval ``[start, stop]``. The endpoint of the interval can optionally - be excluded. + Returns `num` evenly spaced samples, calculated over the + interval [`start`, `stop` ]. + + The endpoint of the interval can optionally be excluded. Parameters ---------- - start : float + start : {float, int} The starting value of the sequence. - stop : float + stop : {float, int} The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. - num : int + num : int, optional Number of samples to generate. Default is 50. - endpoint : bool - If true, `stop` is the last sample. Otherwise, it is not included. + endpoint : bool, optional + If True, `stop` is the last sample. Otherwise, it is not included. Default is True. - retstep : bool + retstep : bool, optional If True, return (`samples`, `step`), where `step` is the spacing between samples. Returns ------- samples : ndarray - `num` equally spaced samples in the closed interval + There are `num` equally spaced samples in the closed interval ``[start, stop]`` or the half-open interval ``[start, stop)`` (depending on whether `endpoint` is True or False). step : float (only if `retstep` is True) @@ -71,8 +72,7 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False): See Also -------- arange : Similiar to `linspace`, but uses a step size (instead of the - number of samples). Note that, when used with a float - endpoint, the endpoint may or may not be included. + number of samples). logspace : Samples uniformly distributed in log space. Examples @@ -409,36 +409,36 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None): Parameters ---------- - sample : array-like - Data to histogram passed as a sequence of D arrays of length N, or - as an (N,D) array. + sample : array_like + Data to histogram passed as a sequence of D arrays of length N, or + as an (N,D) array. bins : sequence or int, optional - The bin specification: + The bin specification: - * A sequence of arrays describing the bin edges along each dimension. - * The number of bins for each dimension (nx, ny, ... =bins) - * The number of bins for all dimensions (nx=ny=...=bins). + * A sequence of arrays describing the bin edges along each dimension. + * The number of bins for each dimension (nx, ny, ... =bins) + * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional - A sequence of lower and upper bin edges to be used if the edges are - not given explicitely in `bins`. Defaults to the minimum and maximum - values along each dimension. + A sequence of lower and upper bin edges to be used if the edges are + not given explicitely in `bins`. Defaults to the minimum and maximum + values along each dimension. normed : boolean, optional - If False, returns the number of samples in each bin. If True, returns - the bin density, ie, the bin count divided by the bin hypervolume. - weights : array-like (N,), optional - An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. - Weights are normalized to 1 if normed is True. If normed is False, the - values of the returned histogram are equal to the sum of the weights - belonging to the samples falling into each bin. + If False, returns the number of samples in each bin. If True, returns + the bin density, ie, the bin count divided by the bin hypervolume. + weights : array_like (N,), optional + An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. + Weights are normalized to 1 if normed is True. If normed is False, the + values of the returned histogram are equal to the sum of the weights + belonging to the samples falling into each bin. Returns ------- - H : array - The multidimensional histogram of sample x. See normed and weights for - the different possible semantics. + H : ndarray + The multidimensional histogram of sample x. See normed and weights for + the different possible semantics. edges : list - A list of D arrays describing the bin edges for each dimension. + A list of D arrays describing the bin edges for each dimension. See Also -------- @@ -572,25 +572,24 @@ def average(a, axis=None, weights=None, returned=False): """ Return the weighted average of array over the specified axis. - Parameters ---------- a : array_like Data to be averaged. - axis : {None, integer}, optional + axis : int, optional Axis along which to average `a`. If `None`, averaging is done over the entire array irrespective of its shape. - weights : {None, array_like}, optional + weights : array_like, optional The importance that each datum has in the computation of the average. - The weights array can either be 1D (in which case its length must be + The weights array can either be 1-D (in which case its length must be the size of `a` along the given axis) or of the same shape as `a`. If `weights=None`, then all data in `a` are assumed to have a weight equal to one. - returned : {False, boolean}, optional - If `True`, the tuple (`average`, `sum_of_weights`) is returned, - otherwise only the average is returned. Note that if `weights=None`, - `sum_of_weights` is equivalent to the number of elements over which - the average is taken. + returned : bool, optional + Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) + is returned, otherwise only the average is returned. Note that + if `weights=None`, `sum_of_weights` is equivalent to the number of + elements over which the average is taken. Returns ------- @@ -660,7 +659,64 @@ def average(a, axis=None, weights=None, returned=False): return avg def asarray_chkfinite(a): - """Like asarray, but check that no NaNs or Infs are present. + """ + Convert the input to an array, checking for NaNs or Infs. + + Parameters + ---------- + a : array_like + Input data, in any form that can be converted to an array. This + includes lists, lists of tuples, tuples, tuples of tuples, tuples + of lists and ndarrays. Success requires no NaNs or Infs. + dtype : data-type, optional + By default, the data-type is inferred from the input data. + order : {'C', 'F'}, optional + Whether to use row-major ('C') or column-major ('FORTRAN') memory + representation. Defaults to 'C'. + + Returns + ------- + out : ndarray + Array interpretation of `a`. No copy is performed if the input + is already an ndarray. If `a` is a subclass of ndarray, a base + class ndarray is returned. + + Raises + ------ + ValueError + Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). + + See Also + -------- + asarray : Create and array. + asanyarray : Similar function which passes through subclasses. + ascontiguousarray : Convert input to a contiguous array. + asfarray : Convert input to a floating point ndarray. + asfortranarray : Convert input to an ndarray with column-major + memory order. + fromiter : Create an array from an iterator. + fromfunction : Construct an array by executing a function on grid + positions. + + Examples + -------- + Convert a list into an array. If all elements are finite + ``asarray_chkfinite`` is identical to ``asarray``. + + >>> a = [1, 2] + >>> np.asarray_chkfinite(a) + array([1, 2]) + + Raises ValueError if array_like contains Nans or Infs. + + >>> a = [1, 2, np.inf] + >>> try: + ... np.asarray_chkfinite(a) + ... except ValueError: + ... print 'ValueError' + ... + ValueError + """ a = asarray(a) if (a.dtype.char in typecodes['AllFloat']) \ @@ -821,6 +877,15 @@ def select(condlist, choicelist, default=0): output += [V[m] for V,C in zip(values,cond) if C[m]] or [default] + Examples + -------- + >>> t = np.arange(10) + >>> s = np.arange(10)*100 + >>> condlist = [t == 4, t > 5] + >>> choicelist = [s, t] + >>> np.select(condlist, choicelist) + array([ 0, 0, 0, 0, 400, 0, 6, 7, 8, 9]) + """ n = len(condlist) n2 = len(choicelist) @@ -1155,14 +1220,18 @@ def angle(z, deg=0): z : array_like A complex number or sequence of complex numbers. deg : bool, optional - Return angle in degrees if True, radians if False. Default is False. + Return angle in degrees if True, radians if False (default). Returns ------- angle : {ndarray, scalar} - The angle is defined as counterclockwise from the positive real axis on + The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. + See Also + -------- + arctan2 + Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians @@ -1233,6 +1302,13 @@ def sort_complex(a): out : complex ndarray Always returns a sorted complex array. + Examples + -------- + >>> 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]) + """ b = array(a,copy=True) b.sort() @@ -1360,9 +1436,27 @@ def extract(condition, arr): return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): - """Similar to putmask arr[mask] = vals but the 1D array vals has the - same number of elements as the non-zero values of mask. Inverse of - extract. + """ + Changes elements of an array based on conditional and input values. + + Similar to ``putmask(a, mask, vals)`` but the 1D array `vals` has the + same number of elements as the non-zero values of `mask`. Inverse of + ``extract``. + + Sets `a`.flat[n] = `values`\\[n] for each n where `mask`.flat[n] is true. + + Parameters + ---------- + a : array_like + Array to put data into. + mask : array_like + Boolean mask array. + values : array_like, shape(number of non-zero `mask`, ) + Values to put into `a`. + + See Also + -------- + putmask, put, take """ return _insert(arr, mask, vals) @@ -1401,46 +1495,111 @@ def _nanop(op, fill, a, axis=None): def nansum(a, axis=None): """ - Sum the array along the given axis, treating NaNs as zero. + Return the sum of array elements over a given axis treating + Not a Numbers (NaNs) as zero. Parameters ---------- - a : array-like - Input array. - axis : {int, None}, optional - Axis along which the sum is computed. By default `a` is flattened. + a : array_like + Array containing numbers whose sum is desired. If `a` is not an + array, a conversion is attempted. + axis : int, optional + Axis along which the sum is computed. The default is to compute + the sum of the flattened array. Returns ------- - y : {ndarray, scalar} - The sum ignoring NaNs. + y : ndarray + An array with the same shape as a, with the specified axis removed. + If a is a 0-d array, or if axis is None, a scalar is returned with + the same dtype as `a`. + + See Also + -------- + numpy.sum : Sum across array including Not a Numbers. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a Number, positive 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. + If positive or negative infinity are present the result is positive or + negative infinity. But if both positive and negative infinity are present, + the result is Not A Number (NaN). + + Arithmetic is modular when using integer types (all elements of `a` must + be finite i.e. no elements that are NaNs, positive infinity and negative + infinity because NaNs are floating point types), and no error is raised + on overflow. + Examples -------- - >>> np.nansum([np.nan, 1]) + >>> np.nansum(1) + 1 + >>> np.nansum([1]) + 1 + >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) + >>> np.nansum(a) + 3.0 >>> np.nansum(a, axis=0) array([ 2., 1.]) + When positive infinity and negative infinity are present + + >>> np.nansum([1, np.nan, np.inf]) + inf + >>> np.nansum([1, np.nan, np.NINF]) + -inf + >>> np.nansum([1, np.nan, np.inf, np.NINF]) + nan + """ return _nanop(np.sum, 0, a, axis) def nanmin(a, axis=None): """ - Find the minimum along the given axis, ignoring NaNs. + Return the minimum of array elements over the given axis ignoring any NaNs. Parameters ---------- a : array_like - Input array. + Array containing numbers whose sum is desired. If `a` is not + an array, a conversion is attempted. axis : int, optional - Axis along which the minimum is computed. By default `a` is flattened. + Axis along which the minimum is computed.The default is to compute + the minimum of the flattened array. Returns ------- y : {ndarray, scalar} - The minimum ignoring NaNs. + An array with the same shape as `a`, with the specified axis removed. + If `a` is a 0-d array, or if axis is None, a scalar is returned. The + the same dtype as `a` is returned. + + + See Also + -------- + numpy.amin : Minimum across array including any Not a Numbers. + numpy.nanmax : Maximum across array ignoring any Not a Numbers. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a Number, positive 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. + Positive infinity is treated as a very large number and negative infinity + is treated as a very small (i.e. negative) number. + + If the input has a integer type, an integer type is returned unless + the input contains NaNs and infinity. + Examples -------- @@ -1452,34 +1611,65 @@ def nanmin(a, axis=None): >>> np.nanmin(a, axis=1) array([ 1., 3.]) + When positive infinity and negative infinity are present: + + >>> np.nanmin([1, 2, np.nan, np.inf]) + 1.0 + >>> np.nanmin([1, 2, np.nan, np.NINF]) + -inf + """ return _nanop(np.min, np.inf, a, axis) def nanargmin(a, axis=None): """ - Return indices of the minimum values along the given axis of `a`, - ignoring NaNs. + Return indices of the minimum values along an axis, ignoring NaNs. - Refer to `numpy.nanargmax` for detailed documentation. + + See Also + -------- + nanargmax : corresponding function for maxima; see for details. """ return _nanop(np.argmin, np.inf, a, axis) def nanmax(a, axis=None): """ - Find the maximum along the given axis, ignoring NaNs. + Return the maximum of array elements over the given axis ignoring any NaNs. Parameters ---------- - a : array-like - Input array. - axis : {int, None}, optional - Axis along which the maximum is computed. By default `a` is flattened. + a : array_like + Array containing numbers whose maximum is desired. If `a` is not + an array, a conversion is attempted. + axis : int, optional + Axis along which the maximum is computed.The default is to compute + the maximum of the flattened array. Returns ------- - y : {ndarray, scalar} - The maximum ignoring NaNs. + y : ndarray + An array with the same shape as `a`, with the specified axis removed. + If `a` is a 0-d array, or if axis is None, a scalar is returned. The + the same dtype as `a` is returned. + + See Also + -------- + numpy.amax : Maximum across array including any Not a Numbers. + numpy.nanmin : Minimum across array ignoring any Not a Numbers. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a Number, positive 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. + Positive infinity is treated as a very large number and negative infinity + is treated as a very small (i.e. negative) number. + + If the input has a integer type, an integer type is returned unless + the input contains NaNs and infinity. Examples -------- @@ -1491,29 +1681,35 @@ def nanmax(a, axis=None): >>> np.nanmax(a, axis=1) array([ 2., 3.]) + When positive infinity and negative infinity are present: + + >>> np.nanmax([1, 2, np.nan, np.NINF]) + 2.0 + >>> np.nanmax([1, 2, np.nan, np.inf]) + inf + """ return _nanop(np.max, -np.inf, a, axis) def nanargmax(a, axis=None): """ - Return indices of the maximum values over the given axis of 'a', - ignoring NaNs. + Return indices of the maximum values over an axis, ignoring NaNs. Parameters ---------- - a : array-like + a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- - index_array : {ndarray, int} + index_array : ndarray An array of indices or a single index value. See Also -------- - argmax + argmax, nanargmin Examples -------- @@ -1531,8 +1727,19 @@ def nanargmax(a, axis=None): return _nanop(np.argmax, -np.inf, a, axis) def disp(mesg, device=None, linefeed=True): - """Display a message to the given device (default is sys.stdout) - with or without a linefeed. + """ + Display a message on a device + + Parameters + ---------- + mesg : string + Message to display. + device : device object with 'write' method + Device to write message. If None, defaults to ``sys.stdout`` which is + very similar to ``print``. + linefeed : bool, optional + Option whether to print a line feed or not. Defaults to True. + """ if device is None: import sys @@ -1695,11 +1902,11 @@ def cov(m, y=None, rowvar=1, bias=0): Parameters ---------- - m : array-like - A 1D or 2D array containing multiple variables and observations. + m : array_like + A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. - y : array-like, optional + y : array_like, optional An additional set of variables and observations. `y` has the same form as that of `m`. rowvar : int, optional @@ -1790,7 +1997,7 @@ def cov(m, y=None, rowvar=1, bias=0): def corrcoef(x, y=None, rowvar=1, bias=0): """ - Correlation coefficients. + Return correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, P, and the @@ -2014,9 +2221,9 @@ def hanning(M): Returns ------- - out : array + out : ndarray, shape(M,) The window, normalized to one (the value one - appears only if the number of samples is odd). + appears only if `M` is odd). See Also -------- @@ -2259,17 +2466,30 @@ def _i0_2(x): def i0(x): """ - Modified Bessel function of the first kind, order 0, :math:`I_0` + Modified Bessel function of the first kind, order 0. + + Usually denoted :math:`I_0`. Parameters ---------- - x : array-like, dtype float or complex + x : array_like, dtype float or complex Argument of the Bessel function. Returns ------- out : ndarray, shape z.shape, dtype z.dtype - The modified Bessel function evaluated for all elements of `x`. + The modified Bessel function evaluated at the elements of `x`. + + See Also + -------- + scipy.special.iv, scipy.special.ive + + References + ---------- + .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", + 10th printing, 1964, pp. 374. http://www.math.sfu.ca/~cbm/aands/ + .. [2] Wikipedia, "Bessel function", + http://en.wikipedia.org/wiki/Bessel_function Examples -------- @@ -2361,11 +2581,11 @@ def kaiser(M,beta): References ---------- - .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by - digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. - John Wiley and Sons, New York, (1966). - .. [2]\tE.R. Kanasewich, "Time Sequence Analysis in Geophysics", The - University of Alberta Press, 1975, pp. 177-178. + .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by + digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. + John Wiley and Sons, New York, (1966). + .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The + University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", http://en.wikipedia.org/wiki/Window_function @@ -2483,6 +2703,28 @@ def sinc(x): return sin(y)/y def msort(a): + """ + Return a copy of an array sorted along the first axis. + + Parameters + ---------- + a : array_like + Array to be sorted. + + Returns + ------- + sorted_array : ndarray + Array of the same type and shape as `a`. + + See Also + -------- + sort + + Notes + ----- + ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``. + + """ b = array(a,subok=True,copy=True) b.sort(0) return b @@ -2593,7 +2835,7 @@ def trapz(y, x=None, dx=1.0, axis=-1): ---------- y : array_like Input array to integrate. - x : {array_like, None}, optional + x : array_like, optional If `x` is None, then spacing between all `y` elements is 1. dx : scalar, optional If `x` is None, spacing given by `dx` is assumed. @@ -2707,11 +2949,11 @@ def delete(arr, obj, axis=None): Parameters ---------- - arr : array-like + arr : array_like Input array. obj : slice, integer or an array of integers Indicate which sub-arrays to remove. - axis : integer or None + axis : integer, optional The axis along which to delete the subarray defined by `obj`. If `axis` is None, `obj` is applied to the flattened array. diff --git a/numpy/lib/getlimits.py b/numpy/lib/getlimits.py index 4c432c0e4..bc5fbbf5e 100644 --- a/numpy/lib/getlimits.py +++ b/numpy/lib/getlimits.py @@ -22,6 +22,8 @@ _convert_to_float = { class finfo(object): """ + finfo(dtype) + Machine limits for floating point types. Attributes @@ -170,6 +172,8 @@ nexp =%(nexp)6s min= -max class iinfo: """ + iinfo(type) + Machine limits for integer types. Attributes diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 02018c87e..3021635dc 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -20,8 +20,6 @@ def unravel_index(x,dims): """ Convert a flat index into an index tuple for an array of given shape. - e.g. for a 2x2 array, unravel_index(2,(2,2)) returns (1,0). - Parameters ---------- x : int @@ -31,25 +29,26 @@ def unravel_index(x,dims): Notes ----- - Since x.flat[p] == x.max() it may be easier to use flattened indexing - than to re-map the index to a tuple. + In the Examples section, since ``arr.flat[x] == arr.max()`` it may be + easier to use flattened indexing than to re-map the index to a tuple. Examples -------- - >>> x = np.ones((5,4)) - >>> x + >>> arr = np.ones((5,4)) + >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) - >>> p = x.argmax() - >>> p + >>> x = arr.argmax() + >>> x 19 - >>> idx = np.unravel_index(p, x.shape) + >>> dims = arr.shape + >>> idx = np.unravel_index(x, dims) >>> idx (4, 3) - >>> x[idx] == x.max() + >>> arr[idx] == arr.max() True """ diff --git a/numpy/lib/io.py b/numpy/lib/io.py index caa790809..deb86fb61 100644 --- a/numpy/lib/io.py +++ b/numpy/lib/io.py @@ -81,36 +81,36 @@ class NpzFile(object): def load(file, memmap=False): """ - Load pickled, ``.npy``, and ``.npz`` binary files. + Load a pickled, ``.npy``, or ``.npz`` binary file. Parameters ---------- file : file-like object or string - The file to read. It must support seek and read methods. + The file to read. It must support ``seek()`` and ``read()`` methods. memmap : bool If True, then memory-map the ``.npy`` file (or unzip the ``.npz`` file - into a temporary directory and memory-map each component). This has no - effect for a pickled file. + into a temporary directory and memory-map each component). This has + no effect for a pickled file. Returns ------- result : array, tuple, dict, etc. Data stored in the file. - - If file contains pickle data, then whatever is stored in the - pickle is returned. - - - If the file is a ``.npy`` file, then an array is returned. - - - If the file is a ``.npz`` file, then a dictionary-like object is - returned, containing {filename: array} key-value pairs, one for - every file in the archive. - Raises ------ IOError If the input file does not exist or cannot be read. + Notes + ----- + - If file contains pickle data, then whatever is stored in the + pickle is returned. + - If the file is a ``.npy`` file, then an array is returned. + - If the file is a ``.npz`` file, then a dictionary-like object is + returned, containing {filename: array} key-value pairs, one for + every file in the archive. + Examples -------- >>> np.save('/tmp/123', np.array([1, 2, 3]) @@ -178,12 +178,23 @@ def save(file, arr): format.write_array(fid, arr) def savez(file, *args, **kwds): - """Save several arrays into an .npz file format which is a zipped-archive + """ + Save several arrays into an .npz file format which is a zipped-archive of arrays 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. + + Parameters + ---------- + file : string + File name of .npz file. + args : Arguments + Function arguments. + kwds : Keyword arguments + Keywords. + """ # Import is postponed to here since zipfile depends on gzip, an optional diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 7e3a02107..4a70c9fa3 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -129,7 +129,7 @@ def roots(p): Parameters ---------- - p : (N,) array_like + p : array_like of shape(M,) Rank-1 array of polynomial co-efficients. Returns @@ -200,7 +200,7 @@ def polyint(p, m=1, k=None): Parameters ---------- - p : poly1d or sequence + p : {array_like, poly1d} Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional @@ -523,7 +523,7 @@ def polyfit(x, y, deg, rcond=None, full=False): def polyval(p, x): """ - Evaluate the polynomial p at x. + Evaluate a polynomial at specific values. If p is of length N, this function returns the value: @@ -543,7 +543,7 @@ def polyval(p, x): Returns ------- - values : {array, poly1d} + values : {ndarray, poly1d} If either p or x is an instance of poly1d, then an instance of poly1d is returned, otherwise a 1D array is returned. In the case where x is a poly1d, the result is the composition of the two polynomials, i.e., @@ -577,7 +577,28 @@ def polyval(p, x): return y def polyadd(a1, a2): - """Adds two polynomials represented as sequences + """ + Returns sum of two polynomials. + + Returns sum of polynomials; `a1` + `a2`. Input polynomials are + represented as an array_like sequence of terms or a poly1d object. + + Parameters + ---------- + a1 : {array_like, poly1d} + Polynomial as sequence of terms. + a2 : {array_like, poly1d} + Polynomial as sequence of terms. + + Returns + ------- + out : {ndarray, poly1d} + Array representing the polynomial terms. + + See Also + -------- + polyval, polydiv, polymul, polyadd + """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) @@ -596,7 +617,35 @@ def polyadd(a1, a2): return val def polysub(a1, a2): - """Subtracts two polynomials represented as sequences + """ + Returns difference from subtraction of two polynomials input as sequences. + + Returns difference of polynomials; `a1` - `a2`. Input polynomials are + represented as an array_like sequence of terms or a poly1d object. + + Parameters + ---------- + a1 : {array_like, poly1d} + Minuend polynomial as sequence of terms. + a2 : {array_like, poly1d} + Subtrahend polynomial as sequence of terms. + + Returns + ------- + out : {ndarray, poly1d} + Array representing the polynomial terms. + + See Also + -------- + polyval, polydiv, polymul, polyadd + + Examples + -------- + .. math:: (2 x^2 + 10x - 2) - (3 x^2 + 10x -4) = (-x^2 + 2) + + >>> np.polysub([2, 10, -2], [3, 10, -4]) + array([-1, 0, 2]) + """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) @@ -616,7 +665,29 @@ def polysub(a1, a2): def polymul(a1, a2): - """Multiplies two polynomials represented as sequences. + """ + Returns product of two polynomials represented as sequences. + + The input arrays specify the polynomial terms in turn with a length equal + to the polynomial degree plus 1. + + Parameters + ---------- + a1 : {array_like, poly1d} + First multiplier polynomial. + a2 : {array_like, poly1d} + Second multiplier polynomial. + + Returns + ------- + out : {ndarray, poly1d} + Product of inputs. + + See Also + -------- + poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, + polyval + """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1,a2 = poly1d(a1),poly1d(a2) @@ -626,8 +697,40 @@ def polymul(a1, a2): return val def polydiv(u, v): - """Computes q and r polynomials so that u(s) = q(s)*v(s) + r(s) - and deg r < deg v. + """ + Returns the quotient and remainder of polynomial division. + + The input arrays specify the polynomial terms in turn with a length equal + to the polynomial degree plus 1. + + Parameters + ---------- + u : {array_like, poly1d} + Dividend polynomial. + v : {array_like, poly1d} + Divisor polynomial. + + Returns + ------- + q : ndarray + Polynomial terms of quotient. + r : ndarray + Remainder of polynomial division. + + See Also + -------- + poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub, + polyval + + Examples + -------- + .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25 + + >>> x = np.array([3.0, 5.0, 2.0]) + >>> y = np.array([2.0, 1.0]) + >>> np.polydiv(x, y) + >>> (array([ 1.5 , 1.75]), array([ 0.25])) + """ truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d)) u = atleast_1d(u) @@ -683,7 +786,7 @@ class poly1d(object): Parameters ---------- c_or_r : array_like - Polynomial coefficients, in decreasing powers. E.g., + Polynomial coefficients, in decreasing powers. For example, ``(1, 2, 3)`` implies :math:`x^2 + 2x + 3`. If `r` is set to True, these coefficients specify the polynomial roots (values where the polynomial evaluate to 0) instead. diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index 8f6073bd5..a890a8a2b 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -12,28 +12,28 @@ def apply_along_axis(func1d,axis,arr,*args): """ Apply function to 1-D slices along the given axis. - Execute `func1d(arr[i],*args)` where `func1d` takes 1-D arrays, `arr` is + 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 `arr`. + function along the given axis for each 1-D subarray in `a`. Parameters ---------- func1d : function This function should be able to take 1-D arrays. It is applied to 1-D - slices of `arr` along the specified axis. + slices of `a` along the specified axis. axis : integer Axis along which `func1d` is applied. - arr : ndarray + a : ndarray Input array. args : any Additional arguments to `func1d`. Returns ------- - outarr : ndarray - The output array. The shape of `outarr` depends on the return - value of `func1d`. If it returns arrays with the same shape as the - input arrays it receives, `outarr` has the same shape as `arr`. + 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`. See Also -------- @@ -112,28 +112,28 @@ def apply_over_axes(func, a, axes): """ Apply a function repeatedly over multiple axes. - `func` is called as `res = func(a, axis)`, with `axis` the first element - of `axes`. The result `res` of the function call has to have - the same or one less dimension(s) as `a`. If `res` has one less dimension - than `a`, a dimension is then inserted before `axis`. + `func` is called as `res = func(a, axis)`, where `axis` is the first + element of `axes`. The result `res` of the function call must have + either the same dimensions as `a` or one less dimension. If `res` has one + less dimension than `a`, a dimension is inserted before `axis`. The call to `func` is then repeated for each axis in `axes`, with `res` as the first argument. Parameters ---------- func : function - This function should take two arguments, `func(a, axis)`. - arr : ndarray + This function must take two arguments, `func(a, axis)`. + a : ndarray Input array. axes : array_like - Axes over which `func` has to be applied, the elements should be + Axes over which `func` is applied, the elements must be integers. Returns ------- val : ndarray - The output array. The number of dimensions is the same as `a`, - the shape can be different, this depends on whether `func` changes + The output array. The number of dimensions is the same as `a`, but + the shape can be different. This depends on whether `func` changes the shape of its output with respect to its input. See Also @@ -448,7 +448,7 @@ def hstack(tup): Stack arrays in sequence horizontally (column wise) Take a sequence of arrays and stack them horizontally to make - a single array. hstack will rebuild arrays divided by hsplit. + a single array. Rebuild arrays divided by ``hsplit``. Parameters ---------- @@ -458,7 +458,18 @@ def hstack(tup): Returns ------- stacked : ndarray - Ndarray formed by stacking the given arrays. + The array formed by stacking the given arrays. + + See Also + -------- + vstack : Stack along first axis. + dstack : Stack along third axis. + concatenate : Join arrays. + hsplit : Split array along second axis. + + Notes + ----- + Equivalent to ``np.concatenate(tup, axis=1)`` Examples -------- @@ -512,11 +523,12 @@ def column_stack(tup): def dstack(tup): """ - Stack arrays in sequence depth wise (along third dimension) + Stack arrays in sequence depth wise (along third axis) - Take a sequence of arrays and stack them along the third axis. + Takes a sequence of arrays and stack them along the third axis + to make a single array. Rebuilds arrays divided by ``dsplit``. This is a simple way to stack 2D arrays (images) into a single - 3D array for processing. dstack will rebuild arrays divided by dsplit. + 3D array for processing. Parameters ---------- @@ -524,6 +536,22 @@ def dstack(tup): Arrays to stack. All of them must have the same shape along all but the third axis. + Returns + ------- + stacked : ndarray + The array formed by stacking the given arrays. + + See Also + -------- + vstack : Stack along first axis. + hstack : Stack along second axis. + concatenate : Join arrays. + dsplit : Split array along third axis. + + Notes + ----- + Equivalent to ``np.concatenate(tup, axis=2)`` + Examples -------- >>> a = np.array((1,2,3)) diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index cc33923ad..e796a065a 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -308,13 +308,13 @@ def tri(N, M=None, k=0, dtype=float): Number of rows in the array. M : int, optional Number of columns in the array. - By default, `M` is taken to equal to `N`. + By default, `M` is taken equal to `N`. k : int, optional The sub-diagonal below which the array is filled. - ``k = 0`` is the main diagonal, while ``k < 0`` is below it, - and ``k > 0`` is above. The default is 0. + `k` = 0 is the main diagonal, while `k` < 0 is below it, + and `k` > 0 is above. The default is 0. dtype : dtype, optional - Data type of the returned array. The default is `float`. + Data type of the returned array. The default is float. Returns ------- @@ -341,13 +341,13 @@ def tri(N, M=None, k=0, dtype=float): def tril(m, k=0): """ - Lower triangular. + Lower triangle of an array. - Return a copy of an array with elements above the k-th diagonal zeroed. + Return a copy of an array with elements above the `k`-th diagonal zeroed. Parameters ---------- - m : array-like, shape (M, N) + m : array_like, shape (M, N) Input array. k : int Diagonal above which to zero elements. @@ -377,7 +377,7 @@ def tril(m, k=0): def triu(m, k=0): """ - Upper triangular. + Upper triangle of an array. Construct a copy of a matrix with elements below the k-th diagonal zeroed. @@ -453,9 +453,9 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): Parameters ---------- - x : array-like (N,) + x : array_like, shape(N,) A sequence of values to be histogrammed along the first dimension. - y : array-like (N,) + y : array_like, shape(M,) A sequence of values to be histogrammed along the second dimension. bins : int or [int, int] or array-like or [array, array], optional The bin specification: @@ -465,7 +465,7 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): * the bin edges for the two dimensions (x_edges=y_edges=bins), * the bin edges in each dimension (x_edges, y_edges = bins). - range : array-like, (2,2), optional + range : array_like, shape(2,2), optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the `bins` parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be @@ -473,7 +473,7 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): normed : boolean, optional If False, returns the number of samples in each bin. If True, returns the bin density, ie, the bin count divided by the bin area. - weights : array-like (N,), optional + weights : array-like, shape(N,), optional An array of values `w_i` weighing each sample `(x_i, y_i)`. Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the @@ -481,13 +481,13 @@ def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): Returns ------- - H : array (nx, ny) + H : ndarray, shape(nx, ny) The bidimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension. - xedges : array (nx,) + xedges : ndarray, shape(nx,) The bin edges along the first dimension. - yedges : array (ny,) + yedges : ndarray, shape(ny,) The bin edges along the second dimension. See Also diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 0a78986ac..6f37326cc 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -42,7 +42,32 @@ def mintypecode(typechars,typeset='GDFgdf',default='d'): return l[0][1] def asfarray(a, dtype=_nx.float_): - """asfarray(a,dtype=None) returns a as a float array.""" + """ + Return an array converted to 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. + + Returns + ------- + out : ndarray, float + Input `a` as a float ndarray. + + Examples + -------- + >>> np.asfarray([2, 3]) + array([ 2., 3.]) + >>> np.asfarray([2, 3], dtype='float') + array([ 2., 3.]) + >>> np.asfarray([2, 3], dtype='int8') + array([ 2., 3.]) + + """ dtype = _nx.obj2sctype(dtype) if not issubclass(dtype, _nx.inexact): dtype = _nx.float_ @@ -54,7 +79,7 @@ def real(val): Parameters ---------- - val : {array_like, scalar} + val : array_like Input array. Returns @@ -100,10 +125,27 @@ def imag(val): return asanyarray(val).imag def iscomplex(x): - """Return a boolean array where elements are True if that element - is complex (has non-zero imaginary part). + """ + Return a bool array, True if element is complex (non-zero imaginary part). For scalars, return a boolean. + + Parameters + ---------- + x : array_like + Input array. + + Returns + ------- + out : ndarray, bool + Output array. + + Examples + -------- + >>> x = np.array([1,2,3.j]) + >>> np.iscomplex(x) + array([False, False, True], dtype=bool) + """ ax = asanyarray(x) if issubclass(ax.dtype.type, _nx.complexfloating): @@ -219,7 +261,7 @@ def real_if_close(a,tol=100): Parameters ---------- - a : {array_like, scalar} + a : array_like Input array. tol : scalar Tolerance for the complex part of the elements in the array. @@ -241,6 +283,16 @@ def real_if_close(a,tol=100): 2.2204460492503131e-16. You can use 'np.finfo(np.float).eps' to print out the machine epsilon for floats. + Examples + -------- + >>> np.finfo(np.float).eps # DOCTEST +skip + 2.2204460492503131e-16 + + >>> np.real_if_close([2.1 + 4e-14j], tol = 1000) + array([ 2.1]) + >>> np.real_if_close([2.1 + 4e-13j], tol = 1000) + array([ 2.1 +4.00000000e-13j]) + """ a = asanyarray(a) if not issubclass(a.dtype.type, _nx.complexfloating): @@ -255,7 +307,24 @@ def real_if_close(a,tol=100): def asscalar(a): - """Convert an array of size 1 to its scalar equivalent. + """ + Convert an array of size 1 to its scalar equivalent. + + Parameters + ---------- + a : ndarray + Input array. + + Returns + ------- + out : scalar + Scalar of size 1 array. + + Examples + -------- + >>> np.asscalar(np.array([24])) + >>> 24 + """ return a.item() @@ -322,19 +391,28 @@ def common_type(*arrays): """ Return the inexact scalar type which is most common in a list of arrays. - The return type will always be a inexact scalar type, even if all - the arrays are integer arrays + The return type will always be an inexact scalar type, even if all the + arrays are integer arrays Parameters ---------- - arrays: sequence of array_like - Input sequence of arrays. + array1, array2, ... : ndarray + Input arrays. Returns ------- - out: data type code + out : data type code Data type code. + See Also + -------- + dtype + + Examples + -------- + >>> np.common_type(np.arange(4), np.array([45,6]), np.array([45.0, 6.0])) + <type 'numpy.float64'> + """ is_complex = False precision = 0 diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 6df529609..24f35da81 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -7,7 +7,38 @@ __all__ = ['fix', 'isneginf', 'isposinf', 'log2'] import numpy.core.numeric as nx def fix(x, y=None): - """ Round x to nearest integer towards zero. + """ + Round to nearest integer towards zero. + + Round an array of floats element-wise to nearest integer towards zero. + The rounded values are returned as floats. + + Parameters + ---------- + x : array_like + An array of floats to be rounded + y : ndarray, optional + Output array + + Returns + ------- + out : ndarray of floats + The array of rounded numbers + + See Also + -------- + floor : Round downwards + around : Round to given number of decimals + + Examples + -------- + >>> np.fix(3.14) + 3.0 + >>> np.fix(3) + 3.0 + >>> np.fix([2.1, 2.9, -2.1, -2.9]) + array([ 2., 2., -2., -2.]) + """ x = nx.asanyarray(x) if y is None: @@ -19,7 +50,10 @@ def fix(x, y=None): def isposinf(x, y=None): """ - Return True where x is +infinity, and False otherwise. + Shows which elements of the input are positive infinity. + + Returns a numpy array resulting from an element-wise test for positive + infinity. Parameters ---------- @@ -31,16 +65,54 @@ def isposinf(x, y=None): Returns ------- y : ndarray - A boolean array where y[i] = True only if x[i] = +Inf. + 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. + + 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. See Also -------- - isneginf, isfinite + 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 + + 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. + + Errors result if second argument is also supplied with scalar input or + if first and second arguments have different shapes. + + Numpy's definitions for positive infinity (PINF) and negative infinity + (NINF) may be change in the future versions. + Examples -------- + >>> np.isposinf(np.PINF) + array(True, dtype=bool) + >>> np.isposinf(np.inf) + array(True, dtype=bool) + >>> np.isposinf(np.NINF) + array(False, dtype=bool) >>> np.isposinf([-np.inf, 0., np.inf]) - array([ False, False, True], dtype=bool) + array([False, False, True], dtype=bool) + >>> 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]) """ if y is None: @@ -95,11 +167,10 @@ def log2(x, y=None): Returns ------- - y : {ndarray, scalar} + y : ndarray The logarithm to the base 2 of `x` elementwise. NaNs are returned where `x` is negative. - See Also -------- log, log1p, log10 diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 0b2731005..d749f00b6 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -42,15 +42,23 @@ def get_include(): return d def get_numarray_include(type=None): - """Return the directory in the package that contains the numpy/*.h header - files. + """ + Return the directory that contains the numarray \\*.h header files. - Extension modules that need to compile against numpy should use this - function to locate the appropriate include directory. Using distutils: + Extension modules that need to compile against numarray should use this + function to locate the appropriate include directory. + + Notes + ----- + When using ``distutils``, for example in ``setup.py``. + :: + + import numpy as np + ... + Extension('extension_name', ... + include_dirs=[np.get_numarray_include()]) + ... - import numpy - Extension('extension_name', ... - include_dirs=[numpy.get_numarray_include()]) """ from numpy.numarray import get_numarray_include_dirs include_dirs = get_numarray_include_dirs() @@ -96,10 +104,7 @@ def deprecate(func, oldname=None, newname=None): depdoc = '%s is DEPRECATED!! -- use %s instead' % (oldname, newname,) def newfunc(*args,**kwds): - """ - Use get_include, get_numpy_include is DEPRECATED. - - """ + """Use get_include, get_numpy_include is DEPRECATED.""" warnings.warn(str1, DeprecationWarning) return func(*args, **kwds) @@ -335,18 +340,30 @@ def _makenamedict(module='numpy'): return thedict, dictlist def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): - """Get help information for a function, class, or module. + """ + Get help information for a function, class, or module. + + Parameters + ---------- + object : optional + Input object to get information about. + maxwidth : int, optional + Printing width. + output : file like object open for writing, optional + Write into file like object. + toplevel : string, optional + Start search at this level. + + Examples + -------- + >>> np.info(np.polyval) # doctest: +SKIP - Example: - >>> np.info(np.polyval) # doctest: +SKIP + polyval(p, x) - polyval(p, x) + Evaluate the polymnomial p at x. - Evaluate the polymnomial p at x. + ... - Description: - If p is of length N, this function returns the value: - p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist # Local import to speed up numpy's import time. diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index c0bb95004..352b47549 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -1137,7 +1137,7 @@ def det(a): Parameters ---------- - a : array-like, shape (M, M) + a : array_like, shape (M, M) Input array. Returns diff --git a/numpy/ma/__init__.py b/numpy/ma/__init__.py index c09f73980..17caa9e02 100644 --- a/numpy/ma/__init__.py +++ b/numpy/ma/__init__.py @@ -17,7 +17,7 @@ When we try to calculate the mean of the data, the result is undetermined: nan The mean is calculated using roughly ``np.sum(x)/len(x)``, but since -any number added to ``NaN`` [*]_ produces ``NaN``, this doesn't work. Enter +any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter masked arrays: >>> m = np.ma.masked_array(x, np.isnan(x)) @@ -32,7 +32,7 @@ may now proceed to calculate the mean of the other values: >>> np.mean(m) 2.6666666666666665 -.. [*] Not-a-Number, a floating point value that is the result of an +.. [1] Not-a-Number, a floating point value that is the result of an invalid operation. """ diff --git a/numpy/ma/core.py b/numpy/ma/core.py index c71fccfa9..670bac597 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -986,14 +986,14 @@ def masked_outside(x, v1, v2, copy=True): # def masked_object(x, value, copy=True, shrink=True): """ - Mask the array ``x`` where the data are exactly equal to value. + 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 :func:`masked_values` instead. + point, please use `masked_values`_ instead. Parameters ---------- - x : array-like + x : array_like Array to mask value : var Comparison value @@ -1474,7 +1474,28 @@ class MaskedArray(ndarray): view.__doc__ = ndarray.view.__doc__ #............................................. def astype(self, newtype): - """Returns a copy of the array cast to newtype.""" + """ + Returns a copy of the MaskedArray cast to given newtype. + + Returns + ------- + output : MaskedArray + A copy of self cast to input newtype. + The returned record shape matches self.shape. + + Examples + -------- + >>> x = np.ma.array([[1,2,3.1],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4) + >>> print x + [[1.0 -- 3.1] + [-- 5.0 --] + [7.0 -- 9.0]] + >>> print x.astype(int32) + [[1 -- 3] + [-- 5 --] + [7 -- 9]] + + """ newtype = np.dtype(newtype) output = self._data.astype(newtype).view(type(self)) output._update_from(self) @@ -1862,7 +1883,25 @@ class MaskedArray(ndarray): return result def compressed(self): - """Return a 1-D array of all the non-masked data. + """ + Return a 1-D array of all the non-masked data. + + Returns + ------- + data : ndarray. + A new ndarray holding the non-masked data is returned. + + Notes + ----- + + The result is NOT a MaskedArray ! + + Examples + -------- + >>> x = array(arange(5), mask=[0]+[1]*4) + >>> print x.compressed() + [0] + >>> print type(x.compressed()) + <type 'numpy.ndarray'> """ data = ndarray.ravel(self._data) @@ -2169,7 +2208,26 @@ masked_%(name)s(data = %(data)s, flatten = _arraymethod('flatten') # def ravel(self): - """Returns a 1D version of self, as a view.""" + """ + Returns a 1D version of self, as a view. + + Returns + ------- + MaskedArray + Output view is of shape ``(self.size,)`` (or + ``(np.ma.product(self.shape),)``). + + 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]] + >>> print x.ravel() + [1 -- 3 -- 5 -- 7 -- 9] + + """ r = ndarray.ravel(self._data).view(type(self)) r._update_from(self) if self._mask is not nomask: @@ -2182,27 +2240,40 @@ masked_%(name)s(data = %(data)s, # def reshape (self, *s, **kwargs): """ - Returns a masked array containing the data of a, but with a new shape. - The result is a view to the original array; if this is not possible, - a ValueError is raised. + Returns a masked array containing the data of a, but with a new shape. + The result is a view to the original array; if this is not possible, + a ValueError is raised. - Parameters - ---------- - shape : shape tuple or int - The new shape should be compatible with the original shape. If an - integer, then the result will be a 1D array of that length. - order : {'C', 'F'}, optional - Determines whether the array data should be viewed as in C - (row-major) order or FORTRAN (column-major) order. + Parameters + ---------- + shape : shape tuple or int + The new shape should be compatible with the original shape. If an + integer, then the result will be a 1D array of that length. + order : {'C', 'F'}, optional + Determines whether the array data should be viewed as in C + (row-major) order or FORTRAN (column-major) order. - Returns - ------- - reshaped_array : array - A new view to the array. + Returns + ------- + reshaped_array : array + A new view to the array. - Notes - ----- - If you want to modify the shape in place, please use ``a.shape = s`` + Notes + ----- + If you want to modify the shape in place, please use ``a.shape = s`` + + Examples + -------- + >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1]) + >>> print x + [[-- 2] + [3 --]] + >>> x = x.reshape((4,1)) + >>> print x + [[--] + [2] + [3] + [--]] """ kwargs.update(order=kwargs.get('order','C')) @@ -2235,13 +2306,48 @@ masked_%(name)s(data = %(data)s, return None # def put(self, indices, values, mode='raise'): - """Set storage-indexed locations to corresponding values. + """ + Set storage-indexed locations to corresponding values. + + Sets self._data.flat[n] = values[n] for each n in indices. + If `values` is shorter than `indices` then it will repeat. + If `values` has some masked values, the initial mask is updated + in consequence, else the corresponding values are unmasked. + + Parameters + ---------- + indicies : 1-D array_like + Target indices, interpreted as integers. + values : array_like + Values to place in self._data copy at target indices. + 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. + + Notes + ----- + `values` can be a scalar or length 1 array. - a.put(values, indices, mode) sets a.flat[n] = values[n] for - each n in indices. If ``values`` is shorter than ``indices`` - then it will repeat. If ``values`` has some masked values, the - initial mask is updated in consequence, else the corresponding - values are unmasked. + 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.put([0,4,8],[10,20,30]) + >>> print x + [[10 -- 3] + [-- 20 --] + [7 -- 30]] + + >>> x.put(4,999) + >>> print x + [[10 -- 3] + [-- 999 --] + [7 -- 30]] """ m = self._mask @@ -2279,36 +2385,35 @@ masked_%(name)s(data = %(data)s, #............................................ def all(self, axis=None, out=None): - """a.all(axis=None, out=None) - - Check if all of the elements of `a` are true. - - Performs a :func:`logical_and` over the given axis and returns the result. - Masked values are considered as True during computation. - For convenience, the output array is masked where ALL the values along the - current axis are masked: if the output would have been a scalar and that - all the values are masked, then the output is `masked`. + """ + Check if all of the elements of `a` are true. - Parameters - ---------- - axis : {None, integer} - Axis to perform the operation over. - If None, perform over flattened array. - out : {None, array}, optional - Array into which the result can be placed. Its type is preserved - and it must be of the right shape to hold the output. + Performs a :func:`logical_and` over the given axis and returns the result. + Masked values are considered as True during computation. + For convenience, the output array is masked where ALL the values along the + current axis are masked: if the output would have been a scalar and that + all the values are masked, then the output is `masked`. - See Also - -------- - all : equivalent function + Parameters + ---------- + axis : {None, integer} + Axis to perform the operation over. + If None, perform over flattened array. + out : {None, array}, optional + Array into which the result can be placed. Its type is preserved + and it must be of the right shape to hold the output. + + See Also + -------- + all : equivalent function - Example - ------- - >>> np.ma.array([1,2,3]).all() - True - >>> a = np.ma.array([1,2,3], mask=True) - >>> (a.all() is np.ma.masked) - True + Examples + -------- + >>> np.ma.array([1,2,3]).all() + True + >>> a = np.ma.array([1,2,3], mask=True) + >>> (a.all() is np.ma.masked) + True """ mask = self._mask.all(axis) @@ -2327,25 +2432,24 @@ masked_%(name)s(data = %(data)s, def any(self, axis=None, out=None): - """a.any(axis=None, out=None) - - Check if any of the elements of `a` are true. - - Performs a logical_or over the given axis and returns the result. - Masked values are considered as False during computation. + """ + Check if any of the elements of `a` are true. - Parameters - ---------- - axis : {None, integer} - Axis to perform the operation over. - If None, perform over flattened array and return a scalar. - out : {None, array}, optional - Array into which the result can be placed. Its type is preserved - and it must be of the right shape to hold the output. + Performs a logical_or over the given axis and returns the result. + Masked values are considered as False during computation. - See Also - -------- - any : equivalent function + Parameters + ---------- + axis : {None, integer} + Axis to perform the operation over. + If None, perform over flattened array and return a scalar. + out : {None, array}, optional + Array into which the result can be placed. Its type is preserved + and it must be of the right shape to hold the output. + + See Also + -------- + any : equivalent function """ mask = self._mask.all(axis) @@ -2383,8 +2487,7 @@ masked_%(name)s(data = %(data)s, def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None): - """a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) - + """ Return the sum along the offset diagonal of the array's indicated `axis1` and `axis2`. @@ -2401,27 +2504,49 @@ masked_%(name)s(data = %(data)s, def sum(self, axis=None, dtype=None, out=None): - """a.sum(axis=None, dtype=None, out=None) + """ + Return the sum of the array elements over the given axis. + Masked elements are set to 0 internally. - Return the sum of the array elements over the given axis. - Masked elements are set to 0 internally. + Parameters + ---------- + axis : {None, -1, int}, optional + Axis along which the sum is computed. The default + (`axis` = None) is to compute over the flattened array. + dtype : {None, dtype}, optional + Determines the type of the returned array and of the accumulator + where the elements are summed. If dtype has the value None and + the type of a is an integer type of precision less than the default + platform integer, then the default platform integer precision is + used. Otherwise, the dtype is the same as that of a. + out : {None, ndarray}, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output + but the type will be cast if necessary. - Parameters - ---------- - axis : {None, -1, int}, optional - Axis along which the sum is computed. The default - (`axis` = None) is to compute over the flattened array. - dtype : {None, dtype}, optional - Determines the type of the returned array and of the accumulator - where the elements are summed. If dtype has the value None and - the type of a is an integer type of precision less than the default - platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of a. - out : {None, ndarray}, optional - Alternative output array in which to place the result. It must - have the same shape and buffer length as the expected output - but the type will be cast if necessary. + Returns + ------- + sum_along_axis : MaskedArray or scalar + An array with the same shape as self, with the specified + axis removed. If self is a 0-d array, or if `axis` is None, a scalar + is returned. If an output array is specified, a reference to + `out` is returned. + 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]] + >>> print x.sum() + 25 + >>> print x.sum(axis=1) + [4 5 16] + >>> print x.sum(axis=0) + [8 5 12] + >>> print type(x.sum(axis=0, dtype=np.int64)[0]) + <type 'numpy.int64'> """ _mask = ndarray.__getattribute__(self, '_mask') @@ -2506,53 +2631,53 @@ masked_%(name)s(data = %(data)s, def prod(self, axis=None, dtype=None, out=None): """ - Return the product of the array elements over the given axis. - Masked elements are set to 1 internally for computation. + Return the product of the array elements over the given axis. + Masked elements are set to 1 internally for computation. - Parameters - ---------- - axis : {None, int}, optional - Axis over which the product is taken. If None is used, then the - product is over all the array elements. - dtype : {None, dtype}, optional - Determines the type of the returned array and of the accumulator - where the elements are multiplied. If ``dtype`` has the value ``None`` - and the type of a is an integer type of precision less than the default - platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of a. - out : {None, array}, 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. + Parameters + ---------- + axis : {None, int}, optional + Axis over which the product is taken. If None is used, then the + product is over all the array elements. + dtype : {None, dtype}, optional + Determines the type of the returned array and of the accumulator + where the elements are multiplied. If ``dtype`` has the value ``None`` + and the type of a is an integer type of precision less than the default + platform integer, then the default platform integer precision is + used. Otherwise, the dtype is the same as that of a. + out : {None, array}, 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. - Returns - ------- - product_along_axis : {array, scalar}, see dtype parameter above. - Returns an array whose shape is the same as a with the specified - axis removed. Returns a 0d array when a is 1d or axis=None. - Returns a reference to the specified output array if specified. + Returns + ------- + product_along_axis : {array, scalar}, see dtype parameter above. + Returns an array whose shape is the same as a with the specified + axis removed. Returns a 0d array when a is 1d or axis=None. + Returns a reference to the specified output array if specified. - See Also - -------- - prod : equivalent function + See Also + -------- + prod : equivalent function - Examples - -------- - >>> np.prod([1.,2.]) - 2.0 - >>> np.prod([1.,2.], dtype=np.int32) - 2 - >>> np.prod([[1.,2.],[3.,4.]]) - 24.0 - >>> np.prod([[1.,2.],[3.,4.]], axis=1) - array([ 2., 12.]) + Notes + ----- + Arithmetic is modular when using integer types, and no error is raised + on overflow. - Notes - ----- - Arithmetic is modular when using integer types, and no error is raised - on overflow. + Examples + -------- + >>> np.prod([1.,2.]) + 2.0 + >>> np.prod([1.,2.], dtype=np.int32) + 2 + >>> np.prod([[1.,2.],[3.,4.]]) + 24.0 + >>> np.prod([[1.,2.],[3.,4.]], axis=1) + array([ 2., 12.]) - """ + """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _mask.all(axis=axis) # No explicit output @@ -2716,6 +2841,16 @@ masked_%(name)s(data = %(data)s, #............................................ def round(self, decimals=0, out=None): + """ + Return an array rounded a to the given number of decimals. + + Refer to `numpy.around` for full documentation. + + See Also + -------- + numpy.around : equivalent function + + """ result = self._data.round(decimals=decimals, out=out).view(type(self)) result._mask = self._mask result._update_from(self) @@ -2780,21 +2915,39 @@ masked_%(name)s(data = %(data)s, def argmin(self, axis=None, fill_value=None, out=None): - """a.argmin(axis=None, out=None) + """ + Return array of indices to the minimum values along the given axis. + + Parameters + ---------- + axis : {None, integer} + If None, the index is into the flattened array, otherwise along + the specified axis + fill_value : {var}, optional + Value used to fill in the masked values. If None, the output of + minimum_fill_value(self._data) is used instead. + out : {None, array}, optional + Array into which the result can be placed. Its type is preserved + and it must be of the right shape to hold the output. - Return array of indices to the minimum values along the given axis. + Returns + ------- + {ndarray, scalar} + If multi-dimension input, returns a new ndarray of indices to the + minimum values along the given axis. Otherwise, returns a scalar + of index to the minimum values along the given axis. - Parameters - ---------- - axis : {None, integer} - If None, the index is into the flattened array, otherwise along - the specified axis - fill_value : {var}, optional - Value used to fill in the masked values. If None, the output of - minimum_fill_value(self._data) is used instead. - out : {None, array}, optional - Array into which the result can be placed. Its type is preserved - and it must be of the right shape to hold the output. + Examples + -------- + >>> x = np.ma.array(arange(4), mask=[1,1,0,0]) + >>> x.shape = (2,2) + >>> print x + [[-- --] + [2 3]] + >>> print x.argmin(axis=0, fill_value=-1) + [0 0] + >>> print x.argmin(axis=0, fill_value=9) + [1 1] """ if fill_value is None: @@ -2804,36 +2957,35 @@ masked_%(name)s(data = %(data)s, def argmax(self, axis=None, fill_value=None, out=None): - """a.argmax(axis=None, out=None) - - Returns array of indices of the maximum values along the given axis. - Masked values are treated as if they had the value fill_value. + """ + Returns array of indices of the maximum values along the given axis. + Masked values are treated as if they had the value fill_value. - Parameters - ---------- - axis : {None, integer} - If None, the index is into the flattened array, otherwise along - the specified axis - fill_value : {var}, optional - Value used to fill in the masked values. If None, the output of - maximum_fill_value(self._data) is used instead. - out : {None, array}, optional - Array into which the result can be placed. Its type is preserved - and it must be of the right shape to hold the output. + Parameters + ---------- + axis : {None, integer} + If None, the index is into the flattened array, otherwise along + the specified axis + fill_value : {var}, optional + Value used to fill in the masked values. If None, the output of + maximum_fill_value(self._data) is used instead. + out : {None, array}, optional + Array into which the result can be placed. Its type is preserved + and it must be of the right shape to hold the output. - Returns - ------- - index_array : {integer_array} + Returns + ------- + index_array : {integer_array} - Examples - -------- - >>> a = np.arange(6).reshape(2,3) - >>> a.argmax() - 5 - >>> a.argmax(0) - array([1, 1, 1]) - >>> a.argmax(1) - array([2, 2]) + Examples + -------- + >>> a = np.arange(6).reshape(2,3) + >>> a.argmax() + 5 + >>> a.argmax(0) + array([1, 1, 1]) + >>> a.argmax(1) + array([2, 2]) """ if fill_value is None: @@ -2975,32 +3127,31 @@ masked_%(name)s(data = %(data)s, #........................ def max(self, axis=None, out=None, fill_value=None): - """a.max(axis=None, out=None, fill_value=None) - - Return the maximum along a given axis. + """ + Return the maximum along a given axis. - Parameters - ---------- - axis : {None, int}, optional - Axis along which to operate. By default, ``axis`` is None and the - flattened input is used. - out : array_like, optional - Alternative output array in which to place the result. Must - be of the same shape and buffer length as the expected output. - fill_value : {var}, optional - Value used to fill in the masked values. - If None, use the output of maximum_fill_value(). + Parameters + ---------- + axis : {None, int}, optional + Axis along which to operate. By default, ``axis`` is None and the + flattened input is used. + out : array_like, optional + Alternative output array in which to place the result. Must + be of the same shape and buffer length as the expected output. + fill_value : {var}, optional + Value used to fill in the masked values. + If None, use the output of maximum_fill_value(). - Returns - ------- - amax : array_like - New array holding the result. - If ``out`` was specified, ``out`` is returned. + Returns + ------- + amax : array_like + New array holding the result. + If ``out`` was specified, ``out`` is returned. - See Also - -------- - maximum_fill_value - Returns the maximum filling value for a given datatype. + See Also + -------- + maximum_fill_value + Returns the maximum filling value for a given datatype. """ _mask = ndarray.__getattribute__(self, '_mask') @@ -3031,29 +3182,27 @@ masked_%(name)s(data = %(data)s, return out def ptp(self, axis=None, out=None, fill_value=None): - """a.ptp(axis=None, out=None) - - Return (maximum - minimum) along the the given dimension - (i.e. peak-to-peak value). - - Parameters - ---------- - axis : {None, int}, optional - Axis along which to find the peaks. If None (default) the - flattened array is used. - out : {None, array_like}, optional - Alternative output array in which to place the result. It must - have the same shape and buffer length as the expected output - but the type will be cast if necessary. - fill_value : {var}, optional - Value used to fill in the masked values. + """ + Return (maximum - minimum) along the the given dimension + (i.e. peak-to-peak value). - Returns - ------- - ptp : ndarray. - A new array holding the result, unless ``out`` was - specified, in which case a reference to ``out`` is returned. + Parameters + ---------- + axis : {None, int}, optional + Axis along which to find the peaks. If None (default) the + flattened array is used. + out : {None, array_like}, optional + Alternative output array in which to place the result. It must + have the same shape and buffer length as the expected output + but the type will be cast if necessary. + fill_value : {var}, optional + Value used to fill in the masked values. + Returns + ------- + ptp : ndarray. + A new array holding the result, unless ``out`` was + specified, in which case a reference to ``out`` is returned. """ if out is None: @@ -3116,8 +3265,7 @@ masked_%(name)s(data = %(data)s, def tostring(self, fill_value=None, order='C'): """ Return a copy of array data as a Python string containing the raw bytes - in the array. - The array is filled beforehand. + in the array. The array is filled beforehand. Parameters ---------- @@ -3125,15 +3273,15 @@ masked_%(name)s(data = %(data)s, Value used to fill in the masked values. If None, uses self.fill_value instead. order : {string} - Order of the data item in the copy {"C","F","A"}. - "C" -- C order (row major) - "Fortran" -- Fortran order (column major) - "Any" -- Current order of array. + Order of the data item in the copy {'C','F','A'}. + 'C' -- C order (row major) + 'Fortran' -- Fortran order (column major) + 'Any' -- Current order of array. None -- Same as "Any" - Warnings - -------- - As for :meth:`ndarray.tostring`, information about the shape, dtype..., + Notes + ----- + As for method:`ndarray.tostring`, information about the shape, dtype..., but also fill_value will be lost. """ @@ -3143,14 +3291,34 @@ masked_%(name)s(data = %(data)s, raise NotImplementedError("Not implemented yet, sorry...") def torecords(self): - """Transforms a masked array into a flexible-type array with two fields: + """ + Transforms a MaskedArray into a flexible-type array with two fields: * the ``_data`` field stores the ``_data`` part of the array; * the ``_mask`` field stores the ``_mask`` part of the array; - Warnings - -------- + Returns + ------- + record : ndarray + A new flexible-type ndarray with two fields: the first element + containing a value, the second element containing the corresponding + mask boolean. The returned record shape matches self.shape. + + Notes + ----- A side-effect of transforming a masked array into a flexible ndarray is - that metainformation (``fill_value``, ...) will be lost. + that meta information (``fill_value``, ...) will be lost. + + 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]] + >>> print x.torecords() + [[(1, False) (2, True) (3, False)] + [(4, True) (5, False) (6, True)] + [(7, False) (8, True) (9, False)]] """ # Get the basic dtype .... diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index ded2d475f..d88022888 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -371,29 +371,30 @@ def average(a, axis=None, weights=None, returned=False): def median(a, axis=None, out=None, overwrite_input=False): - """Compute the median along the specified axis. + """ + Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- - a : array-like + 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. - out : {None, ndarray}, optional + axis : 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. + out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. overwrite_input : {False, True}, optional - If True, then allow use of memory of input array (a) for - calculations. The input array will be modified by the call to - median. This will save memory when you do not need to preserve - the contents of the input array. Treat the input as undefined, - but it will probably be fully or partially sorted. Default is - False. Note that, if overwrite_input is true, and the input - is not already an ndarray, an error will be raised. + If True, then allow use of memory of input array (a) for + calculations. The input array will be modified by the call to + median. This will save memory when you do not need to preserve + the contents of the input array. Treat the input as undefined, + but it will probably be fully or partially sorted. Default is + False. Note that, if overwrite_input is true, and the input + is not already an ndarray, an error will be raised. Returns ------- @@ -404,7 +405,7 @@ def median(a, axis=None, out=None, overwrite_input=False): float64, or the input datatype otherwise. See Also - ------- + -------- mean Notes @@ -697,36 +698,40 @@ def _covhelper(x, y=None, rowvar=True, allow_masked=True): def cov(x, y=None, rowvar=True, bias=False, allow_masked=True): - """Estimates the covariance matrix. + """ + Estimates the covariance matrix. Normalization is by (N-1) where N is the number of observations (unbiased estimate). If bias is True then normalization is by N. By default, masked values are recognized as such. If x and y have the same - shape, a common mask is allocated: if x[i,j] is masked, then y[i,j] will also - be masked. - Setting `allow_masked` to False will raise an exception if values are missing - in either of the input arrays. + shape, a common mask is allocated: if x[i,j] is masked, then y[i,j] will + also be masked. + Setting `allow_masked` to False will raise an exception if values are + missing in either of the input arrays. Parameters ---------- - x : array-like + x : array_like Input data. If x is a 1D array, returns the variance. If x is a 2D array, returns the covariance matrix. - y : {None, array-like}, optional + y : array_like, optional Optional set of variables. rowvar : {False, True} optional - If rowvar is true, then each row is a variable with observations in columns. - If rowvar is False, each column is a variable and the observations are in - the rows. + If rowvar is true, then each row is a variable with observations in + columns. + If rowvar is False, each column is a variable and the observations are + in the rows. bias : {False, True} optional - Whether to use a biased (True) or unbiased (False) estimate of the covariance. - If bias is True, then the normalization is by N, the number of observations. + Whether to use a biased (True) or unbiased (False) estimate of the + covariance. + If bias is True, then the normalization is by N, the number of + observations. Otherwise, the normalization is by (N-1). allow_masked : {True, False} optional - If True, masked values are propagated pair-wise: if a value is masked in x, - the corresponding value is masked in y. + If True, masked values are propagated pair-wise: if a value is masked + in x, the corresponding value is masked in y. If False, raises a ValueError exception when some values are missing. Raises diff --git a/numpy/matlib.py b/numpy/matlib.py index 4ffc0ba13..7026f5c1a 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -14,21 +14,123 @@ def empty(shape, dtype=None, order='C'): return ndarray.__new__(matrix, shape, dtype, order=order) def ones(shape, dtype=None, order='C'): - """return a matrix initialized to all ones + """ + Matrix of ones. + + Return a matrix of given shape and type, filled with ones. + + Parameters + ---------- + shape : {sequence of ints, int} + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is np.float64. + order : {'C', 'F'}, optional + Whether to store matrix in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Matrix of ones of given shape, dtype, and order. + + See Also + -------- + ones : Array of ones. + matlib.zeros : Zero matrix. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> np.matlib.ones((2,3)) + matrix([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> np.matlib.ones(2) + matrix([[ 1., 1.]] + """ a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(1) return a def zeros(shape, dtype=None, order='C'): - """return a matrix initialized to all zeros + """ + Zero matrix. + + Return a matrix of given shape and type, filled with zeros + + Parameters + ---------- + shape : {sequence of ints, int} + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is np.float64. + order : {'C', 'F'}, optional + Whether to store the result in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Zero matrix of given shape, dtype, and order. + + See Also + -------- + zeros : Zero array. + matlib.ones : Matrix of ones. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> np.matlib.zeros((2,3)) + matrix([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> np.matlib.zeros(2) + matrix([[ 0., 0.]] + """ a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(0) return a def identity(n,dtype=None): - """identity(n) returns the identity matrix of shape n x n. + """ + Returns the square identity matrix of given size. + + Parameters + ---------- + n : int + Size of identity matrix + + dtype : data-type, optional + Data-type of the output. Defaults to ``float``. + + Returns + ------- + out : matrix + `n` x `n` matrix with its main diagonal set to one, + and all other elements zero. + + See Also + -------- + identity : Equivalent array function. + matlib.eye : More general matrix identity function. + + Notes + ----- + For more detailed documentation, see the docstring of the equivalent + array function ``np.identity`` + """ a = array([1]+n*[0],dtype=dtype) b = empty((n,n),dtype=dtype) @@ -36,6 +138,39 @@ def identity(n,dtype=None): return b def eye(n,M=None, k=0, dtype=float): + """ + Return a matrix with ones on the diagonal and zeros elsewhere. + + Parameters + ---------- + n : int + Number of rows in the output. + M : int, optional + Number of columns in the output, defaults to n. + k : int, optional + Index of the diagonal: 0 refers to the main diagonal, + a positive value refers to an upper diagonal, + and a negative value to a lower diagonal. + dtype : dtype, optional + Data-type of the returned matrix. + + Returns + ------- + I : matrix + A `n` x `M` matrix where all elements are equal to zero, + except for the k-th diagonal, whose values are equal to one. + + See Also + -------- + eye : Equivalent array function + matlib.identity : Square identity matrix + + Notes + ----- + For more detailed docuemtation, see the docstring of the equivalent + array function ``np.eye``. + + """ return asmatrix(np.eye(n,M,k,dtype)) def rand(*args): diff --git a/numpy/random/mtrand/mtrand.pyx b/numpy/random/mtrand/mtrand.pyx index ede469e12..7ac9fc12c 100644 --- a/numpy/random/mtrand/mtrand.pyx +++ b/numpy/random/mtrand/mtrand.pyx @@ -532,7 +532,7 @@ cdef class RandomState: Parameters ---------- - seed : {None, int, array-like} + seed : array_like, int, optional Random seed initializing the PRNG. Can be an integer, an array (or other sequence) of integers of any length, or ``None``. @@ -1160,7 +1160,70 @@ cdef class RandomState: """ gamma(shape, scale=1.0, size=None) - Gamma distribution. + Draw samples from a Gamma distribution. + + Samples are drawn from a Gamma distribution with specified parameters, + `shape` (sometimes designated "k") and `scale` (sometimes designated + "theta"), where both parameters are > 0. + + Parameters + ---------- + shape : scalar > 0 + The shape of the gamma distribution. + scale : scalar > 0, optional + The scale of the gamma distribution. Default is equal to 1. + size : shape_tuple, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. + + Returns + ------- + out : ndarray, float + Returns one sample unless `size` parameter is specified. + + See Also + -------- + scipy.stats.distributions.gamma : probability density function, + distribution or cumulative density function, etc. + + Notes + ----- + The probability density for the Gamma distribution is + + .. math:: p(x) = x^{k-1}\\frac{e^{-x/\\theta}}{\\theta^k\\Gamma(k)}, + + where :math:`k` is the shape and :math:`\\theta` the scale, + and :math:`\\Gamma` is the Gamma function. + + The Gamma distribution is often used to model the times to failure of + electronic components, and arises naturally in processes for which the + waiting times between Poisson distributed events are relevant. + + References + ---------- + .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A + Wolfram Web Resource. + http://mathworld.wolfram.com/GammaDistribution.html + .. [2] Wikipedia, "Gamma-distribution", + http://en.wikipedia.org/wiki/Gamma-distribution + + Examples + -------- + Draw samples from the distribution: + + >>> shape, scale = 2., 2. # mean and dispersion + >>> s = np.random.gamma(shape, scale, 1000) + + Display the histogram of the samples, along with + the probability density function: + + >>> import matplotlib.pyplot as plt + >>> import scipy.special as sps + >>> count, bins, ignored = plt.hist(s, 50, normed=True) + >>> y = bins**(shape-1)*((exp(-bins/scale))/\\ + (sps.gamma(shape)*scale**shape)) + >>> plt.plot(bins, y, linewidth=2, color='r') + >>> plt.show() """ cdef ndarray oshape, oscale @@ -1188,7 +1251,81 @@ cdef class RandomState: """ f(dfnum, dfden, size=None) - F distribution. + Draw samples from a F distribution. + + Samples are drawn from an F distribution with specified parameters, + `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of freedom + in denominator), where both parameters should be greater than zero. + + The random variate of the F distribution (also known as the + Fisher distribution) is a continuous probability distribution + that arises in ANOVA tests, and is the ratio of two chi-square + variates. + + Parameters + ---------- + dfnum : float + Degrees of freedom in numerator. Should be greater than zero. + dfden : float + Degrees of freedom in denominator. Should be greater than zero. + size : {tuple, int}, optional + Output shape. If the given shape is, e.g., ``(m, n, k)``, + then ``m * n * k`` samples are drawn. By default only one sample + is returned. + + Returns + ------- + samples : {ndarray, scalar} + Samples from the Fisher distribution. + + See Also + -------- + scipy.stats.distributions.f : probability density function, + distribution or cumulative density function, etc. + + Notes + ----- + + The F statistic is used to compare in-group variances to between-group + variances. Calculating the distribution depends on the sampling, and + so it is a function of the respective degrees of freedom in the + problem. The variable `dfnum` is the number of samples minus one, the + between-groups degrees of freedom, while `dfden` is the within-groups + degrees of freedom, the sum of the number of samples in each group + minus the number of groups. + + References + ---------- + .. [1] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill, + Fifth Edition, 2002. + .. [2] Wikipedia, "F-distribution", + http://en.wikipedia.org/wiki/F-distribution + + Examples + -------- + An example from Glantz[1], pp 47-40. + Two groups, children of diabetics (25 people) and children from people + without diabetes (25 controls). Fasting blood glucose was measured, + case group had a mean value of 86.1, controls had a mean value of + 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these + data consistent with the null hypothesis that the parents diabetic + status does not affect their children's blood glucose levels? + Calculating the F statistic from the data gives a value of 36.01. + + Draw samples from the distribution: + + >>> dfnum = 1. # between group degrees of freedom + >>> dfden = 48. # within groups degrees of freedom + >>> s = np.random.f(dfnum, dfden, 1000) + + The lower bound for the top 1% of the samples is : + + >>> sort(s)[-10] + 7.61988120985 + + So there is about a 1% chance that the F statistic will exceed 7.62, + the measured value is 36, so the null hypothesis is rejected at the 1% + level. """ cdef ndarray odfnum, odfden @@ -1831,8 +1968,8 @@ cdef class RandomState: >>> import matplotlib.pyplot as plt >>> count, bins, ignored = plt.hist(s, 30, normed=True) - >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)* - ... np.exp( -np.exp( -(bins - mu) /beta) ), + >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta) + ... * np.exp( -np.exp( -(bins - mu) /beta) ), ... linewidth=2, color='r') >>> plt.show() @@ -1848,11 +1985,11 @@ cdef class RandomState: >>> count, bins, ignored = plt.hist(maxima, 30, normed=True) >>> beta = np.std(maxima)*np.pi/np.sqrt(6) >>> mu = np.mean(maxima) - 0.57721*beta - >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)* - ... np.exp( -np.exp( -(bins - mu) /beta) ), + >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta) + ... * np.exp(-np.exp(-(bins - mu)/beta)), ... linewidth=2, color='r') - >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi)) * - ... np.exp( - (bins - mu)**2 / (2 * beta**2) ), + >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi)) + ... * np.exp(-(bins - mu)**2 / (2 * beta**2)), ... linewidth=2, color='g') >>> plt.show() @@ -1878,7 +2015,71 @@ cdef class RandomState: """ logistic(loc=0.0, scale=1.0, size=None) - Logistic distribution. + Draw samples from a Logistic distribution. + + Samples are drawn from a Logistic distribution with specified + parameters, loc (location or mean, also median), and scale (>0). + + Parameters + ---------- + loc : float + + scale : float > 0. + + size : {tuple, int} + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. + + Returns + ------- + samples : {ndarray, scalar} + where the values are all integers in [0, n]. + + See Also + -------- + scipy.stats.distributions.logistic : probability density function, + distribution or cumulative density function, etc. + + Notes + ----- + The probability density for the Logistic distribution is + + .. math:: P(x) = P(x) = \\frac{e^{-(x-\\mu)/s}}{s(1+e^{-(x-\\mu)/s})^2}, + + where :math:`\\mu` = location and :math:`s` = scale. + + The Logistic distribution is used in Extreme Value problems where it + can act as a mixture of Gumbel distributions, in Epidemiology, and by + the World Chess Federation (FIDE) where it is used in the Elo ranking + system, assuming the performance of each player is a logistically + distributed random variable. + + References + ---------- + .. [1] Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme + Values, from Insurance, Finance, Hydrology and Other Fields, + Birkhauser Verlag, Basel, pp 132-133. + .. [2] Weisstein, Eric W. "Logistic Distribution." From + MathWorld--A Wolfram Web Resource. + http://mathworld.wolfram.com/LogisticDistribution.html + .. [3] Wikipedia, "Logistic-distribution", + http://en.wikipedia.org/wiki/Logistic-distribution + + Examples + -------- + Draw samples from the distribution: + + >>> loc, scale = 10, 1 + >>> s = np.random.logistic(loc, scale, 10000) + >>> count, bins, ignored = plt.hist(s, bins=50) + + # plot against distribution + + >>> def logist(x, loc, scale): + ... return exp((loc-x)/scale)/(scale*(1+exp((loc-x)/scale))**2) + >>> plt.plot(bins, logist(bins, loc, scale)*count.max()/\\ + ... logist(bins, loc, scale).max()) + >>> plt.show() """ cdef ndarray oloc, oscale @@ -2126,7 +2327,81 @@ cdef class RandomState: """ binomial(n, p, size=None) - Binomial distribution of n trials and p probability of success. + Draw samples from a binomial distribution. + + Samples are drawn from a Binomial distribution with specified + parameters, n trials and p probability of success where + n an integer > 0 and p is in the interval [0,1]. (n may be + input as a float, but it is truncated to an integer in use) + + Parameters + ---------- + n : float (but truncated to an integer) + parameter, > 0. + p : float + parameter, >= 0 and <=1. + size : {tuple, int} + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. + + Returns + ------- + samples : {ndarray, scalar} + where the values are all integers in [0, n]. + + See Also + -------- + scipy.stats.distributions.binom : probability density function, + distribution or cumulative density function, etc. + + Notes + ----- + The probability density for the Binomial distribution is + + .. math:: P(N) = \\binom{n}{N}p^N(1-p)^{n-N}, + + where :math:`n` is the number of trials, :math:`p` is the probability + of success, and :math:`N` is the number of successes. + + When estimating the standard error of a proportion in a population by + using a random sample, the normal distribution works well unless the + product p*n <=5, where p = population proportion estimate, and n = + number of samples, in which case the binomial distribution is used + instead. For example, a sample of 15 people shows 4 who are left + handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, + so the binomial distribution should be used in this case. + + References + ---------- + .. [1] Dalgaard, Peter, "Introductory Statistics with R", + Springer-Verlag, 2002. + .. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill, + Fifth Edition, 2002. + .. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden + and Quigley, 1972. + .. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A + Wolfram Web Resource. + http://mathworld.wolfram.com/BinomialDistribution.html + .. [5] Wikipedia, "Binomial-distribution", + http://en.wikipedia.org/wiki/Binomial_distribution + + Examples + -------- + Draw samples from the distribution: + + >>> n, p = 10, .5 # number of trials, probability of each trial + >>> s = np.random.binomial(n, p, 1000) + # result of flipping a coin 10 times, tested 1000 times. + + A real world example. A company drills 9 wild-cat oil exploration + wells, each with an estimated probability of success of 0.1. All nine + wells fail. What is the probability of that happening? + + Let's do 20,000 trials of the model, and count the number that + generate zero positive results. + + >>> sum(np.random.binomial(9,0.1,20000)==0)/20000. + answer = 0.38885, or 38%. """ cdef ndarray on, op @@ -2377,12 +2652,84 @@ cdef class RandomState: """ hypergeometric(ngood, nbad, nsample, size=None) - Hypergeometric distribution. + Draw samples from a Hypergeometric distribution. + + Samples are drawn from a Hypergeometric distribution with specified + parameters, ngood (ways to make a good selection), nbad (ways to make + a bad selection), and nsample = number of items sampled, which is less + than or equal to the sum ngood + nbad. + + Parameters + ---------- + ngood : float (but truncated to an integer) + parameter, > 0. + nbad : float + parameter, >= 0. + nsample : float + parameter, > 0 and <= ngood+nbad + size : {tuple, int} + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. + + Returns + ------- + samples : {ndarray, scalar} + where the values are all integers in [0, n]. + + See Also + -------- + scipy.stats.distributions.hypergeom : probability density function, + distribution or cumulative density function, etc. + + Notes + ----- + The probability density for the Hypergeometric distribution is + + .. math:: P(x) = \\frac{\\binom{m}{n}\\binom{N-m}{n-x}}{\\binom{N}{n}}, + + where :math:`0 \\le x \\le m` and :math:`n+m-N \\le x \\le n` + + for P(x) the probability of x successes, n = ngood, m = nbad, and + N = number of samples. + + Consider an urn with black and white marbles in it, ngood of them + black and nbad are white. If you draw nsample balls without + replacement, then the Hypergeometric distribution describes the + distribution of black balls in the drawn sample. + + Note that this distribution is very similar to the Binomial + distribution, except that in this case, samples are drawn without + replacement, whereas in the Binomial case samples are drawn with + replacement (or the sample space is infinite). As the sample space + becomes large, this distribution approaches the Binomial. + + References + ---------- + .. [1] Lentner, Marvin, "Elementary Applied Statistics", Bogden + and Quigley, 1972. + .. [2] Weisstein, Eric W. "Hypergeometric Distribution." From + MathWorld--A Wolfram Web Resource. + http://mathworld.wolfram.com/HypergeometricDistribution.html + .. [3] Wikipedia, "Hypergeometric-distribution", + http://en.wikipedia.org/wiki/Hypergeometric-distribution + + Examples + -------- + Draw samples from the distribution: - Consider an urn with ngood "good" balls and nbad "bad" balls. If one - were to draw nsample balls from the urn without replacement, then - the hypergeometric distribution describes the distribution of "good" - balls in the sample. + >>> ngood, nbad, nsamp = 100, 2, 10 + # number of good, number of bad, and number of samples + >>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000) + >>> hist(s) + # note that it is very unlikely to grab both bad items + + Suppose you have an urn with 15 white and 15 black marbles. + If you pull 15 marbles at random, how likely is it that + 12 or more of them are one color? + + >>> s = np.random.hypergeometric(15, 15, 15, 100000) + >>> sum(s>=12)/100000. + sum(s<=3)/100000. + # answer = 0.003 ... pretty unlikely! """ cdef ndarray ongood, onbad, onsample @@ -2424,7 +2771,74 @@ cdef class RandomState: """ logseries(p, size=None) - Logarithmic series distribution. + Draw samples from a Logarithmic Series distribution. + + Samples are drawn from a Log Series distribution with specified + parameter, p (probability, 0 < p < 1). + + Parameters + ---------- + loc : float + + scale : float > 0. + + size : {tuple, int} + Output shape. If the given shape is, e.g., ``(m, n, k)``, then + ``m * n * k`` samples are drawn. + + Returns + ------- + samples : {ndarray, scalar} + where the values are all integers in [0, n]. + + See Also + -------- + scipy.stats.distributions.logser : probability density function, + distribution or cumulative density function, etc. + + Notes + ----- + The probability density for the Log Series distribution is + + .. math:: P(k) = \\frac{-p^k}{k \\ln(1-p)}, + + where p = probability. + + The Log Series distribution is frequently used to represent species + richness and occurrence, first proposed by Fisher, Corbet, and + Williams in 1943 [2]. It may also be used to model the numbers of + occupants seen in cars [3]. + + References + ---------- + .. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional + species diversity through the log series distribution of + occurrences: BIODIVERSITY RESEARCH Diversity & Distributions, + Volume 5, Number 5, September 1999 , pp. 187-195(9). + .. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The + relation between the number of species and the number of + individuals in a random sample of an animal population. + Journal of Animal Ecology, 12:42-58. + .. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small + Data Sets, CRC Press, 1994. + .. [4] Wikipedia, "Logarithmic-distribution", + http://en.wikipedia.org/wiki/Logarithmic-distribution + + Examples + -------- + Draw samples from the distribution: + + >>> a = .6 + >>> s = np.random.logseries(a, 10000) + >>> count, bins, ignored = plt.hist(s) + + # plot against distribution + + >>> def logseries(k, p): + ... return -p**k/(k*log(1-p)) + >>> plt.plot(bins, logseries(bins, a)*count.max()/\\ + logseries(bins, a).max(),'r') + >>> plt.show() """ cdef ndarray op |