From f07c79d3709a7f81219abc3c516fd772f469c167 Mon Sep 17 00:00:00 2001 From: Jarrod Millman Date: Fri, 13 Nov 2009 17:49:06 +0000 Subject: [PATCH] first set of checkins from the doc editor --- numpy/compat/__init__.py | 11 +- numpy/core/arrayprint.py | 8 +- numpy/core/defchararray.py | 274 ++++++++++++++++++++---------- numpy/core/fromnumeric.py | 109 +++++++++--- numpy/core/memmap.py | 17 +- numpy/core/numeric.py | 43 +++-- numpy/core/records.py | 11 +- numpy/ctypeslib.py | 24 ++- numpy/distutils/ccompiler.py | 209 +++++++++++++++++++++-- numpy/distutils/misc_util.py | 243 ++++++++++++++++++-------- numpy/distutils/npy_pkg_config.py | 90 ++++++++++ numpy/distutils/unixccompiler.py | 24 +++ numpy/fft/fftpack.py | 24 +-- numpy/lib/_datasource.py | 3 +- numpy/lib/_iotools.py | 34 +++- numpy/lib/scimath.py | 107 ++++++------ numpy/lib/utils.py | 9 +- numpy/linalg/linalg.py | 42 ++--- numpy/ma/core.py | 68 ++++++-- numpy/ma/extras.py | 188 +++++++++++++++++--- numpy/matlib.py | 206 +++++++++++++++++++--- 21 files changed, 1359 insertions(+), 385 deletions(-) diff --git a/numpy/compat/__init__.py b/numpy/compat/__init__.py index 2e37a43501c1..9db56bca1055 100644 --- a/numpy/compat/__init__.py +++ b/numpy/compat/__init__.py @@ -1,9 +1,12 @@ -"""Compatibility module. +""" +Compatibility module. -This module contains duplicated code from python itself or 3rd party +This module contains duplicated code from Python itself or 3rd party extensions, which may be included for the following reasons: - - compatibility - - we may only need a small subset of the copied library/module + + * compatibility + * we may only need a small subset of the copied library/module + """ import _inspect from _inspect import getargspec, formatargspec diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index df5662b1bf93..fb83af3fb91e 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -122,8 +122,8 @@ def get_printoptions(): - edgeitems : int - linewidth : int - suppress : bool - - nanstr : string - - infstr : string + - nanstr : str + - infstr : str For a full description of these options, see `set_printoptions`. @@ -253,9 +253,9 @@ def array2string(a, max_line_width = None, precision = None, suppress_small : bool, optional Represent very small numbers as zero. A number is "very small" if it is smaller than the current printing precision. - separator : string, optional + separator : str, optional Inserted between elements. - prefix : string, optional + prefix : str, optional An array is typically printed as:: 'prefix(' + array2string(a) + ')' diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 257eeff40f7e..108eb7086e6f 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -3,15 +3,17 @@ operations and methods. .. note:: - The chararray module exists for backwards compatibility with + The `chararray` class exists for backwards compatibility with Numarray, it is not recommended for new development. If one needs arrays of strings, use arrays of `dtype` `object_`, `string_` or - `unicode_`. + `unicode_`, and use the free functions in the `numpy.char` module + for fast vectorized string operations. -Methods will only be available if the corresponding str method is +Some methods will only be available if the corresponding str method is available in your version of Python. The preferred alias for `defchararray` is `numpy.char`. + """ import sys @@ -281,12 +283,14 @@ def multiply(a, i): Parameters ---------- a : array_like of str or unicode + i : array_like of ints Returns ------- out : ndarray Output array of str or unicode, depending on input types + """ a_arr = numpy.asarray(a) i_arr = numpy.asarray(i) @@ -305,6 +309,7 @@ def mod(a, values): Parameters ---------- a : array_like of str or unicode + values : array_like of values These values will be element-wise interpolated into the string. @@ -316,6 +321,7 @@ def mod(a, values): See also -------- str.__mod__ + """ return _to_string_or_unicode_array( _vec_string(a, object_, '__mod__', (values,))) @@ -366,6 +372,7 @@ def center(a, width, fillchar=' '): Parameters ---------- a : array_like of str or unicode + width : int The length of the resulting strings fillchar : str or unicode, optional @@ -380,6 +387,7 @@ def center(a, width, fillchar=' '): See also -------- str.center + """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) @@ -425,8 +433,10 @@ def count(a, sub, start=0, end=None): Parameters ---------- a : array_like of str or unicode + sub : str or unicode - The substring to search for + The substring to search for. + start, end : int, optional Optional arguments `start` and `end` are interpreted as slice notation to specify the range in which to count. @@ -454,6 +464,7 @@ def count(a, sub, start=0, end=None): array([2, 1, 1]) >>> np.char.count(c, 'A', start=1, end=3) array([1, 0, 0]) + """ return _vec_string(a, integer, 'count', [sub, start] + _clean_args(end)) @@ -461,11 +472,17 @@ def decode(a, encoding=None, errors=None): """ Calls `str.decode` element-wise. + The set of available codecs comes from the Python standard library, + and may be extended at runtime. For more information, see the + :mod:`codecs` module. + Parameters ---------- a : array_like of str or unicode + encoding : str, optional The name of an encoding + errors : str, optional Specifies how to handle encoding errors @@ -473,14 +490,14 @@ def decode(a, encoding=None, errors=None): ------- out : ndarray - Notes - ----- - The type of the result will depend on the encoding specified. - See also -------- str.decode + Notes + ----- + The type of the result will depend on the encoding specified. + Examples -------- >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']) @@ -491,6 +508,7 @@ def decode(a, encoding=None, errors=None): array(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@', '\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'], dtype='|S7') + """ return _to_string_or_unicode_array( _vec_string(a, object_, 'decode', _clean_args(encoding, errors))) @@ -499,11 +517,17 @@ def encode(a, encoding=None, errors=None): """ Calls `str.encode` element-wise. + The set of available codecs comes from the Python standard library, + and may be extended at runtime. For more information, see the codecs + module. + Parameters ---------- a : array_like of str or unicode + encoding : str, optional The name of an encoding + errors : str, optional Specifies how to handle encoding errors @@ -511,13 +535,14 @@ def encode(a, encoding=None, errors=None): ------- out : ndarray + See also + -------- + str.encode + Notes ----- The type of the result will depend on the encoding specified. - See also - -------- - str.encode """ return _to_string_or_unicode_array( _vec_string(a, object_, 'encode', _clean_args(encoding, errors))) @@ -532,7 +557,9 @@ def endswith(a, suffix, start=0, end=None): Parameters ---------- a : array_like of str or unicode + suffix : str + start, end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. @@ -558,6 +585,7 @@ def endswith(a, suffix, start=0, end=None): array([False, True], dtype=bool) >>> s.endswith(s, 'a', start=1, end=2) array([False, True], dtype=bool) + """ return _vec_string( a, bool_, 'endswith', [suffix, start] + _clean_args(end)) @@ -607,19 +635,22 @@ def find(a, sub, start=0, end=None): Parameters ---------- a : array_like of str or unicode + sub : str or unicode + start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. Returns ------- - out : {ndarray, integer} + out : ndarray or int Output array of ints. Returns -1 if `sub` is not found. See also -------- str.find + """ return _vec_string( a, integer, 'find', [sub, start] + _clean_args(end)) @@ -638,7 +669,9 @@ def index(a, sub, start=0, end=None): Parameters ---------- a : array_like of str or unicode + sub : str or unicode + start, end : int, optional Returns @@ -649,6 +682,7 @@ def index(a, sub, start=0, end=None): See also -------- find, str.find + """ return _vec_string( a, integer, 'index', [sub, start] + _clean_args(end)) @@ -859,6 +893,7 @@ def ljust(a, width, fillchar=' '): Parameters ---------- a : array_like of str or unicode + width : int The length of the resulting strings fillchar : str or unicode, optional @@ -872,6 +907,7 @@ def ljust(a, width, fillchar=' '): See also -------- str.ljust + """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) @@ -950,6 +986,7 @@ def lstrip(a, chars=None): Parameters ---------- a : array-like of str or unicode + chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` @@ -982,6 +1019,7 @@ def lstrip(a, chars=None): True >>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all() True + """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'lstrip', (chars,)) @@ -1028,7 +1066,9 @@ def replace(a, old, new, count=None): Parameters ---------- a : array-like of str or unicode + old, new : str or unicode + count : int, optional If the optional argument `count` is given, only the first `count` occurrences are replaced. @@ -1041,6 +1081,7 @@ def replace(a, old, new, count=None): See also -------- str.replace + """ return _to_string_or_unicode_array( _vec_string( @@ -1057,7 +1098,9 @@ def rfind(a, sub, start=0, end=None): Parameters ---------- a : array-like of str or unicode + sub : str or unicode + start, end : int, optional Optional arguments `start` and `end` are interpreted as in slice notation. @@ -1070,6 +1113,7 @@ def rfind(a, sub, start=0, end=None): See also -------- str.rfind + """ return _vec_string( a, integer, 'rfind', [sub, start] + _clean_args(end)) @@ -1084,7 +1128,9 @@ def rindex(a, sub, start=0, end=None): Parameters ---------- a : array-like of str or unicode + sub : str or unicode + start, end : int, optional Returns @@ -1095,6 +1141,7 @@ def rindex(a, sub, start=0, end=None): See also -------- rfind, str.rindex + """ return _vec_string( a, integer, 'rindex', [sub, start] + _clean_args(end)) @@ -1110,6 +1157,7 @@ def rjust(a, width, fillchar=' '): Parameters ---------- a : array_like of str or unicode + width : int The length of the resulting strings fillchar : str or unicode, optional @@ -1123,6 +1171,7 @@ def rjust(a, width, fillchar=' '): See also -------- str.rjust + """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) @@ -1204,6 +1253,7 @@ def rsplit(a, sep=None, maxsplit=None): Parameters ---------- a : array_like of str or unicode + sep : str or unicode, optional If `sep` is not specified or `None`, any whitespace string is a separator. @@ -1219,6 +1269,7 @@ def rsplit(a, sep=None, maxsplit=None): See also -------- str.rsplit, split + """ # This will return an array of lists of different sizes, so we # leave it as an object array @@ -1235,6 +1286,7 @@ def rstrip(a, chars=None): Parameters ---------- a : array-like of str or unicode + chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` @@ -1262,6 +1314,7 @@ def rstrip(a, chars=None): >>> np.char.rstrip(c, 'A') array(['aAaAa', 'abBABba'], dtype='|S7') + """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'rstrip', (chars,)) @@ -1276,9 +1329,11 @@ def split(a, sep=None, maxsplit=None): Parameters ---------- a : array_like of str or unicode + sep : str or unicode, optional If `sep` is not specified or `None`, any whitespace string is a separator. + maxsplit : int, optional If `maxsplit` is given, at most `maxsplit` splits are done. @@ -1290,6 +1345,7 @@ def split(a, sep=None, maxsplit=None): See also -------- str.split, rsplit + """ # This will return an array of lists of different sizes, so we # leave it as an object array @@ -1306,6 +1362,7 @@ def splitlines(a, keepends=None): Parameters ---------- a : array_like of str or unicode + keepends : bool, optional Line breaks are not included in the resulting list unless keepends is given and true. @@ -1318,6 +1375,7 @@ def splitlines(a, keepends=None): See also -------- str.splitlines + """ return _vec_string( a, object_, 'splitlines', _clean_args(keepends)) @@ -1332,9 +1390,10 @@ def startswith(a, prefix, start=0, end=None): Parameters ---------- a : array_like of str or unicode + suffix : str + start, end : int, optional - end : int, optional With optional `start`, test beginning at that position. With optional `end`, stop comparing at that position. @@ -1346,6 +1405,7 @@ def startswith(a, prefix, start=0, end=None): See also -------- str.startswith + """ return _vec_string( a, bool_, 'startswith', [prefix, start] + _clean_args(end)) @@ -1360,6 +1420,7 @@ def strip(a, chars=None): Parameters ---------- a : array-like of str or unicode + chars : str or unicode, optional The `chars` argument is a string specifying the set of characters to be removed. If omitted or None, the `chars` @@ -1391,6 +1452,7 @@ def strip(a, chars=None): >>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails array(['aAaAa', ' aA', 'abBABba'], dtype='|S7') + """ a_arr = numpy.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'strip', _clean_args(chars)) @@ -1476,7 +1538,9 @@ def translate(a, table, deletechars=None): Parameters ---------- a : array-like of str or unicode + table : str of length 256 + deletechars : str Returns @@ -1487,6 +1551,7 @@ def translate(a, table, deletechars=None): See also -------- str.translate + """ a_arr = numpy.asarray(a) if issubclass(a_arr.dtype.type, unicode_): @@ -1621,11 +1686,11 @@ class chararray(ndarray): Provides a convenient view on arrays of string and unicode values. .. note:: - This class is provided for numarray backward-compatibility. - New code (not concerned with numarray compatibility) should use - arrays of type string_ or unicode_ and use the free - functions in :mod:`numpy.char ` for - fast vectorized string operations instead. + The `chararray` class exists for backwards compatibility with + Numarray, it is not recommended for new development. If one needs + arrays of strings, use arrays of `dtype` `object_`, `string_` or + `unicode_`, and use the free functions in the `numpy.char` module + for fast vectorized string operations. Versus a regular Numpy array of type `str` or `unicode`, this class adds the following functionality: @@ -1637,64 +1702,58 @@ class adds the following functionality: end when comparing values 3) vectorized string operations are provided as methods - (e.g. `.endswith`) and infix operators (e.g. +, *, %) + (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``) - chararrays should be created using `numpy.char.array - ` or `numpy.char.asarray - `, rather than this constructor - directly. + chararrays should be created using `numpy.char.array` or + `numpy.char.asarray`, rather than this constructor directly. - 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 "C order," unless both ``len(shape) >= 2`` - and ``order='Fortran'``, in which case `strides` is in "Fortran - order." + This constructor creates the array, using `buffer` (with `offset` + and `strides`) if it is not ``None``. If `buffer` is ``None``, then + constructs a new array with `strides` in "C order", unless both + ``len(shape) >= 2`` and ``order='Fortran'``, in which case `strides` + is in "Fortran order". Parameters ---------- shape : tuple - Shape of the array. - - itemsize : int_like, > 0, optional - Length of each array element, in number of characters. Default is 1. - + Shape of the array. + itemsize : int, optional + Length of each array element, in number of characters. Default is 1. unicode : bool, optional - Are the array elements of unicode-type (`True`) or string-type - (`False`, the default). - - buffer : int, > 0, optional - Memory address of the start of the array data. If `None` - (the default), a new array is created. - - offset : int, >= 0, optional - Fixed stride displacement from the beginning of an axis? - Default is 0. - - strides : array_like, optional - Strides for the array (see `numpy.ndarray.strides` for full - description), default is `None`. - + Are the array elements of type unicode (True) or string (False). + Default is False. + buffer : int, optional + Memory address of the start of the array data. Default is None, + in which case a new array is created. + offset : int, optional + Fixed stride displacement from the beginning of an axis? + Default is 0. Needs to be >=0. + strides : array_like of ints, optional + Strides for the array (see `ndarray.strides` for full description). + Default is None. order : {'C', 'F'}, optional - The order in which the array data is stored in memory: 'C' -> - "row major" order (the default), 'F' -> "column major" - (Fortran) order. + The order in which the array data is stored in memory: 'C' -> + "row major" order (the default), 'F' -> "column major" + (Fortran) order. Examples -------- >>> charar = np.chararray((3, 3)) - >>> charar[:,:] = 'abc' + >>> charar[:, :] = 'abc' >>> charar chararray([['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']], dtype='|S1') + >>> charar = np.chararray(charar.shape, itemsize=5) - >>> charar[:,:] = 'abc' + >>> charar[:, :] = 'abc' >>> charar chararray([['abc', 'abc', 'abc'], ['abc', 'abc', 'abc'], ['abc', 'abc', 'abc']], dtype='|S5') + """ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C'): @@ -1889,7 +1948,8 @@ def capitalize(self): See also -------- - capitalize + char.capitalize + """ return asarray(capitalize(self)) @@ -1923,7 +1983,8 @@ def count(self, sub, start=0, end=None): See also -------- - count + char.count + """ return count(self, sub, start, end) @@ -1934,7 +1995,8 @@ def decode(self, encoding=None, errors=None): See also -------- - decode + char.decode + """ return decode(self, encoding, errors) @@ -1944,7 +2006,8 @@ def encode(self, encoding=None, errors=None): See also -------- - encode + char.encode + """ return encode(self, encoding, errors) @@ -1955,7 +2018,8 @@ def endswith(self, suffix, start=0, end=None): See also -------- - endswith + char.endswith + """ return endswith(self, suffix, start, end) @@ -1966,7 +2030,8 @@ def expandtabs(self, tabsize=8): See also -------- - expandtabs + char.expandtabs + """ return asarray(expandtabs(self, tabsize)) @@ -1977,7 +2042,8 @@ def find(self, sub, start=0, end=None): See also -------- - find + char.find + """ return find(self, sub, start, end) @@ -1987,7 +2053,8 @@ def index(self, sub, start=0, end=None): See also -------- - index + char.index + """ return index(self, sub, start, end) @@ -1999,7 +2066,8 @@ def isalnum(self): See also -------- - isalnum + char.isalnum + """ return isalnum(self) @@ -2011,7 +2079,8 @@ def isalpha(self): See also -------- - isalpha + char.isalpha + """ return isalpha(self) @@ -2022,7 +2091,8 @@ def isdigit(self): See also -------- - isdigit + char.isdigit + """ return isdigit(self) @@ -2034,7 +2104,8 @@ def islower(self): See also -------- - islower + char.islower + """ return islower(self) @@ -2046,7 +2117,8 @@ def isspace(self): See also -------- - isspace + char.isspace + """ return isspace(self) @@ -2057,7 +2129,8 @@ def istitle(self): See also -------- - istitle + char.istitle + """ return istitle(self) @@ -2069,7 +2142,8 @@ def isupper(self): See also -------- - isupper + char.isupper + """ return isupper(self) @@ -2080,7 +2154,8 @@ def join(self, seq): See also -------- - join + char.join + """ return join(self, seq) @@ -2092,7 +2167,8 @@ def ljust(self, width, fillchar=' '): See also -------- - ljust + char.ljust + """ return asarray(ljust(self, width, fillchar)) else: @@ -2111,9 +2187,11 @@ def lower(self): """ Return an array with the elements of `self` converted to lowercase. + See also -------- - lower + char.lower + """ return asarray(lower(self)) @@ -2124,7 +2202,8 @@ def lstrip(self, chars=None): See also -------- - lstrip + char.lstrip + """ return asarray(lstrip(self, chars)) @@ -2146,7 +2225,8 @@ def replace(self, old, new, count=None): See also -------- - replace + char.replace + """ return asarray(replace(self, old, new, count)) @@ -2158,7 +2238,8 @@ def rfind(self, sub, start=0, end=None): See also -------- - rfind + char.rfind + """ return rfind(self, sub, start, end) @@ -2169,7 +2250,8 @@ def rindex(self, sub, start=0, end=None): See also -------- - rindex + char.rindex + """ return rindex(self, sub, start, end) @@ -2181,7 +2263,8 @@ def rjust(self, width, fillchar=' '): See also -------- - rjust + char.rjust + """ return asarray(rjust(self, width, fillchar)) else: @@ -2215,7 +2298,8 @@ def rsplit(self, sep=None, maxsplit=None): See also -------- - rsplit + char.rsplit + """ return rsplit(self, sep, maxsplit) @@ -2226,7 +2310,8 @@ def rstrip(self, chars=None): See also -------- - rstrip + char.rstrip + """ return asarray(rstrip(self, chars)) @@ -2237,7 +2322,8 @@ def split(self, sep=None, maxsplit=None): See also -------- - split + char.split + """ return split(self, sep, maxsplit) @@ -2248,7 +2334,8 @@ def splitlines(self, keepends=None): See also -------- - splitlines + char.splitlines + """ return splitlines(self, keepends) @@ -2259,7 +2346,8 @@ def startswith(self, prefix, start=0, end=None): See also -------- - startswith + char.startswith + """ return startswith(self, prefix, start, end) @@ -2270,7 +2358,8 @@ def strip(self, chars=None): See also -------- - strip + char.strip + """ return asarray(strip(self, chars)) @@ -2281,7 +2370,8 @@ def swapcase(self): See also -------- - swapcase + char.swapcase + """ return asarray(swapcase(self)) @@ -2293,7 +2383,8 @@ def title(self): See also -------- - title + char.title + """ return asarray(title(self)) @@ -2306,7 +2397,8 @@ def translate(self, table, deletechars=None): See also -------- - translate + char.translate + """ return asarray(translate(self, table, deletechars)) @@ -2317,7 +2409,8 @@ def upper(self): See also -------- - upper + char.upper + """ return asarray(upper(self)) @@ -2328,7 +2421,8 @@ def zfill(self, width): See also -------- - zfill + char.zfill + """ return asarray(zfill(self, width)) @@ -2339,7 +2433,8 @@ def isnumeric(self): See also -------- - isnumeric + char.isnumeric + """ return isnumeric(self) @@ -2350,7 +2445,8 @@ def isdecimal(self): See also -------- - isdecimal + char.isdecimal + """ return isdecimal(self) diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index eb7da718a19d..4b3970f00682 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -154,52 +154,121 @@ def reshape(a, newshape, order='C'): def choose(a, choices, out=None, mode='raise'): """ - Use an index array to construct a new array from a set of choices. + Construct an array from an index array and a set of arrays to choose from. - Given an array of integers and a set of n choice arrays, this function - will create a new array that merges each of the choice arrays. Where a - value in `a` is i, then the new array will have the value that - choices[i] contains in the same place. + First of all, if confused or uncertain, definitely look at the Examples - + in its full generality, this function is less simple than it might + seem from the following code description (below ndi = + `numpy.lib.index_tricks`): + + ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``. + + But this omits some subtleties. Here is a fully general summary: + + Given an "index" array (`a`) of integers and a sequence of `n` arrays + (`choices`), `a` and each choice array are first broadcast, as necessary, + to arrays of a common shape; calling these *Ba* and *Bchoices[i], i = + 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape`` + for each `i`. Then, a new array with shape ``Ba.shape`` is created as + follows: + + * if ``mode=raise`` (the default), then, first of all, each element of + `a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that + `i` (in that range) is the value at the `(j0, j1, ..., jm)` position + in `Ba` - then the value at the same position in the new array is the + value in `Bchoices[i]` at that same position; + + * if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed) + integer; modular arithmetic is used to map integers outside the range + `[0, n-1]` back into that range; and then the new array is constructed + as above; + + * if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed) + integer; negative integers are mapped to 0; values greater than `n-1` + are mapped to `n-1`; and then the new array is constructed as above. Parameters ---------- a : int array - This array must contain integers in [0, n-1], where n is the number - of choices. + This array must contain integers in `[0, n-1]`, where `n` is the number + of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any + integers are permissible. choices : sequence of arrays - Choice arrays. The index array and all of the choices should be - broadcastable to the same shape. + Choice arrays. `a` and all of the choices must be broadcastable to the + same shape. If `choices` is itself an array (not recommended), then + its outermost dimension (i.e., the one corresponding to + ``choices.shape[0]``) is taken as defining the "sequence". out : array, optional If provided, the result will be inserted into this array. It should - be of the appropriate shape and dtype - mode : {'raise', 'wrap', 'clip'}, optional - Specifies how out-of-bounds indices will behave: + be of the appropriate shape and dtype. + mode : {'raise' (default), 'wrap', 'clip'}, optional + Specifies how indices outside `[0, n-1]` will be treated: - * 'raise' : raise an error - * 'wrap' : wrap around - * 'clip' : clip to the range + * 'raise' : an exception is raised + * 'wrap' : value becomes value mod `n` + * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns ------- merged_array : array - The merged results. + The merged result. + + Raises + ------ + ValueError: shape mismatch + If `a` and each choice array are not all broadcastable to the same + shape. See Also -------- ndarray.choose : equivalent method - numpy.doc.ufuncs : Section "Output arguments" + + Notes + ----- + To reduce the chance of misinterpretation, even though the following + "abuse" is nominally supported, `choices` should neither be, nor be + thought of as, a single array, i.e., the outermost sequence-like container + should be either a list or a tuple. Examples -------- >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], ... [20, 21, 22, 23], [30, 31, 32, 33]] - >>> np.choose([2, 3, 1, 0], choices) + >>> np.choose([2, 3, 1, 0], choices + ... # the first element of the result will be the first element of the + ... # third (2+1) "array" in choices, namely, 20; the second element + ... # will be the second element of the fourth (3+1) choice array, i.e., + ... # 31, etc. + ... ) array([20, 31, 12, 3]) - >>> np.choose([2, 4, 1, 0], choices, mode='clip') + >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1) array([20, 31, 12, 3]) - >>> np.choose([2, 4, 1, 0], choices, mode='wrap') + >>> # because there are 4 choice arrays + >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4) array([20, 1, 12, 3]) + >>> # i.e., 0 + + A couple examples illustrating how choose broadcasts: + + >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]] + >>> choices = [-10, 10] + >>> np.choose(a, choices) + array([[ 10, -10, 10], + [-10, 10, -10], + [ 10, -10, 10]]) + + >>> # With thanks to Anne Archibald + >>> a = np.array([0, 1]).reshape((2,1,1)) + >>> c1 = np.array([1, 2, 3]).reshape((1,3,1)) + >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5)) + >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2 + array([[[ 1, 1, 1, 1, 1], + [ 2, 2, 2, 2, 2], + [ 3, 3, 3, 3, 3]], + [[-1, -2, -3, -4, -5], + [-1, -2, -3, -4, -5], + [-1, -2, -3, -4, -5]]]) """ try: diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index c11859fad89a..996d5562c369 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -26,12 +26,11 @@ class memmap(ndarray): Parameters ---------- - filename : string or file-like object - The file name or file object to be used as the array data - buffer. + filename : str or file-like object + The file name or file object to be used as the array data buffer. dtype : data-type, optional The data-type used to interpret the file contents. - Default is `uint8` + Default is `uint8`. mode : {'r+', 'r', 'w+', 'c'}, optional The file is opened in this mode: @@ -48,10 +47,10 @@ class memmap(ndarray): +------+-------------------------------------------------------------+ Default is 'r+'. - offset : integer, optional + offset : int, optional In the file, array data starts at this offset. Since `offset` is measured in bytes, it should be a multiple of the byte-size of - `dtype`. Requires `shape=None`. The default is 0. + `dtype`. Requires ``shape=None``. The default is 0. shape : tuple, optional The desired shape of the array. By default, the returned array will be 1-D with the number of elements determined by file size and data-type. @@ -248,16 +247,12 @@ def flush(self): -------- memmap - Examples - -------- - Awaiting one... - """ if self._mmap is not None: self._mmap.flush() def sync(self): - """Flush any changes in the array to the file on disk.""" + """This method is deprecated, use `flush`.""" warnings.warn("Use ``flush``.", DeprecationWarning) self.flush() diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 3ca2d988fbbe..be10d5005166 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -105,29 +105,43 @@ def zeros_like(a): def empty_like(a): """ - Create a new array with the same shape and type as another. + Return a new array with the same shape and type as a given array. Parameters ---------- - a : ndarray - Returned array will have same shape and type as `a`. + a : array_like + The shape and data-type of `a` define the parameters of the + returned array. + + Returns + ------- + out : ndarray + Array of random data with the same shape and type as `a`. See Also -------- - zeros_like, ones_like, zeros, ones, empty + ones_like : Return an array of ones with shape and type of input. + zeros_like : Return an array of zeros with shape and type of input. + empty : Return a new uninitialized array. + ones : Return a new array setting values to one. + zeros : Return a new array setting values to zero. Notes ----- This function does *not* initialize the returned array; to do that use - `zeros_like` or `ones_like` instead. + `zeros_like` or `ones_like` instead. It may be marginally faster than the + functions that do set the array values. Examples -------- - >>> a = np.array([[1,2,3],[4,5,6]]) + >>> a = ([1,2,3], [4,5,6]) # a is array-like >>> np.empty_like(a) + array([[-1073741821, -1073741821, 3], #random + [ 0, 0, -1073741821]]) + >>> a = np.array([[1., 2., 3.],[4.,5.,6.]]) >>> np.empty_like(a) - array([[-1073741821, -1067702173, 65538], #random data - [ 25670, 23454291, 71800]]) + array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], #random + [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) """ if isinstance(a, ndarray): @@ -1661,11 +1675,11 @@ def base_repr (number, base=2, padding=0): ---------- number : scalar The value to convert. Only positive values are handled. - base : int + base : int, optional Convert `number` to the `base` number system. The valid range is 2-36, the default value is 2. padding : int, optional - Number of zeros padded on the left. + Number of zeros padded on the left. Default is 0 (no padding). Returns ------- @@ -1679,13 +1693,18 @@ def base_repr (number, base=2, padding=0): Examples -------- - >>> np.base_repr(3, 5) - '3' + >>> np.base_repr(5) + '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' + >>> np.base_repr(10, base=16) + 'A' + >>> np.base_repr(32, base=16) + '20' + """ if number < 0: raise ValueError("negative numbers not handled in base_repr") diff --git a/numpy/core/records.py b/numpy/core/records.py index a41a712b8d30..b974d63419a1 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -261,6 +261,7 @@ def __setattr__(self, attr, val): "attribute '%s'" % attr def pprint(self): + """Pretty-print all fields.""" # pretty-print all fields names = self.dtype.names maxlen = max([len(name) for name in names]) @@ -303,7 +304,7 @@ class recarray(ndarray): Note that `formats` must be a list, not a tuple. Given that `formats` is somewhat limited, we recommend specifying `dtype` instead. - names : tuple of strings, optional + names : tuple of str, optional The name of each column, e.g. ``('x', 'y', 'z')``. buf : buffer, optional By default, a new array is created of the given shape and data-type. @@ -313,14 +314,14 @@ class recarray(ndarray): Other Parameters ---------------- - titles : tuple of strings, optional + titles : tuple of str, optional Aliases for column names. For example, if `names` were ``('x', 'y', 'z')`` and `titles` is ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``. byteorder : {'<', '>', '='}, optional Byte-order for all fields. - aligned : {True, False}, optional + aligned : bool, optional Align the fields in memory as the C-compiler would. strides : tuple of ints, optional Buffer (`buf`) is interpreted according to these strides (strides @@ -337,8 +338,8 @@ class recarray(ndarray): See Also -------- rec.fromrecords : Construct a record array from data. - record : fundamental data-type for recarray - format_parser : determine a data-type from formats, names, titles + record : fundamental data-type for `recarray`. + format_parser : determine a data-type from formats, names, titles. Notes ----- diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index e2eb9f24772d..459770a47747 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -63,6 +63,15 @@ if ctypes is None: def _dummy(*args, **kwds): + """ + Dummy object that raises an ImportError if ctypes is not available. + + Raises + ------ + ImportError + If ctypes is not available. + + """ raise ImportError, "ctypes is not available." ctypes_load_library = _dummy load_library = _dummy @@ -194,7 +203,7 @@ def ndpointer(dtype=None, ndim=None, shape=None, flags=None): Number of array dimensions. shape : tuple of ints, optional Array shape. - flags : string or tuple of strings + flags : str or tuple of str Array flags; may be one or more of: - C_CONTIGUOUS / C / CONTIGUOUS @@ -204,9 +213,20 @@ def ndpointer(dtype=None, ndim=None, shape=None, flags=None): - ALIGNED / A - UPDATEIFCOPY / U + Returns + ------- + klass : ndpointer type object + A type object, which is an ``_ndtpr`` instance containing + dtype, ndim, shape and flags information. + + Raises + ------ + TypeError + If a given array does not satisfy the specified restrictions. + Examples -------- - >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=float64, + >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index 63f9744f7327..3137cc03f0c5 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -26,6 +26,27 @@ def replace_method(klass, method_name, func): # Using customized CCompiler.spawn. def CCompiler_spawn(self, cmd, display=None): + """ + Execute a command in a sub-process. + + Parameters + ---------- + cmd : str + The command to execute. + display : str or sequence of str, optional + The text to add to the log file kept by `numpy.distutils`. + If not given, `display` is equal to `cmd`. + + Returns + ------- + None + + Raises + ------ + DistutilsExecError + If the command failed, i.e. the exit status was not 0. + + """ if display is None: display = cmd if is_sequence(display): @@ -46,6 +67,28 @@ def CCompiler_spawn(self, cmd, display=None): replace_method(CCompiler, 'spawn', CCompiler_spawn) def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''): + """ + Return the name of the object files for the given source files. + + Parameters + ---------- + source_filenames : list of str + The list of paths to source files. Paths can be either relative or + absolute, this is handled transparently. + strip_dir : bool, optional + Whether to strip the directory from the returned paths. If True, + the file name prepended by `output_dir` is returned. Default is False. + output_dir : str, optional + If given, this path is prepended to the returned paths to the + object files. + + Returns + ------- + obj_names : list of str + The list of paths to the object files corresponding to the source + files in `source_filenames`. + + """ if output_dir is None: output_dir = '' obj_names = [] @@ -74,6 +117,41 @@ def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=' def CCompiler_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): + """ + Compile one or more source files. + + Please refer to the Python distutils API reference for more details. + + Parameters + ---------- + sources : list of str + A list of filenames + output_dir : str, optional + Path to the output directory. + macros : list of tuples + A list of macro definitions. + include_dirs : list of str, optional + The directories to add to the default include file search path for + this compilation only. + debug : bool, optional + Whether or not to output debug symbols in or alongside the object + file(s). + extra_preargs, extra_postargs : ? + Extra pre- and post-arguments. + depends : list of str, optional + A list of file names that all targets depend on. + + Returns + ------- + objects : list of str + A list of object file names, one per source file `sources`. + + Raises + ------ + CompileError + If compilation fails. + + """ # This method is effective only with Python >=2.3 distutils. # Any changes here should be applied also to fcompiler.compile # method to support pre Python 2.3 distutils. @@ -122,7 +200,23 @@ def CCompiler_compile(self, sources, output_dir=None, macros=None, replace_method(CCompiler, 'compile', CCompiler_compile) def CCompiler_customize_cmd(self, cmd, ignore=()): - """ Customize compiler using distutils command. + """ + Customize compiler using distutils command. + + Parameters + ---------- + cmd : class instance + An instance inheriting from `distutils.cmd.Command`. + ignore : sequence of str, optional + List of `CCompiler` commands (without ``'set_'``) that should not be + altered. Strings that are checked for are: + ``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs', + 'rpath', 'link_objects')``. + + Returns + ------- + None + """ log.info('customize %s using %s' % (self.__class__.__name__, cmd.__class__.__name__)) @@ -169,6 +263,22 @@ def _compiler_to_string(compiler): return '\n'.join(lines) def CCompiler_show_customization(self): + """ + Print the compiler customizations to stdout. + + Parameters + ---------- + None + + Returns + ------- + None + + Notes + ----- + Printing is only done if the distutils log threshold is < 2. + + """ if 0: for attrname in ['include_dirs','define','undef', 'libraries','library_dirs', @@ -190,6 +300,35 @@ def CCompiler_show_customization(self): replace_method(CCompiler, 'show_customization', CCompiler_show_customization) def CCompiler_customize(self, dist, need_cxx=0): + """ + Do any platform-specific customization of a compiler instance. + + This method calls `distutils.sysconfig.customize_compiler` for + platform-specific customization, as well as optionally remove a flag + to suppress spurious warnings in case C++ code is being compiled. + + Parameters + ---------- + dist : object + This parameter is not used for anything. + need_cxx : bool, optional + Whether or not C++ has to be compiled. If so (True), the + ``"-Wstrict-prototypes"`` option is removed to prevent spurious + warnings. Default is False. + + Returns + ------- + None + + Notes + ----- + All the default options used by distutils can be extracted with:: + + from distutils import sysconfig + sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS', + 'CCSHARED', 'LDSHARED', 'SO') + + """ # See FCompiler.customize for suggested usage. log.info('customize %s' % (self.__class__.__name__)) customize_compiler(self) @@ -225,18 +364,29 @@ def CCompiler_customize(self, dist, need_cxx=0): def simple_version_match(pat=r'[-.\d]+', ignore='', start=''): """ - Simple matching of version numbers, for use in CCompiler and FCompiler - classes. - - :Parameters: - pat : regex matching version numbers. - ignore : false or regex matching expressions to skip over. - start : false or regex matching the start of where to start looking - for version numbers. - - :Returns: - A function that is appropiate to use as the .version_match - attribute of a CCompiler class. + Simple matching of version numbers, for use in CCompiler and FCompiler. + + Parameters + ---------- + pat : str, optional + A regular expression matching version numbers. + Default is ``r'[-.\\d]+'``. + ignore : str, optional + A regular expression matching patterns to skip. + Default is ``''``, in which case nothing is skipped. + start : str, optional + A regular expression matching the start of where to start looking + for version numbers. + Default is ``''``, in which case searching is started at the + beginning of the version string given to `matcher`. + + Returns + ------- + matcher : callable + A function that is appropriate to use as the ``.version_match`` + attribute of a `CCompiler` class. `matcher` takes a single parameter, + a version string. + """ def matcher(self, version_string): pos = 0 @@ -257,7 +407,25 @@ def matcher(self, version_string): return matcher def CCompiler_get_version(self, force=False, ok_status=[0]): - """Compiler version. Returns None if compiler is not available.""" + """ + Return compiler version, or None if compiler is not available. + + Parameters + ---------- + force : bool, optional + If True, force a new determination of the version, even if the + compiler already has a version attribute. Default is False. + ok_status : list of int, optional + The list of status values returned by the version look-up process + for which a version string is returned. If the status value is not + in `ok_status`, None is returned. Default is ``[0]``. + + Returns + ------- + version : str or None + Version string, in the format of `distutils.version.LooseVersion`. + + """ if not force and hasattr(self,'version'): return self.version self.find_executables() @@ -294,6 +462,19 @@ def matcher(version_string): replace_method(CCompiler, 'get_version', CCompiler_get_version) def CCompiler_cxx_compiler(self): + """ + Return the C++ compiler. + + Parameters + ---------- + None + + Returns + ------- + cxx : class instance + The C++ compiler, as a `CCompiler` instance. + + """ if self.compiler_type=='msvc': return self cxx = copy(self) cxx.compiler_so = [cxx.compiler_cxx[0]] + cxx.compiler_so[1:] diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index a9b6a7ace7ea..7653f04c1820 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -26,6 +26,27 @@ 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info'] class InstallableLib: + """ + Container to hold information on an installable library. + + Parameters + ---------- + name : str + Name of the installed library. + build_info : dict + Dictionary holding build information. + target_dir : str + Absolute path specifying where to install the library. + + See Also + -------- + Configuration.add_installed_library + + Notes + ----- + The three parameters are stored as attributes with the same names. + + """ def __init__(self, name, build_info, target_dir): self.name = name self.build_info = build_info @@ -591,6 +612,34 @@ def get_frame(level=0): return frame class SconsInfo(object): + """ + Container object holding build info for building a package with scons. + + Parameters + ---------- + scons_path : str or None + Path to scons script, relative to the directory of setup.py. + If None, no scons script is specified. This can be useful to add only + pre- and post-hooks to a configuration. + parent_name : str or None + Name of the parent package (for example "numpy"). + pre_hook : sequence of callables or None + Callables that are executed before scons is invoked. + Each callable should be defined as ``callable(*args, **kw)``. + post_hook : sequence of callables or None + Callables that are executed after scons is invoked. + Each callable should be defined as ``callable(*args, **kw)``. + source_files : list of str or None + List of paths to source files, relative to the directory of setup.py. + pkg_path : str or None + Path to the package for which the `SconsInfo` instance holds the + build info, relative to the directory of setup.py. + + Notes + ----- + All parameters are available as attributes of a `SconsInfo` instance. + + """ def __init__(self, scons_path, parent_name, pre_hook, post_hook, source_files, pkg_path): self.scons_path = scons_path @@ -1375,21 +1424,22 @@ def add_extension(self,name,sources,**kw): return ext def add_library(self,name,sources,**build_info): - """Add library to configuration. + """ + Add library to configuration. Parameters ---------- - name: str - name of the extension - sources: seq - list of the sources. The list of sources may contain functions + name : str + Name of the extension. + sources : sequence + List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. - build_info: dict + build_info : dict, optional The following keys are allowed: * depends @@ -1398,6 +1448,7 @@ def add_library(self,name,sources,**build_info): * extra_compiler_args * f2py_options * language + """ self._add_library(name, sources, None, build_info) @@ -1424,33 +1475,46 @@ def _add_library(self, name, sources, install_dir, build_info): self.libraries.append((name, build_info)) def add_installed_library(self, name, sources, install_dir, build_info=None): - """Similar to add_library, but the corresponding library is installed. + """ + Similar to add_library, but the specified library is installed. - Most C libraries are only used to build python extensions, but - libraries built through this method will be installed so that they can - be reused by third-party. install_dir is relative to the current - subpackage. + Most C libraries used with `distutils` are only used to build python + extensions, but libraries built through this method will be installed + so that they can be reused by third-party packages. Parameters ---------- - name: str - name of the installed library - sources: seq - list of source files of the library - install_dir: str - path where to install the library (relatively to the current - sub-package) + name : str + Name of the installed library. + sources : sequence + List of the library's source files. See `add_library` for details. + install_dir : str + Path to install the library, relative to the current sub-package. + build_info : dict, optional + The following keys are allowed: - See also + * depends + * macros + * include_dirs + * extra_compiler_args + * f2py_options + * language + + Returns + ------- + None + + See Also -------- add_library, add_npy_pkg_config, get_info Notes ----- - The best way to encode the necessary options to link against those C - libraries is to use a libname.ini file, and use get_info to retrieve - those informations (see add_npy_pkg_config method for more + The best way to encode the options required to link against the specified + C libraries is to use a "libname.ini" file, and use `get_info` to + retrieve the required options (see `add_npy_pkg_config` for more information). + """ if not build_info: build_info = {} @@ -1460,20 +1524,23 @@ def add_installed_library(self, name, sources, install_dir, build_info=None): self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) def add_npy_pkg_config(self, template, install_dir, subst_dict=None): - """Generate a npy-pkg config file from the template, and install it in - given install directory, using subst_dict for variable substitution. + """ + Generate and install a npy-pkg config file from a template. + + The config file generated from `template` is installed in the + given install directory, using `subst_dict` for variable substitution. Parameters ---------- - template: str - the path of the template, relatively to the current package path - install_dir: str - where to install the npy-pkg config file, relatively to the current - package path - subst_dict: dict (None by default) - if given, any string of the form @key@ will be replaced by - subst_dict[key] in the template file when installed. The install - prefix is always available through the variable @prefix@, since the + template : str + The path of the template, relatively to the current package path. + install_dir : str + Where to install the npy-pkg config file, relatively to the current + package path. + subst_dict : dict, optional + If given, any string of the form ``@key@`` will be replaced by + ``subst_dict[key]`` in the template file when installed. The install + prefix is always available through the variable ``@prefix@``, since the install prefix is not easy to get reliably from setup.py. See also @@ -1483,11 +1550,13 @@ def add_npy_pkg_config(self, template, install_dir, subst_dict=None): Notes ----- This works for both standard installs and in-place builds, i.e. the - @prefix@ refer to the source directory for in-place builds. + ``@prefix@`` refer to the source directory for in-place builds. Examples -------- - config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) + :: + + config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) Assuming the foo.ini.in file has the following content:: @@ -1512,6 +1581,7 @@ def add_npy_pkg_config(self, template, install_dir, subst_dict=None): Libs= and will be installed as foo.ini in the 'lib' subpath. + """ if subst_dict is None: subst_dict = {} @@ -1526,7 +1596,16 @@ def add_npy_pkg_config(self, template, install_dir, subst_dict=None): subst_dict)] def add_scons_installed_library(self, name, install_dir): - """Add an scons-built installable library to distutils. + """ + Add a scons-built installable library to distutils. + + Parameters + ---------- + name : str + The name of the library. + install_dir : str + Path to install the library, relative to the current sub-package. + """ install_dir = os.path.join(self.package_path, install_dir) self.installed_libraries.append(InstallableLib(name, {}, install_dir)) @@ -1901,27 +1980,34 @@ def get_npy_pkg_dir(): return d def get_pkg_info(pkgname, dirs=None): - """Given a clib package name, returns a info dict with the necessary - options to use the clib. + """ + Return library info for the given package. Parameters ---------- - pkgname: str - name of the package (should match the name of the .ini file, without - the extension, e.g. foo for the file foo.ini) - dirs: seq {None} - if given, should be a sequence of additional directories where to look - for npy-pkg-config files. Those directories are search prior to the - numpy one. - - Note - ---- - Raise a numpy.distutils.PkgNotFound exception if the package is not - found. + pkgname : str + Name of the package (should match the name of the .ini file, without + the extension, e.g. foo for the file foo.ini). + dirs : sequence, optional + If given, should be a sequence of additional directories where to look + for npy-pkg-config files. Those directories are searched prior to the + NumPy directory. + + Returns + ------- + pkginfo : class instance + The `LibraryInfo` instance containing the build information. + + Raises + ------ + PkgNotFound + If the package is not found. See Also -------- - add_npy_pkg_info, add_installed_library, get_info + Configuration.add_npy_pkg_config, Configuration.add_installed_library, + get_info + """ from numpy.distutils.npy_pkg_config import read_config @@ -1932,34 +2018,49 @@ def get_pkg_info(pkgname, dirs=None): return read_config(pkgname, dirs) def get_info(pkgname, dirs=None): - """Given a clib package name, returns a info dict with the necessary - options to use the clib. + """ + Return an info dict for a given C library. + + The info dict contains the necessary options to use the C library. Parameters ---------- - pkgname: str - name of the package (should match the name of the .ini file, without - the extension, e.g. foo for the file foo.ini) - dirs: seq {None} - if given, should be a sequence of additional directories where to look - for npy-pkg-config files. Those directories are search prior to the - numpy one. - - Note - ---- - Raise a numpy.distutils.PkgNotFound exception if the package is not - found. + pkgname : str + Name of the package (should match the name of the .ini file, without + the extension, e.g. foo for the file foo.ini). + dirs : sequence, optional + If given, should be a sequence of additional directories where to look + for npy-pkg-config files. Those directories are searched prior to the + NumPy directory. + + Returns + ------- + info : dict + The dictionary with build information. + + Raises + ------ + PkgNotFound + If the package is not found. See Also -------- - add_npy_pkg_info, add_installed_library, get_pkg_info + Configuration.add_npy_pkg_config, Configuration.add_installed_library, + get_pkg_info - Example - ------- - To get the necessary informations for the npymath library from NumPy: + Examples + -------- + To get the necessary information for the npymath library from NumPy: + + >>> npymath_info = np.distutils.misc_util.get_info('npymath') + >>> npymath_info + {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': + ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} + + This info dict can then be used as input to a `Configuration` instance:: + + config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) - >>> npymath_info = get_info('npymath') - >>> config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) """ from numpy.distutils.npy_pkg_config import parse_flags pkg_info = get_pkg_info(pkgname, dirs) diff --git a/numpy/distutils/npy_pkg_config.py b/numpy/distutils/npy_pkg_config.py index 75bc971854e0..c8421d651001 100644 --- a/numpy/distutils/npy_pkg_config.py +++ b/numpy/distutils/npy_pkg_config.py @@ -9,6 +9,10 @@ _VAR = re.compile('\$\{([a-zA-Z0-9_-]+)\}') class FormatError(IOError): + """ + Exception thrown when there is a problem parsing a configuration file. + + """ def __init__(self, msg): self.msg = msg @@ -16,6 +20,7 @@ def __str__(self): return self.msg class PkgNotFound(IOError): + """Exception raised when a package can not be located.""" def __init__(self, msg): self.msg = msg @@ -23,6 +28,27 @@ def __str__(self): return self.msg def parse_flags(line): + """ + Parse a line from a config file containing compile flags. + + Parameters + ---------- + line : str + A single line containing one or more compile flags. + + Returns + ------- + d : dict + Dictionary of parsed flags, split into relevant categories. + These categories are the keys of `d`: + + * 'include_dirs' + * 'library_dirs' + * 'libraries' + * 'macros' + * 'ignored' + + """ lexer = shlex.shlex(line) lexer.whitespace_split = True @@ -59,6 +85,32 @@ def _escape_backslash(val): return val.replace('\\', '\\\\') class LibraryInfo(object): + """ + Object containing build information about a library. + + Parameters + ---------- + name : str + The library name. + description : str + Description of the library. + version : str + Version string. + sections : dict + The sections of the configuration file for the library. The keys are + the section headers, the values the text under each header. + vars : class instance + A `VariableSet` instance, which contains ``(name, value)`` pairs for + variables defined in the configuration file for the library. + requires : sequence, optional + The required libraries for the library to be installed. + + Notes + ----- + All input parameters (except "sections" which is a method) are available as + attributes of the same name. + + """ def __init__(self, name, description, version, sections, vars, requires=None): self.name = name self.description = description @@ -71,6 +123,19 @@ def __init__(self, name, description, version, sections, vars, requires=None): self.vars = vars def sections(self): + """ + Return the section headers of the config file. + + Parameters + ---------- + None + + Returns + ------- + keys : list of str + The list of section headers. + + """ return self._sections.keys() def cflags(self, section="default"): @@ -93,6 +158,18 @@ def __str__(self): return "\n".join(m) class VariableSet(object): + """ + Container object for the variables defined in a config file. + + `VariableSet` can be used as a plain dictionary, with the variable names + as keys. + + Parameters + ---------- + d : dict + Dict of items in the "variables" section of the configuration file. + + """ def __init__(self, d): self._raw_data = dict([(k, v) for k, v in d.items()]) @@ -125,6 +202,19 @@ def _interpolate(value): return value def variables(self): + """ + Return the list of variable names. + + Parameters + ---------- + None + + Returns + ------- + names : list of str + The names of all variables in the `VariableSet` instance. + + """ return self._raw_data.keys() # Emulate a dict to set/get variables values diff --git a/numpy/distutils/unixccompiler.py b/numpy/distutils/unixccompiler.py index 416bffc82b63..f3a4b7cbdd96 100644 --- a/numpy/distutils/unixccompiler.py +++ b/numpy/distutils/unixccompiler.py @@ -12,6 +12,7 @@ # Note that UnixCCompiler._compile appeared in Python 2.3 def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + """Compile a single source files with a Unix-style compiler.""" display = '%s: %s' % (os.path.basename(self.compiler_so[0]),src) try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + @@ -24,6 +25,29 @@ def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts def UnixCCompiler_create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None): + """ + Build a static library in a separate sub-process. + + Parameters + ---------- + objects : list or tuple of str + List of paths to object files used to build the static library. + output_libname : str + The library name as an absolute or relative (if `output_dir` is used) + path. + output_dir : str, optional + The path to the output directory. Default is None, in which case + the ``output_dir`` attribute of the UnixCCompiler instance. + debug : bool, optional + This parameter is not used. + target_lang : str, optional + This parameter is not used. + + Returns + ------- + None + + """ objects, output_dir = self._fix_object_args(objects, output_dir) output_filename = \ diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index d74307f5e3fa..a6397791264c 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -458,30 +458,34 @@ def hfft(a, n=None, axis=-1): def ihfft(a, n=None, axis=-1): """ - Compute the inverse fft of a signal whose spectrum has Hermitian symmetry. + Compute the inverse FFT of a signal whose spectrum has Hermitian symmetry. Parameters ---------- a : array_like Input array. n : int, optional - Length of the ihfft. + Length of the inverse FFT. axis : int, optional - Axis over which to compute the ihfft. + Axis over which to compute the inverse FFT, assuming Hermitian + symmetry of the spectrum. Default is the last axis. + + Returns + ------- + out : ndarray + The transformed input. See also -------- - rfft, hfft + hfft, irfft Notes ----- - These are a pair analogous to rfft/irfft, but for the + `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the opposite case: here the signal is real in the frequency domain and has - Hermite symmetry in the time domain. So here it's hermite_fft for which - you must supply the length of the result if it is to be odd. - - ihfft(hfft(a), len(a)) == a - within numerical accuracy. + Hermite symmetry in the time domain. So here it's `hfft` for which + you must supply the length of the result if it is to be odd: + ``ihfft(hfft(a), len(a)) == a``, within numerical accuracy. """ diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index 4bfbf0ac4d26..957e7cb1827a 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -176,12 +176,11 @@ class DataSource (object): Examples -------- - :: >>> ds = DataSource('/home/guido') >>> urlname = 'http://www.google.com/index.html' - >>> gfile = ds.open('http://www.google.com/index.html') # open remote file + >>> gfile = ds.open('http://www.google.com/index.html') # remote file >>> ds.abspath(urlname) '/home/guido/www.google.com/site/index.html' diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py index c69bd84dcd92..2c062f1b02ca 100644 --- a/numpy/lib/_iotools.py +++ b/numpy/lib/_iotools.py @@ -391,12 +391,29 @@ def str2bool(value): class ConverterError(Exception): + """ + Exception raised when an error occurs in a converter for string values. + + """ pass class ConverterLockError(ConverterError): + """ + Exception raised when an attempt is made to upgrade a locked converter. + + """ pass class ConversionWarning(UserWarning): + """ + Warning issued when a string converter has a problem. + + Notes + ----- + In `genfromtxt` a `ConversionWarning` is issued if raising exceptions + is explicitly suppressed with the "invalid_raise" keyword. + + """ pass @@ -708,22 +725,23 @@ def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): """ Convenience function to create a `np.dtype` object. - The function processes the input dtype and matches it with the given names. + The function processes the input `dtype` and matches it with the given + names. Parameters ---------- ndtype : var - Definition of the dtype. Can be any string or dictionary recognized - by the `np.dtype` function or a sequence of types. + Definition of the dtype. Can be any string or dictionary + recognized by the `np.dtype` function, or a sequence of types. names : str or sequence, optional Sequence of strings to use as field names for a structured dtype. For convenience, `names` can be a string of a comma-separated list of - names + names. defaultfmt : str, optional - Format string used to define missing names, such as "f%i" (default), - "fields_%02i"... + Format string used to define missing names, such as ``"f%i"`` + (default) or ``"fields_%02i"``. validationargs : optional - A series of optional arguments used to initialize a NameValidator. + A series of optional arguments used to initialize a `NameValidator`. Examples -------- @@ -733,10 +751,12 @@ def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs): dtype([('f0', '>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i") dtype([('field_000', '>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c") dtype([('a', '>> np.lib._iotools.easy_dtype(float, names="a,b,c") dtype([('a', ' 0 and -pi < t <= pi. The principal square root is then - sqrt(r) e^(i t/2). + See Also + -------- + numpy.sqrt Examples -------- - - For real, non-negative inputs this works just like numpy.sqrt(): + For real, non-negative inputs this works just like `numpy.sqrt`: >>> np.lib.scimath.sqrt(1) 1.0 - - >>> np.lib.scimath.sqrt([1,4]) + >>> np.lib.scimath.sqrt([1, 4]) array([ 1., 2.]) But it automatically handles negative inputs: >>> np.lib.scimath.sqrt(-1) (0.0+1.0j) - >>> np.lib.scimath.sqrt([-1,4]) array([ 0.+1.j, 2.+0.j]) @@ -227,14 +218,14 @@ def log(x): Parameters ---------- - x : array_like or scalar + x : array_like The value(s) whose log is (are) required. Returns ------- out : ndarray or scalar The log of the `x` value(s). If `x` was a scalar, so is `out`, - otherwise an array object is returned. + otherwise an array is returned. See Also -------- @@ -252,8 +243,8 @@ def log(x): >>> np.emath.log(np.exp(1)) 1.0 - Negative arguments are handled "correctly" (recall that `exp(log(x)) == x` - does *not* hold for real `x < 0`): + Negative arguments are handled "correctly" (recall that + ``exp(log(x)) == x`` does *not* hold for real ``x < 0``): >>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j) True @@ -314,28 +305,29 @@ def logn(n, x): """ Take log base n of x. - If x contains negative inputs, the answer is computed and returned in the + If `x` contains negative inputs, the answer is computed and returned in the complex domain. Parameters ---------- + n : int + The base in which the log is taken. x : array_like + The value(s) whose log base `n` is (are) required. Returns ------- - out : array_like + out : ndarray or scalar + The log base `n` of the `x` value(s). If `x` was a scalar, so is + `out`, otherwise an array is returned. Examples -------- - - (We set the printing precision so the example can be auto-tested) - >>> np.set_printoptions(precision=4) - >>> np.lib.scimath.logn(2,[4,8]) + >>> np.lib.scimath.logn(2, [4, 8]) array([ 2., 3.]) - - >>> np.lib.scimath.logn(2,[-4,-8,8]) + >>> np.lib.scimath.logn(2, [-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ @@ -354,14 +346,14 @@ def log2(x): Parameters ---------- - x : array_like or scalar + x : array_like The value(s) whose log base 2 is (are) required. Returns ------- out : ndarray or scalar The log base 2 of the `x` value(s). If `x` was a scalar, so is `out`, - otherwise an array object is returned. + otherwise an array is returned. See Also -------- @@ -376,14 +368,12 @@ def log2(x): Examples -------- - - (We set the printing precision so the example can be auto-tested) + We set the printing precision so the example can be auto-tested: >>> np.set_printoptions(precision=4) >>> np.emath.log2(8) 3.0 - >>> np.emath.log2([-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) @@ -393,34 +383,40 @@ def log2(x): def power(x, p): """ - Return x**p. - - If x contains negative values, it is converted to the complex domain. + Return x to the power p, (x**p). - If p contains negative values, it is converted to floating point. + If `x` contains negative values, the output is converted to the + complex domain. Parameters ---------- x : array_like - p : array_like of integers + The input value(s). + p : array_like of ints + The power(s) to which `x` is raised. If `x` contains multiple values, + `p` has to either be a scalar, or contain the same number of values + as `x`. In the latter case, the result is + ``x[0]**p[0], x[1]**p[1], ...``. Returns ------- - out : array_like + out : ndarray or scalar + The result of ``x**p``. If `x` and `p` are scalars, so is `out`, + otherwise an array is returned. - Examples + See Also -------- - (We set the printing precision so the example can be auto-tested) + numpy.power + Examples + -------- >>> np.set_printoptions(precision=4) - >>> np.lib.scimath.power([2,4],2) + >>> np.lib.scimath.power([2, 4], 2) array([ 4, 16]) - - >>> np.lib.scimath.power([2,4],-2) + >>> np.lib.scimath.power([2, 4], -2) array([ 0.25 , 0.0625]) - - >>> np.lib.scimath.power([-2,4],2) + >>> np.lib.scimath.power([-2, 4], 2) array([ 4.+0.j, 16.+0.j]) """ @@ -527,14 +523,14 @@ def arctanh(x): Parameters ---------- - x : array_like or scalar + x : array_like The value(s) whose arctanh is (are) required. Returns ------- out : ndarray or scalar The inverse hyperbolic tangent(s) of the `x` value(s). If `x` was - a scalar so is `out`, otherwise an array object is returned. + a scalar so is `out`, otherwise an array is returned. See Also @@ -551,10 +547,9 @@ def arctanh(x): -------- >>> np.set_printoptions(precision=4) - >>> np.emath.arctanh(np.matrix(np.eye(2))) # Note: an array is returned + >>> np.emath.arctanh(np.matrix(np.eye(2))) array([[ Inf, 0.], [ 0., Inf]]) - >>> np.emath.arctanh([1j]) array([ 0.+0.7854j]) diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index e030abf4fc19..43d6ede1fb46 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -96,9 +96,14 @@ def _set_function_name(func, name): return func class _Deprecate(object): - """Decorator class to deprecate old functions. + """ + Decorator class to deprecate old functions. + + Refer to `deprecate` for details. - Refer to ``decorate``. + See Also + -------- + deprecate """ def __init__(self, old_name=None, new_name=None, message=None): diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index 0b7aa132ec8e..ce319c17afad 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -231,12 +231,13 @@ def solve(a, b): ---------- a : array_like, shape (M, M) Coefficient matrix. - b : array_like, shape (M,) + b : array_like, shape (M,) or (M, N) Ordinate or "dependent variable" values. Returns ------- - x : ndarray, shape (M,) + x : ndarray, shape (M,) or (M, N) depending on b + Solution to the system a x = b Raises ------ @@ -531,27 +532,28 @@ def qr(a, mode='full'): Returns ------- - mode = 'full' - q : double or complex array, shape (M, K) + * If mode = 'full': - r : double or complex array, shape (K, N) + * q : ndarray of float or complex, shape (M, K) + * r : ndarray of float or complex, shape (K, N) - Size K = min(M, N) + Size K = min(M, N) - mode = 'r' - r : double or complex array, shape (K, N) + * If mode = 'r': - mode = 'economic' - a2 : double or complex array, shape (M, N) + * r : ndarray of float or complex, shape (K, N) - The diagonal and the upper triangle of a2 contains r, - while the rest of the matrix is undefined. + * If mode = 'economic': - If `a` is a matrix, so are all the return values. + * a2 : ndarray of float or complex, shape (M, N) + + The diagonal and the upper triangle of a2 contains r, + while the rest of the matrix is undefined. Raises ------ - LinAlgError : if factoring fails + LinAlgError + If factoring fails. Notes ----- @@ -561,16 +563,18 @@ def qr(a, mode='full'): For more information on the qr factorization, see for example: http://en.wikipedia.org/wiki/QR_factorization + Subclasses of `ndarray` are preserved, so if `a` is of type `matrix`, + all the return values will be matrices too. Examples -------- >>> a = np.random.randn(9, 6) >>> q, r = np.linalg.qr(a) - >>> np.allclose(a, np.dot(q, r)) # a does equal qr + >>> np.allclose(a, np.dot(q, r)) # a does equal qr True >>> r2 = np.linalg.qr(a, mode='r') >>> r3 = np.linalg.qr(a, mode='economic') - >>> np.allclose(r, r2) # mode='r' returns the same r as mode='full' + >>> np.allclose(r, r2) # mode='r' returns the same r as mode='full' True >>> # But only triu parts are guaranteed equal when mode='economic' >>> np.allclose(r, np.triu(r3[:6,:6], k=0)) @@ -582,11 +586,11 @@ def qr(a, mode='full'): What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points and you'll see that it should be y0 = 0, m = 1.) The answer is provided - by solving the over-determined matrix equation ``Ax = b``, where: + by solving the over-determined matrix equation ``Ax = b``, where:: A = array([[0, 1], [1, 1], [1, 1], [2, 1]]) - - x = array([[y0], [m]]) b = array([[1], [0], [2], [1]]) + x = array([[y0], [m]]) + b = array([[1], [0], [2], [1]]) If A = qr such that q is orthonormal (which is always possible via Gram-Schmidt), then ``x = inv(r) * (q.T) * b``. (In numpy practice, diff --git a/numpy/ma/core.py b/numpy/ma/core.py index cba3191e612b..688e57ade564 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -1431,13 +1431,13 @@ def make_mask(m, copy=False, shrink=True, flag=None, dtype=MaskType): ---------- m : array_like Potential mask. - copy : bool + copy : bool, optional Whether to return a copy of `m` (True) or `m` itself (False). - shrink : bool + shrink : bool, optional Whether to shrink `m` to ``nomask`` if all its values are False. - flag : bool + flag : bool, optional Deprecated equivalent of `shrink`. - dtype : dtype + dtype : dtype, optional Data-type of the output mask. By default, the output mask has a dtype of MaskType (bool). If the dtype is flexible, each field has a boolean dtype. @@ -1639,21 +1639,23 @@ def flatten_mask(mask): Parameters ---------- mask : array_like - Array of booleans + Input array, which will be interpreted as booleans. Returns ------- - flattened_mask : ndarray - Boolean array. + flattened_mask : ndarray of bools + The flattened input. Examples -------- >>> mask = np.array([0, 0, 1], dtype=np.bool) >>> flatten_mask(mask) array([False, False, True], dtype=bool) + >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)]) >>> flatten_mask(mask) array([False, False, False, True], dtype=bool) + >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])] >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype) >>> flatten_mask(mask) @@ -3134,14 +3136,30 @@ def _set_recordmask(self): #............................................ def harden_mask(self): - """Force the mask to hard. + """ + Force the mask to hard. + + Whether the mask of a masked array is hard or soft is determined by + its `hardmask` property. `harden_mask` sets `hardmask` to True. + + See Also + -------- + hardmask """ self._hardmask = True return self def soften_mask(self): - """Force the mask to soft. + """ + Force the mask to soft. + + Whether the mask of a masked array is hard or soft is determined by + its `hardmask` property. `soften_mask` sets `hardmask` to False. + + See Also + -------- + hardmask """ self._hardmask = False @@ -3152,7 +3170,16 @@ def soften_mask(self): def unshare_mask(self): - """Copy the mask and set the sharedmask flag to False. + """ + Copy the mask and set the sharedmask flag to False. + + Whether the mask is shared between masked arrays can be seen from + the `sharedmask` property. `unshare_mask` ensures the mask is not shared. + A copy of the mask is only made if it was shared. + + See Also + -------- + sharedmask """ if self._sharedmask: @@ -3164,7 +3191,26 @@ def unshare_mask(self): doc="Share status of the mask (read-only).") def shrink_mask(self): - """Reduce a mask to nomask when possible. + """ + Reduce a mask to nomask when possible. + + Parameters + ---------- + None + + Returns + ------- + None + + Examples + -------- + >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4) + >>> x.mask + array([[False, False], + [False, False]], dtype=bool) + >>> x.shrink_mask() + >>> x.mask + False """ m = self._mask diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index 0f0d504c5b9c..5804cf3c11b9 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -1473,6 +1473,12 @@ class mr_class(MAxisConcatenator): """ Translate slice objects to concatenation along the first axis. + This is the masked array version of `lib.index_tricks.RClass`. + + See Also + -------- + lib.index_tricks.RClass + Examples -------- >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])] @@ -1490,8 +1496,44 @@ def __init__(self): def flatnotmasked_edges(a): """ - Find the indices of the first and last valid values in a 1D masked array. - If all values are masked, returns None. + Find the indices of the first and last unmasked values. + + Expects a 1-D `MaskedArray`, returns None if all values are masked. + + Parameters + ---------- + arr : array_like + Input 1-D `MaskedArray` + + Returns + ------- + edges : ndarray or None + The indices of first and last non-masked value in the array. + Returns None if all values are masked. + + See Also + -------- + flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges + + Notes + ----- + Only accepts 1-D arrays. + + Examples + -------- + >>> a = np.arange(10) + >>> mask = (a < 3) | (a > 8) | (a == 5) + + >>> ma = np.ma.array(a, mask=m) + >>> np.array(ma[~ma.mask]) + array([3, 4, 6, 7, 8]) + + >>> flatnotmasked_edges(ma) + array([3, 8]) + + >>> ma = np.ma.array(a, mask=np.ones_like(a)) + >>> print flatnotmasked_edges(ma) + None """ m = getmask(a) @@ -1506,18 +1548,43 @@ def flatnotmasked_edges(a): def notmasked_edges(a, axis=None): """ - Find the indices of the first and last not masked values along - the given axis in a masked array. + Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list - of 2 tuples, corresponding to the indices of the first and last + of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- + a : array_like + The input array. axis : int, optional Axis along which to perform the operation. - If None, applies to a flattened version of the array. + If None (default), applies to a flattened version of the array. + + Returns + ------- + edges : ndarray or list + An array of start and end indexes if there are any masked data in + the array. If there are no masked data in the array, `edges` is a + list of the first and last index. + + See Also + -------- + flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous + + Examples + -------- + >>> a = np.arange(9).reshape((3, 3)) + >>> m = np.zeros_like(a) + >>> m[1:, 1:] = 1 + + >>> ma = np.ma.array(a, mask=m) + >>> np.array(ma[~ma.mask]) + array([0, 1, 2, 3, 6]) + + >>> np.ma.extras.notmasked_edges(ma) + array([0, 6]) """ a = asarray(a) @@ -1531,9 +1598,39 @@ def notmasked_edges(a, axis=None): def flatnotmasked_contiguous(a): """ - Find contiguous unmasked data in a flattened masked array. + Find contiguous unmasked data in a masked array along the given axis. - Return a sorted sequence of slices (start index, end index). + Parameters + ---------- + a : narray + The input array. + + Returns + ------- + slice_list : list + A sorted sequence of slices (start index, end index). + + See Also + -------- + flatnotmasked_edges, notmasked_contiguous, notmasked_edges + + Notes + ----- + Only accepts 2-D arrays at most. + + Examples + -------- + >>> a = np.arange(10) + >>> mask = (a < 3) | (a > 8) | (a == 5) + >>> ma = np.ma.array(a, mask=mask) + >>> np.array(ma[~ma.mask]) + array([3, 4, 6, 7, 8]) + + >>> np.ma.extras.flatnotmasked_contiguous(ma) + [slice(3, 4, None), slice(6, 8, None)] + >>> ma = np.ma.array(a, mask=np.ones_like(a)) + >>> print np.ma.extras.flatnotmasked_edges(ma) + None """ m = getmask(a) @@ -1556,17 +1653,38 @@ def notmasked_contiguous(a, axis=None): Parameters ---------- + a : array_like + The input array. axis : int, optional Axis along which to perform the operation. - If None, applies to a flattened version of the array. + If None (default), applies to a flattened version of the array. Returns ------- - A sorted sequence of slices (start index, end index). + endpoints : list + A list of slices (start and end indexes) of unmasked indexes + in the array. + + See Also + -------- + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges Notes ----- - Only accepts 2D arrays at most. + Only accepts 2-D arrays at most. + + Examples + -------- + >>> a = np.arange(9).reshape((3, 3)) + >>> mask = np.zeros_like(a) + >>> mask[1:, 1:] = 1 + + >>> ma = np.ma.array(a, mask=mask) + >>> np.array(ma[~ma.mask]) + array([0, 1, 2, 3, 6]) + + >>> np.ma.extras.notmasked_contiguous(ma) + [slice(0, 3, None), slice(6, 6, None)] """ a = asarray(a) @@ -1607,16 +1725,30 @@ def _ezclump(mask): def clump_unmasked(a): """ - Returns a list of slices corresponding to the unmasked clumps of a 1D array. + Return list of slices corresponding to the unmasked clumps of a 1-D array. + + Parameters + ---------- + a : ndarray + A one-dimensional masked array. + + Returns + ------- + slices : list of slice + The list of slices, one for each continuous region of unmasked + elements in `a`. + + Notes + ----- + .. versionadded:: 1.4.0 Examples -------- - >>> a = ma.masked_array(np.arange(10)) - >>> a[[0, 1, 2, 6, 8, 9]] = ma.masked - >>> clump_unmasked(a) + >>> a = np.ma.masked_array(np.arange(10)) + >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked + >>> np.ma.extras.clump_unmasked(a) [slice(3, 6, None), slice(7, 8, None)] - .. versionadded:: 1.4.0 """ mask = getattr(a, '_mask', nomask) if mask is nomask: @@ -1631,16 +1763,30 @@ def clump_unmasked(a): def clump_masked(a): """ - Returns a list of slices corresponding to the masked clumps of a 1D array. + Returns a list of slices corresponding to the masked clumps of a 1-D array. + + Parameters + ---------- + a : ndarray + A one-dimensional masked array. + + Returns + ------- + slices : list of slice + The list of slices, one for each continuous region of masked elements + in `a`. + + Notes + ----- + .. versionadded:: 1.4.0 Examples -------- - >>> a = ma.masked_array(np.arange(10)) - >>> a[[0, 1, 2, 6, 8, 9]] = ma.masked - >>> clump_masked(a) + >>> a = np.ma.masked_array(np.arange(10)) + >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked + >>> np.ma.extras.clump_masked(a) [slice(0, 3, None), slice(6, 7, None), slice(8, None, None)] - .. versionadded:: 1.4.0 """ mask = ma.getmask(a) if mask is nomask: diff --git a/numpy/matlib.py b/numpy/matlib.py index 286ac7364e3e..9e80dd475d5b 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -9,7 +9,40 @@ __all__ += ['rand', 'randn', 'repmat'] def empty(shape, dtype=None, order='C'): - """return an empty matrix of the given shape + """ + Return a new matrix of given shape and type, without initializing entries. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty matrix. + dtype : data-type, optional + Desired output data-type. + order : {'C', 'F'}, optional + Whether to store multi-dimensional data in C (row-major) or + Fortran (column-major) order in memory. + + See Also + -------- + empty_like, zeros + + Notes + ----- + `empty`, unlike `zeros`, does not set the matrix values to zero, + and may therefore be marginally faster. On the other hand, it requires + the user to manually set all the values in the array, and should be + used with caution. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.empty((2, 2)) # filled with random data + matrix([[ 6.76425276e-320, 9.79033856e-307], + [ 7.39337286e-309, 3.22135945e-309]]) + >>> np.matlib.empty((2, 2), dtype=int) + matrix([[ 6600475, 0], + [ 6586976, 22740995]]) + """ return ndarray.__new__(matrix, shape, dtype, order=order) @@ -60,16 +93,14 @@ def ones(shape, dtype=None, order='C'): def zeros(shape, dtype=None, order='C'): """ - Zero matrix. - - Return a matrix of given shape and type, filled with zeros + Return a matrix of given shape and type, filled with zeros. Parameters ---------- - shape : {sequence of ints, int} + shape : int or sequence of ints Shape of the matrix dtype : data-type, optional - The desired data-type for the matrix, default is np.float64. + The desired data-type for the matrix, default is float. order : {'C', 'F'}, optional Whether to store the result in C- or Fortran-contiguous order, default is 'C'. @@ -81,8 +112,8 @@ def zeros(shape, dtype=None, order='C'): See Also -------- - zeros : Zero array. - matlib.ones : Matrix of ones. + numpy.zeros : Equivalent array function. + matlib.ones : Return a matrix of ones. Notes ----- @@ -91,7 +122,8 @@ def zeros(shape, dtype=None, order='C'): Examples -------- - >>> np.matlib.zeros((2,3)) + >>> import numpy.matlib + >>> np.matlib.zeros((2, 3)) matrix([[ 0., 0., 0.], [ 0., 0., 0.]]) @@ -110,8 +142,7 @@ def identity(n,dtype=None): Parameters ---------- n : int - Size of identity matrix - + Size of the returned identity matrix. dtype : data-type, optional Data-type of the output. Defaults to ``float``. @@ -123,13 +154,16 @@ def identity(n,dtype=None): See Also -------- - identity : Equivalent array function. + numpy.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`` + Examples + -------- + >>> import numpy.matlib + >>> np.identity(3, dtype=int) + array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) """ a = array([1]+n*[0],dtype=dtype) @@ -146,7 +180,7 @@ def eye(n,M=None, k=0, dtype=float): n : int Number of rows in the output. M : int, optional - Number of columns in the output, defaults to n. + 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, @@ -158,33 +192,155 @@ def eye(n,M=None, k=0, dtype=float): ------- 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. + except for the `k`-th diagonal, whose values are equal to one. See Also -------- - eye : Equivalent array function - matlib.identity : Square identity matrix + numpy.eye : Equivalent array function. + identity : Square identity matrix. - Notes - ----- - For more detailed docuemtation, see the docstring of the equivalent - array function ``np.eye``. + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.eye(3, k=1, dtype=float) + matrix([[ 0., 1., 0.], + [ 0., 0., 1.], + [ 0., 0., 0.]]) """ return asmatrix(np.eye(n,M,k,dtype)) def rand(*args): + """ + Return a matrix of random values with given shape. + + Create a matrix of the given shape and propagate it with + random samples from a uniform distribution over ``[0, 1)``. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. + If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + out : ndarray + The matrix of random values with shape given by `\\*args`. + + See Also + -------- + randn, numpy.random.rand + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.rand(2, 3) + matrix([[ 0.68340382, 0.67926887, 0.83271405], + [ 0.00793551, 0.20468222, 0.95253525]]) + >>> np.matlib.rand((2, 3)) + matrix([[ 0.84682055, 0.73626594, 0.11308016], + [ 0.85429008, 0.3294825 , 0.89139555]]) + + If the first argument is a tuple, other arguments are ignored: + + >>> np.matlib.rand((2, 3), 4) + matrix([[ 0.46898646, 0.15163588, 0.95188261], + [ 0.59208621, 0.09561818, 0.00583606]]) + + """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.rand(*args)) def randn(*args): + """ + Return a random matrix with data from the "standard normal" distribution. + + `randn` generates a matrix filled with random floats sampled from a + univariate "normal" (Gaussian) distribution of mean 0 and variance 1. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + Z : matrix of floats + A matrix of floating-point samples drawn from the standard normal + distribution. + + See Also + -------- + rand, random.randn + + Notes + ----- + For random samples from :math:`N(\\mu, \\sigma^2)`, use: + + ``sigma * np.matlib.randn(...) + mu`` + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.randn(1) + matrix([[-0.09542833]]) + >>> np.matlib.randn(1, 2, 3) + matrix([[ 0.16198284, 0.0194571 , 0.18312985], + [-0.7509172 , 1.61055 , 0.45298599]]) + + Two-by-four matrix of samples from :math:`N(3, 6.25)`: + + >>> 2.5 * np.matlib.randn((2, 4)) + 3 + matrix([[ 4.74085004, 8.89381862, 4.09042411, 4.83721922], + [ 7.52373709, 5.07933944, -2.64043543, 0.45610557]]) + + """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.randn(*args)) def repmat(a, m, n): - """Repeat a 0-d to 2-d array mxn times + """ + Repeat a 0-D to 2-D array or matrix MxN times. + + Parameters + ---------- + a : array_like + The array or matrix to be repeated. + m, n : int + The number of times `a` is repeated along the first and second axes. + + Returns + ------- + out : ndarray + The result of repeating `a`. + + Examples + -------- + >>> import numpy.matlib + >>> a0 = np.array(1) + >>> np.matlib.repmat(a0, 2, 3) + array([[1, 1, 1], + [1, 1, 1]]) + + >>> a1 = np.arange(4) + >>> np.matlib.repmat(a1, 2, 2) + array([[0, 1, 2, 3, 0, 1, 2, 3], + [0, 1, 2, 3, 0, 1, 2, 3]]) + + >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3)) + >>> np.matlib.repmat(a2, 2, 3) + matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5], + [0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5]]) + """ a = asanyarray(a) ndim = a.ndim