From 15437fc1140e83d0c6dde31af9b38813cc514c2e Mon Sep 17 00:00:00 2001 From: Travis Oliphant Date: Fri, 28 Dec 2007 22:14:14 +0000 Subject: Improve docstrings --- numpy/__init__.py | 11 +- numpy/_import_tools.py | 29 +-- numpy/add_newdocs.py | 608 ++++++++++++++++++++++++------------------------ numpy/core/defmatrix.py | 227 ++++++++++-------- numpy/core/numeric.py | 41 +++- numpy/core/records.py | 55 +++++ 6 files changed, 544 insertions(+), 427 deletions(-) (limited to 'numpy') diff --git a/numpy/__init__.py b/numpy/__init__.py index 000d60341..dbba4f88d 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -1,4 +1,4 @@ -"""\ +""" NumPy ========== @@ -7,11 +7,11 @@ the book "Guide to NumPy" at http://www.trelgol.com -It is being distributed for a fee for only a few years to +It is being distributed for a fee until Oct. 2010 to cover some of the costs of development. After the restriction period it will also be freely available. -Additional documentation is available in the docstrings and at +Documentation is available in the docstrings and at http://www.scipy.org. """ @@ -34,6 +34,7 @@ else: loader = PackageLoader(infunc=True) return loader(*packages, **options) + pkgload.__doc__ = PackageLoader.__call__.__doc__ import testing from testing import ScipyTest, NumpyTest import core @@ -79,8 +80,8 @@ distutils --- Enhancements to distutils with support for Global symbols from subpackages ------------------------------- -core --> * -lib --> * +core --> * (use numpy.* not numpy.core.*) +lib --> * (use numpy.* not numpy.lib.*) testing --> NumpyTest """ diff --git a/numpy/_import_tools.py b/numpy/_import_tools.py index 7940e84ff..d289a752b 100644 --- a/numpy/_import_tools.py +++ b/numpy/_import_tools.py @@ -131,8 +131,6 @@ class PackageLoader: def __call__(self,*packages, **options): """Load one or more packages into parent package top-level namespace. - Usage: - This function is intended to shorten the need to import many subpackages, say of scipy, constantly with statements such as @@ -152,21 +150,18 @@ class PackageLoader: If a name which doesn't exist in scipy's namespace is given, a warning is shown. - Inputs: - - - the names (one or more strings) of all the numpy modules one - wishes to load into the top-level namespace. - - Optional keyword inputs: - - - verbose - integer specifying verbosity level [default: -1]. - verbose=-1 will suspend also warnings. - - force - when True, force reloading loaded packages - [default: False]. - - postpone - when True, don't load packages [default: False] - - If no input arguments are given, then all of scipy's subpackages - are imported. + Parameters + ---------- + *packges : arg-tuple + the names (one or more strings) of all the modules one + wishes to load into the top-level namespace. + verbose= : integer + verbosity level [default: -1]. + verbose=-1 will suspend also warnings. + force= : bool + when True, force reloading loaded packages [default: False]. + postpone= : bool + when True, don't load packages [default: False] """ frame = self.parent_frame diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index ce4b43107..9d954229a 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -1,3 +1,7 @@ +# This is only meant to add docs to +# objects defined in C-extension modules. +# The purpose is to allow easier editing of the +# docstrings without requiring a re-compile. from lib import add_newdoc add_newdoc('numpy.core','dtype', @@ -132,30 +136,37 @@ add_newdoc('numpy.core.multiarray','array', Return an array from object with the specified date-type. - Inputs: - object - an array, any object exposing the array interface, any - object whose __array__ method returns an array, or any - (nested) sequence. - dtype - The desired data-type for the array. If not given, then - the type will be determined as the minimum type required - to hold the objects in the sequence. This argument can only - be used to 'upcast' the array. For downcasting, use the - .astype(t) method. - copy - If true, then force a copy. Otherwise a copy will only occur - if __array__ returns a copy, obj is a nested sequence, or - a copy is needed to satisfy any of the other requirements - order - Specify the order of the array. If order is 'C', then the - array will be in C-contiguous order (last-index varies the - fastest). If order is 'FORTRAN', then the returned array - will be in Fortran-contiguous order (first-index varies the - fastest). If order is None, then the returned array may - be in either C-, or Fortran-contiguous order or even - discontiguous. - subok - If True, then sub-classes will be passed-through, otherwise - the returned array will be forced to be a base-class array - ndmin - Specifies the minimum number of dimensions that the resulting - array should have. 1's will be pre-pended to the shape as - needed to meet this requirement. + Parameters + ---------- + object : array-like + an array, any object exposing the array interface, any + object whose __array__ method returns an array, or any + (nested) sequence. + dtype : data-type + The desired data-type for the array. If not given, then + the type will be determined as the minimum type required + to hold the objects in the sequence. This argument can only + be used to 'upcast' the array. For downcasting, use the + .astype(t) method. + copy : bool + If true, then force a copy. Otherwise a copy will only occur + if __array__ returns a copy, obj is a nested sequence, or + a copy is needed to satisfy any of the other requirements + order : {'C', 'F', 'A' (None)} + Specify the order of the array. If order is 'C', then the + array will be in C-contiguous order (last-index varies the + fastest). If order is 'FORTRAN', then the returned array + will be in Fortran-contiguous order (first-index varies the + fastest). If order is None, then the returned array may + be in either C-, or Fortran-contiguous order or even + discontiguous. + subok : bool + If True, then sub-classes will be passed-through, otherwise + the returned array will be forced to be a base-class array + ndmin : int + Specifies the minimum number of dimensions that the resulting + array should have. 1's will be pre-pended to the shape as + needed to meet this requirement. """) @@ -220,13 +231,16 @@ add_newdoc('numpy.core.multiarray','fromiter', add_newdoc('numpy.core.multiarray','fromfile', """fromfile(file=, dtype=float, count=-1, sep='') -> array. - Required arguments: - file -- open file object or string containing file name. - - Keyword arguments: - dtype -- type and order of the returned array (default float) - count -- number of items to input (default all) - sep -- separater between items if file is a text file (default "") + Parameters + ---------- + file : file or string + open file object or string containing file name. + dtype : data-type + data type of the returned array + count : int + number of items to read (-1 mean 'all') + sep : string + separater between items if file is a text file (default "") Return an array of the given data type from a text or binary file. The 'file' argument can be an open file or a string with the name of a file to @@ -236,7 +250,6 @@ add_newdoc('numpy.core.multiarray','fromfile', the separator between elements in a text file. The 'dtype' value is also used to determine the size and order of the items in binary files. - Data written using the tofile() method can be conveniently recovered using this function. @@ -268,8 +281,8 @@ add_newdoc('numpy.core.multiarray','concatenate', The tuple of sequences (a1, a2, ...) are joined along the given axis (default is the first one) into a single numpy array. - Example: - + Examples + -------- >>> concatenate( ([0,1,2], [5,6,7]) ) array([0, 1, 2, 5, 6, 7]) @@ -343,26 +356,29 @@ add_newdoc('numpy.core.multiarray','where', Return elements from `x` or `y`, depending on `condition`. - *Parameters*: - condition : array of bool - When True, yield x, otherwise yield y. - x,y : 1-dimensional arrays - Values from which to choose. + Parameters + ---------- + condition : array of bool + When True, yield x, otherwise yield y. + x,y : 1-dimensional arrays + Values from which to choose. - *Notes* - This is equivalent to + Notes + ----- + This is equivalent to - [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] + [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] - The result is shaped like `condition` and has elements of `x` - or `y` where `condition` is respectively True or False. + The result is shaped like `condition` and has elements of `x` + or `y` where `condition` is respectively True or False. - In the special case, where only `condition` is given, the - tuple condition.nonzero() is returned, instead. + In the special case, where only `condition` is given, the + tuple condition.nonzero() is returned, instead. - *Examples* - >>> where([True,False,True],[1,2,3],[4,5,6]) - array([1, 5, 3]) + Examples + -------- + >>> where([True,False,True],[1,2,3],[4,5,6]) + array([1, 5, 3]) """) @@ -379,35 +395,35 @@ add_newdoc('numpy.core.multiarray','lexsort', sort order, and so on). The keys argument must be a sequence of things that can be converted to arrays of the same shape. - *Parameters*: - - keys : (k,N) array or tuple of (N,) sequences - Array containing values that the returned indices should sort. - - axis : integer - Axis to be indirectly sorted. Default is -1 (i.e. last axis). - - *Returns*: + Parameters + ---------- + keys : (k,N) array or tuple of (N,) sequences + Array containing values that the returned indices should sort. - indices : (N,) integer array - Array of indices that sort the keys along the specified axis. + axis : integer + Axis to be indirectly sorted. Default is -1 (i.e. last axis). - *See Also*: - - `argsort` : indirect sort - `sort` : inplace sort + Returns + ------- + indices : (N,) integer array + Array of indices that sort the keys along the specified axis. - *Examples* + See Also + -------- + argsort : indirect sort + sort : inplace sort - >>> a = [1,5,1,4,3,6,7] - >>> b = [9,4,0,4,0,4,3] - >>> ind = lexsort((b,a)) - >>> print ind - [2 0 4 3 1 5 6] - >>> print take(a,ind) - [1 1 3 4 5 6 7] - >>> print take(b,ind) - [0 9 0 4 4 4 3] + Examples + -------- + >>> a = [1,5,1,4,3,6,7] + >>> b = [9,4,0,4,0,4,3] + >>> ind = lexsort((b,a)) + >>> print ind + [2 0 4 3 1 5 6] + >>> print take(a,ind) + [1 1 3 4 5 6 7] + >>> print take(b,ind) + [0 9 0 4 4 4 3] """) @@ -623,12 +639,13 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__', Return a copy of the array. - Argument: - order -- Order of returned copy (default 'C') - If order is 'C' (False) then the result is contiguous (default). - If order is 'Fortran' (True) then the result has fortran order. - If order is 'Any' (None) then the result has fortran order - only if m is already in fortran order.; + Parameters + ---------- + order : {'C', 'F', 'A'} + If order is 'C' (False) then the result is contiguous (default). + If order is 'Fortran' (True) then the result has fortran order. + If order is 'Any' (None) then the result has fortran order + only if m is already in fortran order.; """)) @@ -650,16 +667,19 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__', add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__', - """a.__setstate__(version, shape, typecode, isfortran, rawdata) + """a.__setstate__(version, shape, dtype, isfortran, rawdata) For unpickling. - Arguments: - version -- optional pickle version. If omitted defaults to 0. - shape -- a tuple giving the shape - typecode -- a typecode - isFortran -- a bool stating if Fortran or no - rawdata -- a binary string with the data (or a list if Object array) + Parameters + ---------- + version : int + optional pickle version. If omitted defaults to 0. + shape : tuple + dtype : data-type + isFortran : bool + rawdata : string or list + a binary string with the data (or a list if 'a' is an object array) """)) @@ -695,33 +715,31 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', by the kind keyword. It returns an array of indices of the same shape as 'a' that index data along the given axis in sorted order. - :Parameters: - - axis : integer - Axis to be indirectly sorted. 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 - which fields to compare first, second, etc. Not all fields need be - specified. - - :Returns: - - indices : integer array - Array of indices that sort 'a' along the specified axis. - - :SeeAlso: + Parameters + ---------- + axis : integer + Axis to be indirectly sorted. 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 + which fields to compare first, second, etc. Not all fields need be + specified. + + Returns + ------- + indices : integer array + Array of indices that sort 'a' along the specified axis. - - lexsort : indirect stable sort with multiple keys - - sort : inplace sort + SeeAlso + ------- + lexsort : indirect stable sort with multiple keys + sort : inplace sort - :Notes: - ------ + Notes + ----- The various sorts are characterized by average speed, worst case performance, need for work space, and whether they are stable. A stable @@ -803,12 +821,13 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('copy', Return a copy of the array. - Argument: - order -- Order of returned copy (default 'C') - If order is 'C' (False) then the result is contiguous (default). - If order is 'Fortran' (True) then the result has fortran order. - If order is 'Any' (None) then the result has fortran order - only if m is already in fortran order.; + Parameters + ---------- + order : Order of returned copy (default 'C') + If order is 'C' (False) then the result is contiguous (default). + If order is 'Fortran' (True) then the result has fortran order. + If order is 'Any' (None) then the result has fortran order + only if m is already in fortran order.; """)) @@ -835,30 +854,32 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal', be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. - :Parameters: - offset : integer - Offset of the diagonal from the main diagonal. Can be both positive - and negative. Defaults to main diagonal. - axis1 : integer - Axis to be used as the first axis of the 2-d subarrays from which - the diagonals should be taken. Defaults to first index. - axis2 : integer - Axis to be used as the second axis of the 2-d subarrays from which - the diagonals should be taken. Defaults to second index. - - :Returns: - array_of_diagonals : same type as original array - If a is 2-d, then a 1-d array containing the diagonal is returned. - If a is n-d, n > 2, then an array of diagonals is returned. - - :SeeAlso: - - diag : matlab workalike for 1-d and 2-d arrays. - - diagflat : creates diagonal arrays - - trace : sum along diagonals + Parameters + ---------- + offset : integer + Offset of the diagonal from the main diagonal. Can be both positive + and negative. Defaults to main diagonal. + axis1 : integer + Axis to be used as the first axis of the 2-d subarrays from which + the diagonals should be taken. Defaults to first index. + axis2 : integer + Axis to be used as the second axis of the 2-d subarrays from which + the diagonals should be taken. Defaults to second index. + + Returns + ------- + array_of_diagonals : same type as original array + If a is 2-d, then a 1-d array containing the diagonal is returned. + If a is n-d, n > 2, then an array of diagonals is returned. + + SeeAlso + ------- + diag : matlab workalike for 1-d and 2-d arrays. + diagflat : creates diagonal arrays + trace : sum along diagonals Examples -------- - >>> a = arange(4).reshape(2,2) >>> a array([[0, 1], @@ -943,38 +964,35 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('mean', Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. - :Parameters: - - axis : integer - Axis along which the means are computed. The default is - to compute the standard deviation of the flattened array. - - dtype : type - Type to use in computing the means. For arrays of - integer type the default is float32, for arrays of float types it - is the same as the array type. - - out : ndarray - 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: - - mean : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - :SeeAlso: + Parameters + ---------- + axis : integer + Axis along which the means are computed. The default is + to compute the standard deviation of the flattened array. + dtype : type + Type to use in computing the means. For arrays of + integer type the default is float32, for arrays of float types it + is the same as the array type. + out : ndarray + 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 + ------- + mean : The return type varies, see above. + A new array holding the result is returned unless out is specified, + in which case a reference to out is returned. - - var : variance - - std : standard deviation + SeeAlso + ------- + var : variance + std : standard deviation Notes ----- - - The mean is the sum of the elements along the axis divided by the - number of elements. + The mean is the sum of the elements along the axis divided by the + number of elements. """)) @@ -1070,14 +1088,17 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('resize', add_newdoc('numpy.core.multiarray', 'ndarray', ('round', - """a.round(decimals=0, out=None) -> out (a). Rounds to 'decimals' places. + """a.round(decimals=0, out=None) -> out (new). Rounds to 'decimals' places. - Keyword arguments: - decimals -- number of decimals to round to (default 0). May be negative. - out -- existing array to use for output (default a). + Parameters + ---------- + decimals : integer + number of decimals to round to. May be negative. + out : existing array to use for output (default new array). - Return: - Reference to out, where None specifies the original array a. + Returns + ------- + Reference to out, where None specifies a new array. Round to the specified number of decimals. When 'decimals' is negative it specifies the number of positions to the left of the decimal point. The @@ -1085,9 +1106,10 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('round', is done if the array is not of float type and 'decimals' is >= 0. The keyword 'out' may be used to specify a different array to hold the - result rather than the default 'a'. If the type of the array specified by - 'out' differs from that of 'a', the result is cast to the new type, - otherwise the original type is kept. Floats round to floats by default. + result rather than the default new array. If the type of the array + specified by 'out' differs from that of 'a', the result is cast to the + new type, otherwise the original type is kept. Floats round to floats + by default. Numpy rounds to even. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation @@ -1107,31 +1129,28 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted', is out of bounds, then the length of a is returned, i.e., the key would need to be appended. The returned index array has the same shape as v. - :Parameters: - - v : array or list type - Array of keys to be searched for in a. - - side : string - Possible values are : 'left', 'right'. Default is 'left'. Return - the first or last index where the key could be inserted. - - :Returns: + Parameters + ---------- + v : array or list type + Array of keys to be searched for in a. + side : string + Possible values are : 'left', 'right'. Default is 'left'. Return + the first or last index where the key could be inserted. - indices : integer array - The returned array has the same shape as v. - - :SeeAlso: - - - sort - - histogram - - :Notes: + Returns ------- + indices : integer array + The returned array has the same shape as v. - The array a must be 1-d and is assumed to be sorted in ascending order. - Searchsorted uses binary search to find the required insertion points. + SeeAlso + ------- + sort + histogram + Notes + ----- + The array a must be 1-d and is assumed to be sorted in ascending order. + Searchsorted uses binary search to find the required insertion points. """)) @@ -1154,33 +1173,27 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', Perform an inplace sort along the given axis using the algorithm specified by the kind keyword. - :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 - which fields to compare first, second, etc. Not all fields need be - specified. - - :Returns: - - None - - :SeeAlso: - - - argsort : indirect sort - - lexsort : indirect stable sort on multiple keys - - searchsorted : find keys in sorted array + 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 + which fields to compare first, second, etc. Not all fields need be + specified. + + SeeAlso + ------- + argsort : indirect sort + lexsort : indirect stable sort on multiple keys + searchsorted : find keys in sorted array - :Notes: - ------ + Notes + ----- The various sorts are characterized by average speed, worst case performance, need for work space, and whether they are stable. A stable @@ -1195,10 +1208,9 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', |'heapsort' | 3 | O(n*log(n)) | 0 | no | |------------------------------------------------------| - 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. - + 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. """)) @@ -1215,40 +1227,37 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('std', spread of a distribution. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. - :Parameters: - - axis : integer - Axis along which the standard deviation is computed. The default is - to compute the standard deviation of the flattened array. - - dtype : type - Type to use in computing the standard deviation. For arrays of - integer type the default is float32, for arrays of float types it - is the same as the array type. - - out : ndarray - 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: - - standard deviation : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - :SeeAlso: + Parameters + ---------- + axis : integer + Axis along which the standard deviation is computed. The default is + to compute the standard deviation of the flattened array. + dtype : type + Type to use in computing the standard deviation. For arrays of + integer type the default is float32, for arrays of float types it + is the same as the array type. + out : ndarray + 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 + ------- + standard deviation : The return type varies, see above. + A new array holding the result is returned unless out is specified, + in which case a reference to out is returned. - - var : variance - - mean : average + SeeAlso + ------- + var : variance + mean : average Notes ----- - - The standard deviation is the square root of the average of the squared - deviations from the mean, i.e. var = sqrt(mean((x - x.mean())**2)). The - computed standard deviation is biased, i.e., the mean is computed by - dividing by the number of elements, N, rather than by N-1. + The standard deviation is the square root of the average of the squared + deviations from the mean, i.e. var = sqrt(mean((x - x.mean())**2)). The + computed standard deviation is biased, i.e., the mean is computed by + dividing by the number of elements, N, rather than by N-1. """)) @@ -1270,8 +1279,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('sum', Warning: The arithmetic is modular and no error is raised on overflow. - Examples: - + Examples + -------- >>> array([0.5, 1.5]).sum() 2.0 >>> array([0.5, 1.5]).sum(dtype=int32) @@ -1282,7 +1291,6 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('sum', array([1, 5]) >>> ones(128, dtype=int8).sum(dtype=int8) # overflow! -128 - """)) @@ -1304,12 +1312,14 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('take', add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile', """a.tofile(fid, sep="", format="%s") -> None. Write the data to a file. - Required arguments: - file -- an open file object or a string containing a filename - - Keyword arguments: - sep -- separator for text output. Write binary if empty (default "") - format -- format string for text file output (default "%s") + Parameters + ---------- + fid : file or string + an open file object or a string containing a filename + sep : string + separation for text output. Write binary if this is empty. + format : string + format string for text file output A convenience function for quick storage of array data. Information on endianess and precision is lost, so this method is not a good choice for @@ -1341,8 +1351,10 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', """a.tostring(order='C') -> raw copy of array data as a Python string. - Keyword arguments: - order -- order of the data item in the copy {"C","F","A"} (default "C") + Parameters + ---------- + order : {'C', 'F', 'A', None} + order of the data item in the copy Construct a Python string containing the raw bytes in the array. The order of the data in arrays with ndim > 1 is specified by the 'order' keyword and @@ -1373,7 +1385,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose', array, this is the usual matrix transpose. If axes are given, they describe how the axes are permuted. - Example: + Examples + -------- >>> a = array([[1,2],[3,4]]) >>> a array([[1, 2], @@ -1398,40 +1411,37 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('var', distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. - :Parameters: - - axis : integer - Axis along which the variance is computed. The default is to - compute the variance of the flattened array. - - dtype : type - Type to use in computing the variance. For arrays of integer type - the default is float32, for arrays of float types it is the same as - the array type. - - out : ndarray - 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: - - variance : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - :SeeAlso: + Parameters + ---------- + axis : integer + Axis along which the variance is computed. The default is to + compute the variance of the flattened array. + dtype : data-type + Type to use in computing the variance. For arrays of integer type + the default is float32, for arrays of float types it is the same as + the array type. + out : ndarray + 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 + ------- + variance : The return type varies, see above. + A new array holding the result is returned unless out is specified, + in which case a reference to out is returned. - - std : standard deviation - - mean: average + SeeAlso + ------- + std : standard deviation + mean: average Notes ----- - - The variance is the average of the squared deviations from the mean, i.e. - var = mean((x - x.mean())**2). The computed variance is biased, i.e., - the mean is computed by dividing by the number of elements, N, rather - than by N-1. + The variance is the average of the squared deviations from the mean, i.e. + var = mean((x - x.mean())**2). The computed variance is biased, i.e., + the mean is computed by dividing by the number of elements, N, rather + than by N-1. """)) diff --git a/numpy/core/defmatrix.py b/numpy/core/defmatrix.py index 37cef8fc0..7e1cacfce 100644 --- a/numpy/core/defmatrix.py +++ b/numpy/core/defmatrix.py @@ -49,6 +49,34 @@ def asmatrix(data, dtype=None): class matrix(N.ndarray): + """mat = matrix(data, dtype=None, copy=True) + + Returns a matrix from an array-like object, or a string of + data. A matrix is a specialized 2-d array that retains + it's 2-d nature through operations and where '*' means matrix + multiplication and '**' means matrix power. + + Parameters + ---------- + data : array-like or string + If data is a string, then interpret the string as a matrix + with commas or spaces separating columns and semicolons + separating rows. + If data is array-like than convert the array to a matrix. + dtype : data-type + Anything that can be interpreted as a NumPy datatype. + copy : bool + If data is already an ndarray, then this flag determines whether + or not the data will be copied + + Examples + -------- + >>> import numpy as np + >>> a = np.matrix('1 2; 3 4') + >>> print a + [[1 2] + [3 4]] + """ __array_priority__ = 10.0 def __new__(subtype, data, dtype=None, copy=True): if isinstance(data, matrix): @@ -244,39 +272,37 @@ class matrix(N.ndarray): Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. - :Parameters: - - axis : integer - Axis along which the means are computed. The default is - to compute the standard deviation of the flattened array. - - dtype : type - Type to use in computing the means. For arrays of integer type - the default is float32, for arrays of float types it is the - same as the array type. - - out : ndarray - 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: - - mean : The return type varies, see above. - A new array holding the result is returned unless out is - specified, in which case a reference to out is returned. - - :SeeAlso: - - - var : variance - - std : standard deviation + Parameters + ---------- + axis : integer + Axis along which the means are computed. The default is + to compute the standard deviation of the flattened array. + + dtype : type + Type to use in computing the means. For arrays of integer type + the default is float32, for arrays of float types it is the + same as the array type. + + out : ndarray + 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 + ------- + mean : The return type varies, see above. + A new array holding the result is returned unless out is + specified, in which case a reference to out is returned. + + SeeAlso + ------- + var : variance + std : standard deviation Notes ----- - - The mean is the sum of the elements along the axis divided by the - number of elements. - + The mean is the sum of the elements along the axis divided by the + number of elements. """ return N.ndarray.mean(self, axis, out)._align(axis) @@ -287,43 +313,41 @@ class matrix(N.ndarray): spread of a distribution. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. - :Parameters: - - axis : integer - Axis along which the standard deviation is computed. The - default is to compute the standard deviation of the flattened - array. - - dtype : type - Type to use in computing the standard deviation. For arrays of - integer type the default is float32, for arrays of float types - it is the same as the array type. - - out : ndarray - 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: - - standard deviation : The return type varies, see above. - A new array holding the result is returned unless out is - specified, in which case a reference to out is returned. - - :SeeAlso: - - - var : variance - - mean : average + Parameters + ---------- + axis : integer + Axis along which the standard deviation is computed. The + default is to compute the standard deviation of the flattened + array. + + dtype : type + Type to use in computing the standard deviation. For arrays of + integer type the default is float32, for arrays of float types + it is the same as the array type. + + out : ndarray + 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 + ------- + standard deviation : The return type varies, see above. + A new array holding the result is returned unless out is + specified, in which case a reference to out is returned. + + SeeAlso + ------- + var : variance + mean : average Notes - ----- - - The standard deviation is the square root of the average of the - squared deviations from the mean, i.e. var = sqrt(mean((x - - x.mean())**2)). The computed standard deviation is biased, i.e., the - mean is computed by dividing by the number of elements, N, rather - than by N-1. - + ----- + The standard deviation is the square root of the + average of the squared deviations from the mean, i.e. var = + sqrt(mean((x - x.mean())**2)). The computed standard + deviation is biased, i.e., the mean is computed by dividing by + the number of elements, N, rather than by N-1. """ return N.ndarray.std(self, axis, dtype, out)._align(axis) @@ -334,41 +358,38 @@ class matrix(N.ndarray): a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. - :Parameters: - - axis : integer - Axis along which the variance is computed. The default is to - compute the variance of the flattened array. - - dtype : type - Type to use in computing the variance. For arrays of integer - type the default is float32, for arrays of float types it is - the same as the array type. - - out : ndarray - 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: - - variance : depends, see above - A new array holding the result is returned unless out is - specified, in which case a reference to out is returned. - - :SeeAlso: - - - std : standard deviation - - mean : average + Parameters + ---------- + axis : integer + Axis along which the variance is computed. The default is to + compute the variance of the flattened array. + dtype : data-type + Type to use in computing the variance. For arrays of integer + type the default is float32, for arrays of float types it is + the same as the array type. + out : ndarray + 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 + ------- + variance : depends, see above + A new array holding the result is returned unless out is + specified, in which case a reference to out is returned. + + SeeAlso + ------- + std : standard deviation + mean : average Notes ----- - The variance is the average of the squared deviations from the mean, - i.e. var = mean((x - x.mean())**2). The computed variance is - biased, i.e., the mean is computed by dividing by the number of - elements, N, rather than by N-1. - + The variance is the average of the squared deviations from the + mean, i.e. var = mean((x - x.mean())**2). The computed + variance is biased, i.e., the mean is computed by dividing by + the number of elements, N, rather than by N-1. """ return N.ndarray.var(self, axis, dtype, out)._align(axis) @@ -458,14 +479,16 @@ def _from_string(str,gdict,ldict): def bmat(obj, ldict=None, gdict=None): """Build a matrix object from string, nested sequence, or array. - Ex: F = bmat('A, B; C, D') - F = bmat([[A,B],[C,D]]) - F = bmat(r_[c_[A,B],c_[C,D]]) + Example + -------- + F = bmat('A, B; C, D') + F = bmat([[A,B],[C,D]]) + F = bmat(r_[c_[A,B],c_[C,D]]) - all produce the same Matrix Object [ A B ] - [ C D ] + all produce the same Matrix Object [ A B ] + [ C D ] - if A, B, C, and D are appropriately shaped 2-d arrays. + if A, B, C, and D are appropriately shaped 2-d arrays. """ if isinstance(obj, str): if gdict is None: diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index b2f141312..6b35d2ab9 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -40,10 +40,11 @@ BUFSIZE = multiarray.BUFSIZE # from Fernando Perez's IPython def zeros_like(a): - """Return an array of zeros of the shape and typecode of a. + """Return an array of zeros of the shape and data-type of a. If you don't explicitly need the array to be zeroed, you should instead - use empty_like(), which is faster as it only allocates memory.""" + use empty_like(), which is faster as it only allocates memory. + """ try: return zeros(a.shape, a.dtype, a.flags.fnc) except AttributeError: @@ -58,7 +59,7 @@ def zeros_like(a): return res def empty_like(a): - """Return an empty (uninitialized) array of the shape and typecode of a. + """Return an empty (uninitialized) array of the shape and data-type of a. Note that this does NOT initialize the returned array. If you require your array to be initialized, you should use zeros_like(). @@ -147,6 +148,29 @@ def asfortranarray(a, dtype=None): return array(a, dtype, copy=False, order='F', ndmin=1) def require(a, dtype=None, requirements=None): + """Return an ndarray of the provided type that satisfies requirements. + + This function is useful to be sure that an array with the correct flags + is returned for passing to compiled code (perhaps through ctypes). + + Parameters + ---------- + 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) + requirements : list of strings + The requirements list can be any of the + 'ENSUREARRAY' ('E') - ensure that a base-class ndarray + 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array + 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array + 'ALIGNED' ('A') - ensure a data-type aligned array + 'WRITEABLE' ('W') - ensure a writeable array + 'OWNDATA' ('O') - ensure an array that owns its own data + + The returned array will be guaranteed to have the listed requirements + by making a copy if needed. + """ if requirements is None: requirements = [] else: @@ -252,11 +276,13 @@ def vdot(a, b): try: # importing this changes the dot function for basic 4 types # to blas-optimized versions. - from _dotblas import dot, vdot, inner, alterdot, restoredot + from _dotblas import dot, vdot, inner, alterdot, restoredot except ImportError: def alterdot(): + "Does Nothing" pass def restoredot(): + "Does Nothing" pass @@ -847,6 +873,9 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8): return all(less_equal(absolute(x-y), atol + rtol * absolute(y))) def array_equal(a1, a2): + """Returns True if a1 and a2 have identical shapes + and all elements equal and False otherwise. + """ try: a1, a2 = asarray(a1), asarray(a2) except: @@ -856,6 +885,10 @@ def array_equal(a1, a2): return 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. + """ try: a1, a2 = asarray(a1), asarray(a2) except: diff --git a/numpy/core/records.py b/numpy/core/records.py index b86a71d7b..2067ed059 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -43,10 +43,40 @@ def find_duplicate(list): return dup class format_parser: + """Class to convert formats, names, titles description to a dtype + + After constructing the format_parser object, the dtype attribute is + the converted data-type. + + dtype = format_parser(formats, names, titles).dtype + + Parameters + ---------- + formats : string or list + comma-separated format descriptions --- 'f8, i4, a5' + list of format description strings --- ['f8', 'i4', 'a5'] + names : string or (list or tuple of strings) + comma-separated field names --- 'col1, col2, col3' + list or tuple of field names + titles : sequence + sequence of title strings or unicode + aligned : bool + align the fields by padding as the C-compiler would + byteorder : + If specified, all the fields will be changed to the + provided byteorder. Otherwise, the default byteorder is + used. + + Returns + ------- + object + A Python object whose dtype attribute is a data-type. + """ def __init__(self, formats, names, titles, aligned=False, byteorder=None): self._parseFormats(formats, aligned) self._setfieldnames(names, titles) self._createdescr(byteorder) + self.dtype = self._descr def _parseFormats(self, formats, aligned=0): """ Parse the field formats """ @@ -115,6 +145,8 @@ class format_parser: self._descr = descr class record(nt.void): + """A data-type scalar that allows field access as attribute lookup. + """ def __repr__(self): return self.__str__() @@ -182,6 +214,29 @@ class record(nt.void): # the fields (and any subfields) class recarray(ndarray): + """recarray(shape, dtype=None, buf=None, **kwds) + + Subclass of ndarray that allows field access using attribute lookup. + + Parameters + ---------- + shape : tuple + shape of record array + dtype : data-type or None + The desired data-type. If this is None, then the data-type is determined + by the *formats*, *names*, *titles*, *aligned*, and *byteorder* keywords. + buf : [buffer] or None + If this is None, then a new array is created of the given shape and data-type + If this is an object exposing the buffer interface, then the array will + use the memory from an existing buffer. In this case, the *offset* and + *strides* keywords can also be used. + + See Also + -------- + format_parser : determine a data-type from formats, names, titles + record : fundamental data-type for recarray + + """ def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False): -- cgit v1.2.1