From numpy-svn at scipy.org Sun Aug 1 07:03:49 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:03:49 -0500 (CDT) Subject: [Numpy-svn] r8573 - branches/1.5.x/numpy/core/tests Message-ID: <20100801110349.6E3F039CC70@scipy.org> Author: rgommers Date: 2010-08-01 06:03:49 -0500 (Sun, 01 Aug 2010) New Revision: 8573 Modified: branches/1.5.x/numpy/core/tests/test_getlimits.py Log: BUG: (backport of r8568) remove unnecessary import and reload in test_getlimits. This was causing errors when running the test suite. Modified: branches/1.5.x/numpy/core/tests/test_getlimits.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_getlimits.py 2010-07-31 13:48:52 UTC (rev 8572) +++ branches/1.5.x/numpy/core/tests/test_getlimits.py 2010-08-01 11:03:49 UTC (rev 8573) @@ -3,14 +3,6 @@ from numpy.testing import * -import numpy.lib -try: - reload(numpy.lib) -except NameError: - # Py3K - import imp - imp.reload(numpy.lib) - from numpy.core import finfo, iinfo from numpy import single,double,longdouble import numpy as np From numpy-svn at scipy.org Sun Aug 1 07:07:50 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:07:50 -0500 (CDT) Subject: [Numpy-svn] r8574 - trunk/numpy/core Message-ID: <20100801110750.91AA939CD6B@scipy.org> Author: rgommers Date: 2010-08-01 06:07:50 -0500 (Sun, 01 Aug 2010) New Revision: 8574 Modified: trunk/numpy/core/SConscript Log: BUG: Fix typo in commit r8564-66. Modified: trunk/numpy/core/SConscript =================================================================== --- trunk/numpy/core/SConscript 2010-08-01 11:03:49 UTC (rev 8573) +++ trunk/numpy/core/SConscript 2010-08-01 11:07:50 UTC (rev 8574) @@ -82,7 +82,7 @@ if st: numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '#define NPY_HAVE_ENDIAN_H 1')) else: - numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '')) + numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '')) def check_type(type, include = None): st = config.CheckTypeSize(type, includes = include) From numpy-svn at scipy.org Sun Aug 1 07:09:34 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:09:34 -0500 (CDT) Subject: [Numpy-svn] r8575 - branches/1.5.x/numpy/core Message-ID: <20100801110934.641F139CD6E@scipy.org> Author: rgommers Date: 2010-08-01 06:09:34 -0500 (Sun, 01 Aug 2010) New Revision: 8575 Modified: branches/1.5.x/numpy/core/SConscript Log: BUG: (backport of r8574) fix typo in commit r8564-66. Modified: branches/1.5.x/numpy/core/SConscript =================================================================== --- branches/1.5.x/numpy/core/SConscript 2010-08-01 11:07:50 UTC (rev 8574) +++ branches/1.5.x/numpy/core/SConscript 2010-08-01 11:09:34 UTC (rev 8575) @@ -82,7 +82,7 @@ if st: numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '#define NPY_HAVE_ENDIAN_H 1')) else: - numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '')) + numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '')) def check_type(type, include = None): st = config.CheckTypeSize(type, includes = include) From numpy-svn at scipy.org Sun Aug 1 07:10:35 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:10:35 -0500 (CDT) Subject: [Numpy-svn] r8576 - branches/1.4.x/numpy/core Message-ID: <20100801111035.EBE4539CDEC@scipy.org> Author: rgommers Date: 2010-08-01 06:10:35 -0500 (Sun, 01 Aug 2010) New Revision: 8576 Modified: branches/1.4.x/numpy/core/SConscript Log: BUG: (backport of r8574) fix typo in commit r8564-66. Modified: branches/1.4.x/numpy/core/SConscript =================================================================== --- branches/1.4.x/numpy/core/SConscript 2010-08-01 11:09:34 UTC (rev 8575) +++ branches/1.4.x/numpy/core/SConscript 2010-08-01 11:10:35 UTC (rev 8576) @@ -82,7 +82,7 @@ if st: numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '#define NPY_HAVE_ENDIAN_H 1')) else: - numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '')) + numpyconfig_sym.append(('DEFINE_NPY_HAVE_ENDIAN_H', '')) def check_type(type, include = None): st = config.CheckTypeSize(type, includes = include) From numpy-svn at scipy.org Sun Aug 1 07:19:44 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:19:44 -0500 (CDT) Subject: [Numpy-svn] r8577 - branches/1.5.x/numpy/distutils Message-ID: <20100801111944.C2EED39CDFE@scipy.org> Author: rgommers Date: 2010-08-01 06:19:44 -0500 (Sun, 01 Aug 2010) New Revision: 8577 Modified: branches/1.5.x/numpy/distutils/npy_pkg_config.py Log: DOC: wiki merge, add distutils.npy_pkg_config.read_config docstring. Modified: branches/1.5.x/numpy/distutils/npy_pkg_config.py =================================================================== --- branches/1.5.x/numpy/distutils/npy_pkg_config.py 2010-08-01 11:10:35 UTC (rev 8576) +++ branches/1.5.x/numpy/distutils/npy_pkg_config.py 2010-08-01 11:19:44 UTC (rev 8577) @@ -325,12 +325,12 @@ if not vars.has_key("pkgdir") and vars.has_key("pkgname"): pkgname = vars["pkgname"] if not pkgname in sys.modules: - raise ValueError("You should import %s to get information on %s" % + raise ValueError("You should import %s to get information on %s" % (pkgname, meta["name"])) mod = sys.modules[pkgname] vars["pkgdir"] = _escape_backslash(os.path.dirname(mod.__file__)) - + return LibraryInfo(name=meta["name"], description=meta["description"], version=meta["version"], sections=sections, vars=VariableSet(vars)) @@ -340,6 +340,44 @@ # problem in practice _CACHE = {} def read_config(pkgname, dirs=None): + """ + Return library info for a package from its configuration file. + + 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 : sequence, optional + If given, should be a sequence of directories - usually including + the NumPy base directory - where to look for npy-pkg-config files. + + Returns + ------- + pkginfo : class instance + The `LibraryInfo` instance containing the build information. + + Raises + ------ + PkgNotFound + If the package is not found. + + See Also + -------- + misc_util.get_info, misc_util.get_pkg_info + + Examples + -------- + >>> npymath_info = np.distutils.npy_pkg_config.read_config('npymath') + >>> type(npymath_info) + + >>> print npymath_info + Name: npymath + Description: Portable, core math library implementing C99 standard + Requires: + Version: 0.1 #random + + """ try: return _CACHE[pkgname] except KeyError: From numpy-svn at scipy.org Sun Aug 1 07:20:00 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:20:00 -0500 (CDT) Subject: [Numpy-svn] r8578 - branches/1.5.x/numpy Message-ID: <20100801112000.856E839CE05@scipy.org> Author: rgommers Date: 2010-08-01 06:20:00 -0500 (Sun, 01 Aug 2010) New Revision: 8578 Modified: branches/1.5.x/numpy/add_newdocs.py Log: DOC: wiki merge, add itemset method doc. Modified: branches/1.5.x/numpy/add_newdocs.py =================================================================== --- branches/1.5.x/numpy/add_newdocs.py 2010-08-01 11:19:44 UTC (rev 8577) +++ branches/1.5.x/numpy/add_newdocs.py 2010-08-01 11:20:00 UTC (rev 8578) @@ -2566,6 +2566,52 @@ """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('itemset', + """ + a.itemset(*args) + + Insert scalar into an array (scalar is cast to array's dtype, if possible) + + There must be at least 1 argument, and define the last argument + as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster + than ``a[args] = item``. The item should be a scalar value and `args` + must select a single item in the array `a`. + + Parameters + ---------- + \*args : Arguments + If one argument: a scalar, only used in case `a` is of size 1. + If two arguments: the last argument is the value to be set + and must be a scalar, the first argument specifies a single array + element location. It is either an int or a tuple. + + Notes + ----- + Compared to indexing syntax, `itemset` provides some speed increase + for placing a scalar into a particular location in an `ndarray`, + if you must do this. However, generally this is discouraged: + among other problems, it complicates the appearance of the code. + Also, when using `itemset` (and `item`) inside a loop, be sure + to assign the methods to a local variable to avoid the attribute + look-up at each loop iteration. + + Examples + -------- + >>> x = np.random.randint(9, size=(3, 3)) + >>> x + array([[3, 1, 7], + [2, 8, 3], + [8, 5, 3]]) + >>> x.itemset(4, 0) + >>> x.itemset((2, 2), 9) + >>> x + array([[3, 1, 7], + [2, 0, 3], + [8, 5, 9]]) + + """)) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('max', """ a.max(axis=None, out=None) @@ -3990,10 +4036,10 @@ add_newdoc('numpy.core', 'ufunc', ('identity', """ The identity value. - + Data attribute containing the identity element for the ufunc, if it has one. If it does not, the attribute value is None. - + Examples -------- >>> np.add.identity @@ -4009,15 +4055,15 @@ add_newdoc('numpy.core', 'ufunc', ('nargs', """ The number of arguments. - + Data attribute containing the number of arguments the ufunc takes, including optional ones. - + Notes ----- Typically this value will be one more than what you might expect because all ufuncs take the optional "out" argument. - + Examples -------- >>> np.add.nargs @@ -4033,9 +4079,9 @@ add_newdoc('numpy.core', 'ufunc', ('nin', """ The number of inputs. - + Data attribute containing the number of arguments the ufunc treats as input. - + Examples -------- >>> np.add.nin @@ -4051,13 +4097,13 @@ add_newdoc('numpy.core', 'ufunc', ('nout', """ The number of outputs. - + Data attribute containing the number of arguments the ufunc treats as output. - + Notes ----- Since all ufuncs can take output arguments, this will always be (at least) 1. - + Examples -------- >>> np.add.nout @@ -4074,14 +4120,14 @@ add_newdoc('numpy.core', 'ufunc', ('ntypes', """ The number of types. - + The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate. - + See Also -------- numpy.ufunc.types - + Examples -------- >>> np.add.ntypes From numpy-svn at scipy.org Sun Aug 1 07:20:19 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:20:19 -0500 (CDT) Subject: [Numpy-svn] r8579 - in branches/1.5.x/doc/source: reference user Message-ID: <20100801112019.D755039CE09@scipy.org> Author: rgommers Date: 2010-08-01 06:20:19 -0500 (Sun, 01 Aug 2010) New Revision: 8579 Modified: branches/1.5.x/doc/source/reference/arrays.dtypes.rst branches/1.5.x/doc/source/user/basics.byteswapping.rst branches/1.5.x/doc/source/user/index.rst branches/1.5.x/doc/source/user/install.rst Log: DOC: wiki merge, rst docs. Modified: branches/1.5.x/doc/source/reference/arrays.dtypes.rst =================================================================== --- branches/1.5.x/doc/source/reference/arrays.dtypes.rst 2010-08-01 11:20:00 UTC (rev 8578) +++ branches/1.5.x/doc/source/reference/arrays.dtypes.rst 2010-08-01 11:20:19 UTC (rev 8579) @@ -246,7 +246,7 @@ on the shape if it is greater than 1-d. NumPy allows a modification on the format in that any string that can uniquely identify the type can be used to specify the data-type in a field. - The generated data-type fields are named ``'f0'``, ``'f2'``, ..., + The generated data-type fields are named ``'f0'``, ``'f1'``, ..., ``'f'`` where N (>1) is the number of comma-separated basic formats in the string. If the optional shape specifier is provided, then the data-type for the corresponding field describes a sub-array. Modified: branches/1.5.x/doc/source/user/basics.byteswapping.rst =================================================================== --- branches/1.5.x/doc/source/user/basics.byteswapping.rst 2010-08-01 11:20:00 UTC (rev 8578) +++ branches/1.5.x/doc/source/user/basics.byteswapping.rst 2010-08-01 11:20:19 UTC (rev 8579) @@ -1,5 +1,5 @@ -************ -Broadcasting -************ +************* +Byte-swapping +************* .. automodule:: numpy.doc.byteswapping Modified: branches/1.5.x/doc/source/user/index.rst =================================================================== --- branches/1.5.x/doc/source/user/index.rst 2010-08-01 11:20:00 UTC (rev 8578) +++ branches/1.5.x/doc/source/user/index.rst 2010-08-01 11:20:19 UTC (rev 8579) @@ -13,12 +13,16 @@ This "User Guide" is still a work in progress; some of the material is not organized, and several aspects of NumPy are not yet covered - in sufficient detail. However, we are continually working to - improve the documentation. + sufficient detail. We are an open source community continually + working to improve the documentation and eagerly encourage interested + parties to contribute. For information on how to do so, please visit + the NumPy `doc wiki `_. More documentation for NumPy can be found on the `numpy.org `__ website. + Thanks! + .. toctree:: :maxdepth: 2 Modified: branches/1.5.x/doc/source/user/install.rst =================================================================== --- branches/1.5.x/doc/source/user/install.rst 2010-08-01 11:20:00 UTC (rev 8578) +++ branches/1.5.x/doc/source/user/install.rst 2010-08-01 11:20:19 UTC (rev 8579) @@ -15,11 +15,21 @@ `_ (which provides binary installers for Windows, OS X and Redhat) and `Python (x, y) `_. Both of these packages include Python, NumPy and -many additional packages. A lightweight alternative is to download the Python +many additional packages. + +A lightweight alternative is to download the Python installer from `www.python.org `_ and the NumPy installer for your Python version from the Sourceforge `download site `_ +The NumPy installer includes binaries for different CPU's (without SSE +instructions, with SSE2 or with SSE3) and installs the correct one +automatically. If needed, this can be bypassed from the command line with :: + + numpy-<1.y.z>-superpack-win32.exe /arch nosse + +or 'sse2' or 'sse3' instead of 'nosse'. + Linux ----- @@ -95,15 +105,15 @@ Choosing the fortran compiler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To build with g77: +To build with g77:: python setup.py build --fcompiler=gnu -To build with gfortran: +To build with gfortran:: python setup.py build --fcompiler=gnu95 -For more information see: +For more information see:: python setup.py build --help-fcompiler @@ -116,19 +126,27 @@ has been used. If both are dependencies, this means both have been used, which is almost always a very bad idea. +Disabling ATLAS and other accelerater libraries +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Usage of ATLAS and other accelerated libraries in Numpy can be disabled +via:: + + BLAS=None LAPACK=None ATLAS=None python setup.py build + Building with ATLAS support --------------------------- Ubuntu 8.10 (Intrepid) and 9.04 (Jaunty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can install the necessary packages for optimized ATLAS with this command: +You can install the necessary packages for optimized ATLAS with this command:: sudo apt-get install libatlas-base-dev If you have a recent CPU with SIMD suppport (SSE, SSE2, etc...), you should also install the corresponding package for optimal performances. For example, -for SSE2: +for SSE2:: sudo apt-get install libatlas3gf-sse2 @@ -142,12 +160,12 @@ Ubuntu 8.04 and lower ~~~~~~~~~~~~~~~~~~~~~ -You can install the necessary packages for optimized ATLAS with this command: +You can install the necessary packages for optimized ATLAS with this command:: sudo apt-get install atlas3-base-dev If you have a recent CPU with SIMD suppport (SSE, SSE2, etc...), you should also install the corresponding package for optimal performances. For example, -for SSE2: +for SSE2:: sudo apt-get install atlas3-sse2 From numpy-svn at scipy.org Sun Aug 1 07:20:36 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:20:36 -0500 (CDT) Subject: [Numpy-svn] r8580 - branches/1.5.x/numpy/core Message-ID: <20100801112036.05DE439CE0A@scipy.org> Author: rgommers Date: 2010-08-01 06:20:35 -0500 (Sun, 01 Aug 2010) New Revision: 8580 Modified: branches/1.5.x/numpy/core/fromnumeric.py Log: DOC: wiki merge, fromnumeric.py Modified: branches/1.5.x/numpy/core/fromnumeric.py =================================================================== --- branches/1.5.x/numpy/core/fromnumeric.py 2010-08-01 11:20:19 UTC (rev 8579) +++ branches/1.5.x/numpy/core/fromnumeric.py 2010-08-01 11:20:35 UTC (rev 8580) @@ -810,25 +810,25 @@ """ Return a new array with the specified shape. - If the new array is larger than the original array, then the new array - is filled with repeated copied of `a`. Note that this behavior is different - from a.resize(new_shape) which fills with zeros instead of repeated - copies of `a`. + If the new array is larger than the original array, then the new + array is filled with repeated copies of `a`. Note that this behavior + is different from a.resize(new_shape) which fills with zeros instead + of repeated copies of `a`. Parameters ---------- a : array_like Array to be resized. - new_shape : {tuple, int} + new_shape : int or tuple of int Shape of resized array. Returns ------- reshaped_array : ndarray The new array is formed from the data in the old array, repeated - if necessary to fill out the required number of elements. The data - are repeated in the order that the data are stored in memory. + if necessary to fill out the required number of elements. The + data are repeated in the order that they are stored in memory. See Also -------- @@ -903,33 +903,34 @@ Return specified diagonals. If `a` is 2-D, returns the diagonal of `a` with the given offset, - i.e., the collection of elements of the form `a[i,i+offset]`. - If `a` has more than two dimensions, then the axes specified - by `axis1` and `axis2` are used to determine the 2-D subarray - whose diagonal is returned. The shape of the resulting array - can be determined by removing `axis1` and `axis2` and appending - an index to the right equal to the size of the resulting diagonals. + i.e., the collection of elements of the form ``a[i, i+offset]``. If + `a` has more than two dimensions, then the axes specified by `axis1` + and `axis2` are used to determine the 2-D sub-array whose diagonal is + returned. The shape of the resulting array can be determined by + removing `axis1` and `axis2` and appending an index to the right equal + to the size of the resulting diagonals. Parameters ---------- a : array_like Array from which the diagonals are taken. offset : int, optional - Offset of the diagonal from the main diagonal. Can be both positive - and negative. Defaults to main diagonal (0). + Offset of the diagonal from the main diagonal. Can be positive or + negative. Defaults to main diagonal (0). axis1 : int, optional - Axis to be used as the first axis of the 2-D subarrays from which - the diagonals should be taken. Defaults to first axis (0). + Axis to be used as the first axis of the 2-D sub-arrays from which + the diagonals should be taken. Defaults to first axis (0). axis2 : int, optional - Axis to be used as the second axis of the 2-D subarrays from which - the diagonals should be taken. Defaults to second axis (1). + Axis to be used as the second axis of the 2-D sub-arrays from + which the diagonals should be taken. Defaults to second axis (1). Returns ------- array_of_diagonals : ndarray - If `a` is 2-D, a 1-D array containing the diagonal is - returned. If `a` has larger dimensions, then an array of - diagonals is returned. + If `a` is 2-D, a 1-D array containing the diagonal is returned. + If the dimension of `a` is larger, then an array of diagonals is + returned, "packed" from left-most dimension to right-most (e.g., + if `a` is 3-D, then the diagonals are "packed" along rows). Raises ------ @@ -938,7 +939,7 @@ See Also -------- - diag : Matlab workalike for 1-D and 2-D arrays. + diag : MATLAB work-a-like for 1-D and 2-D arrays. diagflat : Create diagonal arrays. trace : Sum along diagonals. @@ -953,16 +954,30 @@ >>> a.diagonal(1) array([1]) - >>> a = np.arange(8).reshape(2,2,2) - >>> a + A 3-D example: + + >>> a = np.arange(8).reshape(2,2,2); a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) - >>> a.diagonal(0,-2,-1) - array([[0, 3], - [4, 7]]) + >>> a.diagonal(0, # Main diagonals of two arrays created by skipping + ... 0, # across the outer(left)-most axis last and + ... 1) # the "middle" (row) axis first. + array([[0, 6], + [1, 7]]) + The sub-arrays whose main diagonals we just obtained; note that each + corresponds to fixing the right-most (column) axis, and that the + diagonals are "packed" in rows. + + >>> a[:,:,0] # main diagonal is [0 6] + array([[0, 2], + [4, 6]]) + >>> a[:,:,1] # main diagonal is [1 7] + array([[1, 3], + [5, 7]]) + """ return asarray(a).diagonal(offset, axis1, axis2) @@ -1470,33 +1485,33 @@ a : array_like Input array or object that can be converted to an array. axis : int, optional - Axis along which a logical OR is performed. - The default (`axis` = `None`) is to perform a logical OR - over a flattened input array. `axis` may be negative, in which - case it counts from the last to the first axis. + Axis along which a logical OR is performed. The default + (`axis` = `None`) is to perform a logical OR over a flattened + input array. `axis` may be negative, in which case it counts + from the last to the first axis. out : ndarray, optional - Alternative output array in which to place the result. - It must have the same shape as the expected output and - the type is preserved. See `doc.ufuncs` (Section - "Output arguments") for details. + Alternate output array in which to place the result. It must have + the same shape as the expected output and its type is preserved + (e.g., if it is of type float, then it will remain so, returning + 1.0 for True and 0.0 for False, regardless of the type of `a`). + See `doc.ufuncs` (Section "Output arguments") for details. Returns ------- - any : bool, ndarray - A new boolean or `ndarray` is returned unless `out` is - specified, in which case a reference to `out` is returned. + any : bool or ndarray + A new boolean or `ndarray` is returned unless `out` is specified, + in which case a reference to `out` is returned. See Also -------- ndarray.any : equivalent method - all : Test whether all array elements along a given axis evaluate - to True. + all : Test whether all elements along a given axis evaluate to True. Notes ----- - Not a Number (NaN), positive infinity and negative infinity - evaluate to `True` because these are not equal to zero. + Not a Number (NaN), positive infinity and negative infinity evaluate + to `True` because these are not equal to zero. Examples -------- @@ -1541,25 +1556,26 @@ axis : int, optional Axis along which a logical AND is performed. The default (`axis` = `None`) is to perform a logical AND - over a flattened input array. `axis` may be negative, in which + over a flattened input array. `axis` may be negative, in which case it counts from the last to the first axis. out : ndarray, optional - Alternative output array in which to place the result. - It must have the same shape as the expected output and - the type is preserved. See `doc.ufuncs` (Section "Output - arguments") for more details. + Alternate output array in which to place the result. + It must have the same shape as the expected output and its + type is preserved (e.g., if ``dtype(out)`` is float, the result + will consist of 0.0's and 1.0's). See `doc.ufuncs` (Section + "Output arguments") for more details. Returns ------- all : ndarray, bool - A new boolean or array is returned unless `out` is - specified, in which case a reference to `out` is returned. + A new boolean or array is returned unless `out` is specified, + in which case a reference to `out` is returned. See Also -------- ndarray.all : equivalent method - any : Test whether any array element along a given axis evaluates to True. + any : Test whether any element along a given axis evaluates to True. Notes ----- @@ -1735,26 +1751,26 @@ axis : int, optional Axis along which to operate. By default flattened input is used. out : ndarray, optional - Alternative output array in which to place the result. Must - be of the same shape and buffer length as the expected output. - See `doc.ufuncs` (Section "Output arguments") for more details. + Alternate output array in which to place the result. Must be of + the same shape and buffer length as the expected output. See + `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- amax : ndarray - A new array or a scalar array with the result. + A new array or scalar array with the result. See Also -------- - nanmax : nan values are ignored instead of being propagated - fmax : same behavior as the C99 fmax function - argmax : Indices of the maximum values. + nanmax : NaN values are ignored instead of being propagated. + fmax : same behavior as the C99 fmax function. + argmax : indices of the maximum values. Notes ----- - NaN values are propagated, that is if at least one item is nan, the - corresponding max value will be nan as well. To ignore NaN values (matlab - behavior), please use nanmax. + NaN values are propagated, that is if at least one item is NaN, the + corresponding max value will be NaN as well. To ignore NaN values + (MATLAB behavior), please use nanmax. Examples -------- @@ -1969,14 +1985,14 @@ a : array_like Input array. axis : int, optional - Axis along which the cumulative product is computed. By default the - input is flattened. + Axis along which the cumulative product is computed. By default + the input is flattened. dtype : dtype, optional Type of the returned array, as well as of the accumulator in which - the elements are multiplied. If dtype is not specified, it defaults - to the dtype of `a`, unless `a` has an integer dtype with a precision - less than that of the default platform integer. In that case, the - default platform integer is used instead. + the elements are multiplied. If *dtype* is not specified, it + defaults to the dtype of `a`, unless `a` has an integer dtype with + a precision less than that of the default platform integer. In + that case, the default platform integer is used instead. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output @@ -2007,15 +2023,13 @@ >>> np.cumprod(a, dtype=float) # specify type of output array([ 1., 2., 6., 24., 120., 720.]) - The cumulative product for each column (i.e., over the rows of) - `a`: + The cumulative product for each column (i.e., over the rows) of `a`: >>> np.cumprod(a, axis=0) array([[ 1, 2, 3], [ 4, 10, 18]]) - The cumulative product for each row (i.e. over the columns of) - `a`: + The cumulative product for each row (i.e. over the columns) of `a`: >>> np.cumprod(a,axis=1) array([[ 1, 2, 6], @@ -2253,10 +2267,9 @@ """ Compute the arithmetic mean along the specified axis. - Returns the average of the array elements. The average is taken - over the flattened array by default, otherwise over the specified - axis. float64 intermediate and return values are used for integer - inputs. + Returns the average of the array elements. The average is taken over + the flattened array by default, otherwise over the specified axis. + `float64` intermediate and return values are used for integer inputs. Parameters ---------- @@ -2266,14 +2279,15 @@ axis : int, optional Axis along which the means are computed. The default is to compute the mean of the flattened array. - dtype : dtype, optional - Type to use in computing the mean. For integer inputs, the default - is float64; for floating point, inputs it is the same as the input - dtype. + dtype : data-type, optional + Type to use in computing the mean. For integer inputs, the default + is `float64`; for floating point inputs, it is the same as the + input dtype. out : ndarray, optional - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. See `doc.ufuncs` for details. + Alternate output array in which to place the result. The default + is ``None``; if provided, it must have the same shape as the + expected output, but the type will be cast if necessary. + See `doc.ufuncs` for details. Returns ------- @@ -2290,11 +2304,11 @@ The arithmetic mean is the sum of the elements along the axis divided by the number of elements. - Note that for floating-point input, the mean is computed using the same - precision the input has. Depending on the input data, this can cause - the results to be inaccurate, especially for float32 (see example below). - Specifying a higher-accuracy accumulator using the `dtype` keyword can - alleviate this issue. + Note that for floating-point input, the mean is computed using the + same precision the input has. Depending on the input data, this can + cause the results to be inaccurate, especially for `float32` (see + example below). Specifying a higher-precision accumulator using the + `dtype` keyword can alleviate this issue. Examples -------- @@ -2425,35 +2439,35 @@ Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a - distribution. The variance is computed for the flattened array by default, - otherwise over the specified axis. + distribution. The variance is computed for the flattened array by + default, otherwise over the specified axis. Parameters ---------- a : array_like - Array containing numbers whose variance is desired. If `a` is not an + Array containing numbers whose variance is desired. If `a` is not an array, a conversion is attempted. axis : int, optional - Axis along which the variance is computed. The default is to compute + Axis along which the variance is computed. The default is to compute the variance of the flattened array. - dtype : dtype, optional - 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 + dtype : data-type, optional + 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, optional - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type is cast if + Alternate output array in which to place the result. It must have + the same shape as the expected output, but the type is cast if necessary. ddof : int, optional - "Delta Degrees of Freedom": the divisor used in calculation is + "Delta Degrees of Freedom": the divisor used in the calculation is ``N - ddof``, where ``N`` represents the number of elements. By default `ddof` is zero. Returns ------- variance : ndarray, see dtype parameter above - If out=None, returns a new array containing the variance; otherwise - a reference to the output array is returned. + If ``out=None``, returns a new array containing the variance; + otherwise, a reference to the output array is returned. See Also -------- @@ -2468,19 +2482,19 @@ The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used - instead. In standard statistical practice, ``ddof=1`` provides an - unbiased estimator of the variance of the infinite population. ``ddof=0`` - provides a maximum likelihood estimate of the variance for normally - distributed variables. + instead. In standard statistical practice, ``ddof=1`` provides an + unbiased estimator of the variance of a hypothetical infinite population. + ``ddof=0`` provides a maximum likelihood estimate of the variance for + normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same - precision the input has. Depending on the input data, this can cause - the results to be inaccurate, especially for float32 (see example below). - Specifying a higher-accuracy accumulator using the `dtype` keyword can - alleviate this issue. + precision the input has. Depending on the input data, this can cause + the results to be inaccurate, especially for `float32` (see example + below). Specifying a higher-accuracy accumulator using the ``dtype`` + keyword can alleviate this issue. Examples -------- From numpy-svn at scipy.org Sun Aug 1 07:20:55 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:20:55 -0500 (CDT) Subject: [Numpy-svn] r8581 - branches/1.5.x/numpy/core Message-ID: <20100801112055.10DEC39CE0B@scipy.org> Author: rgommers Date: 2010-08-01 06:20:54 -0500 (Sun, 01 Aug 2010) New Revision: 8581 Modified: branches/1.5.x/numpy/core/numeric.py Log: DOC: wiki merge, core/numeric.py Modified: branches/1.5.x/numpy/core/numeric.py =================================================================== --- branches/1.5.x/numpy/core/numeric.py 2010-08-01 11:20:35 UTC (rev 8580) +++ branches/1.5.x/numpy/core/numeric.py 2010-08-01 11:20:54 UTC (rev 8581) @@ -69,13 +69,13 @@ Parameters ---------- a : array_like - The shape and data-type of `a` define the parameters of + The shape and data-type of `a` define these same attributes of the returned array. Returns ------- out : ndarray - Array of zeros with same shape and type as `a`. + Array of zeros with the same shape and type as `a`. See Also -------- @@ -124,7 +124,7 @@ Parameters ---------- a : array_like - The shape and data-type of `a` define the parameters of the + The shape and data-type of `a` define these same attributes of the returned array. Returns @@ -143,8 +143,8 @@ Notes ----- This function does *not* initialize the returned array; to do that use - `zeros_like` or `ones_like` instead. It may be marginally faster than the - functions that do set the array values. + `zeros_like` or `ones_like` instead. It may be marginally faster than + the functions that do set the array values. Examples -------- @@ -154,7 +154,7 @@ [ 0, 0, -1073741821]]) >>> a = np.array([[1., 2., 3.],[4.,5.,6.]]) >>> np.empty_like(a) - array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], #random + array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000],#random [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) """ @@ -285,14 +285,14 @@ def asanyarray(a, dtype=None, order=None): """ - Convert the input to a ndarray, but pass ndarray subclasses through. + Convert the input to an ndarray, but pass ndarray subclasses through. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, - tuples of lists and ndarrays. + tuples of lists, and ndarrays. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional @@ -312,7 +312,8 @@ asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. - asarray_chkfinite : Similar function which checks input for NaNs and Infs. + asarray_chkfinite : Similar function which checks input for NaNs and + Infs. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. @@ -1133,7 +1134,8 @@ The axis to roll backwards. The positions of the other axes do not change relative to one another. start : int, optional - The axis is rolled until it lies before this position. + The axis is rolled until it lies before this position. The default, + 0, results in a "complete" roll. Returns ------- @@ -1143,7 +1145,7 @@ See Also -------- roll : Roll the elements of an array by a number of positions along a - given axis. + given axis. Examples -------- @@ -1400,23 +1402,25 @@ """ Return a string representation of the data in an array. - The data in the array is returned as a single string. This function - is similar to `array_repr`, the difference is that `array_repr` also - returns information on the type of array and data type. + The data in the array is returned as a single string. This function is + similar to `array_repr`, the difference being that `array_repr` also + returns information on the kind of array and its data type. Parameters ---------- a : ndarray Input array. max_line_width : int, optional - Inserts newlines if text is longer than `max_line_width`. + Inserts newlines if text is longer than `max_line_width`. The + default is, indirectly, 75. precision : int, optional - Floating point precision. Default is the current printing precision - (usually 8), which can be altered using set_printoptions. + Floating point precision. Default is the current printing precision + (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional - Represent very small numbers as zero, default is False. Very small is - defined by precision, if the precision is 8 then numbers smaller than - 5e-9 are represented as zero. + Represent numbers "very close" to zero as zero; default is False. + Very close is defined by precision: if the precision is 8, e.g., + numbers smaller (in absolute value) than 5e-9 are represented as + zero. See Also -------- @@ -1844,11 +1848,11 @@ """ Return a new array of given shape and type, filled with ones. - Please refer to the documentation for `zeros`. + Please refer to the documentation for `zeros` for further details. See Also -------- - zeros + zeros, ones_like Examples -------- From numpy-svn at scipy.org Sun Aug 1 07:21:13 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:21:13 -0500 (CDT) Subject: [Numpy-svn] r8582 - branches/1.5.x/numpy/core/code_generators Message-ID: <20100801112113.4CDF839CE0D@scipy.org> Author: rgommers Date: 2010-08-01 06:21:13 -0500 (Sun, 01 Aug 2010) New Revision: 8582 Modified: branches/1.5.x/numpy/core/code_generators/ufunc_docstrings.py Log: DOC: wiki merge, core.umath Modified: branches/1.5.x/numpy/core/code_generators/ufunc_docstrings.py =================================================================== --- branches/1.5.x/numpy/core/code_generators/ufunc_docstrings.py 2010-08-01 11:20:54 UTC (rev 8581) +++ branches/1.5.x/numpy/core/code_generators/ufunc_docstrings.py 2010-08-01 11:21:13 UTC (rev 8582) @@ -20,7 +20,7 @@ Returns ------- - res : ndarray + absolute : ndarray An ndarray containing the absolute value of each element in `x`. For complex input, ``a + ib``, the absolute value is :math:`\\sqrt{ a^2 + b^2 }`. @@ -56,12 +56,14 @@ Parameters ---------- x1, x2 : array_like - The arrays to be added. + The arrays to be added. If ``x1.shape != x2.shape``, they must be + broadcastable to a common shape (which may be the shape of one or + the other). Returns ------- - y : {ndarray, scalar} - The sum of `x1` and `x2`, element-wise. Returns scalar if + y : ndarray or scalar + The sum of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes @@ -112,25 +114,23 @@ Notes ----- `arccos` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `cos(z) = x`. The convention is to return the - angle `z` whose real part lies in `[0, pi]`. + many numbers `z` such that `cos(z) = x`. The convention is to return + the angle `z` whose real part lies in `[0, pi]`. For real-valued input data types, `arccos` always returns real output. - For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. - For complex-valued input, `arccos` is a complex analytical function that - has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above - on the former and from below on the latter. + For complex-valued input, `arccos` is a complex analytic function that + has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from + above on the former and from below on the latter. The inverse `cos` is also known as `acos` or cos^-1. References ---------- - .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", - 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ - .. [2] Wikipedia, "Inverse trigonometric function", - http://en.wikipedia.org/wiki/Inverse_trigonometric_function + M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", + 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ Examples -------- @@ -204,23 +204,23 @@ add_newdoc('numpy.core.umath', 'arcsin', """ - Inverse sine elementwise. + Inverse sine, element-wise. Parameters ---------- x : array_like - `y`-coordinate on the unit circle. + `y`-coordinate on the unit circle. out : ndarray, optional - Array of the same shape as `x`, to store results in. See - `doc.ufuncs` (Section "Output arguments") for more details. + Array of the same shape as `x`, in which to store the results. + See `doc.ufuncs` (Section "Output arguments") for more details. Returns ------- angle : ndarray - The angle of the ray intersecting the unit circle at the given - `y`-coordinate in radians ``[-pi, pi]``. If `x` is a scalar then - a scalar is returned, otherwise an array is returned. + The inverse sine of each element in `x`, in radians and in the + closed interval ``[-pi/2, pi/2]``. If `x` is a scalar, a scalar + is returned, otherwise an array. See Also -------- @@ -229,25 +229,24 @@ Notes ----- `arcsin` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `sin(z) = x`. The convention is to return the - angle `z` whose real part lies in `[-pi/2, pi/2]`. + many numbers `z` such that :math:`sin(z) = x`. The convention is to + return the angle `z` whose real part lies in [-pi/2, pi/2]. - For real-valued input data types, `arcsin` always returns real output. - For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For real-valued input data types, *arcsin* always returns real output. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. - For complex-valued input, `arcsin` is a complex analytical function that - has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above - on the former and from below on the latter. + For complex-valued input, `arcsin` is a complex analytic function that + has, by convention, the branch cuts [-inf, -1] and [1, inf] and is + continuous from above on the former and from below on the latter. - The inverse sine is also known as `asin` or ``sin^-1``. + The inverse sine is also known as `asin` or sin^{-1}. References ---------- - .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", - 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ - .. [2] Wikipedia, "Inverse trigonometric function", - http://en.wikipedia.org/wiki/Inverse_trigonometric_function + Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*, + 10th printing, New York: Dover, 1964, pp. 79ff. + http://www.math.sfu.ca/~cbm/aands/ Examples -------- @@ -311,8 +310,7 @@ """ Trigonometric inverse tangent, element-wise. - The inverse of tan, so that if ``y = tan(x)`` then - ``x = arctan(y)``. + The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``. Parameters ---------- @@ -322,39 +320,41 @@ Returns ------- out : ndarray - Out has the same shape as `x`. Its real part is - in ``[-pi/2, pi/2]``. It is a scalar if `x` is a scalar. + Out has the same shape as `x`. Its real part is in + ``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``). + It is a scalar if `x` is a scalar. See Also -------- - arctan2 : Calculate the arctan of y/x. + arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`) + and the positive `x`-axis. + angle : Argument of complex values. Notes ----- - `arctan` is a multivalued function: for each `x` there are infinitely - many numbers `z` such that `tan(z) = x`. The convention is to return the - angle `z` whose real part lies in `[-pi/2, pi/2]`. + `arctan` is a multi-valued function: for each `x` there are infinitely + many numbers `z` such that tan(`z`) = `x`. The convention is to return + the angle `z` whose real part lies in [-pi/2, pi/2]. For real-valued input data types, `arctan` always returns real output. - For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + For each value that cannot be expressed as a real number or infinity, + it yields ``nan`` and sets the `invalid` floating point error flag. - For complex-valued input, `arctan` is a complex analytical function that - has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from the - left on the former and from the right on the latter. + For complex-valued input, `arctan` is a complex analytic function that + has [`1j, infj`] and [`-1j, -infj`] as branch cuts, and is continuous + from the left on the former and from the right on the latter. - The inverse tangent is also known as `atan` or ``tan^-1``. + The inverse tangent is also known as `atan` or tan^{-1}. References ---------- - .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", - 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/ - .. [2] Wikipedia, "Inverse trigonometric function", - http://en.wikipedia.org/wiki/Arctan + Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*, + 10th printing, New York: Dover, 1964, pp. 79. + http://www.math.sfu.ca/~cbm/aands/ Examples -------- - We expect the arctan of 0 to be 0, and of 1 to be :math:`\\pi/4`: + We expect the arctan of 0 to be 0, and of 1 to be pi/4: >>> np.arctan([0, 1]) array([ 0. , 0.78539816]) @@ -374,22 +374,27 @@ add_newdoc('numpy.core.umath', 'arctan2', """ - Elementwise arc tangent of ``x1/x2`` choosing the quadrant correctly. + Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly. - The quadrant (ie. branch) is chosen so that ``arctan2(x1, x2)`` - is the signed angle in radians between the line segments - ``(0,0) - (1,0)`` and ``(0,0) - (x2,x1)``. This function is defined - also for `x2` = 0. + The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is + the signed angle in radians between the ray ending at the origin and + passing through the point (1,0), and the ray ending at the origin and + passing through the point (`x2`, `x1`). (Note the role reversal: the + "`y`-coordinate" is the first function parameter, the "`x`-coordinate" + is the second.) By IEEE convention, this function is defined for + `x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see + Notes for specific values). - `arctan2` is not defined for complex-valued arguments. + This function is not defined for complex-valued arguments; for the + so-called argument of complex values, use `angle`. Parameters ---------- x1 : array_like, real-valued - y-coordinates. + `y`-coordinates. x2 : array_like, real-valued - x-coordinates. `x2` must be broadcastable to match the shape of `x1`, - or vice versa. + `x`-coordinates. `x2` must be broadcastable to match the shape of + `x1` or vice versa. Returns ------- @@ -398,12 +403,13 @@ See Also -------- - arctan, tan + arctan, tan, angle Notes ----- - `arctan2` is identical to the `atan2` function of the underlying - C library. The following special values are defined in the C standard [2]: + *arctan2* is identical to the `atan2` function of the underlying + C library. The following special values are defined in the C + standard: [1]_ ====== ====== ================ `x1` `x2` `arctan2(x1,x2)` @@ -416,13 +422,12 @@ +/-inf -inf +/- (3*pi/4) ====== ====== ================ - Note that +0 and -0 are distinct floating point numbers. + Note that +0 and -0 are distinct floating point numbers, as are +inf + and -inf. References ---------- - .. [1] Wikipedia, "atan2", - http://en.wikipedia.org/wiki/Atan2 - .. [2] ISO/IEC standard 9899:1999, "Programming language C", 1999. + .. [1] ISO/IEC standard 9899:1999, "Programming language C." Examples -------- @@ -841,7 +846,8 @@ Returns ------- y : ndarray of floats - The corresponding degree values. + The corresponding degree values; if `out` was supplied this is a + reference to it. See Also -------- @@ -1291,18 +1297,21 @@ add_newdoc('numpy.core.umath', 'greater', """ - Return (x1 > x2) element-wise. + Return the truth value of (x1 > x2) element-wise. Parameters ---------- x1, x2 : array_like - Input arrays. + Input arrays. If ``x1.shape != x2.shape``, they must be + broadcastable to a common shape (which may be the shape of one or + the other). Returns ------- - Out : {ndarray, bool} - Output array of bools, or a single bool if `x1` and `x2` are scalars. + out : bool or ndarray of bool + Array of bools, or a single bool if `x1` and `x2` are scalars. + See Also -------- greater_equal, less, less_equal, equal, not_equal @@ -1323,17 +1332,19 @@ add_newdoc('numpy.core.umath', 'greater_equal', """ - Return (x1 >= x2) element-wise. + Return the truth value of (x1 >= x2) element-wise. Parameters ---------- x1, x2 : array_like - Input arrays. + Input arrays. If ``x1.shape != x2.shape``, they must be + broadcastable to a common shape (which may be the shape of one or + the other). Returns ------- - out : {ndarray, bool} - Output array of bools, or a single bool if x1 and x2 are scalars. + out : bool or ndarray of bool + Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- @@ -1532,30 +1543,33 @@ add_newdoc('numpy.core.umath', 'isinf', """ - Test element-wise for positive or negative infinity, return result as bool - array. + Test element-wise for positive or negative infinity. + Return a bool-type array, the same shape as `x`, True where ``x == + +/-inf``, False everywhere else. + Parameters ---------- x : array_like Input values - y : array_like, optional + out : array_like, optional An array with the same shape as `x` to store the result. Returns ------- - y : {ndarray, bool} + y : bool (scalar) or bool-type ndarray For scalar input, the result is a new boolean with value True if the input is positive or negative infinity; otherwise the value is False. For array input, the result is a boolean array with the same - dimensions as the input and the values are True if the corresponding - element of the input is positive or negative infinity; otherwise the - values are False. If a second argument is supplied the result is - stored there. If the type of that array is a numeric type the result - is represented as zeros and ones, if the type is boolean then as - False and True. The return value `y` is then a reference to that array. + shape as the input and the values are True where the + corresponding element of the input is positive or negative + infinity; elsewhere the values are False. If a second argument + was supplied the result is stored there. If the type of that array + is a numeric type the result is represented as zeros and ones, if + the type is boolean then as False and True, respectively. + The return value `y` is then a reference to that array. See Also -------- @@ -1566,8 +1580,9 @@ Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). - Errors result if second argument is also supplied with scalar input or - if first and second arguments have different shapes. + Errors result if the second argument is supplied when the first + argument is a scalar, or if the first and second arguments have + different shapes. Examples -------- @@ -1670,21 +1685,23 @@ add_newdoc('numpy.core.umath', 'less', """ - Return (x1 < x2) element-wise. + Return the truth value of (x1 < x2) element-wise. Parameters ---------- x1, x2 : array_like - Input arrays. + Input arrays. If ``x1.shape != x2.shape``, they must be + broadcastable to a common shape (which may be the shape of one or + the other). Returns ------- - Out : ndarray of bools - Output array of bools, or a single bool if `x1` and `x2` are scalars. + out : bool or ndarray of bool + Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- - less_equal, greater, greater_equal, equal, not_equal + greater, less_equal, greater_equal, equal, not_equal Examples -------- @@ -1695,26 +1712,28 @@ add_newdoc('numpy.core.umath', 'less_equal', """ - Return (x1 <= x2) element-wise. + Return the truth value of (x1 =< x2) element-wise. Parameters ---------- x1, x2 : array_like - Input arrays. + Input arrays. If ``x1.shape != x2.shape``, they must be + broadcastable to a common shape (which may be the shape of one or + the other). Returns ------- - Out : {ndarray, bool} - Output array of bools, or a single bool if `x1` and `x2` are scalars. + out : bool or ndarray of bool + Array of bools, or a single bool if `x1` and `x2` are scalars. See Also -------- - less, greater_equal, greater, equal, not_equal + greater, less, greater_equal, equal, not_equal Examples -------- - >>> np.less_equal([1, 2, 3], [2, 2, 2]) - array([ True, True, False], dtype=bool) + >>> np.less_equal([4, 2, 1], [2, 2, 2]) + array([False, True, True], dtype=bool) """) @@ -2041,7 +2060,7 @@ Returns ------- - y : {ndarray, bool} + y : bool or ndarray of bool Boolean result with the same shape as `x` of the NOT operation on elements of `x`. @@ -2098,24 +2117,24 @@ add_newdoc('numpy.core.umath', 'logical_xor', """ - Compute the truth value of x1 XOR x2 elementwise. + Compute the truth value of x1 XOR x2, element-wise. Parameters ---------- x1, x2 : array_like - Logical XOR is applied to the elements of `x1` and `x2`. - They have to be of the same shape. + Logical XOR is applied to the elements of `x1` and `x2`. They must + be broadcastable to the same shape. Returns ------- - y : {ndarray, bool} - Boolean result with the same shape as `x1` and `x2` of the logical - XOR operation on elements of `x1` and `x2`. + y : bool or ndarray of bool + Boolean result of the logical XOR operation applied to the elements + of `x1` and `x2`; the shape is determined by whether or not + broadcasting of one or both arrays was required. See Also -------- - logical_and, logical_or, logical_not - bitwise_xor + logical_and, logical_or, logical_not, bitwise_xor Examples -------- @@ -2128,6 +2147,12 @@ >>> np.logical_xor(x < 1, x > 3) array([ True, False, False, False, True], dtype=bool) + Simple example showing support of broadcasting + + >>> np.logical_xor(0, np.eye(2)) + array([[ True, False], + [False, True]], dtype=bool) + """) add_newdoc('numpy.core.umath', 'maximum', @@ -2417,13 +2442,13 @@ Parameters ---------- - x : {array_like, scalar} + x : array_like or scalar Input array. Returns ------- - y : {ndarray, scalar} - Returned array or scalar `y=-x`. + y : ndarray or scalar + Returned array or scalar: `y = -x`. Examples -------- @@ -2471,11 +2496,11 @@ Equivalent to ``a.copy().fill(1)``. - Please refer to the documentation for `zeros_like`. + Please refer to the documentation for `zeros_like` for further details. See Also -------- - zeros_like + zeros_like, ones Examples -------- @@ -2488,10 +2513,10 @@ add_newdoc('numpy.core.umath', 'power', """ - Returns element-wise base array raised to power from second array. + First array elements raised to powers from second array, element-wise. - Raise each base in `x1` to the power of the exponents in `x2`. This - requires that `x1` and `x2` must be broadcastable to the same shape. + Raise each base in `x1` to the positionally-corresponding power in + `x2`. `x1` and `x2` must be broadcastable to the same shape. Parameters ---------- @@ -2542,7 +2567,7 @@ x : array_like Input array in degrees. out : ndarray, optional - Output array of same shape as x. + Output array of same shape as `x`. Returns ------- @@ -2776,12 +2801,13 @@ The input value(s). out : ndarray, optional Array into which the output is placed. Its type is preserved - and it must be of the right shape to hold the output. See doc.ufuncs. + and it must be of the right shape to hold the output. + See `doc.ufuncs`. Returns ------- - out : array_like, bool - Output array. + result : ndarray of bool + Output array, or reference to `out` if that was supplied. Examples -------- @@ -3011,24 +3037,32 @@ Parameters ---------- x : array_like - The square root of each element in this array is calculated. + The values whose square-roots are required. + out : ndarray, optional + Alternate array object in which to put the result; if provided, it + must have the same shape as `x` Returns ------- y : ndarray - An array of the same shape as `x`, containing the square-root of - each element in `x`. If any element in `x` - is complex, a complex array is returned. If all of the elements - of `x` are real, negative elements return numpy.nan elements. + An array of the same shape as `x`, containing the positive + square-root of each element in `x`. If any element in `x` is + complex, a complex array is returned (and the square-roots of + negative reals are calculated). If all of the elements in `x` + are real, so is `y`, with negative elements returning ``nan``. + If `out` was provided, `y` is a reference to it. See Also -------- - numpy.lib.scimath.sqrt + lib.scimath.sqrt A version which returns complex numbers when given negative reals. Notes ----- - `sqrt` has a branch cut ``[-inf, 0)`` and is continuous from above on it. + *sqrt* has--consistent with common convention--as its branch cut the + real "interval" [`-inf`, 0), and is continuous from above on it. + (A branch cut is a curve in the complex plane across which a given + complex function fails to be continuous.) Examples -------- From numpy-svn at scipy.org Sun Aug 1 07:21:38 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:21:38 -0500 (CDT) Subject: [Numpy-svn] r8583 - branches/1.5.x/numpy/lib Message-ID: <20100801112138.C3FC039CE0F@scipy.org> Author: rgommers Date: 2010-08-01 06:21:38 -0500 (Sun, 01 Aug 2010) New Revision: 8583 Modified: branches/1.5.x/numpy/lib/format.py branches/1.5.x/numpy/lib/function_base.py branches/1.5.x/numpy/lib/npyio.py Log: DOC: wiki merge, npyio, format and function_base Modified: branches/1.5.x/numpy/lib/format.py =================================================================== --- branches/1.5.x/numpy/lib/format.py 2010-08-01 11:21:13 UTC (rev 8582) +++ branches/1.5.x/numpy/lib/format.py 2010-08-01 11:21:38 UTC (rev 8583) @@ -366,19 +366,19 @@ """ Write an array to an NPY file, including a header. - If the array is neither C-contiguous or Fortran-contiguous AND if the - filelike object is not a real file object, then this function will have - to copy data in memory. + If the array is neither C-contiguous nor Fortran-contiguous AND the + file_like object is not a real file object, this function will have to + copy data in memory. Parameters ---------- - fp : filelike object - An open, writable file object or similar object with a `.write()` + fp : file_like object + An open, writable file object, or similar object with a ``.write()`` method. - array : numpy.ndarray + array : ndarray The array to write to disk. version : (int, int), optional - The version number of the format. + The version number of the format. Default: (1, 0) Raises ------ @@ -386,7 +386,7 @@ If the array cannot be persisted. Various other errors If the array contains Python objects as part of its dtype, the - process of pickling them may raise arbitrary errors if the objects + process of pickling them may raise various errors if the objects are not picklable. """ @@ -418,13 +418,13 @@ Parameters ---------- - fp : filelike object - If this is not a real file object, then this may take extra memory and - time. + fp : file_like object + If this is not a real file object, then this may take extra memory + and time. Returns ------- - array : numpy.ndarray + array : ndarray The array from the data on disk. Raises @@ -477,27 +477,31 @@ Parameters ---------- filename : str - The name of the file on disk. This may not be a file-like object. + The name of the file on disk. This may *not* be a file-like + object. mode : str, optional - The mode to open the file with. In addition to the standard file modes, - 'c' is also accepted to mean "copy on write". See `numpy.memmap` for - the available mode strings. - dtype : dtype, optional + The mode in which to open the file; the default is 'r+'. In + addition to the standard file modes, 'c' is also accepted to + mean "copy on write." See `memmap` for the available mode strings. + dtype : data-type, optional The data type of the array if we are creating a new file in "write" - mode. - shape : tuple of int, optional + mode, if not, `dtype` is ignored. The default value is None, + which results in a data-type of `float64`. + shape : tuple of int The shape of the array if we are creating a new file in "write" - mode. + mode, in which case this parameter is required. Otherwise, this + parameter is ignored and is thus optional. fortran_order : bool, optional Whether the array should be Fortran-contiguous (True) or - C-contiguous (False) if we are creating a new file in "write" mode. + C-contiguous (False, the default) if we are creating a new file + in "write" mode. version : tuple of int (major, minor) If the mode is a "write" mode, then this is the version of the file - format used to create the file. + format used to create the file. Default: (1,0) Returns ------- - marray : numpy.memmap + marray : memmap The memory-mapped array. Raises @@ -509,7 +513,7 @@ See Also -------- - numpy.memmap + memmap """ if not isinstance(filename, basestring): Modified: branches/1.5.x/numpy/lib/function_base.py =================================================================== --- branches/1.5.x/numpy/lib/function_base.py 2010-08-01 11:21:13 UTC (rev 8582) +++ branches/1.5.x/numpy/lib/function_base.py 2010-08-01 11:21:38 UTC (rev 8583) @@ -29,9 +29,31 @@ from utils import deprecate import numpy as np -#end Fernando's utilities def iterable(y): + """ + Check whether or not an object can be iterated over. + + Parameters + ---------- + y : object + Input object. + + Returns + ------- + b : {0, 1} + Return 1 if the object has an iterator method or is a sequence, + and 0 otherwise. + + + Examples + -------- + >>> np.iterable([1, 2, 3]) + 1 + >>> np.iterable(2) + 0 + + """ try: iter(y) except: return 0 return 1 @@ -1237,7 +1259,7 @@ """ Change elements of an array based on conditional and input values. - Similar to ``np.putmask(a, mask, vals)``, the difference is that `place` + Similar to ``np.putmask(arr, mask, vals)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `putmask` uses the elements where `mask` is True. @@ -1245,7 +1267,7 @@ Parameters ---------- - a : array_like + arr : array_like Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. @@ -1260,9 +1282,9 @@ Examples -------- - >>> x = np.arange(6).reshape(2, 3) - >>> np.place(x, x>2, [44, 55]) - >>> x + >>> arr = np.arange(6).reshape(2, 3) + >>> np.place(arr, arr>2, [44, 55]) + >>> arr array([[ 0, 1, 2], [44, 55, 44]]) @@ -1936,12 +1958,12 @@ Return correlation coefficients. Please refer to the documentation for `cov` for more detail. The - relationship between the correlation coefficient matrix, P, and the - covariance matrix, C, is + relationship between the correlation coefficient matrix, `P`, and the + covariance matrix, `C`, is .. math:: P_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } - The values of P are between -1 and 1. + The values of `P` are between -1 and 1, inclusive. Parameters ---------- @@ -1989,22 +2011,22 @@ """ Return the Blackman window. - The Blackman window is a taper formed by using the the first - three terms of a summation of cosines. It was designed to have close - to the minimal leakage possible. - It is close to optimal, only slightly worse than a Kaiser window. + The Blackman window is a taper formed by using the the first three + terms of a summation of cosines. It was designed to have close to the + minimal leakage possible. It is close to optimal, only slightly worse + than a Kaiser window. Parameters ---------- M : int - Number of points in the output window. If zero or less, an - empty array is returned. + Number of points in the output window. If zero or less, an empty + array is returned. Returns ------- - out : array - The window, normalized to one (the value one - appears only if the number of samples is odd). + out : ndarray + The window, normalized to one (the value one appears only if the + number of samples is odd). See Also -------- @@ -2016,7 +2038,6 @@ .. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M) - Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means @@ -2027,13 +2048,12 @@ References ---------- - .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power - spectra, Dover Publications, New York. - .. [2] Wikipedia, "Window function", - http://en.wikipedia.org/wiki/Window_function - .. [3] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. - Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. + Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, + Dover Publications, New York. + Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. + Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. + Examples -------- >>> from numpy import blackman Modified: branches/1.5.x/numpy/lib/npyio.py =================================================================== --- branches/1.5.x/numpy/lib/npyio.py 2010-08-01 11:21:13 UTC (rev 8582) +++ branches/1.5.x/numpy/lib/npyio.py 2010-08-01 11:21:38 UTC (rev 8583) @@ -367,7 +367,7 @@ def savez(file, *args, **kwds): """ - Save several arrays into a single, compressed file in ``.npz`` format. + Save several arrays into a single, archive file in ``.npz`` format. If arguments are passed in with no keywords, the corresponding variable names, in the .npz file, are 'arr_0', 'arr_1', etc. If keyword arguments @@ -401,8 +401,9 @@ Notes ----- The ``.npz`` file format is a zipped archive of files named after the - variables they contain. Each file contains one variable in ``.npy`` - format. For a description of the ``.npy`` format, see `format`. + variables they contain. The archive is not compressed and each file + in the archive contains one variable in ``.npy`` format. For a + description of the ``.npy`` format, see `format`. When opening the saved ``.npz`` file with `load` a `NpzFile` object is returned. This is a dictionary-like object which can be queried for @@ -509,30 +510,32 @@ fname : file or str File or filename to read. If the filename extension is ``.gz`` or ``.bz2``, the file is first decompressed. - dtype : dtype, optional - Data type of the resulting array. If this is a record data-type, - the resulting array will be 1-dimensional, and each row will be - interpreted as an element of the array. In this case, the number - of columns used must match the number of fields in the data-type. + dtype : data-type, optional + Data-type of the resulting array; default: float. If this is a record + data-type, the resulting array will be 1-dimensional, and each row + will be interpreted as an element of the array. In this case, the + number of columns used must match the number of fields in the + data-type. comments : str, optional - The character used to indicate the start of a comment. + The character used to indicate the start of a comment; default: '#'. delimiter : str, optional The string used to separate values. By default, this is any whitespace. converters : dict, optional A dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: - ``converters = {0: datestr2num}``. Converters can also be used to + ``converters = {0: datestr2num}``. Converters can also be used to provide a default value for missing data: - ``converters = {3: lambda s: float(s or 0)}``. + ``converters = {3: lambda s: float(s or 0)}``. Default: None. skiprows : int, optional - Skip the first `skiprows` lines. + Skip the first `skiprows` lines; default: 0. usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. + The default, None, results in all columns being read. unpack : bool, optional If True, the returned array is transposed, so that arguments may be - unpacked using ``x, y, z = loadtxt(...)``. Default is False. + unpacked using ``x, y, z = loadtxt(...)``. The default is False. Returns ------- @@ -543,11 +546,11 @@ -------- load, fromstring, fromregex genfromtxt : Load data with missing values handled as specified. - scipy.io.loadmat : reads Matlab(R) data files + scipy.io.loadmat : reads MATLAB data files Notes ----- - This function aims to be a fast reader for simply formatted files. The + This function aims to be a fast reader for simply formatted files. The `genfromtxt` function provides more sophisticated handling of, e.g., lines with missing values. From numpy-svn at scipy.org Sun Aug 1 07:21:57 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:21:57 -0500 (CDT) Subject: [Numpy-svn] r8584 - branches/1.5.x/numpy/lib Message-ID: <20100801112157.E29E639CE11@scipy.org> Author: rgommers Date: 2010-08-01 06:21:57 -0500 (Sun, 01 Aug 2010) New Revision: 8584 Modified: branches/1.5.x/numpy/lib/scimath.py branches/1.5.x/numpy/lib/shape_base.py branches/1.5.x/numpy/lib/stride_tricks.py branches/1.5.x/numpy/lib/twodim_base.py Log: DOC: wiki merge, twodim_base and a few loose ones. Modified: branches/1.5.x/numpy/lib/scimath.py =================================================================== --- branches/1.5.x/numpy/lib/scimath.py 2010-08-01 11:21:38 UTC (rev 8583) +++ branches/1.5.x/numpy/lib/scimath.py 2010-08-01 11:21:57 UTC (rev 8584) @@ -3,16 +3,17 @@ whose output data-type is different than the input data-type in certain domains of the input. -For example, for functions like log() with branch cuts, the versions in this -module provide the mathematically valid answers in the complex plane: +For example, for functions like `log` with branch cuts, the versions in this +module provide the mathematically valid answers in the complex plane:: ->>> import math ->>> from numpy.lib import scimath ->>> scimath.log(-math.exp(1)) == (1+1j*math.pi) -True + >>> import math + >>> from numpy.lib import scimath + >>> scimath.log(-math.exp(1)) == (1+1j*math.pi) + True -Similarly, sqrt(), other base logarithms, power() and trig functions are +Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. + """ __all__ = ['sqrt', 'log', 'log2', 'logn','log10', 'power', 'arccos', Modified: branches/1.5.x/numpy/lib/shape_base.py =================================================================== --- branches/1.5.x/numpy/lib/shape_base.py 2010-08-01 11:21:38 UTC (rev 8583) +++ branches/1.5.x/numpy/lib/shape_base.py 2010-08-01 11:21:57 UTC (rev 8584) @@ -126,27 +126,26 @@ `func` is called as `res = func(a, axis)`, where `axis` is the first element of `axes`. The result `res` of the function call must have - either the same dimensions as `a` or one less dimension. If `res` has one - less dimension than `a`, a dimension is inserted before `axis`. - The call to `func` is then repeated for each axis in `axes`, + either the same dimensions as `a` or one less dimension. If `res` + has one less dimension than `a`, a dimension is inserted before + `axis`. The call to `func` is then repeated for each axis in `axes`, with `res` as the first argument. Parameters ---------- func : function This function must take two arguments, `func(a, axis)`. - a : ndarray + a : array_like Input array. axes : array_like - Axes over which `func` is applied, the elements must be - integers. + Axes over which `func` is applied; the elements must be integers. Returns ------- val : ndarray - The output array. The number of dimensions is the same as `a`, but - the shape can be different. This depends on whether `func` changes - the shape of its output with respect to its input. + The output array. The number of dimensions is the same as `a`, + but the shape can be different. This depends on whether `func` + changes the shape of its output with respect to its input. See Also -------- Modified: branches/1.5.x/numpy/lib/stride_tricks.py =================================================================== --- branches/1.5.x/numpy/lib/stride_tricks.py 2010-08-01 11:21:38 UTC (rev 8583) +++ branches/1.5.x/numpy/lib/stride_tricks.py 2010-08-01 11:21:57 UTC (rev 8584) @@ -33,16 +33,16 @@ Parameters ---------- - `*args` : arrays + `*args` : array_likes The arrays to broadcast. Returns ------- broadcasted : list of arrays - These arrays are views on the original arrays. They are typically not - contiguous. Furthermore, more than one element of a broadcasted array - may refer to a single memory location. If you need to write to the - arrays, make copies first. + These arrays are views on the original arrays. They are typically + not contiguous. Furthermore, more than one element of a + broadcasted array may refer to a single memory location. If you + need to write to the arrays, make copies first. Examples -------- Modified: branches/1.5.x/numpy/lib/twodim_base.py =================================================================== --- branches/1.5.x/numpy/lib/twodim_base.py 2010-08-01 11:21:38 UTC (rev 8583) +++ branches/1.5.x/numpy/lib/twodim_base.py 2010-08-01 11:21:57 UTC (rev 8584) @@ -172,20 +172,22 @@ M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional - Index of the diagonal: 0 refers to the main diagonal, a positive value - refers to an upper diagonal, and a negative value to a lower diagonal. - dtype : dtype, optional + Index of the diagonal: 0 (the default) refers to the main diagonal, + a positive value refers to an upper diagonal, and a negative value + to a lower diagonal. + dtype : data-type, optional Data-type of the returned array. Returns ------- - I : ndarray (N,M) + I : ndarray of shape (N,M) An array where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- - diag : Return a diagonal 2-D array using a 1-D array specified by the user. + identity : (almost) equivalent function + diag : diagonal 2-D array from a 1-D array specified by the user. Examples -------- @@ -294,7 +296,9 @@ Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional - Diagonal to set. The default is 0. + Diagonal to set; 0, the default, corresponds to the "main" diagonal, + a positive (negative) `k` giving the number of the diagonal above + (below) the main. Returns ------- @@ -303,7 +307,7 @@ See Also -------- - diag : Matlab workalike for 1-D and 2-D arrays. + diag : MATLAB work-alike for 1-D and 2-D arrays. diagonal : Return specified diagonals. trace : Sum along diagonals. @@ -342,7 +346,7 @@ def tri(N, M=None, k=0, dtype=float): """ - Construct an array filled with ones at and below the given diagonal. + An array with ones at and below the given diagonal and zeros elsewhere. Parameters ---------- @@ -352,7 +356,7 @@ Number of columns in the array. By default, `M` is taken equal to `N`. k : int, optional - The sub-diagonal below which the array is filled. + The sub-diagonal at and below which the array is filled. `k` = 0 is the main diagonal, while `k` < 0 is below it, and `k` > 0 is above. The default is 0. dtype : dtype, optional @@ -360,9 +364,9 @@ Returns ------- - T : (N,M) ndarray - Array with a lower triangle filled with ones, in other words - ``T[i,j] == 1`` for ``i <= j + k``. + T : ndarray of shape (N, M) + Array with its lower triangle filled with ones and zero elsewhere; + in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise. Examples -------- @@ -391,9 +395,9 @@ ---------- m : array_like, shape (M, N) Input array. - k : int - Diagonal above which to zero elements. - `k = 0` is the main diagonal, `k < 0` is below it and `k > 0` is above. + k : int, optional + Diagonal above which to zero elements. `k = 0` (the default) is the + main diagonal, `k < 0` is below it and `k > 0` is above. Returns ------- @@ -402,7 +406,7 @@ See Also -------- - triu + triu : same thing, only for the upper triangle Examples -------- @@ -421,13 +425,14 @@ """ Upper triangle of an array. - Construct a copy of a matrix with elements below the k-th diagonal zeroed. + Return a copy of a matrix with the elements below the `k`-th diagonal + zeroed. - Please refer to the documentation for `tril`. + Please refer to the documentation for `tril` for further details. See Also -------- - tril + tril : lower triangle of an array Examples -------- @@ -448,17 +453,17 @@ Generate a Van der Monde matrix. The columns of the output matrix are decreasing powers of the input - vector. Specifically, the i-th output column is the input vector to - the power of ``N - i - 1``. Such a matrix with a geometric progression - in each row is named Van Der Monde, or Vandermonde matrix, from - Alexandre-Theophile Vandermonde. + vector. Specifically, the `i`-th output column is the input vector + raised element-wise to the power of ``N - i - 1``. Such a matrix with + a geometric progression in each row is named for Alexandre-Theophile + Vandermonde. Parameters ---------- x : array_like 1-D input array. N : int, optional - Order of (number of columns in) the output. If `N` is not specified, + Order of (number of columns in) the output. If `N` is not specified, a square array is returned (``N = len(x)``). Returns @@ -467,11 +472,6 @@ Van der Monde matrix of order `N`. The first column is ``x^(N-1)``, the second ``x^(N-2)`` and so forth. - References - ---------- - .. [1] Wikipedia, "Vandermonde matrix", - http://en.wikipedia.org/wiki/Vandermonde_matrix - Examples -------- >>> x = np.array([1, 2, 3, 5]) @@ -586,10 +586,12 @@ We can now use the Matplotlib to visualize this 2-dimensional histogram: - >>> extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] + >>> extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]] >>> import matplotlib.pyplot as plt - >>> plt.imshow(H, extent=extent) + >>> plt.imshow(H, extent=extent, interpolation='nearest') + >>> plt.colorbar() + >>> plt.show() """ From numpy-svn at scipy.org Sun Aug 1 07:22:14 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:22:14 -0500 (CDT) Subject: [Numpy-svn] r8585 - in branches/1.5.x/numpy: . matrixlib Message-ID: <20100801112214.3CB1539CE12@scipy.org> Author: rgommers Date: 2010-08-01 06:22:14 -0500 (Sun, 01 Aug 2010) New Revision: 8585 Modified: branches/1.5.x/numpy/add_newdocs.py branches/1.5.x/numpy/matrixlib/__init__.py branches/1.5.x/numpy/matrixlib/defmatrix.py Log: DOC: wiki merge, matrlixlib and some ndarray methods. Modified: branches/1.5.x/numpy/add_newdocs.py =================================================================== --- branches/1.5.x/numpy/add_newdocs.py 2010-08-01 11:21:57 UTC (rev 8584) +++ branches/1.5.x/numpy/add_newdocs.py 2010-08-01 11:22:14 UTC (rev 8585) @@ -2748,7 +2748,7 @@ """ a.put(indices, values, mode='raise') - Set a.flat[n] = values[n] for all n in indices. + Set ``a.flat[n] = values[n]`` for all `n` in indices. Refer to `numpy.put` for full documentation. @@ -2942,7 +2942,7 @@ """ a.round(decimals=0, out=None) - Return an array rounded a to the given number of decimals. + Return `a` with each element rounded to the given number of decimals. Refer to `numpy.around` for full documentation. @@ -3208,7 +3208,7 @@ """ a.take(indices, axis=None, out=None, mode='raise') - Return an array formed from the elements of a at the given indices. + Return an array formed from the elements of `a` at the given indices. Refer to `numpy.take` for full documentation. @@ -3418,24 +3418,26 @@ Parameters ---------- - dtype : data-type - Data-type descriptor of the returned view, e.g. float32 or int16. - type : python type - Type of the returned view, e.g. ndarray or matrix. + dtype : data-type, optional + Data-type descriptor of the returned view, e.g., float32 or int16. + The default, None, results in the view having the same data-type + as `a`. + type : Python type, optional + Type of the returned view, e.g., ndarray or matrix. Again, the + default None results in type preservation. - Notes ----- + ``a.view()`` is used two different ways: - `a.view()` is used two different ways. - - `a.view(some_dtype)` or `a.view(dtype=some_dtype)` constructs a view of - the array's memory with a different dtype. This can cause a + ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view + of the array's memory with a different data-type. This can cause a reinterpretation of the bytes of memory. - `a.view(ndarray_subclass)`, or `a.view(type=ndarray_subclass)`, just - returns an instance of ndarray_subclass that looks at the same array (same - shape, dtype, etc.). This does not cause a reinterpretation of the memory. + ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just + returns an instance of `ndarray_subclass` that looks at the same array + (same shape, dtype, etc.) This does not cause a reinterpretation of the + memory. Examples Modified: branches/1.5.x/numpy/matrixlib/__init__.py =================================================================== --- branches/1.5.x/numpy/matrixlib/__init__.py 2010-08-01 11:21:57 UTC (rev 8584) +++ branches/1.5.x/numpy/matrixlib/__init__.py 2010-08-01 11:22:14 UTC (rev 8585) @@ -1,3 +1,4 @@ +"""Sub-package containing the matrix class and related functions.""" from defmatrix import * __all__ = defmatrix.__all__ Modified: branches/1.5.x/numpy/matrixlib/defmatrix.py =================================================================== --- branches/1.5.x/numpy/matrixlib/defmatrix.py 2010-08-01 11:21:57 UTC (rev 8584) +++ branches/1.5.x/numpy/matrixlib/defmatrix.py 2010-08-01 11:22:14 UTC (rev 8585) @@ -196,23 +196,22 @@ """ matrix(data, dtype=None, copy=True) - Returns a matrix from an array-like object, or from a string - of data. A matrix is a specialized 2-d array that retains - its 2-d nature through operations. It has certain special - operators, such as ``*`` (matrix multiplication) and - ``**`` (matrix power). + Returns a matrix from an array-like object, or from a string of data. + A matrix is a specialized 2-D array that retains its 2-D nature + through operations. It has certain special operators, such as ``*`` + (matrix multiplication) and ``**`` (matrix power). Parameters ---------- data : array_like or string - If data is a string, the string is interpreted as a matrix - with commas or spaces separating columns, and semicolons - separating rows. + If `data` is a string, it is interpreted as a matrix with commas + or spaces separating columns, and semicolons separating rows. dtype : data-type Data-type of the output matrix. copy : bool - If data is already an ndarray, then this flag determines whether - the data is copied, or whether a view is constructed. + If `data` is already an `ndarray`, then this flag determines + whether the data is copied (the default), or whether a view is + constructed. See Also -------- @@ -1009,9 +1008,9 @@ Parameters ---------- - obj : string, sequence or array - Input data. Variables names in the current scope may - be referenced, even if `obj` is a string. + obj : str or array_like + Input data. Names of variables in the current scope may be + referenced, even if `obj` is a string. Returns ------- From numpy-svn at scipy.org Sun Aug 1 07:36:22 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:36:22 -0500 (CDT) Subject: [Numpy-svn] r8586 - branches/1.5.x Message-ID: <20100801113622.B3E4F39CE15@scipy.org> Author: rgommers Date: 2010-08-01 06:36:22 -0500 (Sun, 01 Aug 2010) New Revision: 8586 Modified: branches/1.5.x/setup.py Log: REL: Set version to 1.5.0b1, released = True. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-01 11:22:14 UTC (rev 8585) +++ branches/1.5.x/setup.py 2010-08-01 11:36:22 UTC (rev 8586) @@ -56,8 +56,8 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = False -VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) +ISRELEASED = True +VERSION = '%d.%d.%db1' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise def svn_version(): From numpy-svn at scipy.org Sun Aug 1 07:37:13 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 1 Aug 2010 06:37:13 -0500 (CDT) Subject: [Numpy-svn] r8587 - tags Message-ID: <20100801113713.D675639CE18@scipy.org> Author: rgommers Date: 2010-08-01 06:37:13 -0500 (Sun, 01 Aug 2010) New Revision: 8587 Added: tags/1.5.0b1/ Log: Create tag 1.5.0b1 Copied: tags/1.5.0b1 (from rev 8586, branches/1.5.x) From numpy-svn at scipy.org Tue Aug 3 17:37:48 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:37:48 -0500 (CDT) Subject: [Numpy-svn] r8588 - trunk/numpy/core/src/multiarray Message-ID: <20100803213748.C7B3C39CC9C@scipy.org> Author: ptvirtan Date: 2010-08-03 16:37:48 -0500 (Tue, 03 Aug 2010) New Revision: 8588 Modified: trunk/numpy/core/src/multiarray/convert_datatype.c Log: BUG: core: fix a missed PyCObject call (#1571) Modified: trunk/numpy/core/src/multiarray/convert_datatype.c =================================================================== --- trunk/numpy/core/src/multiarray/convert_datatype.c 2010-08-01 11:37:13 UTC (rev 8587) +++ trunk/numpy/core/src/multiarray/convert_datatype.c 2010-08-03 21:37:48 UTC (rev 8588) @@ -103,7 +103,7 @@ cobj = PyDict_GetItem(obj, key); Py_DECREF(key); if (NpyCapsule_Check(cobj)) { - castfunc = PyCObject_AsVoidPtr(cobj); + castfunc = NpyCapsule_AsVoidPtr(cobj); } } } From numpy-svn at scipy.org Tue Aug 3 17:38:16 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:38:16 -0500 (CDT) Subject: [Numpy-svn] r8589 - trunk/numpy/core/code_generators Message-ID: <20100803213816.61D4839CC9C@scipy.org> Author: ptvirtan Date: 2010-08-03 16:38:16 -0500 (Tue, 03 Aug 2010) New Revision: 8589 Modified: trunk/numpy/core/code_generators/generate_umath.py Log: BUG: core/3K: use bytes.maketrans instead of the deprecated string.maketrans (fixes #1571) Modified: trunk/numpy/core/code_generators/generate_umath.py =================================================================== --- trunk/numpy/core/code_generators/generate_umath.py 2010-08-03 21:37:48 UTC (rev 8588) +++ trunk/numpy/core/code_generators/generate_umath.py 2010-08-03 21:38:16 UTC (rev 8589) @@ -113,7 +113,7 @@ if sys.version_info[0] < 3: UPPER_TABLE = string.maketrans(string.ascii_lowercase, string.ascii_uppercase) else: - UPPER_TABLE = string.maketrans(bytes(string.ascii_lowercase, "ascii"), + UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, "ascii"), bytes(string.ascii_uppercase, "ascii")) def english_upper(s): From numpy-svn at scipy.org Tue Aug 3 17:51:40 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:51:40 -0500 (CDT) Subject: [Numpy-svn] r8590 - branches/1.5.x Message-ID: <20100803215140.7748139CCEE@scipy.org> Author: ptvirtan Date: 2010-08-03 16:51:40 -0500 (Tue, 03 Aug 2010) New Revision: 8590 Modified: branches/1.5.x/setup.py Log: REL: Set as released=False Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-03 21:38:16 UTC (rev 8589) +++ branches/1.5.x/setup.py 2010-08-03 21:51:40 UTC (rev 8590) @@ -56,7 +56,7 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = True +ISRELEASED = False VERSION = '%d.%d.%db1' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise From numpy-svn at scipy.org Tue Aug 3 17:52:04 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:52:04 -0500 (CDT) Subject: [Numpy-svn] r8591 - in branches/1.5.x/numpy/core: src/multiarray tests Message-ID: <20100803215204.EE6DF39CCEE@scipy.org> Author: ptvirtan Date: 2010-08-03 16:52:04 -0500 (Tue, 03 Aug 2010) New Revision: 8591 Modified: branches/1.5.x/numpy/core/src/multiarray/methods.c branches/1.5.x/numpy/core/tests/test_regression.py Log: BUG: (backport r8548) core/umath: do not create views unnecessarily in ndarray.__array_prepare__ (fixes #1548) Modified: branches/1.5.x/numpy/core/src/multiarray/methods.c =================================================================== --- branches/1.5.x/numpy/core/src/multiarray/methods.c 2010-08-03 21:51:40 UTC (rev 8590) +++ branches/1.5.x/numpy/core/src/multiarray/methods.c 2010-08-03 21:52:04 UTC (rev 8591) @@ -843,6 +843,12 @@ return NULL; } + if (Py_TYPE(self) == Py_TYPE(arr)) { + /* No need to create a new view */ + Py_INCREF(arr); + return arr; + } + Py_INCREF(PyArray_DESCR(arr)); ret = PyArray_NewFromDescr(Py_TYPE(self), PyArray_DESCR(arr), Modified: branches/1.5.x/numpy/core/tests/test_regression.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-03 21:51:40 UTC (rev 8590) +++ branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-03 21:52:04 UTC (rev 8591) @@ -1350,5 +1350,13 @@ x[(0,)] = 2 # shouldn't raise an exception assert_equal(x[0], 2) + def test_ufunc_no_unnecessary_views(self): + # ticket #1548 + class Subclass(np.ndarray): + pass + x = np.array([1,2,3]).view(Subclass) + y = np.add(x, x, x) + assert_equal(id(x), id(y)) + if __name__ == "__main__": run_module_suite() From numpy-svn at scipy.org Tue Aug 3 17:52:29 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:52:29 -0500 (CDT) Subject: [Numpy-svn] r8592 - in branches/1.5.x/numpy/core: src/multiarray tests Message-ID: <20100803215229.92F6139CCEE@scipy.org> Author: ptvirtan Date: 2010-08-03 16:52:29 -0500 (Tue, 03 Aug 2010) New Revision: 8592 Modified: branches/1.5.x/numpy/core/src/multiarray/item_selection.c branches/1.5.x/numpy/core/tests/test_regression.py Log: BUG: (backport r8572) core: fix refcount error in PyArray_Take (#939) Modified: branches/1.5.x/numpy/core/src/multiarray/item_selection.c =================================================================== --- branches/1.5.x/numpy/core/src/multiarray/item_selection.c 2010-08-03 21:52:04 UTC (rev 8591) +++ branches/1.5.x/numpy/core/src/multiarray/item_selection.c 2010-08-03 21:52:29 UTC (rev 8592) @@ -43,6 +43,7 @@ PyArray_INTP, 1, 0); if (indices == NULL) { + Py_XINCREF(ret); goto fail; } n = m = chunk = 1; Modified: branches/1.5.x/numpy/core/tests/test_regression.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-03 21:52:04 UTC (rev 8591) +++ branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-03 21:52:29 UTC (rev 8592) @@ -1358,5 +1358,19 @@ y = np.add(x, x, x) assert_equal(id(x), id(y)) + def test_take_refcount(self): + # ticket #939 + a = np.arange(16, dtype=np.float) + a.shape = (4,4) + lut = np.ones((5 + 3, 4), np.float) + rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype) + c1 = sys.getrefcount(rgba) + try: + lut.take(a, axis=0, mode='clip', out=rgba) + except TypeError: + pass + c2 = sys.getrefcount(rgba) + assert_equal(c1, c2) + if __name__ == "__main__": run_module_suite() From numpy-svn at scipy.org Tue Aug 3 17:52:53 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:52:53 -0500 (CDT) Subject: [Numpy-svn] r8593 - branches/1.5.x/numpy/core/src/multiarray Message-ID: <20100803215253.4980E39CCEE@scipy.org> Author: ptvirtan Date: 2010-08-03 16:52:53 -0500 (Tue, 03 Aug 2010) New Revision: 8593 Modified: branches/1.5.x/numpy/core/src/multiarray/convert_datatype.c Log: BUG: (backport r8588) core: fix a missed PyCObject call (#1571) Modified: branches/1.5.x/numpy/core/src/multiarray/convert_datatype.c =================================================================== --- branches/1.5.x/numpy/core/src/multiarray/convert_datatype.c 2010-08-03 21:52:29 UTC (rev 8592) +++ branches/1.5.x/numpy/core/src/multiarray/convert_datatype.c 2010-08-03 21:52:53 UTC (rev 8593) @@ -103,7 +103,7 @@ cobj = PyDict_GetItem(obj, key); Py_DECREF(key); if (NpyCapsule_Check(cobj)) { - castfunc = PyCObject_AsVoidPtr(cobj); + castfunc = NpyCapsule_AsVoidPtr(cobj); } } } From numpy-svn at scipy.org Tue Aug 3 17:53:13 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 16:53:13 -0500 (CDT) Subject: [Numpy-svn] r8594 - branches/1.5.x/numpy/core/code_generators Message-ID: <20100803215313.D62DB39CCEE@scipy.org> Author: ptvirtan Date: 2010-08-03 16:53:13 -0500 (Tue, 03 Aug 2010) New Revision: 8594 Modified: branches/1.5.x/numpy/core/code_generators/generate_umath.py Log: BUG: (backport r8589) core/3K: use bytes.maketrans instead of the deprecated string.maketrans (fixes #1571) Modified: branches/1.5.x/numpy/core/code_generators/generate_umath.py =================================================================== --- branches/1.5.x/numpy/core/code_generators/generate_umath.py 2010-08-03 21:52:53 UTC (rev 8593) +++ branches/1.5.x/numpy/core/code_generators/generate_umath.py 2010-08-03 21:53:13 UTC (rev 8594) @@ -113,7 +113,7 @@ if sys.version_info[0] < 3: UPPER_TABLE = string.maketrans(string.ascii_lowercase, string.ascii_uppercase) else: - UPPER_TABLE = string.maketrans(bytes(string.ascii_lowercase, "ascii"), + UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, "ascii"), bytes(string.ascii_uppercase, "ascii")) def english_upper(s): From numpy-svn at scipy.org Tue Aug 3 18:21:09 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 3 Aug 2010 17:21:09 -0500 (CDT) Subject: [Numpy-svn] r8595 - trunk/numpy/distutils Message-ID: <20100803222109.8C8FA39CC9C@scipy.org> Author: ptvirtan Date: 2010-08-03 17:21:09 -0500 (Tue, 03 Aug 2010) New Revision: 8595 Modified: trunk/numpy/distutils/mingw32ccompiler.py Log: 3K: distutils: fix __code__ object access in mingw32ccompiler Modified: trunk/numpy/distutils/mingw32ccompiler.py =================================================================== --- trunk/numpy/distutils/mingw32ccompiler.py 2010-08-03 21:53:13 UTC (rev 8594) +++ trunk/numpy/distutils/mingw32ccompiler.py 2010-08-03 22:21:09 UTC (rev 8595) @@ -174,7 +174,10 @@ func = distutils.cygwinccompiler.CygwinCCompiler.link else: func = UnixCCompiler.link - func(*args[:func.im_func.func_code.co_argcount]) + if sys.version_info[0] >= 3: + func(*args[:func.__code__.co_argcount]) + else: + func(*args[:func.im_func.func_code.co_argcount]) return def object_filenames (self, From numpy-svn at scipy.org Wed Aug 4 06:45:51 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 4 Aug 2010 05:45:51 -0500 (CDT) Subject: [Numpy-svn] r8596 - trunk Message-ID: <20100804104551.3587B39CB4B@scipy.org> Author: rgommers Date: 2010-08-04 05:45:51 -0500 (Wed, 04 Aug 2010) New Revision: 8596 Modified: trunk/setup.py Log: BUG: add tools/py3tool.py to installed/distributed files. Modified: trunk/setup.py =================================================================== --- trunk/setup.py 2010-08-03 22:21:09 UTC (rev 8595) +++ trunk/setup.py 2010-08-04 10:45:51 UTC (rev 8596) @@ -54,7 +54,7 @@ AUTHOR_EMAIL = "oliphant at enthought.com" PLATFORMS = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"] MAJOR = 2 -MINOR = 0 +MINOR = 0 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) @@ -152,7 +152,8 @@ config.add_data_files(('numpy','*.txt'), ('numpy','COMPATIBILITY'), - ('numpy','site.cfg.example')) + ('numpy','site.cfg.example'), + ('numpy/tools', 'tools/py3tool.py')) config.get_version('numpy/version.py') # sets config.version From numpy-svn at scipy.org Wed Aug 4 06:57:50 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 4 Aug 2010 05:57:50 -0500 (CDT) Subject: [Numpy-svn] r8597 - branches/1.5.x Message-ID: <20100804105750.2204339CB4B@scipy.org> Author: rgommers Date: 2010-08-04 05:57:50 -0500 (Wed, 04 Aug 2010) New Revision: 8597 Modified: branches/1.5.x/setup.py Log: BUG: (backport of r8596) add tool/py3tool.py to installed/distributed files. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-04 10:45:51 UTC (rev 8596) +++ branches/1.5.x/setup.py 2010-08-04 10:57:50 UTC (rev 8597) @@ -152,7 +152,8 @@ config.add_data_files(('numpy','*.txt'), ('numpy','COMPATIBILITY'), - ('numpy','site.cfg.example')) + ('numpy','site.cfg.example'), + ('numpy/tools', 'tools/py3tool.py')) config.get_version('numpy/version.py') # sets config.version From numpy-svn at scipy.org Wed Aug 4 08:01:30 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 4 Aug 2010 07:01:30 -0500 (CDT) Subject: [Numpy-svn] r8598 - trunk Message-ID: <20100804120130.38D7A39CD13@scipy.org> Author: ptvirtan Date: 2010-08-04 07:01:29 -0500 (Wed, 04 Aug 2010) New Revision: 8598 Modified: trunk/MANIFEST.in trunk/setup.py Log: ENH: include /*.txt etc. in source dist only, rather than installing it Modified: trunk/MANIFEST.in =================================================================== --- trunk/MANIFEST.in 2010-08-04 10:57:50 UTC (rev 8597) +++ trunk/MANIFEST.in 2010-08-04 12:01:29 UTC (rev 8598) @@ -4,10 +4,13 @@ # data, etc files to distribution. Avoid using MANIFEST.in for that. # include MANIFEST.in -include LICENSE.txt +include COMPATIBILITY +include *.txt include setupscons.py include setupsconsegg.py include setupegg.py +include site.cfg.example +include tools/py3tool.py # Adding scons build related files not found by distutils recursive-include numpy/core/code_generators *.py *.txt recursive-include numpy/core *.in *.h Modified: trunk/setup.py =================================================================== --- trunk/setup.py 2010-08-04 10:57:50 UTC (rev 8597) +++ trunk/setup.py 2010-08-04 12:01:29 UTC (rev 8598) @@ -150,11 +150,6 @@ config.add_subpackage('numpy') - config.add_data_files(('numpy','*.txt'), - ('numpy','COMPATIBILITY'), - ('numpy','site.cfg.example'), - ('numpy/tools', 'tools/py3tool.py')) - config.get_version('numpy/version.py') # sets config.version return config From numpy-svn at scipy.org Wed Aug 4 15:40:55 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 4 Aug 2010 14:40:55 -0500 (CDT) Subject: [Numpy-svn] r8599 - trunk/numpy/core/blasdot Message-ID: <20100804194055.85C3439CCEE@scipy.org> Author: ptvirtan Date: 2010-08-04 14:40:55 -0500 (Wed, 04 Aug 2010) New Revision: 8599 Modified: trunk/numpy/core/blasdot/_dotblas.c Log: 3K: fix core/dotblas module initialization. Modified: trunk/numpy/core/blasdot/_dotblas.c =================================================================== --- trunk/numpy/core/blasdot/_dotblas.c 2010-08-04 12:01:29 UTC (rev 8598) +++ trunk/numpy/core/blasdot/_dotblas.c 2010-08-04 19:40:55 UTC (rev 8599) @@ -2,6 +2,7 @@ "This module provides a BLAS optimized\nmatrix multiply, inner product and dot for numpy arrays"; #include "Python.h" +#include "npy_config.h" #include "numpy/ndarrayobject.h" #ifndef CBLAS_HEADER #define CBLAS_HEADER "cblas.h" @@ -1174,13 +1175,38 @@ {NULL, NULL, 0, NULL} /* sentinel */ }; +#if defined(NPY_PY3K) +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "_dotblas", + NULL, + -1, + dotblas_module_methods, + NULL, + NULL, + NULL, + NULL +}; +#endif + /* Initialization function for the module */ -PyMODINIT_FUNC init_dotblas(void) { +#if defined(NPY_PY3K) +#define RETVAL m +PyObject *PyInit__dotblas(void) +#else +#define RETVAL +PyMODINIT_FUNC init_dotblas(void) +#endif +{ int i; - PyObject *d, *s; + PyObject *d, *s, *m; /* Create the module and add the functions */ - Py_InitModule3("_dotblas", dotblas_module_methods, module_doc); +#if defined(NPY_PY3K) + m = PyModule_Create(&moduledef); +#else + m = Py_InitModule3("_dotblas", dotblas_module_methods, module_doc); +#endif /* Import the array object */ import_array(); @@ -1195,4 +1221,5 @@ Py_DECREF(d); Py_DECREF(s); + return RETVAL; } From numpy-svn at scipy.org Wed Aug 4 15:54:58 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 4 Aug 2010 14:54:58 -0500 (CDT) Subject: [Numpy-svn] r8600 - branches/1.5.x/numpy/core/blasdot Message-ID: <20100804195458.6016F39CCC0@scipy.org> Author: ptvirtan Date: 2010-08-04 14:54:58 -0500 (Wed, 04 Aug 2010) New Revision: 8600 Modified: branches/1.5.x/numpy/core/blasdot/_dotblas.c Log: 3K: (backport r8599) fix core/dotblas module initialization. Modified: branches/1.5.x/numpy/core/blasdot/_dotblas.c =================================================================== --- branches/1.5.x/numpy/core/blasdot/_dotblas.c 2010-08-04 19:40:55 UTC (rev 8599) +++ branches/1.5.x/numpy/core/blasdot/_dotblas.c 2010-08-04 19:54:58 UTC (rev 8600) @@ -2,6 +2,7 @@ "This module provides a BLAS optimized\nmatrix multiply, inner product and dot for numpy arrays"; #include "Python.h" +#include "npy_config.h" #include "numpy/ndarrayobject.h" #ifndef CBLAS_HEADER #define CBLAS_HEADER "cblas.h" @@ -1174,13 +1175,38 @@ {NULL, NULL, 0, NULL} /* sentinel */ }; +#if defined(NPY_PY3K) +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "_dotblas", + NULL, + -1, + dotblas_module_methods, + NULL, + NULL, + NULL, + NULL +}; +#endif + /* Initialization function for the module */ -PyMODINIT_FUNC init_dotblas(void) { +#if defined(NPY_PY3K) +#define RETVAL m +PyObject *PyInit__dotblas(void) +#else +#define RETVAL +PyMODINIT_FUNC init_dotblas(void) +#endif +{ int i; - PyObject *d, *s; + PyObject *d, *s, *m; /* Create the module and add the functions */ - Py_InitModule3("_dotblas", dotblas_module_methods, module_doc); +#if defined(NPY_PY3K) + m = PyModule_Create(&moduledef); +#else + m = Py_InitModule3("_dotblas", dotblas_module_methods, module_doc); +#endif /* Import the array object */ import_array(); @@ -1195,4 +1221,5 @@ Py_DECREF(d); Py_DECREF(s); + return RETVAL; } From numpy-svn at scipy.org Thu Aug 5 06:23:03 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 5 Aug 2010 05:23:03 -0500 (CDT) Subject: [Numpy-svn] r8601 - trunk Message-ID: <20100805102303.5251E39CCEE@scipy.org> Author: rgommers Date: 2010-08-05 05:23:03 -0500 (Thu, 05 Aug 2010) New Revision: 8601 Modified: trunk/pavement.py Log: 3K: copy built installers from build/py3k/dist instead of dist/. Modified: trunk/pavement.py =================================================================== --- trunk/pavement.py 2010-08-04 19:54:58 UTC (rev 8600) +++ trunk/pavement.py 2010-08-05 10:23:03 UTC (rev 8601) @@ -194,7 +194,10 @@ pyver = options.python_version def copy_bdist(arch): # Copy the wininst in dist into the release directory - source = os.path.join('dist', wininst_name(pyver)) + if pyver[0] >= 3: + source = os.path.join('build', 'py3k', 'dist', wininst_name(pyver)) + else: + source = os.path.join('dist', wininst_name(pyver)) target = os.path.join(SUPERPACK_BINDIR, internal_wininst_name(arch)) if os.path.exists(target): os.remove(target) From numpy-svn at scipy.org Thu Aug 5 06:24:59 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 5 Aug 2010 05:24:59 -0500 (CDT) Subject: [Numpy-svn] r8602 - branches/1.5.x/numpy/distutils Message-ID: <20100805102459.C9C2D39CCEE@scipy.org> Author: rgommers Date: 2010-08-05 05:24:59 -0500 (Thu, 05 Aug 2010) New Revision: 8602 Modified: branches/1.5.x/numpy/distutils/mingw32ccompiler.py Log: 3K: (backport of r8595) distutils: fix __code__ object access in mingw32ccompiler Modified: branches/1.5.x/numpy/distutils/mingw32ccompiler.py =================================================================== --- branches/1.5.x/numpy/distutils/mingw32ccompiler.py 2010-08-05 10:23:03 UTC (rev 8601) +++ branches/1.5.x/numpy/distutils/mingw32ccompiler.py 2010-08-05 10:24:59 UTC (rev 8602) @@ -174,7 +174,10 @@ func = distutils.cygwinccompiler.CygwinCCompiler.link else: func = UnixCCompiler.link - func(*args[:func.im_func.func_code.co_argcount]) + if sys.version_info[0] >= 3: + func(*args[:func.__code__.co_argcount]) + else: + func(*args[:func.im_func.func_code.co_argcount]) return def object_filenames (self, From numpy-svn at scipy.org Thu Aug 5 06:25:13 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 5 Aug 2010 05:25:13 -0500 (CDT) Subject: [Numpy-svn] r8603 - branches/1.5.x Message-ID: <20100805102513.738D739CCEE@scipy.org> Author: rgommers Date: 2010-08-05 05:25:13 -0500 (Thu, 05 Aug 2010) New Revision: 8603 Modified: branches/1.5.x/pavement.py Log: 3K: (backport of r8601) copy built installers from build/py3k/dist instead of dist/. Modified: branches/1.5.x/pavement.py =================================================================== --- branches/1.5.x/pavement.py 2010-08-05 10:24:59 UTC (rev 8602) +++ branches/1.5.x/pavement.py 2010-08-05 10:25:13 UTC (rev 8603) @@ -202,7 +202,10 @@ pyver = options.python_version def copy_bdist(arch): # Copy the wininst in dist into the release directory - source = os.path.join('dist', wininst_name(pyver)) + if pyver[0] >= 3: + source = os.path.join('build', 'py3k', 'dist', wininst_name(pyver)) + else: + source = os.path.join('dist', wininst_name(pyver)) target = os.path.join(SUPERPACK_BINDIR, internal_wininst_name(arch)) if os.path.exists(target): os.remove(target) From numpy-svn at scipy.org Thu Aug 5 06:50:36 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 5 Aug 2010 05:50:36 -0500 (CDT) Subject: [Numpy-svn] r8604 - trunk/numpy/ma Message-ID: <20100805105036.EDA5E39CCEE@scipy.org> Author: rgommers Date: 2010-08-05 05:50:36 -0500 (Thu, 05 Aug 2010) New Revision: 8604 Modified: trunk/numpy/ma/extras.py Log: DEP: Remove ma.extras functions that were deprecated in 1.4.0. Modified: trunk/numpy/ma/extras.py =================================================================== --- trunk/numpy/ma/extras.py 2010-08-05 10:25:13 UTC (rev 8603) +++ trunk/numpy/ma/extras.py 2010-08-05 10:50:36 UTC (rev 8604) @@ -22,14 +22,14 @@ 'ediff1d', 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack', - 'in1d', 'intersect1d', 'intersect1d_nu', + 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows', 'masked_all', 'masked_all_like', 'median', 'mr_', 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack', - 'setdiff1d', 'setmember1d', 'setxor1d', - 'unique', 'unique1d', 'union1d', + 'setdiff1d', 'setxor1d', + 'unique', 'union1d', 'vander', 'vstack', ] @@ -48,7 +48,6 @@ from numpy.lib.index_tricks import AxisConcatenator from numpy.linalg import lstsq -from numpy.lib.utils import deprecate #............................................................................... def issequence(seq): @@ -1199,56 +1198,7 @@ else: return ma.asarray(ar1)[aux == 0] - at deprecate -def unique1d(ar1, return_index=False, return_inverse=False): - """ This function is deprecated. Use ma.unique() instead. """ - output = np.unique1d(ar1, - return_index=return_index, - return_inverse=return_inverse) - if isinstance(output, tuple): - output = list(output) - output[0] = output[0].view(MaskedArray) - output = tuple(output) - else: - output = output.view(MaskedArray) - return output - at deprecate -def intersect1d_nu(ar1, ar2): - """ This function is deprecated. Use ma.intersect1d() instead.""" - # Might be faster than unique1d( intersect1d( ar1, ar2 ) )? - aux = ma.concatenate((unique1d(ar1), unique1d(ar2))) - aux.sort() - return aux[aux[1:] == aux[:-1]] - - at deprecate -def setmember1d(ar1, ar2): - """ This function is deprecated. Use ma.in1d() instead.""" - ar1 = ma.asanyarray(ar1) - ar2 = ma.asanyarray(ar2) - ar = ma.concatenate((ar1, ar2)) - b1 = ma.zeros(ar1.shape, dtype=np.int8) - b2 = ma.ones(ar2.shape, dtype=np.int8) - tt = ma.concatenate((b1, b2)) - - # We need this to be a stable sort, so always use 'mergesort' here. The - # values from the first array should always come before the values from the - # second array. - perm = ar.argsort(kind='mergesort') - aux = ar[perm] - aux2 = tt[perm] -# flag = ediff1d( aux, 1 ) == 0 - flag = ma.concatenate((aux[1:] == aux[:-1], [False])) - ii = ma.where(flag * aux2)[0] - aux = perm[ii + 1] - perm[ii + 1] = perm[ii] - perm[ii] = aux - # - indx = perm.argsort(kind='mergesort')[:len(ar1)] - # - return flag[indx] - - #####-------------------------------------------------------------------------- #---- --- Covariance --- #####-------------------------------------------------------------------------- From numpy-svn at scipy.org Sat Aug 7 21:02:46 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 7 Aug 2010 20:02:46 -0500 (CDT) Subject: [Numpy-svn] r8605 - trunk/doc/sphinxext Message-ID: <20100808010246.3143539CAEC@scipy.org> Author: ptvirtan Date: 2010-08-07 20:02:46 -0500 (Sat, 07 Aug 2010) New Revision: 8605 Modified: trunk/doc/sphinxext/plot_directive.py Log: sphinxext: bug fix + some features in plot_directive Modified: trunk/doc/sphinxext/plot_directive.py =================================================================== --- trunk/doc/sphinxext/plot_directive.py 2010-08-05 10:50:36 UTC (rev 8604) +++ trunk/doc/sphinxext/plot_directive.py 2010-08-08 01:02:46 UTC (rev 8605) @@ -64,6 +64,9 @@ that determine the file format and the DPI. For entries whose DPI was omitted, sensible defaults are chosen. + plot_html_show_formats + Whether to show links to the files in HTML. + TODO ---- @@ -96,6 +99,7 @@ app.add_config_value('plot_include_source', False, True) app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) app.add_config_value('plot_basedir', None, True) + app.add_config_value('plot_html_show_formats', True, True) app.add_directive('plot', plot_directive, True, (0, 1, False), **plot_directive_options) @@ -174,19 +178,24 @@ {{ option }} {% endfor %} - ( {%- if not source_code -%} - `Source code <{{source_link}}>`__ + (`Source code <{{source_link}}>`__ + {%- if html_show_formats -%} {%- for fmt in img.formats -%} , `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} + {%- endif -%} + ) {%- else -%} + {%- if html_show_formats -%} + ( {%- for fmt in img.formats -%} {%- if not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} + ) + {%- endif -%} {%- endif -%} - ) {% endfor %} {{ only_latex }} @@ -321,12 +330,12 @@ only_latex=only_latex, options=opts, images=images, - source_code=source_code) + source_code=source_code, + html_show_formats=config.plot_html_show_formats) lines = result.split("\n") if len(lines): - state_machine.insert_input( - lines, state_machine.input_lines.source(0)) + state_machine.insert_input(lines, source=source_file_name) # copy image files to builder's output directory if not os.path.exists(dest_dir): From numpy-svn at scipy.org Sun Aug 8 02:41:28 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 8 Aug 2010 01:41:28 -0500 (CDT) Subject: [Numpy-svn] r8606 - trunk/numpy/core/tests Message-ID: <20100808064128.B72BA39CAEC@scipy.org> Author: rgommers Date: 2010-08-08 01:41:28 -0500 (Sun, 08 Aug 2010) New Revision: 8606 Modified: trunk/numpy/core/tests/test_memmap.py Log: TST: fix memmap test error. Closes #1550. Thanks to Christoph Gohlke. Modified: trunk/numpy/core/tests/test_memmap.py =================================================================== --- trunk/numpy/core/tests/test_memmap.py 2010-08-08 01:02:46 UTC (rev 8605) +++ trunk/numpy/core/tests/test_memmap.py 2010-08-08 06:41:28 UTC (rev 8606) @@ -56,6 +56,7 @@ self.assertEquals(abspath, fp.filename) b = fp[:1] self.assertEquals(abspath, b.filename) + del b del fp os.unlink(tmpname) From numpy-svn at scipy.org Sun Aug 8 02:43:28 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 8 Aug 2010 01:43:28 -0500 (CDT) Subject: [Numpy-svn] r8607 - branches/1.5.x/numpy/core/tests Message-ID: <20100808064328.6836E39CAEC@scipy.org> Author: rgommers Date: 2010-08-08 01:43:28 -0500 (Sun, 08 Aug 2010) New Revision: 8607 Modified: branches/1.5.x/numpy/core/tests/test_memmap.py Log: TST: (backport of r8606) fix memmap test error. Closes #1550. Thanks to Christoph Gohlke. Modified: branches/1.5.x/numpy/core/tests/test_memmap.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_memmap.py 2010-08-08 06:41:28 UTC (rev 8606) +++ branches/1.5.x/numpy/core/tests/test_memmap.py 2010-08-08 06:43:28 UTC (rev 8607) @@ -56,6 +56,7 @@ self.assertEquals(abspath, fp.filename) b = fp[:1] self.assertEquals(abspath, b.filename) + del b del fp os.unlink(tmpname) From numpy-svn at scipy.org Sun Aug 8 03:32:32 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 8 Aug 2010 02:32:32 -0500 (CDT) Subject: [Numpy-svn] r8608 - trunk/numpy/core Message-ID: <20100808073232.6DBF839CAEC@scipy.org> Author: rgommers Date: 2010-08-08 02:32:32 -0500 (Sun, 08 Aug 2010) New Revision: 8608 Modified: trunk/numpy/core/shape_base.py Log: ENH: Make atleast_3d respect ndarray subclasses. Closes #1560. Modified: trunk/numpy/core/shape_base.py =================================================================== --- trunk/numpy/core/shape_base.py 2010-08-08 06:43:28 UTC (rev 8607) +++ trunk/numpy/core/shape_base.py 2010-08-08 07:32:32 UTC (rev 8608) @@ -1,7 +1,7 @@ __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack'] import numeric as _nx -from numeric import array, asarray, newaxis +from numeric import array, asanyarray, newaxis def atleast_1d(*arys): """ @@ -146,7 +146,7 @@ """ res = [] for ary in arys: - ary = asarray(ary) + ary = asanyarray(ary) if len(ary.shape) == 0: result = ary.reshape(1,1,1) elif len(ary.shape) == 1: From numpy-svn at scipy.org Sun Aug 8 03:33:43 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 8 Aug 2010 02:33:43 -0500 (CDT) Subject: [Numpy-svn] r8609 - branches/1.5.x/numpy/core Message-ID: <20100808073343.1000A39CAEC@scipy.org> Author: rgommers Date: 2010-08-08 02:33:42 -0500 (Sun, 08 Aug 2010) New Revision: 8609 Modified: branches/1.5.x/numpy/core/shape_base.py Log: ENH: (backport of r8608) Make atleast_3d respect ndarray subclasses. Closes #1560. Modified: branches/1.5.x/numpy/core/shape_base.py =================================================================== --- branches/1.5.x/numpy/core/shape_base.py 2010-08-08 07:32:32 UTC (rev 8608) +++ branches/1.5.x/numpy/core/shape_base.py 2010-08-08 07:33:42 UTC (rev 8609) @@ -1,7 +1,7 @@ __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack'] import numeric as _nx -from numeric import array, asarray, newaxis +from numeric import array, asanyarray, newaxis def atleast_1d(*arys): """ @@ -146,7 +146,7 @@ """ res = [] for ary in arys: - ary = asarray(ary) + ary = asanyarray(ary) if len(ary.shape) == 0: result = ary.reshape(1,1,1) elif len(ary.shape) == 1: From numpy-svn at scipy.org Sun Aug 8 14:52:01 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 8 Aug 2010 13:52:01 -0500 (CDT) Subject: [Numpy-svn] r8610 - trunk/doc/sphinxext Message-ID: <20100808185201.3464E39CC26@scipy.org> Author: ptvirtan Date: 2010-08-08 13:52:01 -0500 (Sun, 08 Aug 2010) New Revision: 8610 Modified: trunk/doc/sphinxext/plot_directive.py Log: sphinxext: plot_directive: insert figures at points where plt.show() is called in the text Modified: trunk/doc/sphinxext/plot_directive.py =================================================================== --- trunk/doc/sphinxext/plot_directive.py 2010-08-08 07:33:42 UTC (rev 8609) +++ trunk/doc/sphinxext/plot_directive.py 2010-08-08 18:52:01 UTC (rev 8610) @@ -164,40 +164,38 @@ {{ only_html }} - {% if source_code %} - (`Source code <{{ source_link }}>`__) + {% if source_link or (html_show_formats and not multi_image) %} + ( + {%- if source_link -%} + `Source code <{{ source_link }}>`__ + {%- endif -%} + {%- if html_show_formats and not multi_image -%} + {%- for img in images -%} + {%- for fmt in img.formats -%} + {%- if source_link or not loop.first -%}, {% endif -%} + `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ + {%- endfor -%} + {%- endfor -%} + {%- endif -%} + ) + {% endif %} - .. admonition:: Output - :class: plot-output + {% for img in images %} + .. figure:: {{ build_dir }}/{{ img.basename }}.png + {%- for option in options %} + {{ option }} + {% endfor %} - {% endif %} + {% if html_show_formats and multi_image -%} + ( + {%- for fmt in img.formats -%} + {%- if not loop.first -%}, {% endif -%} + `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ + {%- endfor -%} + ) + {%- endif -%} + {% endfor %} - {% for img in images %} - .. figure:: {{ build_dir }}/{{ img.basename }}.png - {%- for option in options %} - {{ option }} - {% endfor %} - - {%- if not source_code -%} - (`Source code <{{source_link}}>`__ - {%- if html_show_formats -%} - {%- for fmt in img.formats -%} - , `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ - {%- endfor -%} - {%- endif -%} - ) - {%- else -%} - {%- if html_show_formats -%} - ( - {%- for fmt in img.formats -%} - {%- if not loop.first -%}, {% endif -%} - `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ - {%- endfor -%} - ) - {%- endif -%} - {%- endif -%} - {% endfor %} - {{ only_latex }} {% for img in images %} @@ -290,60 +288,75 @@ # make figures try: - images = makefig(code, source_file_name, build_dir, output_base, - config) + results = makefig(code, source_file_name, build_dir, output_base, + config) + errors = [] except PlotError, err: reporter = state.memo.reporter sm = reporter.system_message( - 3, "Exception occurred in plotting %s: %s" % (output_base, err), + 2, "Exception occurred in plotting %s: %s" % (output_base, err), line=lineno) - return [sm] + results = [(code, [])] + errors = [sm] # generate output restructuredtext - if options['include-source']: - if is_doctest: - lines = [''] - lines += [row.rstrip() for row in code.split('\n')] + total_lines = [] + for j, (code_piece, images) in enumerate(results): + if options['include-source']: + if is_doctest: + lines = [''] + lines += [row.rstrip() for row in code_piece.split('\n')] + else: + lines = ['.. code-block:: python', ''] + lines += [' %s' % row.rstrip() + for row in code_piece.split('\n')] + source_code = "\n".join(lines) else: - lines = ['.. code-block:: python', ''] - lines += [' %s' % row.rstrip() for row in code.split('\n')] - source_code = "\n".join(lines) - else: - source_code = "" + source_code = "" - opts = [':%s: %s' % (key, val) for key, val in options.items() - if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] + opts = [':%s: %s' % (key, val) for key, val in options.items() + if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] - if sphinx.__version__ >= "0.6": - only_html = ".. only:: html" - only_latex = ".. only:: latex" - else: - only_html = ".. htmlonly::" - only_latex = ".. latexonly::" + if sphinx.__version__ >= "0.6": + only_html = ".. only:: html" + only_latex = ".. only:: latex" + else: + only_html = ".. htmlonly::" + only_latex = ".. latexonly::" - result = format_template( - TEMPLATE, - dest_dir=dest_dir_link, - build_dir=build_dir_link, - source_link=source_link, - only_html=only_html, - only_latex=only_latex, - options=opts, - images=images, - source_code=source_code, - html_show_formats=config.plot_html_show_formats) + if j == 0: + src_link = source_link + else: + src_link = None - lines = result.split("\n") - if len(lines): - state_machine.insert_input(lines, source=source_file_name) + result = format_template( + TEMPLATE, + dest_dir=dest_dir_link, + build_dir=build_dir_link, + source_link=src_link, + multi_image=len(images) > 1, + only_html=only_html, + only_latex=only_latex, + options=opts, + images=images, + source_code=source_code, + html_show_formats=config.plot_html_show_formats) + total_lines.extend(result.split("\n")) + total_lines.extend("\n") + + if total_lines: + state_machine.insert_input(total_lines, source=source_file_name) + # copy image files to builder's output directory if not os.path.exists(dest_dir): os.makedirs(dest_dir) - for img in images: - for fn in img.filenames(): - shutil.copyfile(fn, os.path.join(dest_dir, os.path.basename(fn))) + for code_piece, images in results: + for img in images: + for fn in img.filenames(): + shutil.copyfile(fn, os.path.join(dest_dir, + os.path.basename(fn))) # copy script (if necessary) if source_file_name == rst_file: @@ -352,7 +365,7 @@ f.write(unescape_doctest(code)) f.close() - return [] + return errors #------------------------------------------------------------------------------ @@ -398,10 +411,32 @@ code += "\n" return code +def split_code_at_show(text): + """ + Split code at plt.show() + + """ + + parts = [] + is_doctest = contains_doctest(text) + + part = [] + for line in text.split("\n"): + if (not is_doctest and line.strip() == 'plt.show()') or \ + (is_doctest and line.strip() == '>>> plt.show()'): + part.append(line) + parts.append("\n".join(part)) + part = [] + else: + part.append(line) + if "\n".join(part).strip(): + parts.append("\n".join(part)) + return parts + class PlotError(RuntimeError): pass -def run_code(code, code_path): +def run_code(code, code_path, ns=None): # Change the working directory to the directory of the example, so # it can get at its data files, if any. pwd = os.getcwd() @@ -422,8 +457,10 @@ try: try: code = unescape_doctest(code) - ns = {} - exec setup.config.plot_pre_code in ns + if ns is None: + ns = {} + if not ns: + exec setup.config.plot_pre_code in ns exec code in ns except (Exception, SystemExit), err: raise PlotError(traceback.format_exc()) @@ -468,6 +505,8 @@ # -- Try to determine if all images already exist + code_pieces = split_code_at_show(code) + # Look for single-figure output files first all_exists = True img = ImageFile(output_base, output_dir) @@ -478,56 +517,68 @@ img.formats.append(format) if all_exists: - return [img] + return [(code, [img])] # Then look for multi-figure output files - images = [] + results = [] all_exists = True - for i in xrange(1000): - img = ImageFile('%s_%02d' % (output_base, i), output_dir) - for format, dpi in formats: - if out_of_date(code_path, img.filename(format)): - all_exists = False + for i, code_piece in enumerate(code_pieces): + images = [] + for j in xrange(1000): + img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir) + for format, dpi in formats: + if out_of_date(code_path, img.filename(format)): + all_exists = False + break + img.formats.append(format) + + # assume that if we have one, we have them all + if not all_exists: + all_exists = (j > 0) break - img.formats.append(format) - - # assume that if we have one, we have them all + images.append(img) if not all_exists: - all_exists = (i > 0) break - images.append(img) + results.append((code_piece, images)) if all_exists: - return images + return results # -- We didn't find the files, so build them - # Clear between runs - plt.close('all') + results = [] + ns = {} - # Run code - run_code(code, code_path) + for i, code_piece in enumerate(code_pieces): + # Clear between runs + plt.close('all') - # Collect images - images = [] + # Run code + run_code(code_piece, code_path, ns) - fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() - for i, figman in enumerate(fig_managers): - if len(fig_managers) == 1: - img = ImageFile(output_base, output_dir) - else: - img = ImageFile("%s_%02d" % (output_base, i), output_dir) - images.append(img) - for format, dpi in formats: - try: - figman.canvas.figure.savefig(img.filename(format), dpi=dpi) - except exceptions.BaseException, err: - raise PlotError(traceback.format_exc()) - img.formats.append(format) + # Collect images + images = [] + fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() + for j, figman in enumerate(fig_managers): + if len(fig_managers) == 1 and len(code_pieces) == 1: + img = ImageFile(output_base, output_dir) + else: + img = ImageFile("%s_%02d_%02d" % (output_base, i, j), + output_dir) + images.append(img) + for format, dpi in formats: + try: + figman.canvas.figure.savefig(img.filename(format), dpi=dpi) + except exceptions.BaseException, err: + raise PlotError(traceback.format_exc()) + img.formats.append(format) - return images + # Results + results.append((code_piece, images)) + return results + #------------------------------------------------------------------------------ # Relative pathnames #------------------------------------------------------------------------------ From numpy-svn at scipy.org Sun Aug 8 14:52:19 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 8 Aug 2010 13:52:19 -0500 (CDT) Subject: [Numpy-svn] r8611 - trunk/doc Message-ID: <20100808185219.97A8D39CC26@scipy.org> Author: ptvirtan Date: 2010-08-08 13:52:19 -0500 (Sun, 08 Aug 2010) New Revision: 8611 Modified: trunk/doc/Makefile Log: DOC: add FILES option to doc Makefile, for partial rebuilds Modified: trunk/doc/Makefile =================================================================== --- trunk/doc/Makefile 2010-08-08 18:52:01 UTC (rev 8610) +++ trunk/doc/Makefile 2010-08-08 18:52:19 UTC (rev 8611) @@ -9,6 +9,8 @@ SPHINXBUILD = LANG=C sphinx-build PAPER = +FILES= + NEED_AUTOSUMMARY = $(shell $(PYTHON) -c 'import sphinx; print sphinx.__version__ < "0.7" and "1" or ""') # Internal variables. @@ -106,14 +108,14 @@ html: generate mkdir -p build/html build/doctrees - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html $(FILES) $(PYTHON) postprocess.py html build/html/*.html @echo @echo "Build finished. The HTML pages are in build/html." pickle: generate mkdir -p build/pickle build/doctrees - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle $(FILES) @echo @echo "Build finished; now you can process the pickle files or run" @echo " sphinx-web build/pickle" @@ -123,7 +125,7 @@ htmlhelp: generate mkdir -p build/htmlhelp build/doctrees - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp $(FILES) @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in build/htmlhelp." @@ -134,11 +136,11 @@ qthelp: generate mkdir -p build/qthelp build/doctrees - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) build/qthelp + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) build/qthelp $(FILES) latex: generate mkdir -p build/latex build/doctrees - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex $(FILES) $(PYTHON) postprocess.py tex build/latex/*.tex perl -pi -e 's/\t(latex.*|pdflatex) (.*)/\t-$$1 -interaction batchmode $$2/' build/latex/Makefile @echo @@ -148,18 +150,18 @@ coverage: build mkdir -p build/coverage build/doctrees - $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) build/coverage + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) build/coverage $(FILES) @echo "Coverage finished; see c.txt and python.txt in build/coverage" changes: generate mkdir -p build/changes build/doctrees - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes $(FILES) @echo @echo "The overview file is in build/changes." linkcheck: generate mkdir -p build/linkcheck build/doctrees - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck $(FILES) @echo @echo "Link check complete; look for any errors in the above output " \ "or in build/linkcheck/output.txt." From numpy-svn at scipy.org Mon Aug 9 15:27:14 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 9 Aug 2010 14:27:14 -0500 (CDT) Subject: [Numpy-svn] r8612 - trunk/numpy/ma Message-ID: <20100809192714.B914039CB4B@scipy.org> Author: pierregm Date: 2010-08-09 14:27:14 -0500 (Mon, 09 Aug 2010) New Revision: 8612 Modified: trunk/numpy/ma/extras.py Log: * fixed numpy.ma.extras.flatnotmasked_contiguous (bug #1576) Modified: trunk/numpy/ma/extras.py =================================================================== --- trunk/numpy/ma/extras.py 2010-08-08 18:52:19 UTC (rev 8611) +++ trunk/numpy/ma/extras.py 2010-08-09 19:27:14 UTC (rev 8612) @@ -1644,16 +1644,14 @@ """ m = getmask(a) if m is nomask: - return (a.size, [0, -1]) - unmasked = np.flatnonzero(~m) - if len(unmasked) == 0: - return None + return slice(0, a.size, None) + i = 0 result = [] - for (k, group) in itertools.groupby(enumerate(unmasked), lambda (i, x):i - x): - tmp = np.array([g[1] for g in group], int) -# result.append((tmp.size, tuple(tmp[[0,-1]]))) - result.append(slice(tmp[0], tmp[-1])) - result.sort() + for (k, g) in itertools.groupby(m.ravel()): + n = len(list(g)) + if not k: + result.append(slice(i, i + n)) + i += n return result def notmasked_contiguous(a, axis=None): @@ -1711,7 +1709,7 @@ # for i in range(a.shape[other]): idx[other] = i - result.append(flatnotmasked_contiguous(a[idx])) + result.append(flatnotmasked_contiguous(a[idx]) or None) return result From numpy-svn at scipy.org Mon Aug 9 15:57:33 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 9 Aug 2010 14:57:33 -0500 (CDT) Subject: [Numpy-svn] r8613 - in trunk/numpy/ma: . tests Message-ID: <20100809195733.DB36F39CCFC@scipy.org> Author: pierregm Date: 2010-08-09 14:57:33 -0500 (Mon, 09 Aug 2010) New Revision: 8613 Modified: trunk/numpy/ma/extras.py trunk/numpy/ma/tests/test_extras.py Log: ma.extras * fixed the documentation of (flat)notmasked_xxx Modified: trunk/numpy/ma/extras.py =================================================================== --- trunk/numpy/ma/extras.py 2010-08-09 19:27:14 UTC (rev 8612) +++ trunk/numpy/ma/extras.py 2010-08-09 19:57:33 UTC (rev 8613) @@ -1522,7 +1522,8 @@ See Also -------- - flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges + flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges, + clump_masked, clump_unmasked Notes ----- @@ -1530,24 +1531,26 @@ Examples -------- - >>> a = np.arange(10) + >>> a = np.ma.arange(10) + >>> flatnotmasked_edges(a) + [0,-1] + >>> mask = (a < 3) | (a > 8) | (a == 5) - - >>> ma = np.ma.array(a, mask=m) - >>> np.array(ma[~ma.mask]) + >>> a[mask] = np.ma.masked + >>> np.array(a[~a.mask]) array([3, 4, 6, 7, 8]) - >>> flatnotmasked_edges(ma) + >>> flatnotmasked_edges(a) array([3, 8]) - >>> ma = np.ma.array(a, mask=np.ones_like(a)) + >>> a[:] = np.ma.masked >>> print flatnotmasked_edges(ma) None """ m = getmask(a) if m is nomask or not np.any(m): - return [0, -1] + return np.array([0, a.size - 1]) unmasked = np.flatnonzero(~m) if len(unmasked) > 0: return unmasked[[0, -1]] @@ -1580,7 +1583,8 @@ See Also -------- - flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous + flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, + clump_masked, clump_unmasked Examples -------- @@ -1588,8 +1592,8 @@ >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 - >>> ma = np.ma.array(a, mask=m) - >>> np.array(ma[~ma.mask]) + >>> am = np.ma.array(a, mask=m) + >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.extras.notmasked_edges(ma) @@ -1621,7 +1625,8 @@ See Also -------- - flatnotmasked_edges, notmasked_contiguous, notmasked_edges + flatnotmasked_edges, notmasked_contiguous, notmasked_edges, + clump_masked, clump_unmasked Notes ----- @@ -1629,16 +1634,19 @@ Examples -------- - >>> a = np.arange(10) + >>> a = np.ma.arange(10) + >>> np.ma.extras.flatnotmasked_contiguous(a) + slice(0, 10, None) + >>> mask = (a < 3) | (a > 8) | (a == 5) - >>> ma = np.ma.array(a, mask=mask) - >>> np.array(ma[~ma.mask]) + >>> a[mask] = np.ma.masked + >>> np.array(a[~a.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) + >>> np.ma.extras.flatnotmasked_contiguous(a) + [slice(3, 5, None), slice(6, 9, None)] + >>> a[:] = np.ma.masked + >>> print np.ma.extras.flatnotmasked_edges(a) None """ @@ -1652,7 +1660,7 @@ if not k: result.append(slice(i, i + n)) i += n - return result + return result or None def notmasked_contiguous(a, axis=None): """ @@ -1674,7 +1682,8 @@ See Also -------- - flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, + clump_masked, clump_unmasked Notes ----- @@ -1691,7 +1700,7 @@ array([0, 1, 2, 3, 6]) >>> np.ma.extras.notmasked_contiguous(ma) - [slice(0, 3, None), slice(6, 6, None)] + [slice(0, 4, None), slice(6, 7, None)] """ a = asarray(a) @@ -1792,7 +1801,7 @@ >>> 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)] + [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)] """ mask = ma.getmask(a) Modified: trunk/numpy/ma/tests/test_extras.py =================================================================== --- trunk/numpy/ma/tests/test_extras.py 2010-08-09 19:27:14 UTC (rev 8612) +++ trunk/numpy/ma/tests/test_extras.py 2010-08-09 19:57:33 UTC (rev 8613) @@ -88,6 +88,20 @@ control = [slice(3, 6), slice(7, 8), ] assert_equal(test, control) + def test_flatnotmasked_contiguous(self): + "Test flatnotmasked_contiguous" + a = arange(10) + # No mask + test = flatnotmasked_contiguous(a) + assert_equal(test, slice(0, a.size)) + # Some mask + a[(a < 3) | (a > 8) | (a == 5)] = masked + test = flatnotmasked_contiguous(a) + assert_equal(test, [slice(3, 5), slice(6, 9)]) + # + a[:] = masked + test = flatnotmasked_contiguous(a) + assert_equal(test, []) class TestAverage(TestCase): @@ -261,9 +275,9 @@ [1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 0], ]) tmp = notmasked_contiguous(a, None) - assert_equal(tmp[-1], slice(23, 23, None)) - assert_equal(tmp[-2], slice(16, 21, None)) - assert_equal(tmp[-3], slice(0, 3, None)) + assert_equal(tmp[-1], slice(23, 24, None)) + assert_equal(tmp[-2], slice(16, 22, None)) + assert_equal(tmp[-3], slice(0, 4, None)) # tmp = notmasked_contiguous(a, 0) self.assertTrue(len(tmp[-1]) == 1) @@ -272,10 +286,10 @@ self.assertTrue(len(tmp[0]) == 2) # tmp = notmasked_contiguous(a, 1) - assert_equal(tmp[0][-1], slice(0, 3, None)) + assert_equal(tmp[0][-1], slice(0, 4, None)) self.assertTrue(tmp[1] is None) - assert_equal(tmp[2][-1], slice(7, 7, None)) - assert_equal(tmp[2][-2], slice(0, 5, None)) + assert_equal(tmp[2][-1], slice(7, 8, None)) + assert_equal(tmp[2][-2], slice(0, 6, None)) From numpy-svn at scipy.org Mon Aug 9 16:07:06 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 9 Aug 2010 15:07:06 -0500 (CDT) Subject: [Numpy-svn] r8614 - trunk/numpy/ma Message-ID: <20100809200706.D012F39CB4B@scipy.org> Author: pierregm Date: 2010-08-09 15:07:06 -0500 (Mon, 09 Aug 2010) New Revision: 8614 Modified: trunk/numpy/ma/testutils.py Log: Modified: trunk/numpy/ma/testutils.py =================================================================== --- trunk/numpy/ma/testutils.py 2010-08-09 19:57:33 UTC (rev 8613) +++ trunk/numpy/ma/testutils.py 2010-08-09 20:07:06 UTC (rev 8614) @@ -22,7 +22,7 @@ equal, less #------------------------------------------------------------------------------ -def approx (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): +def approx (a, b, fill_value=True, rtol=1e-5, atol=1e-8): """Returns true if all components of a and b are equal subject to given tolerances. If fill_value is True, masked values considered equal. Otherwise, masked values @@ -35,10 +35,10 @@ d1 = filled(a) d2 = filled(b) if d1.dtype.char == "O" or d2.dtype.char == "O": - return np.equal(d1,d2).ravel() + return np.equal(d1, d2).ravel() x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_) y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_) - d = np.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y)) + d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y)) return d.ravel() @@ -51,46 +51,46 @@ d1 = filled(a) d2 = filled(b) if d1.dtype.char == "O" or d2.dtype.char == "O": - return np.equal(d1,d2).ravel() + return np.equal(d1, d2).ravel() x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_) y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_) - d = np.around(np.abs(x-y),decimal) <= 10.0**(-decimal) + d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal) return d.ravel() #................................................ def _assert_equal_on_sequences(actual, desired, err_msg=''): "Asserts the equality of two non-array sequences." - assert_equal(len(actual),len(desired),err_msg) + assert_equal(len(actual), len(desired), err_msg) for k in range(len(desired)): - assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg)) + assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg)) return -def assert_equal_records(a,b): +def assert_equal_records(a, b): """Asserts that two records are equal. Pretty crude for now.""" assert_equal(a.dtype, b.dtype) for f in a.dtype.names: - (af, bf) = (operator.getitem(a,f), operator.getitem(b,f)) + (af, bf) = (operator.getitem(a, f), operator.getitem(b, f)) if not (af is masked) and not (bf is masked): - assert_equal(operator.getitem(a,f), operator.getitem(b,f)) + assert_equal(operator.getitem(a, f), operator.getitem(b, f)) return -def assert_equal(actual,desired,err_msg=''): +def assert_equal(actual, desired, err_msg=''): """Asserts that two items are equal. """ # Case #1: dictionary ..... if isinstance(desired, dict): if not isinstance(actual, dict): raise AssertionError(repr(type(actual))) - assert_equal(len(actual),len(desired),err_msg) - for k,i in desired.items(): + assert_equal(len(actual), len(desired), err_msg) + for k, i in desired.items(): if not k in actual: - raise AssertionError("%s not in %s" % (k,actual)) - assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) + raise AssertionError("%s not in %s" % (k, actual)) + assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg)) return # Case #2: lists ..... - if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): + if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): return _assert_equal_on_sequences(actual, desired, err_msg='') if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)): msg = build_err_msg([actual, desired], err_msg,) @@ -121,22 +121,22 @@ return assert_array_equal(actual, desired, err_msg) -def fail_if_equal(actual,desired,err_msg='',): +def fail_if_equal(actual, desired, err_msg='',): """Raises an assertion error if two items are equal. """ if isinstance(desired, dict): if not isinstance(actual, dict): raise AssertionError(repr(type(actual))) - fail_if_equal(len(actual),len(desired),err_msg) - for k,i in desired.items(): + fail_if_equal(len(actual), len(desired), err_msg) + for k, i in desired.items(): if not k in actual: raise AssertionError(repr(k)) - fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) + fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg)) return - if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): - fail_if_equal(len(actual),len(desired),err_msg) + if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)): + fail_if_equal(len(actual), len(desired), err_msg) for k in range(len(desired)): - fail_if_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg)) + fail_if_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg)) return if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): return fail_if_array_equal(actual, desired, err_msg) @@ -155,7 +155,7 @@ err_msg=err_msg, verbose=verbose) msg = build_err_msg([actual, desired], err_msg=err_msg, verbose=verbose) - if not round(abs(desired - actual),decimal) == 0: + if not round(abs(desired - actual), decimal) == 0: raise AssertionError(msg) @@ -195,7 +195,7 @@ def fail_if_array_equal(x, y, err_msg='', verbose=True): "Raises an assertion error if two masked arrays are not equal (elementwise)." - def compare(x,y): + def compare(x, y): return (not np.alltrue(approx(x, y))) assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not equal') @@ -206,7 +206,7 @@ number of decimals.""" def compare(x, y): "Returns the result of the loose comparison between x and y)." - return approx(x,y, rtol=10.**-decimal) + return approx(x, y, rtol=10. ** -decimal) assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not almost equal') @@ -216,7 +216,7 @@ number of decimals.""" def compare(x, y): "Returns the result of the loose comparison between x and y)." - return almost(x,y,decimal) + return almost(x, y, decimal) assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose, header='Arrays are not almost equal') From numpy-svn at scipy.org Tue Aug 10 13:24:20 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 12:24:20 -0500 (CDT) Subject: [Numpy-svn] r8615 - trunk/numpy/lib Message-ID: <20100810172420.BCEC439CCC0@scipy.org> Author: charris Date: 2010-08-10 12:24:20 -0500 (Tue, 10 Aug 2010) New Revision: 8615 Modified: trunk/numpy/lib/twodim_base.py Log: BUG: Fix ticket #1579. Do some cleanups. Modified: trunk/numpy/lib/twodim_base.py =================================================================== --- trunk/numpy/lib/twodim_base.py 2010-08-09 20:07:06 UTC (rev 8614) +++ trunk/numpy/lib/twodim_base.py 2010-08-10 17:24:20 UTC (rev 8615) @@ -58,7 +58,7 @@ """ m = asanyarray(m) if m.ndim < 2: - raise ValueError, "Input must be >= 2-d." + raise ValueError("Input must be >= 2-d.") return m[:, ::-1] def flipud(m): @@ -111,7 +111,7 @@ """ m = asanyarray(m) if m.ndim < 1: - raise ValueError, "Input must be >= 1-d." + raise ValueError("Input must be >= 1-d.") return m[::-1,...] def rot90(m, k=1): @@ -154,12 +154,17 @@ """ m = asanyarray(m) if m.ndim < 2: - raise ValueError, "Input must >= 2-d." + raise ValueError("Input must >= 2-d.") k = k % 4 - if k == 0: return m - elif k == 1: return fliplr(m).swapaxes(0,1) - elif k == 2: return fliplr(flipud(m)) - else: return fliplr(m.swapaxes(0,1)) # k==3 + if k == 0: + return m + elif k == 1: + return fliplr(m).swapaxes(0,1) + elif k == 2: + return fliplr(flipud(m)) + else: + # k == 3 + return fliplr(m.swapaxes(0,1)) def eye(N, M=None, k=0, dtype=float): """ @@ -284,9 +289,9 @@ i = (-k) * s[1] return v[:s[1]-k].flat[i::s[1]+1] else: - raise ValueError, "Input must be 1- or 2-d." + raise ValueError("Input must be 1- or 2-d.") -def diagflat(v,k=0): +def diagflat(v, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. @@ -333,7 +338,7 @@ s = len(v) n = s + abs(k) res = zeros((n,n), v.dtype) - if (k>=0): + if (k >= 0): i = arange(0,n-k) fi = i+k+i*n else: @@ -381,7 +386,8 @@ [ 1., 1., 0., 0., 0.]]) """ - if M is None: M = N + if M is None: + M = N m = greater_equal(subtract.outer(arange(N), arange(M)),-k) return m.astype(dtype) @@ -444,7 +450,7 @@ """ m = asanyarray(m) - out = multiply((1-tri(m.shape[0], m.shape[1], k-1, int)),m) + out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, int)), m) return out # borrowed from John Hunter and matplotlib @@ -505,14 +511,15 @@ """ x = asarray(x) - if N is None: N=len(x) + if N is None: + N=len(x) X = ones( (len(x),N), x.dtype) - for i in range(N-1): - X[:,i] = x**(N-i-1) + for i in range(N - 1): + X[:,i] = x**(N - i - 1) return X -def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): +def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): """ Compute the bi-dimensional histogram of two data samples. @@ -608,8 +615,8 @@ hist, edges = histogramdd([x,y], bins, range, normed, weights) return hist, edges[0], edges[1] - -def mask_indices(n,mask_func,k=0): + +def mask_indices(n, mask_func, k=0): """ Return the indices to access (n, n) arrays, given a masking function. @@ -674,21 +681,22 @@ array([1, 2, 5]) """ - m = ones((n,n),int) - a = mask_func(m,k) + m = ones((n,n), int) + a = mask_func(m, k) return where(a != 0) -def tril_indices(n,k=0): +def tril_indices(n, k=0): """ Return the indices for the lower-triangle of an (n, n) array. Parameters ---------- n : int - Sets the size of the arrays for which the returned indices will be valid. + The row dimension of the square arrays for which the returned + indices will be valid. k : int, optional - Diagonal offset (see `tril` for details). + Diagonal offset (see `tril` for details). Returns ------- @@ -748,21 +756,22 @@ [-10, -10, -10, -10]]) """ - return mask_indices(n,tril,k) + return mask_indices(n, tril, k) -def tril_indices_from(arr,k=0): +def tril_indices_from(arr, k=0): """ - Return the indices for the lower-triangle of an (n, n) array. + Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- - n : int - Sets the size of the arrays for which the returned indices will be valid. + arr : array_like + The indices will be valid for square arrays whose dimensions are + the same as arr. k : int, optional - Diagonal offset (see `tril` for details). + Diagonal offset (see `tril` for details). See Also -------- @@ -773,21 +782,22 @@ .. versionadded:: 1.4.0 """ - if not arr.ndim==2 and arr.shape[0] == arr.shape[1]: + if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): raise ValueError("input array must be 2-d and square") - return tril_indices(arr.shape[0],k) + return tril_indices(arr.shape[0], k) - -def triu_indices(n,k=0): + +def triu_indices(n, k=0): """ Return the indices for the upper-triangle of an (n, n) array. Parameters ---------- n : int - Sets the size of the arrays for which the returned indices will be valid. + The size of the arrays for which the returned indices will + be valid. k : int, optional - Diagonal offset (see `triu` for details). + Diagonal offset (see `triu` for details). Returns ------- @@ -848,10 +858,10 @@ [ 12, 13, 14, -1]]) """ - return mask_indices(n,triu,k) + return mask_indices(n, triu, k) -def triu_indices_from(arr,k=0): +def triu_indices_from(arr, k=0): """ Return the indices for the upper-triangle of an (n, n) array. @@ -859,8 +869,9 @@ Parameters ---------- - n : int - Sets the size of the arrays for which the returned indices will be valid. + arr : array_like + The indices will be valid for square arrays whose dimensions are + the same as arr. k : int, optional Diagonal offset (see `triu` for details). @@ -873,7 +884,7 @@ .. versionadded:: 1.4.0 """ - if not arr.ndim==2 and arr.shape[0] == arr.shape[1]: + if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): raise ValueError("input array must be 2-d and square") return triu_indices(arr.shape[0],k) From numpy-svn at scipy.org Tue Aug 10 13:24:23 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 12:24:23 -0500 (CDT) Subject: [Numpy-svn] r8616 - trunk/numpy/lib/tests Message-ID: <20100810172423.8F47F39CD02@scipy.org> Author: charris Date: 2010-08-10 12:24:23 -0500 (Tue, 10 Aug 2010) New Revision: 8616 Modified: trunk/numpy/lib/tests/test_twodim_base.py Log: ENH: Add some tests for ticket #1579. Do some cleanups. Modified: trunk/numpy/lib/tests/test_twodim_base.py =================================================================== --- trunk/numpy/lib/tests/test_twodim_base.py 2010-08-10 17:24:20 UTC (rev 8615) +++ trunk/numpy/lib/tests/test_twodim_base.py 2010-08-10 17:24:23 UTC (rev 8616) @@ -232,76 +232,95 @@ assert_array_equal(tri(3,dtype=bool),out.astype(bool)) -def test_mask_indices(): - # simple test without offset - iu = mask_indices(3, np.triu) - a = np.arange(9).reshape(3, 3) - yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8])) - # Now with an offset - iu1 = mask_indices(3, np.triu, 1) - yield (assert_array_equal, a[iu1], array([1, 2, 5])) +class TestMaskIndices(TestCase): + def test_mask_indices(self): + # simple test without offset + iu = mask_indices(3, np.triu) + a = np.arange(9).reshape(3, 3) + yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8])) + # Now with an offset + iu1 = mask_indices(3, np.triu, 1) + yield (assert_array_equal, a[iu1], array([1, 2, 5])) -def test_tril_indices(): - # indices without and with offset - il1 = tril_indices(4) - il2 = tril_indices(4, 2) +class TestTrilIndices(TestCase): + def test_tril_indices(): + # indices without and with offset + il1 = tril_indices(4) + il2 = tril_indices(4, 2) - a = np.array([[1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12], - [13, 14, 15, 16]]) + a = np.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]]) - # indexing: - yield (assert_array_equal, a[il1], - array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) ) + # indexing: + yield (assert_array_equal, a[il1], + array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) ) - # And for assigning values: - a[il1] = -1 - yield (assert_array_equal, a, - array([[-1, 2, 3, 4], - [-1, -1, 7, 8], - [-1, -1, -1, 12], - [-1, -1, -1, -1]]) ) + # And for assigning values: + a[il1] = -1 + yield (assert_array_equal, a, + array([[-1, 2, 3, 4], + [-1, -1, 7, 8], + [-1, -1, -1, 12], + [-1, -1, -1, -1]]) ) - # These cover almost the whole array (two diagonals right of the main one): - a[il2] = -10 - yield (assert_array_equal, a, - array([[-10, -10, -10, 4], - [-10, -10, -10, -10], - [-10, -10, -10, -10], - [-10, -10, -10, -10]]) ) + # These cover almost the whole array (two diagonals right of the main one): + a[il2] = -10 + yield (assert_array_equal, a, + array([[-10, -10, -10, 4], + [-10, -10, -10, -10], + [-10, -10, -10, -10], + [-10, -10, -10, -10]]) ) -def test_triu_indices(): - iu1 = triu_indices(4) - iu2 = triu_indices(4, 2) +class TestTrilIndicesFrom(TestCase): - a = np.array([[1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12], - [13, 14, 15, 16]]) + def test_exceptions(self): + yield assert_raises(ValueError, tril_indices_from, np.ones((2,))) + yield assert_raises(ValueError, tril_indices_from, np.ones((2,2,2))) + yield assert_raises(ValueError, tril_indices_from, np.ones((2,3))) - # Both for indexing: - yield (assert_array_equal, a[iu1], - array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16])) - # And for assigning values: - a[iu1] = -1 - yield (assert_array_equal, a, - array([[-1, -1, -1, -1], - [ 5, -1, -1, -1], - [ 9, 10, -1, -1], - [13, 14, 15, -1]]) ) +class TestTriuIndices(TestCase): + def test_triu_indices(): + iu1 = triu_indices(4) + iu2 = triu_indices(4, 2) - # These cover almost the whole array (two diagonals right of the main one): - a[iu2] = -10 - yield ( assert_array_equal, a, - array([[ -1, -1, -10, -10], - [ 5, -1, -1, -10], - [ 9, 10, -1, -1], - [ 13, 14, 15, -1]]) ) + a = np.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]]) + # Both for indexing: + yield (assert_array_equal, a[iu1], + array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16])) + # And for assigning values: + a[iu1] = -1 + yield (assert_array_equal, a, + array([[-1, -1, -1, -1], + [ 5, -1, -1, -1], + [ 9, 10, -1, -1], + [13, 14, 15, -1]]) ) + + # These cover almost the whole array (two diagonals right of the main one): + a[iu2] = -10 + yield ( assert_array_equal, a, + array([[ -1, -1, -10, -10], + [ 5, -1, -1, -10], + [ 9, 10, -1, -1], + [ 13, 14, 15, -1]]) ) + + +class TestTriuIndicesFrom(TestCase): + + def test_exceptions(self): + yield assert_raises(ValueError, triu_indices_from, np.ones((2,))) + yield assert_raises(ValueError, triu_indices_from, np.ones((2,2,2))) + yield assert_raises(ValueError, triu_indices_from, np.ones((2,3))) + + if __name__ == "__main__": run_module_suite() From numpy-svn at scipy.org Tue Aug 10 13:24:26 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 12:24:26 -0500 (CDT) Subject: [Numpy-svn] r8617 - trunk/numpy/lib/tests Message-ID: <20100810172426.21D8439CD18@scipy.org> Author: charris Date: 2010-08-10 12:24:25 -0500 (Tue, 10 Aug 2010) New Revision: 8617 Modified: trunk/numpy/lib/tests/test_twodim_base.py Log: BUG: Fix missing 'self' in test cleanups. Modified: trunk/numpy/lib/tests/test_twodim_base.py =================================================================== --- trunk/numpy/lib/tests/test_twodim_base.py 2010-08-10 17:24:23 UTC (rev 8616) +++ trunk/numpy/lib/tests/test_twodim_base.py 2010-08-10 17:24:25 UTC (rev 8617) @@ -244,7 +244,7 @@ class TestTrilIndices(TestCase): - def test_tril_indices(): + def test_tril_indices(self): # indices without and with offset il1 = tril_indices(4) il2 = tril_indices(4, 2) @@ -284,7 +284,7 @@ class TestTriuIndices(TestCase): - def test_triu_indices(): + def test_triu_indices(self): iu1 = triu_indices(4) iu2 = triu_indices(4, 2) From numpy-svn at scipy.org Tue Aug 10 13:32:02 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 12:32:02 -0500 (CDT) Subject: [Numpy-svn] r8618 - in branches/1.5.x/numpy/lib: . tests Message-ID: <20100810173202.D344639CCC0@scipy.org> Author: charris Date: 2010-08-10 12:32:02 -0500 (Tue, 10 Aug 2010) New Revision: 8618 Modified: branches/1.5.x/numpy/lib/tests/test_twodim_base.py branches/1.5.x/numpy/lib/twodim_base.py Log: BUG: Backport fixes for ticket #1579, r8615-r8617. Modified: branches/1.5.x/numpy/lib/tests/test_twodim_base.py =================================================================== --- branches/1.5.x/numpy/lib/tests/test_twodim_base.py 2010-08-10 17:24:25 UTC (rev 8617) +++ branches/1.5.x/numpy/lib/tests/test_twodim_base.py 2010-08-10 17:32:02 UTC (rev 8618) @@ -232,76 +232,95 @@ assert_array_equal(tri(3,dtype=bool),out.astype(bool)) -def test_mask_indices(): - # simple test without offset - iu = mask_indices(3, np.triu) - a = np.arange(9).reshape(3, 3) - yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8])) - # Now with an offset - iu1 = mask_indices(3, np.triu, 1) - yield (assert_array_equal, a[iu1], array([1, 2, 5])) +class TestMaskIndices(TestCase): + def test_mask_indices(self): + # simple test without offset + iu = mask_indices(3, np.triu) + a = np.arange(9).reshape(3, 3) + yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8])) + # Now with an offset + iu1 = mask_indices(3, np.triu, 1) + yield (assert_array_equal, a[iu1], array([1, 2, 5])) -def test_tril_indices(): - # indices without and with offset - il1 = tril_indices(4) - il2 = tril_indices(4, 2) +class TestTrilIndices(TestCase): + def test_tril_indices(self): + # indices without and with offset + il1 = tril_indices(4) + il2 = tril_indices(4, 2) - a = np.array([[1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12], - [13, 14, 15, 16]]) + a = np.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]]) - # indexing: - yield (assert_array_equal, a[il1], - array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) ) + # indexing: + yield (assert_array_equal, a[il1], + array([ 1, 5, 6, 9, 10, 11, 13, 14, 15, 16]) ) - # And for assigning values: - a[il1] = -1 - yield (assert_array_equal, a, - array([[-1, 2, 3, 4], - [-1, -1, 7, 8], - [-1, -1, -1, 12], - [-1, -1, -1, -1]]) ) + # And for assigning values: + a[il1] = -1 + yield (assert_array_equal, a, + array([[-1, 2, 3, 4], + [-1, -1, 7, 8], + [-1, -1, -1, 12], + [-1, -1, -1, -1]]) ) - # These cover almost the whole array (two diagonals right of the main one): - a[il2] = -10 - yield (assert_array_equal, a, - array([[-10, -10, -10, 4], - [-10, -10, -10, -10], - [-10, -10, -10, -10], - [-10, -10, -10, -10]]) ) + # These cover almost the whole array (two diagonals right of the main one): + a[il2] = -10 + yield (assert_array_equal, a, + array([[-10, -10, -10, 4], + [-10, -10, -10, -10], + [-10, -10, -10, -10], + [-10, -10, -10, -10]]) ) -def test_triu_indices(): - iu1 = triu_indices(4) - iu2 = triu_indices(4, 2) +class TestTrilIndicesFrom(TestCase): - a = np.array([[1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12], - [13, 14, 15, 16]]) + def test_exceptions(self): + yield assert_raises(ValueError, tril_indices_from, np.ones((2,))) + yield assert_raises(ValueError, tril_indices_from, np.ones((2,2,2))) + yield assert_raises(ValueError, tril_indices_from, np.ones((2,3))) - # Both for indexing: - yield (assert_array_equal, a[iu1], - array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16])) - # And for assigning values: - a[iu1] = -1 - yield (assert_array_equal, a, - array([[-1, -1, -1, -1], - [ 5, -1, -1, -1], - [ 9, 10, -1, -1], - [13, 14, 15, -1]]) ) +class TestTriuIndices(TestCase): + def test_triu_indices(self): + iu1 = triu_indices(4) + iu2 = triu_indices(4, 2) - # These cover almost the whole array (two diagonals right of the main one): - a[iu2] = -10 - yield ( assert_array_equal, a, - array([[ -1, -1, -10, -10], - [ 5, -1, -1, -10], - [ 9, 10, -1, -1], - [ 13, 14, 15, -1]]) ) + a = np.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16]]) + # Both for indexing: + yield (assert_array_equal, a[iu1], + array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16])) + # And for assigning values: + a[iu1] = -1 + yield (assert_array_equal, a, + array([[-1, -1, -1, -1], + [ 5, -1, -1, -1], + [ 9, 10, -1, -1], + [13, 14, 15, -1]]) ) + + # These cover almost the whole array (two diagonals right of the main one): + a[iu2] = -10 + yield ( assert_array_equal, a, + array([[ -1, -1, -10, -10], + [ 5, -1, -1, -10], + [ 9, 10, -1, -1], + [ 13, 14, 15, -1]]) ) + + +class TestTriuIndicesFrom(TestCase): + + def test_exceptions(self): + yield assert_raises(ValueError, triu_indices_from, np.ones((2,))) + yield assert_raises(ValueError, triu_indices_from, np.ones((2,2,2))) + yield assert_raises(ValueError, triu_indices_from, np.ones((2,3))) + + if __name__ == "__main__": run_module_suite() Modified: branches/1.5.x/numpy/lib/twodim_base.py =================================================================== --- branches/1.5.x/numpy/lib/twodim_base.py 2010-08-10 17:24:25 UTC (rev 8617) +++ branches/1.5.x/numpy/lib/twodim_base.py 2010-08-10 17:32:02 UTC (rev 8618) @@ -58,7 +58,7 @@ """ m = asanyarray(m) if m.ndim < 2: - raise ValueError, "Input must be >= 2-d." + raise ValueError("Input must be >= 2-d.") return m[:, ::-1] def flipud(m): @@ -111,7 +111,7 @@ """ m = asanyarray(m) if m.ndim < 1: - raise ValueError, "Input must be >= 1-d." + raise ValueError("Input must be >= 1-d.") return m[::-1,...] def rot90(m, k=1): @@ -154,12 +154,17 @@ """ m = asanyarray(m) if m.ndim < 2: - raise ValueError, "Input must >= 2-d." + raise ValueError("Input must >= 2-d.") k = k % 4 - if k == 0: return m - elif k == 1: return fliplr(m).swapaxes(0,1) - elif k == 2: return fliplr(flipud(m)) - else: return fliplr(m.swapaxes(0,1)) # k==3 + if k == 0: + return m + elif k == 1: + return fliplr(m).swapaxes(0,1) + elif k == 2: + return fliplr(flipud(m)) + else: + # k == 3 + return fliplr(m.swapaxes(0,1)) def eye(N, M=None, k=0, dtype=float): """ @@ -284,9 +289,9 @@ i = (-k) * s[1] return v[:s[1]-k].flat[i::s[1]+1] else: - raise ValueError, "Input must be 1- or 2-d." + raise ValueError("Input must be 1- or 2-d.") -def diagflat(v,k=0): +def diagflat(v, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. @@ -333,7 +338,7 @@ s = len(v) n = s + abs(k) res = zeros((n,n), v.dtype) - if (k>=0): + if (k >= 0): i = arange(0,n-k) fi = i+k+i*n else: @@ -381,7 +386,8 @@ [ 1., 1., 0., 0., 0.]]) """ - if M is None: M = N + if M is None: + M = N m = greater_equal(subtract.outer(arange(N), arange(M)),-k) return m.astype(dtype) @@ -444,7 +450,7 @@ """ m = asanyarray(m) - out = multiply((1-tri(m.shape[0], m.shape[1], k-1, int)),m) + out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, int)), m) return out # borrowed from John Hunter and matplotlib @@ -505,14 +511,15 @@ """ x = asarray(x) - if N is None: N=len(x) + if N is None: + N=len(x) X = ones( (len(x),N), x.dtype) - for i in range(N-1): - X[:,i] = x**(N-i-1) + for i in range(N - 1): + X[:,i] = x**(N - i - 1) return X -def histogram2d(x,y, bins=10, range=None, normed=False, weights=None): +def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): """ Compute the bi-dimensional histogram of two data samples. @@ -608,8 +615,8 @@ hist, edges = histogramdd([x,y], bins, range, normed, weights) return hist, edges[0], edges[1] - -def mask_indices(n,mask_func,k=0): + +def mask_indices(n, mask_func, k=0): """ Return the indices to access (n, n) arrays, given a masking function. @@ -674,21 +681,22 @@ array([1, 2, 5]) """ - m = ones((n,n),int) - a = mask_func(m,k) + m = ones((n,n), int) + a = mask_func(m, k) return where(a != 0) -def tril_indices(n,k=0): +def tril_indices(n, k=0): """ Return the indices for the lower-triangle of an (n, n) array. Parameters ---------- n : int - Sets the size of the arrays for which the returned indices will be valid. + The row dimension of the square arrays for which the returned + indices will be valid. k : int, optional - Diagonal offset (see `tril` for details). + Diagonal offset (see `tril` for details). Returns ------- @@ -748,21 +756,22 @@ [-10, -10, -10, -10]]) """ - return mask_indices(n,tril,k) + return mask_indices(n, tril, k) -def tril_indices_from(arr,k=0): +def tril_indices_from(arr, k=0): """ - Return the indices for the lower-triangle of an (n, n) array. + Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- - n : int - Sets the size of the arrays for which the returned indices will be valid. + arr : array_like + The indices will be valid for square arrays whose dimensions are + the same as arr. k : int, optional - Diagonal offset (see `tril` for details). + Diagonal offset (see `tril` for details). See Also -------- @@ -773,21 +782,22 @@ .. versionadded:: 1.4.0 """ - if not arr.ndim==2 and arr.shape[0] == arr.shape[1]: + if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): raise ValueError("input array must be 2-d and square") - return tril_indices(arr.shape[0],k) + return tril_indices(arr.shape[0], k) - -def triu_indices(n,k=0): + +def triu_indices(n, k=0): """ Return the indices for the upper-triangle of an (n, n) array. Parameters ---------- n : int - Sets the size of the arrays for which the returned indices will be valid. + The size of the arrays for which the returned indices will + be valid. k : int, optional - Diagonal offset (see `triu` for details). + Diagonal offset (see `triu` for details). Returns ------- @@ -848,10 +858,10 @@ [ 12, 13, 14, -1]]) """ - return mask_indices(n,triu,k) + return mask_indices(n, triu, k) -def triu_indices_from(arr,k=0): +def triu_indices_from(arr, k=0): """ Return the indices for the upper-triangle of an (n, n) array. @@ -859,8 +869,9 @@ Parameters ---------- - n : int - Sets the size of the arrays for which the returned indices will be valid. + arr : array_like + The indices will be valid for square arrays whose dimensions are + the same as arr. k : int, optional Diagonal offset (see `triu` for details). @@ -873,7 +884,7 @@ .. versionadded:: 1.4.0 """ - if not arr.ndim==2 and arr.shape[0] == arr.shape[1]: + if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): raise ValueError("input array must be 2-d and square") return triu_indices(arr.shape[0],k) From numpy-svn at scipy.org Tue Aug 10 21:18:21 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 20:18:21 -0500 (CDT) Subject: [Numpy-svn] r8619 - in trunk/numpy/polynomial: . tests Message-ID: <20100811011821.3532E39CB4B@scipy.org> Author: charris Date: 2010-08-10 20:18:21 -0500 (Tue, 10 Aug 2010) New Revision: 8619 Modified: trunk/numpy/polynomial/polyutils.py trunk/numpy/polynomial/tests/test_polyutils.py Log: BUG: Make mapdomain work for multidimensional arrays as advertized in the documentation. Fixes ticket #1554. Modified: trunk/numpy/polynomial/polyutils.py =================================================================== --- trunk/numpy/polynomial/polyutils.py 2010-08-10 17:32:02 UTC (rev 8618) +++ trunk/numpy/polynomial/polyutils.py 2010-08-11 01:18:21 UTC (rev 8619) @@ -289,8 +289,8 @@ Parameters ---------- old, new : array_like - Each domain must (successfully) convert to a 1-d array containing - precisely two values. + Domains. Each domain must (successfully) convert to a 1-d array + containing precisely two values. Returns ------- @@ -330,13 +330,14 @@ """ Apply linear map to input points. - The linear map ``offset + scale*x`` that maps `old` to `new` is applied - to the points `x`. + The linear map ``offset + scale*x`` that maps the domain `old` to + the domain `new` is applied to the points `x`. Parameters ---------- x : array_like - Points to be mapped. + Points to be mapped. If `x` is a subtype of ndarray the subtype + will be preserved. old, new : array_like The two domains that determine the map. Each must (successfully) convert to 1-d arrays containing precisely two values. @@ -388,6 +389,6 @@ array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j, 0.2-0.2j, 0.6-0.6j, 1.0-1.j ]) """ - [x] = as_series([x], trim=False) + x = np.asanyarray(x) off, scl = mapparms(old, new) return off + scl*x Modified: trunk/numpy/polynomial/tests/test_polyutils.py =================================================================== --- trunk/numpy/polynomial/tests/test_polyutils.py 2010-08-10 17:32:02 UTC (rev 8618) +++ trunk/numpy/polynomial/tests/test_polyutils.py 2010-08-11 01:18:21 UTC (rev 8619) @@ -67,9 +67,25 @@ dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = dom2 - res = pu.mapdomain(dom1, dom1, dom2) + x = dom1 + res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) + # test for multidimensional arrays + dom1 = [0,4] + dom2 = [1,3] + tgt = np.array([dom2, dom2]) + x = np.array([dom1, dom1]) + res = pu.mapdomain(x, dom1, dom2) + assert_almost_equal(res, tgt) + + # test that subtypes are preserved. + dom1 = [0,4] + dom2 = [1,3] + x = np.matrix([dom1, dom1]) + res = pu.mapdomain(x, dom1, dom2) + assert_(isinstance(res, np.matrix)) + def test_mapparms(self) : # test for real values dom1 = [0,4] From numpy-svn at scipy.org Tue Aug 10 21:24:22 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 20:24:22 -0500 (CDT) Subject: [Numpy-svn] r8620 - in branches/1.5.x/numpy/polynomial: . tests Message-ID: <20100811012422.14C3039CB4B@scipy.org> Author: charris Date: 2010-08-10 20:24:21 -0500 (Tue, 10 Aug 2010) New Revision: 8620 Modified: branches/1.5.x/numpy/polynomial/polyutils.py branches/1.5.x/numpy/polynomial/tests/test_polyutils.py Log: BUG: Backport r8619 to fix ticked #1554. Modified: branches/1.5.x/numpy/polynomial/polyutils.py =================================================================== --- branches/1.5.x/numpy/polynomial/polyutils.py 2010-08-11 01:18:21 UTC (rev 8619) +++ branches/1.5.x/numpy/polynomial/polyutils.py 2010-08-11 01:24:21 UTC (rev 8620) @@ -289,8 +289,8 @@ Parameters ---------- old, new : array_like - Each domain must (successfully) convert to a 1-d array containing - precisely two values. + Domains. Each domain must (successfully) convert to a 1-d array + containing precisely two values. Returns ------- @@ -330,13 +330,14 @@ """ Apply linear map to input points. - The linear map ``offset + scale*x`` that maps `old` to `new` is applied - to the points `x`. + The linear map ``offset + scale*x`` that maps the domain `old` to + the domain `new` is applied to the points `x`. Parameters ---------- x : array_like - Points to be mapped. + Points to be mapped. If `x` is a subtype of ndarray the subtype + will be preserved. old, new : array_like The two domains that determine the map. Each must (successfully) convert to 1-d arrays containing precisely two values. @@ -388,6 +389,6 @@ array([-1.0+1.j , -0.6+0.6j, -0.2+0.2j, 0.2-0.2j, 0.6-0.6j, 1.0-1.j ]) """ - [x] = as_series([x], trim=False) + x = np.asanyarray(x) off, scl = mapparms(old, new) return off + scl*x Modified: branches/1.5.x/numpy/polynomial/tests/test_polyutils.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_polyutils.py 2010-08-11 01:18:21 UTC (rev 8619) +++ branches/1.5.x/numpy/polynomial/tests/test_polyutils.py 2010-08-11 01:24:21 UTC (rev 8620) @@ -67,9 +67,25 @@ dom1 = [0 - 1j, 2 + 1j] dom2 = [-2, 2] tgt = dom2 - res = pu.mapdomain(dom1, dom1, dom2) + x = dom1 + res = pu.mapdomain(x, dom1, dom2) assert_almost_equal(res, tgt) + # test for multidimensional arrays + dom1 = [0,4] + dom2 = [1,3] + tgt = np.array([dom2, dom2]) + x = np.array([dom1, dom1]) + res = pu.mapdomain(x, dom1, dom2) + assert_almost_equal(res, tgt) + + # test that subtypes are preserved. + dom1 = [0,4] + dom2 = [1,3] + x = np.matrix([dom1, dom1]) + res = pu.mapdomain(x, dom1, dom2) + assert_(isinstance(res, np.matrix)) + def test_mapparms(self) : # test for real values dom1 = [0,4] From numpy-svn at scipy.org Tue Aug 10 21:59:39 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 10 Aug 2010 20:59:39 -0500 (CDT) Subject: [Numpy-svn] r8621 - in trunk/numpy/ma: . tests Message-ID: <20100811015939.5599139CB4B@scipy.org> Author: pierregm Date: 2010-08-10 20:59:39 -0500 (Tue, 10 Aug 2010) New Revision: 8621 Modified: trunk/numpy/ma/extras.py trunk/numpy/ma/tests/test_extras.py Log: fix (flat)notmasked_/contiguous/edges/ Modified: trunk/numpy/ma/extras.py =================================================================== --- trunk/numpy/ma/extras.py 2010-08-11 01:24:21 UTC (rev 8620) +++ trunk/numpy/ma/extras.py 2010-08-11 01:59:39 UTC (rev 8621) @@ -273,7 +273,7 @@ if len(args) == 1: x = args[0] if isinstance(x, ndarray): - _d = func(np.asarray(x), **params) + _d = func(x.__array__(), **params) _m = func(getmaskarray(x), **params) return masked_array(_d, mask=_m) elif isinstance(x, tuple) or isinstance(x, list): @@ -292,12 +292,12 @@ res.append(masked_array(_d, mask=_m)) return res -#atleast_1d = _fromnxfunction('atleast_1d') -#atleast_2d = _fromnxfunction('atleast_2d') -#atleast_3d = _fromnxfunction('atleast_3d') -atleast_1d = np.atleast_1d -atleast_2d = np.atleast_2d -atleast_3d = np.atleast_3d +atleast_1d = _fromnxfunction('atleast_1d') +atleast_2d = _fromnxfunction('atleast_2d') +atleast_3d = _fromnxfunction('atleast_3d') +#atleast_1d = np.atleast_1d +#atleast_2d = np.atleast_2d +#atleast_3d = np.atleast_3d vstack = row_stack = _fromnxfunction('vstack') hstack = _fromnxfunction('hstack') @@ -1742,6 +1742,7 @@ def clump_unmasked(a): """ Return list of slices corresponding to the unmasked clumps of a 1-D array. + (A "clump" is defined as a contiguous region of the array). Parameters ---------- @@ -1758,6 +1759,11 @@ ----- .. versionadded:: 1.4.0 + See Also + -------- + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, + notmasked_contiguous, clump_masked + Examples -------- >>> a = np.ma.masked_array(np.arange(10)) @@ -1780,6 +1786,7 @@ def clump_masked(a): """ Returns a list of slices corresponding to the masked clumps of a 1-D array. + (A "clump" is defined as a contiguous region of the array). Parameters ---------- @@ -1796,6 +1803,11 @@ ----- .. versionadded:: 1.4.0 + See Also + -------- + flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, + notmasked_contiguous, clump_unmasked + Examples -------- >>> a = np.ma.masked_array(np.arange(10)) Modified: trunk/numpy/ma/tests/test_extras.py =================================================================== --- trunk/numpy/ma/tests/test_extras.py 2010-08-11 01:24:21 UTC (rev 8620) +++ trunk/numpy/ma/tests/test_extras.py 2010-08-11 01:59:39 UTC (rev 8621) @@ -101,7 +101,7 @@ # a[:] = masked test = flatnotmasked_contiguous(a) - assert_equal(test, []) + assert_equal(test, None) class TestAverage(TestCase): @@ -251,7 +251,7 @@ assert_equal(test[1], [(0, 1, 2, 3, 4), (4, 2, 4, 4, 4)]) # test = notmasked_edges(data.data, None) - assert_equal(test, [0, -1]) + assert_equal(test, [0, 24]) test = notmasked_edges(data.data, 0) assert_equal(test[0], [(0, 0, 0, 0, 0), (0, 1, 2, 3, 4)]) assert_equal(test[1], [(4, 4, 4, 4, 4), (0, 1, 2, 3, 4)]) @@ -827,10 +827,19 @@ assert_array_equal(setdiff1d(a, b), np.array(['c'])) + + + class TestShapeBase(TestCase): # - def test_atleast1d(self): - pass + def test_atleast2d(self): + "Test atleast_2d" + a = masked_array([0, 1, 2], mask=[0, 1, 0]) + b = atleast_2d(a) + assert_equal(b.shape, (1, 3)) + assert_equal(b.mask.shape, b.data.shape) + assert_equal(a.shape, (3,)) + assert_equal(a.mask.shape, a.data.shape) ############################################################################### From numpy-svn at scipy.org Sat Aug 14 09:42:38 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:42:38 -0500 (CDT) Subject: [Numpy-svn] r8622 - trunk/numpy/core/include/numpy Message-ID: <20100814134238.5BFC539CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:42:38 -0500 (Sat, 14 Aug 2010) New Revision: 8622 Modified: trunk/numpy/core/include/numpy/ndarraytypes.h Log: BUG: Better format specifier for Py 2.7, 3.2 on win-amd64. Closes #1570. Thanks to Christoph Gohlke. Modified: trunk/numpy/core/include/numpy/ndarraytypes.h =================================================================== --- trunk/numpy/core/include/numpy/ndarraytypes.h 2010-08-11 01:59:39 UTC (rev 8621) +++ trunk/numpy/core/include/numpy/ndarraytypes.h 2010-08-14 13:42:38 UTC (rev 8622) @@ -275,8 +275,12 @@ #define NPY_MAX_INTP NPY_MAX_LONGLONG #define NPY_MIN_INTP NPY_MIN_LONGLONG #define NPY_MAX_UINTP NPY_MAX_ULONGLONG +#ifdef _MSC_VER + #define NPY_INTP_FMT "lld" +#else #define NPY_INTP_FMT "Ld" #endif +#endif /* * We can only use C99 formats for npy_int_p if it is the same as From numpy-svn at scipy.org Sat Aug 14 09:42:59 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:42:59 -0500 (CDT) Subject: [Numpy-svn] r8623 - trunk/numpy/core/tests Message-ID: <20100814134259.6157539CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:42:59 -0500 (Sat, 14 Aug 2010) New Revision: 8623 Modified: trunk/numpy/core/tests/test_umath_complex.py Log: TST: skip C99 nan/inf tests on Windows. Modified: trunk/numpy/core/tests/test_umath_complex.py =================================================================== --- trunk/numpy/core/tests/test_umath_complex.py 2010-08-14 13:42:38 UTC (rev 8622) +++ trunk/numpy/core/tests/test_umath_complex.py 2010-08-14 13:42:59 UTC (rev 8623) @@ -1,3 +1,5 @@ +import sys + from numpy.testing import * import numpy.core.umath as ncu import numpy as np @@ -6,6 +8,20 @@ # TODO: conj 'symmetry' # TODO: FPU exceptions +# At least on Windows the results of many complex functions are not conforming +# to the C99 standard. See ticket 1574. +functions_seem_flaky = (np.exp(complex(np.inf, 0)).imag != 0) +# TODO: replace with a check on whether platform-provided C99 funcs are used +have_platform_functions = (sys.platform == 'win32') +skip_complex_tests = have_platform_functions and functions_seem_flaky + +def platform_skip(func): + return dec.skipif(skip_complex_tests, + "Numpy is using complex functions (e.g. sqrt) provided by your" + "platform's C library. However, they do not seem to behave according" + "to C99 -- so C99 tests are skipped.")(func) + + class TestCexp(object): def test_simple(self): check = check_complex_value @@ -17,6 +33,7 @@ ref = np.exp(1) * np.complex(np.cos(1), np.sin(1)) yield check, f, 1, 1, ref.real, ref.imag, False + @platform_skip def test_special_values(self): # C99: Section G 6.3.1 @@ -127,6 +144,7 @@ for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) + @platform_skip def test_special_values(self): xl = [] yl = [] @@ -297,6 +315,7 @@ #def test_branch_cut(self): # _check_branch_cut(f, -1, 0, 1, -1) + @platform_skip def test_special_values(self): check = check_complex_value f = np.sqrt From numpy-svn at scipy.org Sat Aug 14 09:43:19 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:43:19 -0500 (CDT) Subject: [Numpy-svn] r8624 - trunk/numpy/core/include/numpy Message-ID: <20100814134319.89AEE39CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:43:19 -0500 (Sat, 14 Aug 2010) New Revision: 8624 Modified: trunk/numpy/core/include/numpy/npy_math.h Log: BUG: workaround for undefined isnan/isinf in VS2008. Closes #1502. Thanks to Christoph Gohlke. Modified: trunk/numpy/core/include/numpy/npy_math.h =================================================================== --- trunk/numpy/core/include/numpy/npy_math.h 2010-08-14 13:42:59 UTC (rev 8623) +++ trunk/numpy/core/include/numpy/npy_math.h 2010-08-14 13:43:19 UTC (rev 8624) @@ -147,11 +147,19 @@ #ifndef NPY_HAVE_DECL_ISNAN #define npy_isnan(x) ((x) != (x)) #else - #define npy_isnan(x) isnan((x)) + #ifdef _MSC_VER + #define npy_isnan(x) _isnan((x)) + #else + #define npy_isnan(x) isnan((x)) + #endif #endif #ifndef NPY_HAVE_DECL_ISFINITE - #define npy_isfinite(x) !npy_isnan((x) + (-x)) + #ifdef _MSC_VER + #define npy_isfinite(x) _finite((x)) + #else + #define npy_isfinite(x) !npy_isnan((x) + (-x)) + #endif #else #define npy_isfinite(x) isfinite((x)) #endif @@ -159,7 +167,11 @@ #ifndef NPY_HAVE_DECL_ISINF #define npy_isinf(x) (!npy_isfinite(x) && !npy_isnan(x)) #else - #define npy_isinf(x) isinf((x)) + #ifdef _MSC_VER + #define npy_isinf(x) (!_finite((x)) && !_isnan((x))) + #else + #define npy_isinf(x) isinf((x)) + #endif #endif #ifndef NPY_HAVE_DECL_SIGNBIT From numpy-svn at scipy.org Sat Aug 14 09:43:39 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:43:39 -0500 (CDT) Subject: [Numpy-svn] r8625 - trunk/numpy/core/src/private Message-ID: <20100814134339.8B97D39CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:43:39 -0500 (Sat, 14 Aug 2010) New Revision: 8625 Modified: trunk/numpy/core/src/private/npy_config.h Log: BUG: define LDEXPL/FREXPL functions for MSVC builds (see #1499). Note that this doesn't fix the Solaris issue, so #1499 not closed. Thanks to Christoph Gohlke. Modified: trunk/numpy/core/src/private/npy_config.h =================================================================== --- trunk/numpy/core/src/private/npy_config.h 2010-08-14 13:43:19 UTC (rev 8624) +++ trunk/numpy/core/src/private/npy_config.h 2010-08-14 13:43:39 UTC (rev 8625) @@ -9,6 +9,16 @@ #undef HAVE_HYPOT #endif +/* Safe to use ldexp and frexp for long double for MSVC builds */ +#if (SIZEOF_LONG_DOUBLE == SIZEOF_DOUBLE) || defined(_MSC_VER) + #ifdef HAVE_LDEXP + #define HAVE_LDEXPL 1 + #endif + #ifdef HAVE_FREXP + #define HAVE_FREXPL 1 + #endif +#endif + /* Disable broken Sun Workshop Pro math functions */ #ifdef __SUNPRO_C #undef HAVE_ATAN2 From numpy-svn at scipy.org Sat Aug 14 09:44:49 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:44:49 -0500 (CDT) Subject: [Numpy-svn] r8626 - in trunk/numpy/core: . tests Message-ID: <20100814134449.DFB9839CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:44:49 -0500 (Sat, 14 Aug 2010) New Revision: 8626 Modified: trunk/numpy/core/_internal.py trunk/numpy/core/tests/test_records.py Log: DEP: deprecate behavior for out-of-order field indexing of recarrays. See #1431. Modified: trunk/numpy/core/_internal.py =================================================================== --- trunk/numpy/core/_internal.py 2010-08-14 13:43:39 UTC (rev 8625) +++ trunk/numpy/core/_internal.py 2010-08-14 13:44:49 UTC (rev 8626) @@ -3,6 +3,7 @@ import re import sys +import warnings from numpy.compat import asbytes, bytes @@ -335,18 +336,24 @@ from multiarray import empty, dtype dt = ary.dtype new_dtype = [(name, dt[name]) for name in dt.names if name in fields] + future_dtype = [(name, dt[name]) for name in fields if name in dt.names] + if not new_dtype == future_dtype: + depdoc = "Out of order field selection on recarrays currently returns \ +fields in order. This behavior is deprecated in numpy 1.5 and will change in \ +2.0. See ticket #1431." + warnings.warn(depdoc, DeprecationWarning) if ary.flags.f_contiguous: order = 'F' else: order = 'C' - newarray = empty(ary.shape, dtype=new_dtype, order=order) - + newarray = empty(ary.shape, dtype=new_dtype, order=order) + for name in fields: newarray[name] = ary[name] return newarray - + # Given a string containing a PEP 3118 format specifier, # construct a Numpy dtype Modified: trunk/numpy/core/tests/test_records.py =================================================================== --- trunk/numpy/core/tests/test_records.py 2010-08-14 13:43:39 UTC (rev 8625) +++ trunk/numpy/core/tests/test_records.py 2010-08-14 13:44:49 UTC (rev 8626) @@ -3,6 +3,9 @@ from numpy.testing import * from numpy.compat import asbytes, asunicode +import warnings + + class TestFromrecords(TestCase): def test_fromrecords(self): r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], @@ -131,7 +134,18 @@ x[0].col5 = 1 self.assertRaises(AttributeError, assign_invalid_column, a) + def test_out_of_order_fields(self): + """Ticket #1431. Current behavior deprecated in numpy 1.5""" + x = self.data[['col1', 'col2']] + y = self.data[['col2', 'col1']] + # make sure change is applied in 1.6/2.0 + if np.version.short_version[:3] == '1.5': + assert_array_equal(x, y) + elif float(np.version.short_version[:3]) >= 1.6 and np.version.release: + assert_(y[0][0] == 4) +warnings.filterwarnings('ignore', message="Out of order field selection on recarrays") + def test_find_duplicate(): l1 = [1, 2, 3, 4, 5, 6] assert np.rec.find_duplicate(l1) == [] From numpy-svn at scipy.org Sat Aug 14 09:45:09 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:45:09 -0500 (CDT) Subject: [Numpy-svn] r8627 - in trunk/numpy/core: . tests Message-ID: <20100814134509.8AE9139CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:45:09 -0500 (Sat, 14 Aug 2010) New Revision: 8627 Modified: trunk/numpy/core/numeric.py trunk/numpy/core/tests/test_numeric.py Log: DEP: change default behavior of correlate(), old behavior was deprecated in 1.4.0. The old behavior should be preserved and made available under the name xcorr or similar. Should be done for 2.0, then the old_behavior keyword can be removed. Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2010-08-14 13:44:49 UTC (rev 8626) +++ trunk/numpy/core/numeric.py 2010-08-14 13:45:09 UTC (rev 8627) @@ -640,16 +640,17 @@ return _mode_from_name_dict[mode.lower()[0]] return mode -def correlate(a,v,mode='valid',old_behavior=True): +def correlate(a, v, mode='valid', old_behavior=False): """ - Discrete, linear correlation of two 1-dimensional sequences. + Cross-correlation of two 1-dimensional sequences. - This function is equivalent to + This function computes the correlation as generally defined in signal + processing texts:: - >>> np.convolve(a, v[::-1], mode=mode) - ... #doctest: +SKIP + z[k] = sum_n a[n] * conj(v[n+k]) - where ``v[::-1]`` is the reverse of `v`. + with a and v sequences being zero-padded where necessary and conj being + the conjugate. Parameters ---------- @@ -659,28 +660,14 @@ Refer to the `convolve` docstring. Note that the default is `valid`, unlike `convolve`, which uses `full`. old_behavior : bool - If True, uses the old, numeric behavior (correlate(a,v) == correlate(v, + If True, uses the old behavior from Numeric, (correlate(a,v) == correlate(v, a), and the conjugate is not taken for complex arrays). If False, uses the conventional signal processing definition (see note). See Also -------- - convolve : Discrete, linear convolution of two - one-dimensional sequences. - acorrelate : Discrete correlation following the usual signal processing - definition for complex arrays, and without assuming that - ``correlate(a, b) == correlate(b, a)``. + convolve : Discrete, linear convolution of two one-dimensional sequences. - Notes - ----- - If `old_behavior` is False, this function computes the correlation as - generally defined in signal processing texts:: - - z[k] = sum_n a[n] * conj(v[n+k]) - - with a and v sequences being zero-padded where necessary and conj being - the conjugate. - Examples -------- >>> np.correlate([1, 2, 3], [0, 1, 0.5]) @@ -692,10 +679,12 @@ """ mode = _mode_from_name(mode) +# the old behavior should be made available under a different name, see thread +# http://thread.gmane.org/gmane.comp.python.numeric.general/12609/focus=12630 if old_behavior: warnings.warn(""" -The current behavior of correlate is deprecated for 1.4.0, and will be removed -for NumPy 1.5.0. +The old behavior of correlate was deprecated for 1.4.0, and will be completely removed +for NumPy 2.0. The new behavior fits the conventional definition of correlation: inputs are never swapped, and the second argument is conjugated for complex arrays.""", Modified: trunk/numpy/core/tests/test_numeric.py =================================================================== --- trunk/numpy/core/tests/test_numeric.py 2010-08-14 13:44:49 UTC (rev 8626) +++ trunk/numpy/core/tests/test_numeric.py 2010-08-14 13:45:09 UTC (rev 8627) @@ -938,7 +938,7 @@ x = np.array([1, 2, 3, 4+1j], dtype=np.complex) y = np.array([-1, -2j, 3+1j], dtype=np.complex) r_z = np.array([3+1j, 6, 8-1j, 9+1j, -1-8j, -4-1j], dtype=np.complex) - z = np.correlate(x, y, 'full') + z = np.correlate(x, y, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, r_z) @dec.deprecated() From numpy-svn at scipy.org Sat Aug 14 09:45:26 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:45:26 -0500 (CDT) Subject: [Numpy-svn] r8628 - trunk/doc/release Message-ID: <20100814134526.F173239CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:45:26 -0500 (Sat, 14 Aug 2010) New Revision: 8628 Modified: trunk/doc/release/1.5.0-notes.rst Log: DOC: Complete 1.5.0 release notes. Modified: trunk/doc/release/1.5.0-notes.rst =================================================================== --- trunk/doc/release/1.5.0-notes.rst 2010-08-14 13:45:09 UTC (rev 8627) +++ trunk/doc/release/1.5.0-notes.rst 2010-08-14 13:45:26 UTC (rev 8628) @@ -3,24 +3,33 @@ ========================= -Plans -===== +Highlights +========== -This release has the following aims: +Python 3 compatibility +---------------------- -* Python 3 compatibility -* :pep:`3118` compatibility +This is the first NumPy release which is compatible with Python 3. Support for +Python 3 and Python 2 is done from a single code base. Extensive notes on +changes can be found at +``_. +Porting of SciPy to Python 3 is expected to be completed soon. -Highlights -========== +:pep:`3118` compatibility +------------------------- +The new buffer protocol described by PEP 3118 is fully supported in this +version of Numpy. On Python versions >= 2.6 Numpy arrays expose the buffer +interface, and array(), asarray() and other functions accept new-style buffers +as input. + New features ============ Warning on casting complex to real -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +---------------------------------- Numpy now emits a `numpy.ComplexWarning` when a complex number is cast into a real number. For example: @@ -37,7 +46,7 @@ >>> warnings.simplefilter("ignore", np.ComplexWarning) Dot method for ndarrays -~~~~~~~~~~~~~~~~~~~~~~~ +----------------------- Ndarrays now have the dot product also as a method, which allows writing chains of matrix products as @@ -49,7 +58,7 @@ >>> np.dot(a, np.dot(b, c)) linalg.slogdet function -~~~~~~~~~~~~~~~~~~~~~~~ +----------------------- The slogdet function returns the sign and logarithm of the determinant of a matrix. Because the determinant may involve the product of many @@ -57,7 +66,7 @@ by simple multiplication. new header -~~~~~~~~~~ +---------- The new header file ndarraytypes.h contains the symbols from ndarrayobject.h that do not depend on the PY_ARRAY_UNIQUE_SYMBOL and @@ -67,6 +76,7 @@ enumerations without needing to concern themselves with the macro expansions and their side- effects. + Changes ======= @@ -102,5 +112,12 @@ histogram --------- + After a two years transition period, the old behavior of the histogram function has been phased out, and the "new" keyword has been removed. + +correlate +--------- + +The old behavior of correlate was deprecated in 1.4.0, the new behavior (the +usual definition for cross-correlation) is now the default. From numpy-svn at scipy.org Sat Aug 14 09:57:01 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:57:01 -0500 (CDT) Subject: [Numpy-svn] r8629 - branches/1.5.x/numpy/core/include/numpy Message-ID: <20100814135701.68ABC39CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:57:01 -0500 (Sat, 14 Aug 2010) New Revision: 8629 Modified: branches/1.5.x/numpy/core/include/numpy/ndarraytypes.h Log: BUG: (backport of r8622) Better format specifier for Py 2.7, 3.2 on win-amd64. Closes #1570. Thanks to Christoph Gohlke. Modified: branches/1.5.x/numpy/core/include/numpy/ndarraytypes.h =================================================================== --- branches/1.5.x/numpy/core/include/numpy/ndarraytypes.h 2010-08-14 13:45:26 UTC (rev 8628) +++ branches/1.5.x/numpy/core/include/numpy/ndarraytypes.h 2010-08-14 13:57:01 UTC (rev 8629) @@ -275,8 +275,12 @@ #define NPY_MAX_INTP NPY_MAX_LONGLONG #define NPY_MIN_INTP NPY_MIN_LONGLONG #define NPY_MAX_UINTP NPY_MAX_ULONGLONG +#ifdef _MSC_VER + #define NPY_INTP_FMT "lld" +#else #define NPY_INTP_FMT "Ld" #endif +#endif /* * We can only use C99 formats for npy_int_p if it is the same as From numpy-svn at scipy.org Sat Aug 14 09:57:21 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:57:21 -0500 (CDT) Subject: [Numpy-svn] r8630 - branches/1.5.x/numpy/core/include/numpy Message-ID: <20100814135721.316C339CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:57:21 -0500 (Sat, 14 Aug 2010) New Revision: 8630 Modified: branches/1.5.x/numpy/core/include/numpy/npy_math.h Log: BUG: (backport of r8624) workaround for undefined isnan/isinf in VS2008. Closes #1502. Thanks to Christoph Gohlke. Modified: branches/1.5.x/numpy/core/include/numpy/npy_math.h =================================================================== --- branches/1.5.x/numpy/core/include/numpy/npy_math.h 2010-08-14 13:57:01 UTC (rev 8629) +++ branches/1.5.x/numpy/core/include/numpy/npy_math.h 2010-08-14 13:57:21 UTC (rev 8630) @@ -147,11 +147,19 @@ #ifndef NPY_HAVE_DECL_ISNAN #define npy_isnan(x) ((x) != (x)) #else - #define npy_isnan(x) isnan((x)) + #ifdef _MSC_VER + #define npy_isnan(x) _isnan((x)) + #else + #define npy_isnan(x) isnan((x)) + #endif #endif #ifndef NPY_HAVE_DECL_ISFINITE - #define npy_isfinite(x) !npy_isnan((x) + (-x)) + #ifdef _MSC_VER + #define npy_isfinite(x) _finite((x)) + #else + #define npy_isfinite(x) !npy_isnan((x) + (-x)) + #endif #else #define npy_isfinite(x) isfinite((x)) #endif @@ -159,7 +167,11 @@ #ifndef NPY_HAVE_DECL_ISINF #define npy_isinf(x) (!npy_isfinite(x) && !npy_isnan(x)) #else - #define npy_isinf(x) isinf((x)) + #ifdef _MSC_VER + #define npy_isinf(x) (!_finite((x)) && !_isnan((x))) + #else + #define npy_isinf(x) isinf((x)) + #endif #endif #ifndef NPY_HAVE_DECL_SIGNBIT From numpy-svn at scipy.org Sat Aug 14 09:57:42 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:57:42 -0500 (CDT) Subject: [Numpy-svn] r8631 - branches/1.5.x/numpy/core/src/private Message-ID: <20100814135742.4B94E39CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:57:42 -0500 (Sat, 14 Aug 2010) New Revision: 8631 Modified: branches/1.5.x/numpy/core/src/private/npy_config.h Log: BUG: (backport of r8625) define LDEXPL/FREXPL functions for MSVC builds (see #1499). Note that this doesn't fix the Solaris issue, so #1499 not closed. Thanks to Christoph Gohlke. Modified: branches/1.5.x/numpy/core/src/private/npy_config.h =================================================================== --- branches/1.5.x/numpy/core/src/private/npy_config.h 2010-08-14 13:57:21 UTC (rev 8630) +++ branches/1.5.x/numpy/core/src/private/npy_config.h 2010-08-14 13:57:42 UTC (rev 8631) @@ -9,6 +9,16 @@ #undef HAVE_HYPOT #endif +/* Safe to use ldexp and frexp for long double for MSVC builds */ +#if (SIZEOF_LONG_DOUBLE == SIZEOF_DOUBLE) || defined(_MSC_VER) + #ifdef HAVE_LDEXP + #define HAVE_LDEXPL 1 + #endif + #ifdef HAVE_FREXP + #define HAVE_FREXPL 1 + #endif +#endif + /* Disable broken Sun Workshop Pro math functions */ #ifdef __SUNPRO_C #undef HAVE_ATAN2 From numpy-svn at scipy.org Sat Aug 14 09:58:01 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:58:01 -0500 (CDT) Subject: [Numpy-svn] r8632 - in branches/1.5.x/numpy/core: . tests Message-ID: <20100814135801.1FA5C39CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:58:01 -0500 (Sat, 14 Aug 2010) New Revision: 8632 Modified: branches/1.5.x/numpy/core/_internal.py branches/1.5.x/numpy/core/tests/test_records.py Log: DEP: (backport of r8626) deprecate behavior for out-of-order field indexing of recarrays. See #1431. Modified: branches/1.5.x/numpy/core/_internal.py =================================================================== --- branches/1.5.x/numpy/core/_internal.py 2010-08-14 13:57:42 UTC (rev 8631) +++ branches/1.5.x/numpy/core/_internal.py 2010-08-14 13:58:01 UTC (rev 8632) @@ -3,6 +3,7 @@ import re import sys +import warnings from numpy.compat import asbytes, bytes @@ -306,18 +307,24 @@ from multiarray import empty, dtype dt = ary.dtype new_dtype = [(name, dt[name]) for name in dt.names if name in fields] + future_dtype = [(name, dt[name]) for name in fields if name in dt.names] + if not new_dtype == future_dtype: + depdoc = "Out of order field selection on recarrays currently returns \ +fields in order. This behavior is deprecated in numpy 1.5 and will change in \ +2.0. See ticket #1431." + warnings.warn(depdoc, DeprecationWarning) if ary.flags.f_contiguous: order = 'F' else: order = 'C' - newarray = empty(ary.shape, dtype=new_dtype, order=order) - + newarray = empty(ary.shape, dtype=new_dtype, order=order) + for name in fields: newarray[name] = ary[name] return newarray - + # Given a string containing a PEP 3118 format specifier, # construct a Numpy dtype Modified: branches/1.5.x/numpy/core/tests/test_records.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_records.py 2010-08-14 13:57:42 UTC (rev 8631) +++ branches/1.5.x/numpy/core/tests/test_records.py 2010-08-14 13:58:01 UTC (rev 8632) @@ -3,6 +3,9 @@ from numpy.testing import * from numpy.compat import asbytes, asunicode +import warnings + + class TestFromrecords(TestCase): def test_fromrecords(self): r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], @@ -131,7 +134,18 @@ x[0].col5 = 1 self.assertRaises(AttributeError, assign_invalid_column, a) + def test_out_of_order_fields(self): + """Ticket #1431. Current behavior deprecated in numpy 1.5""" + x = self.data[['col1', 'col2']] + y = self.data[['col2', 'col1']] + # make sure change is applied in 1.6/2.0 + if np.version.short_version[:3] == '1.5': + assert_array_equal(x, y) + elif float(np.version.short_version[:3]) >= 1.6 and np.version.release: + assert_(y[0][0] == 4) +warnings.filterwarnings('ignore', message="Out of order field selection on recarrays") + def test_find_duplicate(): l1 = [1, 2, 3, 4, 5, 6] assert np.rec.find_duplicate(l1) == [] From numpy-svn at scipy.org Sat Aug 14 09:58:18 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:58:18 -0500 (CDT) Subject: [Numpy-svn] r8633 - in branches/1.5.x/numpy/core: . tests Message-ID: <20100814135818.E4AF139CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:58:18 -0500 (Sat, 14 Aug 2010) New Revision: 8633 Modified: branches/1.5.x/numpy/core/numeric.py branches/1.5.x/numpy/core/tests/test_numeric.py Log: DEP: (backport of r8627) change default behavior of correlate(), old behavior was deprecated in 1.4.0. The old behavior should be preserved and made available under the name xcorr or similar. Should be done for 2.0, then the old_behavior keyword can be removed. Modified: branches/1.5.x/numpy/core/numeric.py =================================================================== --- branches/1.5.x/numpy/core/numeric.py 2010-08-14 13:58:01 UTC (rev 8632) +++ branches/1.5.x/numpy/core/numeric.py 2010-08-14 13:58:18 UTC (rev 8633) @@ -640,16 +640,17 @@ return _mode_from_name_dict[mode.lower()[0]] return mode -def correlate(a,v,mode='valid',old_behavior=True): +def correlate(a, v, mode='valid', old_behavior=False): """ - Discrete, linear correlation of two 1-dimensional sequences. + Cross-correlation of two 1-dimensional sequences. - This function is equivalent to + This function computes the correlation as generally defined in signal + processing texts:: - >>> np.convolve(a, v[::-1], mode=mode) - ... #doctest: +SKIP + z[k] = sum_n a[n] * conj(v[n+k]) - where ``v[::-1]`` is the reverse of `v`. + with a and v sequences being zero-padded where necessary and conj being + the conjugate. Parameters ---------- @@ -659,28 +660,14 @@ Refer to the `convolve` docstring. Note that the default is `valid`, unlike `convolve`, which uses `full`. old_behavior : bool - If True, uses the old, numeric behavior (correlate(a,v) == correlate(v, + If True, uses the old behavior from Numeric, (correlate(a,v) == correlate(v, a), and the conjugate is not taken for complex arrays). If False, uses the conventional signal processing definition (see note). See Also -------- - convolve : Discrete, linear convolution of two - one-dimensional sequences. - acorrelate : Discrete correlation following the usual signal processing - definition for complex arrays, and without assuming that - ``correlate(a, b) == correlate(b, a)``. + convolve : Discrete, linear convolution of two one-dimensional sequences. - Notes - ----- - If `old_behavior` is False, this function computes the correlation as - generally defined in signal processing texts:: - - z[k] = sum_n a[n] * conj(v[n+k]) - - with a and v sequences being zero-padded where necessary and conj being - the conjugate. - Examples -------- >>> np.correlate([1, 2, 3], [0, 1, 0.5]) @@ -692,10 +679,12 @@ """ mode = _mode_from_name(mode) +# the old behavior should be made available under a different name, see thread +# http://thread.gmane.org/gmane.comp.python.numeric.general/12609/focus=12630 if old_behavior: warnings.warn(""" -The current behavior of correlate is deprecated for 1.4.0, and will be removed -for NumPy 1.5.0. +The old behavior of correlate was deprecated for 1.4.0, and will be completely removed +for NumPy 2.0. The new behavior fits the conventional definition of correlation: inputs are never swapped, and the second argument is conjugated for complex arrays.""", Modified: branches/1.5.x/numpy/core/tests/test_numeric.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_numeric.py 2010-08-14 13:58:01 UTC (rev 8632) +++ branches/1.5.x/numpy/core/tests/test_numeric.py 2010-08-14 13:58:18 UTC (rev 8633) @@ -938,7 +938,7 @@ x = np.array([1, 2, 3, 4+1j], dtype=np.complex) y = np.array([-1, -2j, 3+1j], dtype=np.complex) r_z = np.array([3+1j, 6, 8-1j, 9+1j, -1-8j, -4-1j], dtype=np.complex) - z = np.correlate(x, y, 'full') + z = np.correlate(x, y, 'full', old_behavior=self.old_behavior) assert_array_almost_equal(z, r_z) @dec.deprecated() From numpy-svn at scipy.org Sat Aug 14 09:58:37 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 08:58:37 -0500 (CDT) Subject: [Numpy-svn] r8634 - branches/1.5.x/doc/release Message-ID: <20100814135837.A53E839CAEC@scipy.org> Author: rgommers Date: 2010-08-14 08:58:37 -0500 (Sat, 14 Aug 2010) New Revision: 8634 Modified: branches/1.5.x/doc/release/1.5.0-notes.rst Log: DOC: (backport of r8628) Complete 1.5.0 release notes. Modified: branches/1.5.x/doc/release/1.5.0-notes.rst =================================================================== --- branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-14 13:58:18 UTC (rev 8633) +++ branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-14 13:58:37 UTC (rev 8634) @@ -3,24 +3,33 @@ ========================= -Plans -===== +Highlights +========== -This release has the following aims: +Python 3 compatibility +---------------------- -* Python 3 compatibility -* :pep:`3118` compatibility +This is the first NumPy release which is compatible with Python 3. Support for +Python 3 and Python 2 is done from a single code base. Extensive notes on +changes can be found at +``_. +Porting of SciPy to Python 3 is expected to be completed soon. -Highlights -========== +:pep:`3118` compatibility +------------------------- +The new buffer protocol described by PEP 3118 is fully supported in this +version of Numpy. On Python versions >= 2.6 Numpy arrays expose the buffer +interface, and array(), asarray() and other functions accept new-style buffers +as input. + New features ============ Warning on casting complex to real -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +---------------------------------- Numpy now emits a `numpy.ComplexWarning` when a complex number is cast into a real number. For example: @@ -37,7 +46,7 @@ >>> warnings.simplefilter("ignore", np.ComplexWarning) Dot method for ndarrays -~~~~~~~~~~~~~~~~~~~~~~~ +----------------------- Ndarrays now have the dot product also as a method, which allows writing chains of matrix products as @@ -49,7 +58,7 @@ >>> np.dot(a, np.dot(b, c)) linalg.slogdet function -~~~~~~~~~~~~~~~~~~~~~~~ +----------------------- The slogdet function returns the sign and logarithm of the determinant of a matrix. Because the determinant may involve the product of many @@ -57,7 +66,7 @@ by simple multiplication. new header -~~~~~~~~~~ +---------- The new header file ndarraytypes.h contains the symbols from ndarrayobject.h that do not depend on the PY_ARRAY_UNIQUE_SYMBOL and @@ -67,6 +76,7 @@ enumerations without needing to concern themselves with the macro expansions and their side- effects. + Changes ======= @@ -102,5 +112,12 @@ histogram --------- + After a two years transition period, the old behavior of the histogram function has been phased out, and the "new" keyword has been removed. + +correlate +--------- + +The old behavior of correlate was deprecated in 1.4.0, the new behavior (the +usual definition for cross-correlation) is now the default. From numpy-svn at scipy.org Sat Aug 14 20:40:26 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 19:40:26 -0500 (CDT) Subject: [Numpy-svn] r8635 - in trunk/numpy/polynomial: . tests Message-ID: <20100815004026.C08FF39CAEC@scipy.org> Author: charris Date: 2010-08-14 19:40:26 -0500 (Sat, 14 Aug 2010) New Revision: 8635 Modified: trunk/numpy/polynomial/chebyshev.py trunk/numpy/polynomial/polynomial.py trunk/numpy/polynomial/tests/test_chebyshev.py trunk/numpy/polynomial/tests/test_polynomial.py Log: BUG: Fix integration of zero polynomials. Remove checks that prevent use of foreign scalar types for lower bounds and integration constants. Cleanup code a bit. Modified: trunk/numpy/polynomial/chebyshev.py =================================================================== --- trunk/numpy/polynomial/chebyshev.py 2010-08-14 13:58:37 UTC (rev 8634) +++ trunk/numpy/polynomial/chebyshev.py 2010-08-15 00:40:26 UTC (rev 8635) @@ -852,8 +852,6 @@ raise ValueError, "The order of derivation must be integer" if cnt < 0 : raise ValueError, "The order of derivation must be non-negative" - if not np.isscalar(scl) : - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) @@ -955,23 +953,24 @@ raise ValueError, "The order of integration must be non-negative" if len(k) > cnt : raise ValueError, "Too many integration constants" - if not np.isscalar(lbnd) : - raise ValueError, "The lbnd parameter must be a scalar" - if not np.isscalar(scl) : - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) if cnt == 0: return cs - else: - k = list(k) + [0]*(cnt - len(k)) - for i in range(cnt) : - zs = _cseries_to_zseries(cs)*scl + + k = list(k) + [0]*(cnt - len(k)) + for i in range(cnt) : + n = len(cs) + cs *= scl + if n == 1 and cs[0] == 0: + cs[0] += k[i] + else: + zs = _cseries_to_zseries(cs) zs = _zseries_int(zs) cs = _zseries_to_cseries(zs) cs[0] += k[i] - chebval(lbnd, cs) - return cs + return cs def chebval(x, cs): """Evaluate a Chebyshev series. Modified: trunk/numpy/polynomial/polynomial.py =================================================================== --- trunk/numpy/polynomial/polynomial.py 2010-08-14 13:58:37 UTC (rev 8634) +++ trunk/numpy/polynomial/polynomial.py 2010-08-15 00:40:26 UTC (rev 8635) @@ -460,8 +460,6 @@ raise ValueError, "The order of derivation must be integer" if cnt < 0: raise ValueError, "The order of derivation must be non-negative" - if not np.isscalar(scl): - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) @@ -558,25 +556,26 @@ raise ValueError, "The order of integration must be non-negative" if len(k) > cnt : raise ValueError, "Too many integration constants" - if not np.isscalar(lbnd) : - raise ValueError, "The lbnd parameter must be a scalar" - if not np.isscalar(scl) : - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) if cnt == 0: return cs - else: - k = list(k) + [0]*(cnt - len(k)) - fac = np.arange(1, len(cs) + cnt)/scl - ret = np.zeros(len(cs) + cnt, dtype=cs.dtype) - ret[cnt:] = cs - for i in range(cnt) : - ret[cnt - i:] /= fac[:len(cs) + i] - ret[cnt - i - 1] += k[i] - polyval(lbnd, ret[cnt - i - 1:]) - return ret + k = list(k) + [0]*(cnt - len(k)) + for i in range(cnt): + n = len(cs) + cs *= scl + if n == 1 and cs[0] == 0: + cs[0] += k[i] + else: + tmp = np.empty(n + 1, dtype=cs.dtype) + tmp[0] = cs[0]*0 + tmp[1:] = cs/np.arange(1, n + 1) + tmp[0] += k[i] - polyval(lbnd, tmp) + cs = tmp + return cs + def polyval(x, cs): """ Evaluate a polynomial. Modified: trunk/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-14 13:58:37 UTC (rev 8634) +++ trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 00:40:26 UTC (rev 8635) @@ -139,9 +139,13 @@ assert_raises(ValueError, ch.chebint, [0], .5) assert_raises(ValueError, ch.chebint, [0], -1) assert_raises(ValueError, ch.chebint, [0], 1, [0,0]) - assert_raises(ValueError, ch.chebint, [0], 1, lbnd=[0,0]) - assert_raises(ValueError, ch.chebint, [0], 1, scl=[0,0]) + # test integration of zero polynomial + for i in range(2, 5): + k = [0]*(i - 2) + [1] + res = ch.chebint([0], m=i, k=k) + assert_almost_equal(res, [0, 1]) + # check single integration with integration constant for i in range(5) : scl = i + 1 Modified: trunk/numpy/polynomial/tests/test_polynomial.py =================================================================== --- trunk/numpy/polynomial/tests/test_polynomial.py 2010-08-14 13:58:37 UTC (rev 8634) +++ trunk/numpy/polynomial/tests/test_polynomial.py 2010-08-15 00:40:26 UTC (rev 8635) @@ -124,9 +124,13 @@ assert_raises(ValueError, poly.polyint, [0], .5) assert_raises(ValueError, poly.polyint, [0], -1) assert_raises(ValueError, poly.polyint, [0], 1, [0,0]) - assert_raises(ValueError, poly.polyint, [0], 1, lbnd=[0,0]) - assert_raises(ValueError, poly.polyint, [0], 1, scl=[0,0]) + # test integration of zero polynomial + for i in range(2, 5): + k = [0]*(i - 2) + [1] + res = poly.polyint([0], m=i, k=k) + assert_almost_equal(res, [0, 1]) + # check single integration with integration constant for i in range(5) : scl = i + 1 From numpy-svn at scipy.org Sat Aug 14 20:50:49 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 14 Aug 2010 19:50:49 -0500 (CDT) Subject: [Numpy-svn] r8636 - in branches/1.5.x/numpy/polynomial: . tests Message-ID: <20100815005049.61EDC39CAEC@scipy.org> Author: charris Date: 2010-08-14 19:50:49 -0500 (Sat, 14 Aug 2010) New Revision: 8636 Modified: branches/1.5.x/numpy/polynomial/chebyshev.py branches/1.5.x/numpy/polynomial/polynomial.py branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py branches/1.5.x/numpy/polynomial/tests/test_polynomial.py Log: BUG: Backport r8635 from trunk. Modified: branches/1.5.x/numpy/polynomial/chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/chebyshev.py 2010-08-15 00:40:26 UTC (rev 8635) +++ branches/1.5.x/numpy/polynomial/chebyshev.py 2010-08-15 00:50:49 UTC (rev 8636) @@ -852,8 +852,6 @@ raise ValueError, "The order of derivation must be integer" if cnt < 0 : raise ValueError, "The order of derivation must be non-negative" - if not np.isscalar(scl) : - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) @@ -955,23 +953,24 @@ raise ValueError, "The order of integration must be non-negative" if len(k) > cnt : raise ValueError, "Too many integration constants" - if not np.isscalar(lbnd) : - raise ValueError, "The lbnd parameter must be a scalar" - if not np.isscalar(scl) : - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) if cnt == 0: return cs - else: - k = list(k) + [0]*(cnt - len(k)) - for i in range(cnt) : - zs = _cseries_to_zseries(cs)*scl + + k = list(k) + [0]*(cnt - len(k)) + for i in range(cnt) : + n = len(cs) + cs *= scl + if n == 1 and cs[0] == 0: + cs[0] += k[i] + else: + zs = _cseries_to_zseries(cs) zs = _zseries_int(zs) cs = _zseries_to_cseries(zs) cs[0] += k[i] - chebval(lbnd, cs) - return cs + return cs def chebval(x, cs): """Evaluate a Chebyshev series. Modified: branches/1.5.x/numpy/polynomial/polynomial.py =================================================================== --- branches/1.5.x/numpy/polynomial/polynomial.py 2010-08-15 00:40:26 UTC (rev 8635) +++ branches/1.5.x/numpy/polynomial/polynomial.py 2010-08-15 00:50:49 UTC (rev 8636) @@ -460,8 +460,6 @@ raise ValueError, "The order of derivation must be integer" if cnt < 0: raise ValueError, "The order of derivation must be non-negative" - if not np.isscalar(scl): - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) @@ -558,25 +556,26 @@ raise ValueError, "The order of integration must be non-negative" if len(k) > cnt : raise ValueError, "Too many integration constants" - if not np.isscalar(lbnd) : - raise ValueError, "The lbnd parameter must be a scalar" - if not np.isscalar(scl) : - raise ValueError, "The scl parameter must be a scalar" # cs is a trimmed copy [cs] = pu.as_series([cs]) if cnt == 0: return cs - else: - k = list(k) + [0]*(cnt - len(k)) - fac = np.arange(1, len(cs) + cnt)/scl - ret = np.zeros(len(cs) + cnt, dtype=cs.dtype) - ret[cnt:] = cs - for i in range(cnt) : - ret[cnt - i:] /= fac[:len(cs) + i] - ret[cnt - i - 1] += k[i] - polyval(lbnd, ret[cnt - i - 1:]) - return ret + k = list(k) + [0]*(cnt - len(k)) + for i in range(cnt): + n = len(cs) + cs *= scl + if n == 1 and cs[0] == 0: + cs[0] += k[i] + else: + tmp = np.empty(n + 1, dtype=cs.dtype) + tmp[0] = cs[0]*0 + tmp[1:] = cs/np.arange(1, n + 1) + tmp[0] += k[i] - polyval(lbnd, tmp) + cs = tmp + return cs + def polyval(x, cs): """ Evaluate a polynomial. Modified: branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 00:40:26 UTC (rev 8635) +++ branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 00:50:49 UTC (rev 8636) @@ -139,9 +139,13 @@ assert_raises(ValueError, ch.chebint, [0], .5) assert_raises(ValueError, ch.chebint, [0], -1) assert_raises(ValueError, ch.chebint, [0], 1, [0,0]) - assert_raises(ValueError, ch.chebint, [0], 1, lbnd=[0,0]) - assert_raises(ValueError, ch.chebint, [0], 1, scl=[0,0]) + # test integration of zero polynomial + for i in range(2, 5): + k = [0]*(i - 2) + [1] + res = ch.chebint([0], m=i, k=k) + assert_almost_equal(res, [0, 1]) + # check single integration with integration constant for i in range(5) : scl = i + 1 Modified: branches/1.5.x/numpy/polynomial/tests/test_polynomial.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_polynomial.py 2010-08-15 00:40:26 UTC (rev 8635) +++ branches/1.5.x/numpy/polynomial/tests/test_polynomial.py 2010-08-15 00:50:49 UTC (rev 8636) @@ -124,9 +124,13 @@ assert_raises(ValueError, poly.polyint, [0], .5) assert_raises(ValueError, poly.polyint, [0], -1) assert_raises(ValueError, poly.polyint, [0], 1, [0,0]) - assert_raises(ValueError, poly.polyint, [0], 1, lbnd=[0,0]) - assert_raises(ValueError, poly.polyint, [0], 1, scl=[0,0]) + # test integration of zero polynomial + for i in range(2, 5): + k = [0]*(i - 2) + [1] + res = poly.polyint([0], m=i, k=k) + assert_almost_equal(res, [0, 1]) + # check single integration with integration constant for i in range(5) : scl = i + 1 From numpy-svn at scipy.org Sun Aug 15 14:16:38 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 13:16:38 -0500 (CDT) Subject: [Numpy-svn] r8637 - in trunk/numpy/polynomial: . tests Message-ID: <20100815181638.A071539CC36@scipy.org> Author: charris Date: 2010-08-15 13:16:38 -0500 (Sun, 15 Aug 2010) New Revision: 8637 Modified: trunk/numpy/polynomial/chebyshev.py trunk/numpy/polynomial/polynomial.py trunk/numpy/polynomial/tests/test_chebyshev.py trunk/numpy/polynomial/tests/test_polynomial.py Log: ENH: Add {cheb,poly}mulx functions as use them to simplify some code. Fix some documentation. Modified: trunk/numpy/polynomial/chebyshev.py =================================================================== --- trunk/numpy/polynomial/chebyshev.py 2010-08-15 00:50:49 UTC (rev 8636) +++ trunk/numpy/polynomial/chebyshev.py 2010-08-15 18:16:38 UTC (rev 8637) @@ -76,9 +76,9 @@ from __future__ import division __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', - 'chebadd', 'chebsub', 'chebmul', 'chebdiv', 'chebval', 'chebder', - 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', 'chebvander', - 'chebfit', 'chebtrim', 'chebroots', 'Chebyshev'] + 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebval', + 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', + 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'Chebyshev'] import numpy as np import numpy.linalg as la @@ -304,8 +304,6 @@ def poly2cheb(pol) : """ - poly2cheb(pol) - Convert a polynomial to a Chebyshev series. Convert an array representing the coefficients of a polynomial (relative @@ -330,36 +328,32 @@ Notes ----- - Note that a consequence of the input needing to be array_like and that - the output is an ndarray, is that if one is going to use this function - to convert a Polynomial instance, P, to a Chebyshev instance, T, the - usage is ``T = Chebyshev(poly2cheb(P.coef))``; see Examples below. + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P - >>> p = P.Polynomial(np.arange(4)) + >>> p = P.Polynomial(range(4)) >>> p Polynomial([ 0., 1., 2., 3.], [-1., 1.]) - >>> c = P.Chebyshev(P.poly2cheb(p.coef)) + >>> c = p.convert(kind=P.Chebyshev) >>> c Chebyshev([ 1. , 3.25, 1. , 0.75], [-1., 1.]) + >>> P.poly2cheb(range(4)) + array([ 1. , 3.25, 1. , 0.75]) """ [pol] = pu.as_series([pol]) - pol = pol[::-1] - zs = pol[:1].copy() - x = np.array([.5, 0, .5], dtype=pol.dtype) - for i in range(1, len(pol)) : - zs = _zseries_mul(zs, x) - zs[i] += pol[i] - return _zseries_to_cseries(zs) + deg = len(pol) - 1 + res = 0 + for i in range(deg, -1, -1) : + res = chebadd(chebmulx(res), pol[i]) + return res def cheb2poly(cs) : """ - cheb2poly(cs) - Convert a Chebyshev series to a polynomial. Convert an array representing the coefficients of a Chebyshev series, @@ -386,32 +380,38 @@ Notes ----- - Note that a consequence of the input needing to be array_like and that - the output is an ndarray, is that if one is going to use this function - to convert a Chebyshev instance, T, to a Polynomial instance, P, the - usage is ``P = Polynomial(cheb2poly(T.coef))``; see Examples below. + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P - >>> c = P.Chebyshev(np.arange(4)) + >>> c = P.Chebyshev(range(4)) >>> c Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) - >>> p = P.Polynomial(P.cheb2poly(c.coef)) + >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([ -2., -8., 4., 12.], [-1., 1.]) + >>> P.cheb2poly(range(4)) + array([ -2., -8., 4., 12.]) """ + from polynomial import polyadd, polysub, polymulx + [cs] = pu.as_series([cs]) - pol = np.zeros(len(cs), dtype=cs.dtype) - quo = _cseries_to_zseries(cs) - x = np.array([.5, 0, .5], dtype=pol.dtype) - for i in range(0, len(cs) - 1) : - quo, rem = _zseries_div(quo, x) - pol[i] = rem[0] - pol[-1] = quo[0] - return pol + n = len(cs) + if n < 3: + return cs + else: + c0 = cs[-2] + c1 = cs[-1] + for i in range(n - 3, -1, -1) : + tmp = c0 + c0 = polysub(cs[i], c1) + c1 = polyadd(tmp, polymulx(c1)*2) + return polyadd(c0, polymulx(c1)) + # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. @@ -521,10 +521,9 @@ else : [roots] = pu.as_series([roots], trim=False) prd = np.array([1], dtype=roots.dtype) - for r in roots : - fac = np.array([.5, -r, .5], dtype=roots.dtype) - prd = _zseries_mul(fac, prd) - return _zseries_to_cseries(prd) + for r in roots: + prd = chebsub(chebmulx(prd), r*prd) + return prd def chebadd(c1, c2): @@ -630,6 +629,41 @@ return pu.trimseq(ret) +def chebmulx(cs): + """Multiply a Chebyshev series by x. + + Multiply the polynomial `cs` by x, where x is the independent + variable. + + + Parameters + ---------- + cs : array_like + 1-d array of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + # The zero series needs special treatment + if len(cs) == 1 and cs[0] == 0: + return cs + + prd = np.empty(len(cs) + 1, dtype=cs.dtype) + prd[0] = cs[0]*0 + prd[1] = cs[0] + if len(cs) > 1: + tmp = cs[1:]/2 + prd[2:] = tmp + prd[0:-2] += tmp + return prd + + def chebmul(c1, c2): """ Multiply one Chebyshev series by another. @@ -1046,7 +1080,7 @@ ---------- x : array_like Array of points. The values are converted to double or complex - doubles. + doubles. If x is scalar it is converted to a 1D array. deg : integer Degree of the resulting matrix. @@ -1057,16 +1091,24 @@ index is the degree. """ - x = np.asarray(x) + 0.0 - order = int(deg) + 1 - v = np.ones((order,) + x.shape, dtype=x.dtype) - if order > 1 : + ideg = int(deg) + if ideg != deg: + raise ValueError("deg must be integer") + if ideg < 0: + raise ValueError("deg must be non-negative") + + x = np.array(x, copy=0, ndmin=1) + 0.0 + v = np.empty((ideg + 1,) + x.shape, dtype=x.dtype) + # Use forward recursion to generate the entries. + v[0] = x*0 + 1 + if ideg > 0 : x2 = 2*x v[1] = x - for i in range(2, order) : + for i in range(2, ideg + 1) : v[i] = v[i-1]*x2 - v[i-2] return np.rollaxis(v, 0, v.ndim) + def chebfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Chebyshev series to data. @@ -1270,12 +1312,17 @@ return np.array([], dtype=cs.dtype) if len(cs) == 2 : return np.array([-cs[0]/cs[1]]) + n = len(cs) - 1 + cs /= cs[-1] cmat = np.zeros((n,n), dtype=cs.dtype) - cmat.flat[1::n+1] = .5 - cmat.flat[n::n+1] = .5 cmat[1, 0] = 1 - cmat[:,-1] -= cs[:-1]*(.5/cs[-1]) + for i in range(1, n): + cmat[i - 1, i] = .5 + if i != n - 1: + cmat[i + 1, i] = .5 + else: + cmat[:, i] -= cs[:-1]*.5 roots = la.eigvals(cmat) roots.sort() return roots @@ -1286,4 +1333,3 @@ # exec polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]') - Modified: trunk/numpy/polynomial/polynomial.py =================================================================== --- trunk/numpy/polynomial/polynomial.py 2010-08-15 00:50:49 UTC (rev 8636) +++ trunk/numpy/polynomial/polynomial.py 2010-08-15 18:16:38 UTC (rev 8637) @@ -48,8 +48,8 @@ """ from __future__ import division -__all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', - 'polyline','polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', +__all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', + 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polyval', 'polyder', 'polyint', 'polyfromroots', 'polyvander', 'polyfit', 'polytrim', 'polyroots', 'Polynomial'] @@ -169,10 +169,9 @@ return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) - prd = np.zeros(len(roots) + 1, dtype=roots.dtype) - prd[-1] = 1 - for i in range(len(roots)) : - prd[-(i+2):-1] -= roots[i]*prd[-(i+1):] + prd = np.array([1], dtype=roots.dtype) + for r in roots: + prd = polysub(polymulx(prd), r*prd) return prd @@ -266,6 +265,37 @@ return pu.trimseq(ret) +def polymulx(cs): + """Multiply a polynomial by x. + + Multiply the polynomial `cs` by x, where x is the independent + variable. + + + Parameters + ---------- + cs : array_like + 1-d array of polynomial coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + # The zero series needs special treatment + if len(cs) == 1 and cs[0] == 0: + return cs + + prd = np.empty(len(cs) + 1, dtype=cs.dtype) + prd[0] = cs[0]*0 + prd[1:] = cs + return prd + + def polymul(c1, c2): """ Multiply one polynomial by another. @@ -632,7 +662,8 @@ Parameters ---------- x : array_like - Array of points. The values are converted to double or complex doubles. + Array of points. The values are converted to double or complex + doubles. If x is scalar it is converted to a 1D array. deg : integer Degree of the resulting matrix. @@ -643,12 +674,18 @@ index is the degree. """ - x = np.asarray(x) + 0.0 - order = int(deg) + 1 - v = np.ones((order,) + x.shape, dtype=x.dtype) - if order > 1 : + ideg = int(deg) + if ideg != deg: + raise ValueError("deg must be integer") + if ideg < 0: + raise ValueError("deg must be non-negative") + + x = np.array(x, copy=0, ndmin=1) + 0.0 + v = np.empty((ideg + 1,) + x.shape, dtype=x.dtype) + v[0] = x*0 + 1 + if ideg > 0 : v[1] = x - for i in range(2, order) : + for i in range(2, ideg + 1) : v[i] = v[i-1]*x return np.rollaxis(v, 0, v.ndim) @@ -874,6 +911,7 @@ return np.array([], dtype=cs.dtype) if len(cs) == 2 : return np.array([-cs[0]/cs[1]]) + n = len(cs) - 1 cmat = np.zeros((n,n), dtype=cs.dtype) cmat.flat[n::n+1] = 1 Modified: trunk/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 00:50:49 UTC (rev 8636) +++ trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 18:16:38 UTC (rev 8637) @@ -78,6 +78,14 @@ res = ch.chebsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) + def test_chebmulx(self): + assert_equal(ch.chebmulx([0]), [0]) + assert_equal(ch.chebmulx([1]), [0,1]) + for i in range(1, 5): + ser = [0]*i + [1] + tgt = [0]*(i - 1) + [.5, 0, .5] + assert_equal(ch.chebmulx(ser), tgt) + def test_chebmul(self) : for i in range(5) : for j in range(5) : Modified: trunk/numpy/polynomial/tests/test_polynomial.py =================================================================== --- trunk/numpy/polynomial/tests/test_polynomial.py 2010-08-15 00:50:49 UTC (rev 8636) +++ trunk/numpy/polynomial/tests/test_polynomial.py 2010-08-15 18:16:38 UTC (rev 8637) @@ -61,6 +61,14 @@ res = poly.polysub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) + def test_polymulx(self): + assert_equal(poly.polymulx([0]), [0]) + assert_equal(poly.polymulx([1]), [0, 1]) + for i in range(1, 5): + ser = [0]*i + [1] + tgt = [0]*(i + 1) + [1] + assert_equal(poly.polymulx(ser), tgt) + def test_polymul(self) : for i in range(5) : for j in range(5) : From numpy-svn at scipy.org Sun Aug 15 15:11:00 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 14:11:00 -0500 (CDT) Subject: [Numpy-svn] r8638 - in trunk: doc/release numpy/lib numpy/polynomial Message-ID: <20100815191100.2DA5039CC36@scipy.org> Author: charris Date: 2010-08-15 14:11:00 -0500 (Sun, 15 Aug 2010) New Revision: 8638 Modified: trunk/doc/release/1.5.0-notes.rst trunk/numpy/lib/npyio.py trunk/numpy/polynomial/chebyshev.py trunk/numpy/polynomial/polynomial.py trunk/numpy/polynomial/polytemplate.py Log: Merge branch 'poly' Conflicts: numpy/polynomial/chebyshev.py numpy/polynomial/polynomial.py Modified: trunk/doc/release/1.5.0-notes.rst =================================================================== --- trunk/doc/release/1.5.0-notes.rst 2010-08-15 18:16:38 UTC (rev 8637) +++ trunk/doc/release/1.5.0-notes.rst 2010-08-15 19:11:00 UTC (rev 8638) @@ -94,6 +94,7 @@ Polynomial domain can be specified by using [] as the domain value. * Weights can be used in both polyfit and Polynomial.fit * A linspace method has been added to the Polynomial class to ease plotting. +* The polymulx function was added. polynomial.chebyshev -------------------- @@ -109,7 +110,9 @@ Chebyshev domain can be specified by using [] as the domain value. * Weights can be used in both chebfit and Chebyshev.fit * A linspace method has been added to the Chebyshev class to ease plotting. +* The chebmulx function was added. + histogram --------- Modified: trunk/numpy/lib/npyio.py =================================================================== --- trunk/numpy/lib/npyio.py 2010-08-15 18:16:38 UTC (rev 8637) +++ trunk/numpy/lib/npyio.py 2010-08-15 19:11:00 UTC (rev 8638) @@ -722,7 +722,7 @@ delimiter : str Character separating columns. newline : str - .. versionadded:: 2.0 + .. versionadded:: 1.5.0 Character separating lines. Modified: trunk/numpy/polynomial/chebyshev.py =================================================================== --- trunk/numpy/polynomial/chebyshev.py 2010-08-15 18:16:38 UTC (rev 8637) +++ trunk/numpy/polynomial/chebyshev.py 2010-08-15 19:11:00 UTC (rev 8638) @@ -647,6 +647,13 @@ out : ndarray Array representing the result of the multiplication. +<<<<<<< HEAD +======= + Notes + ----- + .. versionadded:: 1.5.0 + +>>>>>>> poly """ # cs is a trimmed copy [cs] = pu.as_series([cs]) @@ -978,7 +985,7 @@ """ cnt = int(m) - if np.isscalar(k) : + if not np.iterable(k): k = [k] if cnt != m: Modified: trunk/numpy/polynomial/polynomial.py =================================================================== --- trunk/numpy/polynomial/polynomial.py 2010-08-15 18:16:38 UTC (rev 8637) +++ trunk/numpy/polynomial/polynomial.py 2010-08-15 19:11:00 UTC (rev 8638) @@ -283,6 +283,10 @@ out : ndarray Array representing the result of the multiplication. + Notes + ----- + .. versionadded:: 1.5.0 + """ # cs is a trimmed copy [cs] = pu.as_series([cs]) @@ -544,8 +548,7 @@ Raises ------ ValueError - If ``m < 1``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or - ``np.isscalar(scl) == False``. + If ``m < 1``, ``len(k) > m``. See Also -------- @@ -577,7 +580,7 @@ """ cnt = int(m) - if np.isscalar(k) : + if not np.iterable(k): k = [k] if cnt != m: Modified: trunk/numpy/polynomial/polytemplate.py =================================================================== --- trunk/numpy/polynomial/polytemplate.py 2010-08-15 18:16:38 UTC (rev 8637) +++ trunk/numpy/polynomial/polytemplate.py 2010-08-15 19:11:00 UTC (rev 8638) @@ -308,7 +308,7 @@ Notes ----- - .. versionadded:: 2.0.0 + .. versionadded:: 1.5.0 """ return len(self) - 1 @@ -335,7 +335,7 @@ Notes ----- - .. versionadded:: 2.0.0 + .. versionadded:: 1.5.0 """ return self.truncate(deg + 1) From numpy-svn at scipy.org Sun Aug 15 15:11:02 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 14:11:02 -0500 (CDT) Subject: [Numpy-svn] r8639 - trunk/numpy/polynomial Message-ID: <20100815191102.9020439CD17@scipy.org> Author: charris Date: 2010-08-15 14:11:02 -0500 (Sun, 15 Aug 2010) New Revision: 8639 Modified: trunk/numpy/polynomial/chebyshev.py Log: FIX: Merge munge. Modified: trunk/numpy/polynomial/chebyshev.py =================================================================== --- trunk/numpy/polynomial/chebyshev.py 2010-08-15 19:11:00 UTC (rev 8638) +++ trunk/numpy/polynomial/chebyshev.py 2010-08-15 19:11:02 UTC (rev 8639) @@ -647,13 +647,10 @@ out : ndarray Array representing the result of the multiplication. -<<<<<<< HEAD -======= Notes ----- .. versionadded:: 1.5.0 ->>>>>>> poly """ # cs is a trimmed copy [cs] = pu.as_series([cs]) From numpy-svn at scipy.org Sun Aug 15 15:24:11 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 14:24:11 -0500 (CDT) Subject: [Numpy-svn] r8640 - in branches/1.5.x: doc/release numpy/lib numpy/polynomial numpy/polynomial/tests Message-ID: <20100815192411.83DCD39CC36@scipy.org> Author: charris Date: 2010-08-15 14:24:11 -0500 (Sun, 15 Aug 2010) New Revision: 8640 Modified: branches/1.5.x/doc/release/1.5.0-notes.rst branches/1.5.x/numpy/lib/npyio.py branches/1.5.x/numpy/polynomial/chebyshev.py branches/1.5.x/numpy/polynomial/polynomial.py branches/1.5.x/numpy/polynomial/polytemplate.py branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py branches/1.5.x/numpy/polynomial/tests/test_polynomial.py Log: BUG: Backport r8637-r3639 from trunk. They are a mix of small fixes and enhancements. Modified: branches/1.5.x/doc/release/1.5.0-notes.rst =================================================================== --- branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-15 19:24:11 UTC (rev 8640) @@ -94,6 +94,7 @@ Polynomial domain can be specified by using [] as the domain value. * Weights can be used in both polyfit and Polynomial.fit * A linspace method has been added to the Polynomial class to ease plotting. +* The polymulx function was added. polynomial.chebyshev -------------------- @@ -109,7 +110,9 @@ Chebyshev domain can be specified by using [] as the domain value. * Weights can be used in both chebfit and Chebyshev.fit * A linspace method has been added to the Chebyshev class to ease plotting. +* The chebmulx function was added. + histogram --------- Modified: branches/1.5.x/numpy/lib/npyio.py =================================================================== --- branches/1.5.x/numpy/lib/npyio.py 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/numpy/lib/npyio.py 2010-08-15 19:24:11 UTC (rev 8640) @@ -722,7 +722,7 @@ delimiter : str Character separating columns. newline : str - .. versionadded:: 2.0 + .. versionadded:: 1.5.0 Character separating lines. Modified: branches/1.5.x/numpy/polynomial/chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/chebyshev.py 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/numpy/polynomial/chebyshev.py 2010-08-15 19:24:11 UTC (rev 8640) @@ -76,9 +76,9 @@ from __future__ import division __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', - 'chebadd', 'chebsub', 'chebmul', 'chebdiv', 'chebval', 'chebder', - 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', 'chebvander', - 'chebfit', 'chebtrim', 'chebroots', 'Chebyshev'] + 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebval', + 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', + 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'Chebyshev'] import numpy as np import numpy.linalg as la @@ -304,8 +304,6 @@ def poly2cheb(pol) : """ - poly2cheb(pol) - Convert a polynomial to a Chebyshev series. Convert an array representing the coefficients of a polynomial (relative @@ -330,36 +328,32 @@ Notes ----- - Note that a consequence of the input needing to be array_like and that - the output is an ndarray, is that if one is going to use this function - to convert a Polynomial instance, P, to a Chebyshev instance, T, the - usage is ``T = Chebyshev(poly2cheb(P.coef))``; see Examples below. + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P - >>> p = P.Polynomial(np.arange(4)) + >>> p = P.Polynomial(range(4)) >>> p Polynomial([ 0., 1., 2., 3.], [-1., 1.]) - >>> c = P.Chebyshev(P.poly2cheb(p.coef)) + >>> c = p.convert(kind=P.Chebyshev) >>> c Chebyshev([ 1. , 3.25, 1. , 0.75], [-1., 1.]) + >>> P.poly2cheb(range(4)) + array([ 1. , 3.25, 1. , 0.75]) """ [pol] = pu.as_series([pol]) - pol = pol[::-1] - zs = pol[:1].copy() - x = np.array([.5, 0, .5], dtype=pol.dtype) - for i in range(1, len(pol)) : - zs = _zseries_mul(zs, x) - zs[i] += pol[i] - return _zseries_to_cseries(zs) + deg = len(pol) - 1 + res = 0 + for i in range(deg, -1, -1) : + res = chebadd(chebmulx(res), pol[i]) + return res def cheb2poly(cs) : """ - cheb2poly(cs) - Convert a Chebyshev series to a polynomial. Convert an array representing the coefficients of a Chebyshev series, @@ -386,32 +380,38 @@ Notes ----- - Note that a consequence of the input needing to be array_like and that - the output is an ndarray, is that if one is going to use this function - to convert a Chebyshev instance, T, to a Polynomial instance, P, the - usage is ``P = Polynomial(cheb2poly(T.coef))``; see Examples below. + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. Examples -------- >>> from numpy import polynomial as P - >>> c = P.Chebyshev(np.arange(4)) + >>> c = P.Chebyshev(range(4)) >>> c Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) - >>> p = P.Polynomial(P.cheb2poly(c.coef)) + >>> p = c.convert(kind=P.Polynomial) >>> p Polynomial([ -2., -8., 4., 12.], [-1., 1.]) + >>> P.cheb2poly(range(4)) + array([ -2., -8., 4., 12.]) """ + from polynomial import polyadd, polysub, polymulx + [cs] = pu.as_series([cs]) - pol = np.zeros(len(cs), dtype=cs.dtype) - quo = _cseries_to_zseries(cs) - x = np.array([.5, 0, .5], dtype=pol.dtype) - for i in range(0, len(cs) - 1) : - quo, rem = _zseries_div(quo, x) - pol[i] = rem[0] - pol[-1] = quo[0] - return pol + n = len(cs) + if n < 3: + return cs + else: + c0 = cs[-2] + c1 = cs[-1] + for i in range(n - 3, -1, -1) : + tmp = c0 + c0 = polysub(cs[i], c1) + c1 = polyadd(tmp, polymulx(c1)*2) + return polyadd(c0, polymulx(c1)) + # # These are constant arrays are of integer type so as to be compatible # with the widest range of other types, such as Decimal. @@ -521,10 +521,9 @@ else : [roots] = pu.as_series([roots], trim=False) prd = np.array([1], dtype=roots.dtype) - for r in roots : - fac = np.array([.5, -r, .5], dtype=roots.dtype) - prd = _zseries_mul(fac, prd) - return _zseries_to_cseries(prd) + for r in roots: + prd = chebsub(chebmulx(prd), r*prd) + return prd def chebadd(c1, c2): @@ -630,6 +629,45 @@ return pu.trimseq(ret) +def chebmulx(cs): + """Multiply a Chebyshev series by x. + + Multiply the polynomial `cs` by x, where x is the independent + variable. + + + Parameters + ---------- + cs : array_like + 1-d array of Chebyshev series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + Notes + ----- + .. versionadded:: 1.5.0 + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + # The zero series needs special treatment + if len(cs) == 1 and cs[0] == 0: + return cs + + prd = np.empty(len(cs) + 1, dtype=cs.dtype) + prd[0] = cs[0]*0 + prd[1] = cs[0] + if len(cs) > 1: + tmp = cs[1:]/2 + prd[2:] = tmp + prd[0:-2] += tmp + return prd + + def chebmul(c1, c2): """ Multiply one Chebyshev series by another. @@ -944,7 +982,7 @@ """ cnt = int(m) - if np.isscalar(k) : + if not np.iterable(k): k = [k] if cnt != m: @@ -1046,7 +1084,7 @@ ---------- x : array_like Array of points. The values are converted to double or complex - doubles. + doubles. If x is scalar it is converted to a 1D array. deg : integer Degree of the resulting matrix. @@ -1057,16 +1095,24 @@ index is the degree. """ - x = np.asarray(x) + 0.0 - order = int(deg) + 1 - v = np.ones((order,) + x.shape, dtype=x.dtype) - if order > 1 : + ideg = int(deg) + if ideg != deg: + raise ValueError("deg must be integer") + if ideg < 0: + raise ValueError("deg must be non-negative") + + x = np.array(x, copy=0, ndmin=1) + 0.0 + v = np.empty((ideg + 1,) + x.shape, dtype=x.dtype) + # Use forward recursion to generate the entries. + v[0] = x*0 + 1 + if ideg > 0 : x2 = 2*x v[1] = x - for i in range(2, order) : + for i in range(2, ideg + 1) : v[i] = v[i-1]*x2 - v[i-2] return np.rollaxis(v, 0, v.ndim) + def chebfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Chebyshev series to data. @@ -1270,12 +1316,17 @@ return np.array([], dtype=cs.dtype) if len(cs) == 2 : return np.array([-cs[0]/cs[1]]) + n = len(cs) - 1 + cs /= cs[-1] cmat = np.zeros((n,n), dtype=cs.dtype) - cmat.flat[1::n+1] = .5 - cmat.flat[n::n+1] = .5 cmat[1, 0] = 1 - cmat[:,-1] -= cs[:-1]*(.5/cs[-1]) + for i in range(1, n): + cmat[i - 1, i] = .5 + if i != n - 1: + cmat[i + 1, i] = .5 + else: + cmat[:, i] -= cs[:-1]*.5 roots = la.eigvals(cmat) roots.sort() return roots @@ -1286,4 +1337,3 @@ # exec polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]') - Modified: branches/1.5.x/numpy/polynomial/polynomial.py =================================================================== --- branches/1.5.x/numpy/polynomial/polynomial.py 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/numpy/polynomial/polynomial.py 2010-08-15 19:24:11 UTC (rev 8640) @@ -48,8 +48,8 @@ """ from __future__ import division -__all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', - 'polyline','polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', +__all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', + 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polyval', 'polyder', 'polyint', 'polyfromroots', 'polyvander', 'polyfit', 'polytrim', 'polyroots', 'Polynomial'] @@ -169,10 +169,9 @@ return np.ones(1) else : [roots] = pu.as_series([roots], trim=False) - prd = np.zeros(len(roots) + 1, dtype=roots.dtype) - prd[-1] = 1 - for i in range(len(roots)) : - prd[-(i+2):-1] -= roots[i]*prd[-(i+1):] + prd = np.array([1], dtype=roots.dtype) + for r in roots: + prd = polysub(polymulx(prd), r*prd) return prd @@ -266,6 +265,41 @@ return pu.trimseq(ret) +def polymulx(cs): + """Multiply a polynomial by x. + + Multiply the polynomial `cs` by x, where x is the independent + variable. + + + Parameters + ---------- + cs : array_like + 1-d array of polynomial coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + Notes + ----- + .. versionadded:: 1.5.0 + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + # The zero series needs special treatment + if len(cs) == 1 and cs[0] == 0: + return cs + + prd = np.empty(len(cs) + 1, dtype=cs.dtype) + prd[0] = cs[0]*0 + prd[1:] = cs + return prd + + def polymul(c1, c2): """ Multiply one polynomial by another. @@ -514,8 +548,7 @@ Raises ------ ValueError - If ``m < 1``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or - ``np.isscalar(scl) == False``. + If ``m < 1``, ``len(k) > m``. See Also -------- @@ -547,7 +580,7 @@ """ cnt = int(m) - if np.isscalar(k) : + if not np.iterable(k): k = [k] if cnt != m: @@ -632,7 +665,8 @@ Parameters ---------- x : array_like - Array of points. The values are converted to double or complex doubles. + Array of points. The values are converted to double or complex + doubles. If x is scalar it is converted to a 1D array. deg : integer Degree of the resulting matrix. @@ -643,12 +677,18 @@ index is the degree. """ - x = np.asarray(x) + 0.0 - order = int(deg) + 1 - v = np.ones((order,) + x.shape, dtype=x.dtype) - if order > 1 : + ideg = int(deg) + if ideg != deg: + raise ValueError("deg must be integer") + if ideg < 0: + raise ValueError("deg must be non-negative") + + x = np.array(x, copy=0, ndmin=1) + 0.0 + v = np.empty((ideg + 1,) + x.shape, dtype=x.dtype) + v[0] = x*0 + 1 + if ideg > 0 : v[1] = x - for i in range(2, order) : + for i in range(2, ideg + 1) : v[i] = v[i-1]*x return np.rollaxis(v, 0, v.ndim) @@ -874,6 +914,7 @@ return np.array([], dtype=cs.dtype) if len(cs) == 2 : return np.array([-cs[0]/cs[1]]) + n = len(cs) - 1 cmat = np.zeros((n,n), dtype=cs.dtype) cmat.flat[n::n+1] = 1 Modified: branches/1.5.x/numpy/polynomial/polytemplate.py =================================================================== --- branches/1.5.x/numpy/polynomial/polytemplate.py 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/numpy/polynomial/polytemplate.py 2010-08-15 19:24:11 UTC (rev 8640) @@ -308,7 +308,7 @@ Notes ----- - .. versionadded:: 2.0.0 + .. versionadded:: 1.5.0 """ return len(self) - 1 @@ -335,7 +335,7 @@ Notes ----- - .. versionadded:: 2.0.0 + .. versionadded:: 1.5.0 """ return self.truncate(deg + 1) Modified: branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 19:24:11 UTC (rev 8640) @@ -78,6 +78,14 @@ res = ch.chebsub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) + def test_chebmulx(self): + assert_equal(ch.chebmulx([0]), [0]) + assert_equal(ch.chebmulx([1]), [0,1]) + for i in range(1, 5): + ser = [0]*i + [1] + tgt = [0]*(i - 1) + [.5, 0, .5] + assert_equal(ch.chebmulx(ser), tgt) + def test_chebmul(self) : for i in range(5) : for j in range(5) : Modified: branches/1.5.x/numpy/polynomial/tests/test_polynomial.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_polynomial.py 2010-08-15 19:11:02 UTC (rev 8639) +++ branches/1.5.x/numpy/polynomial/tests/test_polynomial.py 2010-08-15 19:24:11 UTC (rev 8640) @@ -61,6 +61,14 @@ res = poly.polysub([0]*i + [1], [0]*j + [1]) assert_equal(trim(res), trim(tgt), err_msg=msg) + def test_polymulx(self): + assert_equal(poly.polymulx([0]), [0]) + assert_equal(poly.polymulx([1]), [0, 1]) + for i in range(1, 5): + ser = [0]*i + [1] + tgt = [0]*(i + 1) + [1] + assert_equal(poly.polymulx(ser), tgt) + def test_polymul(self) : for i in range(5) : for j in range(5) : From numpy-svn at scipy.org Sun Aug 15 17:06:27 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 16:06:27 -0500 (CDT) Subject: [Numpy-svn] r8641 - in trunk/numpy/polynomial: . tests Message-ID: <20100815210627.3EC7C39CC36@scipy.org> Author: charris Date: 2010-08-15 16:06:27 -0500 (Sun, 15 Aug 2010) New Revision: 8641 Modified: trunk/numpy/polynomial/chebyshev.py trunk/numpy/polynomial/tests/test_chebyshev.py Log: Merge branch 'poly' Modified: trunk/numpy/polynomial/chebyshev.py =================================================================== --- trunk/numpy/polynomial/chebyshev.py 2010-08-15 19:24:11 UTC (rev 8640) +++ trunk/numpy/polynomial/chebyshev.py 2010-08-15 21:06:27 UTC (rev 8641) @@ -36,6 +36,8 @@ - `chebroots` -- find the roots of a Chebyshev series. - `chebvander` -- Vandermonde-like matrix for Chebyshev polynomials. - `chebfit` -- least-squares fit returning a Chebyshev series. +- `chebpts1` -- Chebyshev points of the first kind. +- `chebpts2` -- Chebyshev points of the second kind. - `chebtrim` -- trim leading coefficients from a Chebyshev series. - `chebline` -- Chebyshev series of given straight line. - `cheb2poly` -- convert a Chebyshev series to a polynomial. @@ -78,7 +80,8 @@ __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebval', 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', - 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'Chebyshev'] + 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1', + 'chebpts2', 'Chebyshev'] import numpy as np import numpy.linalg as la @@ -1332,6 +1335,68 @@ return roots +def chebpts1(npts): + """Chebyshev points of the first kind. + + Chebyshev points of the first kind are the set ``{cos(x_k)}``, + where ``x_k = pi*(k + .5)/npts`` for k in ``range(npts}``. + + Parameters + ---------- + npts: int + Number of sample points desired. + + Returns + ------- + pts: ndarray + The Chebyshev points of the second kind. + + Notes + ----- + .. versionadded:: 1.5.0 + + """ + _npts = int(npts) + if _npts != npts: + raise ValueError("npts must be integer") + if _npts < 1: + raise ValueError("npts must be >= 1") + + x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts) + return np.cos(x) + + +def chebpts2(npts): + """Chebyshev points of the second kind. + + Chebyshev points of the second kind are the set ``{cos(x_k)}``, + where ``x_k = pi*/(npts - 1)`` for k in ``range(npts}``. + + Parameters + ---------- + npts: int + Number of sample points desired. + + Returns + ------- + pts: ndarray + The Chebyshev points of the second kind. + + Notes + ----- + .. versionadded:: 1.5.0 + + """ + _npts = int(npts) + if _npts != npts: + raise ValueError("npts must be integer") + if _npts < 2: + raise ValueError("npts must be >= 2") + + x = np.linspace(-np.pi, 0, _npts) + return np.cos(x) + + # # Chebyshev series class # Modified: trunk/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 19:24:11 UTC (rev 8640) +++ trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 21:06:27 UTC (rev 8641) @@ -345,7 +345,40 @@ for i in range(10) : assert_equal(ch.poly2cheb(Tlist[i]), [0]*i + [1]) + def test_chebpts1(self): + #test exceptions + yield assert_raises(ValueError, ch.chebpts1, 1.5) + yield assert_raises(ValueError, ch.chebpts1, 0) + #test points + tgt = [0] + yield assert_almost_equal(ch.chebpts1(1), tgt) + tgt = [-0.70710678118654746, 0.70710678118654746] + yield assert_almost_equal(ch.chebpts1(2), tgt) + tgt = [-0.86602540378443871, 0, 0.86602540378443871] + yield assert_almost_equal(ch.chebpts1(3), tgt) + tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325] + yield assert_almost_equal(ch.chebpts1(4), tgt) + + + def test_chebpts2(self): + #test exceptions + yield assert_raises(ValueError, ch.chebpts2, 1.5) + yield assert_raises(ValueError, ch.chebpts2, 1) + + #test points + tgt = [-1, 1] + yield assert_almost_equal(ch.chebpts2(2), tgt) + tgt = [-1, 0, 1] + yield assert_almost_equal(ch.chebpts2(3), tgt) + tgt = [-1 -0.5, .5, 1] + yield assert_almost_equal(ch.chebpts2(4), tgt) + tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0] + yield assert_almost_equal(ch.chebpts2(5), tgt) + + + + class TestChebyshevClass(TestCase) : p1 = ch.Chebyshev([1,2,3]) From numpy-svn at scipy.org Sun Aug 15 17:06:29 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 16:06:29 -0500 (CDT) Subject: [Numpy-svn] r8642 - trunk/doc/release Message-ID: <20100815210629.86D0139CD17@scipy.org> Author: charris Date: 2010-08-15 16:06:29 -0500 (Sun, 15 Aug 2010) New Revision: 8642 Modified: trunk/doc/release/1.5.0-notes.rst Log: Mention functions for Chebyshev points in release notes. Modified: trunk/doc/release/1.5.0-notes.rst =================================================================== --- trunk/doc/release/1.5.0-notes.rst 2010-08-15 21:06:27 UTC (rev 8641) +++ trunk/doc/release/1.5.0-notes.rst 2010-08-15 21:06:29 UTC (rev 8642) @@ -111,6 +111,7 @@ * Weights can be used in both chebfit and Chebyshev.fit * A linspace method has been added to the Chebyshev class to ease plotting. * The chebmulx function was added. +* Added functions for the Chebyshev points of the first and second kind. histogram From numpy-svn at scipy.org Sun Aug 15 17:12:27 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 16:12:27 -0500 (CDT) Subject: [Numpy-svn] r8643 - in branches/1.5.x: doc/release numpy/polynomial numpy/polynomial/tests Message-ID: <20100815211227.83D4539CC36@scipy.org> Author: charris Date: 2010-08-15 16:12:27 -0500 (Sun, 15 Aug 2010) New Revision: 8643 Modified: branches/1.5.x/doc/release/1.5.0-notes.rst branches/1.5.x/numpy/polynomial/chebyshev.py branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py Log: ENH: Backport r8641-r8642 from trunk. Modified: branches/1.5.x/doc/release/1.5.0-notes.rst =================================================================== --- branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-15 21:06:29 UTC (rev 8642) +++ branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-15 21:12:27 UTC (rev 8643) @@ -111,6 +111,7 @@ * Weights can be used in both chebfit and Chebyshev.fit * A linspace method has been added to the Chebyshev class to ease plotting. * The chebmulx function was added. +* Added functions for the Chebyshev points of the first and second kind. histogram Modified: branches/1.5.x/numpy/polynomial/chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/chebyshev.py 2010-08-15 21:06:29 UTC (rev 8642) +++ branches/1.5.x/numpy/polynomial/chebyshev.py 2010-08-15 21:12:27 UTC (rev 8643) @@ -36,6 +36,8 @@ - `chebroots` -- find the roots of a Chebyshev series. - `chebvander` -- Vandermonde-like matrix for Chebyshev polynomials. - `chebfit` -- least-squares fit returning a Chebyshev series. +- `chebpts1` -- Chebyshev points of the first kind. +- `chebpts2` -- Chebyshev points of the second kind. - `chebtrim` -- trim leading coefficients from a Chebyshev series. - `chebline` -- Chebyshev series of given straight line. - `cheb2poly` -- convert a Chebyshev series to a polynomial. @@ -78,7 +80,8 @@ __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebval', 'chebder', 'chebint', 'cheb2poly', 'poly2cheb', 'chebfromroots', - 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'Chebyshev'] + 'chebvander', 'chebfit', 'chebtrim', 'chebroots', 'chebpts1', + 'chebpts2', 'Chebyshev'] import numpy as np import numpy.linalg as la @@ -1332,6 +1335,68 @@ return roots +def chebpts1(npts): + """Chebyshev points of the first kind. + + Chebyshev points of the first kind are the set ``{cos(x_k)}``, + where ``x_k = pi*(k + .5)/npts`` for k in ``range(npts}``. + + Parameters + ---------- + npts: int + Number of sample points desired. + + Returns + ------- + pts: ndarray + The Chebyshev points of the second kind. + + Notes + ----- + .. versionadded:: 1.5.0 + + """ + _npts = int(npts) + if _npts != npts: + raise ValueError("npts must be integer") + if _npts < 1: + raise ValueError("npts must be >= 1") + + x = np.linspace(-np.pi, 0, _npts, endpoint=False) + np.pi/(2*_npts) + return np.cos(x) + + +def chebpts2(npts): + """Chebyshev points of the second kind. + + Chebyshev points of the second kind are the set ``{cos(x_k)}``, + where ``x_k = pi*/(npts - 1)`` for k in ``range(npts}``. + + Parameters + ---------- + npts: int + Number of sample points desired. + + Returns + ------- + pts: ndarray + The Chebyshev points of the second kind. + + Notes + ----- + .. versionadded:: 1.5.0 + + """ + _npts = int(npts) + if _npts != npts: + raise ValueError("npts must be integer") + if _npts < 2: + raise ValueError("npts must be >= 2") + + x = np.linspace(-np.pi, 0, _npts) + return np.cos(x) + + # # Chebyshev series class # Modified: branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 21:06:29 UTC (rev 8642) +++ branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 21:12:27 UTC (rev 8643) @@ -345,7 +345,40 @@ for i in range(10) : assert_equal(ch.poly2cheb(Tlist[i]), [0]*i + [1]) + def test_chebpts1(self): + #test exceptions + yield assert_raises(ValueError, ch.chebpts1, 1.5) + yield assert_raises(ValueError, ch.chebpts1, 0) + #test points + tgt = [0] + yield assert_almost_equal(ch.chebpts1(1), tgt) + tgt = [-0.70710678118654746, 0.70710678118654746] + yield assert_almost_equal(ch.chebpts1(2), tgt) + tgt = [-0.86602540378443871, 0, 0.86602540378443871] + yield assert_almost_equal(ch.chebpts1(3), tgt) + tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325] + yield assert_almost_equal(ch.chebpts1(4), tgt) + + + def test_chebpts2(self): + #test exceptions + yield assert_raises(ValueError, ch.chebpts2, 1.5) + yield assert_raises(ValueError, ch.chebpts2, 1) + + #test points + tgt = [-1, 1] + yield assert_almost_equal(ch.chebpts2(2), tgt) + tgt = [-1, 0, 1] + yield assert_almost_equal(ch.chebpts2(3), tgt) + tgt = [-1 -0.5, .5, 1] + yield assert_almost_equal(ch.chebpts2(4), tgt) + tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0] + yield assert_almost_equal(ch.chebpts2(5), tgt) + + + + class TestChebyshevClass(TestCase) : p1 = ch.Chebyshev([1,2,3]) From numpy-svn at scipy.org Sun Aug 15 19:51:54 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 18:51:54 -0500 (CDT) Subject: [Numpy-svn] r8644 - branches/1.5.x/numpy/polynomial/tests Message-ID: <20100815235154.8BC5B39CC36@scipy.org> Author: charris Date: 2010-08-15 18:51:54 -0500 (Sun, 15 Aug 2010) New Revision: 8644 Modified: branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py Log: BUG: Fix non-performing test. Modified: branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 21:12:27 UTC (rev 8643) +++ branches/1.5.x/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 23:51:54 UTC (rev 8644) @@ -347,34 +347,34 @@ def test_chebpts1(self): #test exceptions - yield assert_raises(ValueError, ch.chebpts1, 1.5) - yield assert_raises(ValueError, ch.chebpts1, 0) + assert_raises(ValueError, ch.chebpts1, 1.5) + assert_raises(ValueError, ch.chebpts1, 0) #test points tgt = [0] - yield assert_almost_equal(ch.chebpts1(1), tgt) + assert_almost_equal(ch.chebpts1(1), tgt) tgt = [-0.70710678118654746, 0.70710678118654746] - yield assert_almost_equal(ch.chebpts1(2), tgt) + assert_almost_equal(ch.chebpts1(2), tgt) tgt = [-0.86602540378443871, 0, 0.86602540378443871] - yield assert_almost_equal(ch.chebpts1(3), tgt) + assert_almost_equal(ch.chebpts1(3), tgt) tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325] - yield assert_almost_equal(ch.chebpts1(4), tgt) + assert_almost_equal(ch.chebpts1(4), tgt) def test_chebpts2(self): #test exceptions - yield assert_raises(ValueError, ch.chebpts2, 1.5) - yield assert_raises(ValueError, ch.chebpts2, 1) + assert_raises(ValueError, ch.chebpts2, 1.5) + assert_raises(ValueError, ch.chebpts2, 1) #test points tgt = [-1, 1] - yield assert_almost_equal(ch.chebpts2(2), tgt) + assert_almost_equal(ch.chebpts2(2), tgt) tgt = [-1, 0, 1] - yield assert_almost_equal(ch.chebpts2(3), tgt) - tgt = [-1 -0.5, .5, 1] - yield assert_almost_equal(ch.chebpts2(4), tgt) + assert_almost_equal(ch.chebpts2(3), tgt) + tgt = [-1, -0.5, .5, 1] + assert_almost_equal(ch.chebpts2(4), tgt) tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0] - yield assert_almost_equal(ch.chebpts2(5), tgt) + assert_almost_equal(ch.chebpts2(5), tgt) From numpy-svn at scipy.org Sun Aug 15 20:10:29 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 15 Aug 2010 19:10:29 -0500 (CDT) Subject: [Numpy-svn] r8645 - trunk/numpy/polynomial/tests Message-ID: <20100816001029.6B31839CC36@scipy.org> Author: charris Date: 2010-08-15 19:10:29 -0500 (Sun, 15 Aug 2010) New Revision: 8645 Modified: trunk/numpy/polynomial/tests/test_chebyshev.py Log: Merge branch 'poly' Modified: trunk/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-15 23:51:54 UTC (rev 8644) +++ trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-16 00:10:29 UTC (rev 8645) @@ -347,34 +347,34 @@ def test_chebpts1(self): #test exceptions - yield assert_raises(ValueError, ch.chebpts1, 1.5) - yield assert_raises(ValueError, ch.chebpts1, 0) + assert_raises(ValueError, ch.chebpts1, 1.5) + assert_raises(ValueError, ch.chebpts1, 0) #test points tgt = [0] - yield assert_almost_equal(ch.chebpts1(1), tgt) + assert_almost_equal(ch.chebpts1(1), tgt) tgt = [-0.70710678118654746, 0.70710678118654746] - yield assert_almost_equal(ch.chebpts1(2), tgt) + assert_almost_equal(ch.chebpts1(2), tgt) tgt = [-0.86602540378443871, 0, 0.86602540378443871] - yield assert_almost_equal(ch.chebpts1(3), tgt) + assert_almost_equal(ch.chebpts1(3), tgt) tgt = [-0.9238795325, -0.3826834323, 0.3826834323, 0.9238795325] - yield assert_almost_equal(ch.chebpts1(4), tgt) + assert_almost_equal(ch.chebpts1(4), tgt) def test_chebpts2(self): #test exceptions - yield assert_raises(ValueError, ch.chebpts2, 1.5) - yield assert_raises(ValueError, ch.chebpts2, 1) + assert_raises(ValueError, ch.chebpts2, 1.5) + assert_raises(ValueError, ch.chebpts2, 1) #test points tgt = [-1, 1] - yield assert_almost_equal(ch.chebpts2(2), tgt) + assert_almost_equal(ch.chebpts2(2), tgt) tgt = [-1, 0, 1] - yield assert_almost_equal(ch.chebpts2(3), tgt) - tgt = [-1 -0.5, .5, 1] - yield assert_almost_equal(ch.chebpts2(4), tgt) + assert_almost_equal(ch.chebpts2(3), tgt) + tgt = [-1, -0.5, .5, 1] + assert_almost_equal(ch.chebpts2(4), tgt) tgt = [-1.0, -0.707106781187, 0, 0.707106781187, 1.0] - yield assert_almost_equal(ch.chebpts2(5), tgt) + assert_almost_equal(ch.chebpts2(5), tgt) From numpy-svn at scipy.org Mon Aug 16 21:52:11 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 16 Aug 2010 20:52:11 -0500 (CDT) Subject: [Numpy-svn] r8646 - in trunk/numpy/polynomial: . tests Message-ID: <20100817015211.4095239CB4B@scipy.org> Author: charris Date: 2010-08-16 20:52:11 -0500 (Mon, 16 Aug 2010) New Revision: 8646 Added: trunk/numpy/polynomial/legendre.py trunk/numpy/polynomial/tests/test_legendre.py Modified: trunk/numpy/polynomial/__init__.py trunk/numpy/polynomial/chebyshev.py trunk/numpy/polynomial/tests/test_chebyshev.py Log: ENH: Add support for Legendre polynomials. Modified: trunk/numpy/polynomial/__init__.py =================================================================== --- trunk/numpy/polynomial/__init__.py 2010-08-16 00:10:29 UTC (rev 8645) +++ trunk/numpy/polynomial/__init__.py 2010-08-17 01:52:11 UTC (rev 8646) @@ -15,6 +15,7 @@ """ from polynomial import * from chebyshev import * +from legendre import * from polyutils import * from numpy.testing import Tester Modified: trunk/numpy/polynomial/chebyshev.py =================================================================== --- trunk/numpy/polynomial/chebyshev.py 2010-08-16 00:10:29 UTC (rev 8645) +++ trunk/numpy/polynomial/chebyshev.py 2010-08-17 01:52:11 UTC (rev 8646) @@ -408,9 +408,10 @@ else: c0 = cs[-2] c1 = cs[-1] - for i in range(n - 3, -1, -1) : + # i is the current degree of c1 + for i in range(n - 1, 1, -1) : tmp = c0 - c0 = polysub(cs[i], c1) + c0 = polysub(cs[i - 2], c1) c1 = polyadd(tmp, polymulx(c1)*2) return polyadd(c0, polymulx(c1)) Copied: trunk/numpy/polynomial/legendre.py (from rev 8645, trunk/numpy/polynomial/chebyshev.py) =================================================================== --- trunk/numpy/polynomial/legendre.py (rev 0) +++ trunk/numpy/polynomial/legendre.py 2010-08-17 01:52:11 UTC (rev 8646) @@ -0,0 +1,1249 @@ +""" +Objects for dealing with Legendre series. + +This module provides a number of objects (mostly functions) useful for +dealing with Legendre series, including a `Legendre` class that +encapsulates the usual arithmetic operations. (General information +on how this module represents and works with such polynomials is in the +docstring for its "parent" sub-package, `numpy.polynomial`). + +Constants +--------- +- `legdomain` -- Legendre series default domain, [-1,1]. +- `legzero` -- Legendre series that evaluates identically to 0. +- `legone` -- Legendre series that evaluates identically to 1. +- `legx` -- Legendre series for the identity map, ``f(x) = x``. + +Arithmetic +---------- +- `legmulx` -- multiply a Legendre series in ``P_i(x)`` by ``x``. +- `legadd` -- add two Legendre series. +- `legsub` -- subtract one Legendre series from another. +- `legmul` -- multiply two Legendre series. +- `legdiv` -- divide one Legendre series by another. +- `legval` -- evaluate a Legendre series at given points. + +Calculus +-------- +- `legder` -- differentiate a Legendre series. +- `legint` -- integrate a Legendre series. + +Misc Functions +-------------- +- `legfromroots` -- create a Legendre series with specified roots. +- `legroots` -- find the roots of a Legendre series. +- `legvander` -- Vandermonde-like matrix for Legendre polynomials. +- `legfit` -- least-squares fit returning a Legendre series. +- `legtrim` -- trim leading coefficients from a Legendre series. +- `legline` -- Legendre series of given straight line. +- `leg2poly` -- convert a Legendre series to a polynomial. +- `poly2leg` -- convert a polynomial to a Legendre series. + +Classes +------- +- `Legendre` -- A Legendre series class. + +See also +-------- +`numpy.polynomial` + +Notes +----- +The implementations of multiplication, division, integration, and +differentiation use the algebraic identities [1]_: + +.. math :: + T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\ + z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}. + +where + +.. math :: x = \\frac{z + z^{-1}}{2}. + +These identities allow a Chebyshev series to be expressed as a finite, +symmetric Laurent series. In this module, this sort of Laurent series +is referred to as a "z-series." + +References +---------- +.. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev + Polynomials," *Journal of Statistical Planning and Inference 14*, 2008 + (preprint: http://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) + +""" +from __future__ import division + +__all__ = ['legzero', 'legone', 'legx', 'legdomain', 'legline', + 'legadd', 'legsub', 'legmulx', 'legmul', 'legdiv', 'legval', + 'legder', 'legint', 'leg2poly', 'poly2leg', 'legfromroots', + 'legvander', 'legfit', 'legtrim', 'legroots', 'Legendre'] + +import numpy as np +import numpy.linalg as la +import polyutils as pu +import warnings +from polytemplate import polytemplate + +legtrim = pu.trimcoef + +def poly2leg(pol) : + """ + poly2leg(pol) + + Convert a polynomial to a Legendre series. + + Convert an array representing the coefficients of a polynomial (relative + to the "standard" basis) ordered from lowest degree to highest, to an + array of the coefficients of the equivalent Legendre series, ordered + from lowest to highest degree. + + Parameters + ---------- + pol : array_like + 1-d array containing the polynomial coefficients + + Returns + ------- + cs : ndarray + 1-d array containing the coefficients of the equivalent Legendre + series. + + See Also + -------- + leg2poly + + Notes + ----- + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. + + Examples + -------- + >>> from numpy import polynomial as P + >>> p = P.Polynomial(np.arange(4)) + >>> p + Polynomial([ 0., 1., 2., 3.], [-1., 1.]) + >>> c = P.Legendre(P.poly2leg(p.coef)) + >>> c + Legendre([ 1. , 3.25, 1. , 0.75], [-1., 1.]) + + """ + [pol] = pu.as_series([pol]) + deg = len(pol) - 1 + res = 0 + for i in range(deg, -1, -1) : + res = legadd(legmulx(res), pol[i]) + return res + + +def leg2poly(cs) : + """ + Convert a Legendre series to a polynomial. + + Convert an array representing the coefficients of a Legendre series, + ordered from lowest degree to highest, to an array of the coefficients + of the equivalent polynomial (relative to the "standard" basis) ordered + from lowest to highest degree. + + Parameters + ---------- + cs : array_like + 1-d array containing the Legendre series coefficients, ordered + from lowest order term to highest. + + Returns + ------- + pol : ndarray + 1-d array containing the coefficients of the equivalent polynomial + (relative to the "standard" basis) ordered from lowest order term + to highest. + + See Also + -------- + poly2leg + + Notes + ----- + The easy way to do conversions between polynomial basis sets + is to use the convert method of a class instance. + + Examples + -------- + >>> from numpy import polynomial as P + >>> c = P.Chebyshev(np.arange(4)) + >>> c + Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) + >>> p = P.Polynomial(P.cheb2poly(c.coef)) + >>> p + Polynomial([ -2., -8., 4., 12.], [-1., 1.]) + + """ + from polynomial import polyadd, polysub, polymulx + + [cs] = pu.as_series([cs]) + n = len(cs) + if n < 3: + return cs + else: + c0 = cs[-2] + c1 = cs[-1] + # i is the current degree of c1 + for i in range(n - 1, 1, -1) : + tmp = c0 + c0 = polysub(cs[i - 2], (c1*(i - 1))/i) + c1 = polyadd(tmp, (polymulx(c1)*(2*i - 1))/i) + return polyadd(c0, polymulx(c1)) + +# +# These are constant arrays are of integer type so as to be compatible +# with the widest range of other types, such as Decimal. +# + +# Legendre +legdomain = np.array([-1,1]) + +# Legendre coefficients representing zero. +legzero = np.array([0]) + +# Legendre coefficients representing one. +legone = np.array([1]) + +# Legendre coefficients representing the identity x. +legx = np.array([0,1]) + + +def legline(off, scl) : + """ + Legendre series whose graph is a straight line. + + + + Parameters + ---------- + off, scl : scalars + The specified line is given by ``off + scl*x``. + + Returns + ------- + y : ndarray + This module's representation of the Legendre series for + ``off + scl*x``. + + See Also + -------- + polyline, chebline + + Examples + -------- + >>> import numpy.polynomial.legendre as L + >>> L.legline(3,2) + array([3, 2]) + >>> L.legval(-3, L.chebline(3,2)) # should be -3 + -3.0 + + """ + if scl != 0 : + return np.array([off,scl]) + else : + return np.array([off]) + + +def legtimesx(cs): + """Multiply a Legendre series by x. + + Multiply the Legendre series `cs` by x, where x is the independent + variable. + + + Parameters + ---------- + cs : array_like + 1-d array of Legendre series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + Notes + ----- + The multiplication uses the recursion relationship for Legendre + polynomials in the form + + .. math:: + + xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1) + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + # The zero series needs special treatment + if len(cs) == 1 and cs[0] == 0: + return cs + + prd = np.empty(len(cs) + 1, dtype=cs.dtype) + prd[0] = cs[0]*0 + prd[1] = cs[0] + for i in range(1, len(cs)): + j = i + 1 + k = i - 1 + s = i + j + prd[j] = (cs[i]*j)/s + prd[k] += (cs[i]*i)/s + return prd + + +def chebline(off, scl) : + """ + Chebyshev series whose graph is a straight line. + + + + Parameters + ---------- + off, scl : scalars + The specified line is given by ``off + scl*x``. + + Returns + ------- + y : ndarray + This module's representation of the Chebyshev series for + ``off + scl*x``. + + See Also + -------- + polyline + + Examples + -------- + >>> import numpy.polynomial.chebyshev as C + >>> C.chebline(3,2) + array([3, 2]) + >>> C.chebval(-3, C.chebline(3,2)) # should be -3 + -3.0 + + """ + if scl != 0 : + return np.array([off,scl]) + else : + return np.array([off]) + + +def legfromroots(roots) : + """ + Generate a Legendre series with the given roots. + + Return the array of coefficients for the P-series whose roots (a.k.a. + "zeros") are given by *roots*. The returned array of coefficients is + ordered from lowest order "term" to highest, and zeros of multiplicity + greater than one must be included in *roots* a number of times equal + to their multiplicity (e.g., if `2` is a root of multiplicity three, + then [2,2,2] must be in *roots*). + + Parameters + ---------- + roots : array_like + Sequence containing the roots. + + Returns + ------- + out : ndarray + 1-d array of the Legendre series coefficients, ordered from low to + high. If all roots are real, ``out.dtype`` is a float type; + otherwise, ``out.dtype`` is a complex type, even if all the + coefficients in the result are real (see Examples below). + + See Also + -------- + polyfromroots, chebfromroots + + Notes + ----- + What is returned are the :math:`c_i` such that: + + .. math:: + + \\sum_{i=0}^{n} c_i*P_i(x) = \\prod_{i=0}^{n} (x - roots[i]) + + where ``n == len(roots)`` and :math:`P_i(x)` is the `i`-th Legendre + (basis) polynomial over the domain `[-1,1]`. Note that, unlike + `polyfromroots`, due to the nature of the Legendre basis set, the + above identity *does not* imply :math:`c_n = 1` identically (see + Examples). + + Examples + -------- + >>> import numpy.polynomial.legendre as L + >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis + array([ 0. , -0.4, 0. , 0.4]) + >>> j = complex(0,1) + >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis + array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j]) + + """ + if len(roots) == 0 : + return np.ones(1) + else : + [roots] = pu.as_series([roots], trim=False) + prd = np.array([1], dtype=roots.dtype) + for r in roots: + prd = legsub(legmulx(prd), r*prd) + return prd + + +def legadd(c1, c2): + """ + Add one Legendre series to another. + + Returns the sum of two Legendre series `c1` + `c2`. The arguments + are sequences of coefficients ordered from lowest order term to + highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-d arrays of Legendre series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the Legendre series of their sum. + + See Also + -------- + legsub, legmul, legdiv, legpow + + Notes + ----- + Unlike multiplication, division, etc., the sum of two Legendre series + is a Legendre series (without having to "reproject" the result onto + the basis set) so addition, just like that of "standard" polynomials, + is simply "component-wise." + + Examples + -------- + >>> from numpy.polynomial import legendre as L + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> L.legadd(c1,c2) + array([ 4., 4., 4.]) + + """ + # c1, c2 are trimmed copies + [c1, c2] = pu.as_series([c1, c2]) + if len(c1) > len(c2) : + c1[:c2.size] += c2 + ret = c1 + else : + c2[:c1.size] += c1 + ret = c2 + return pu.trimseq(ret) + + +def legsub(c1, c2): + """ + Subtract one Legendre series from another. + + Returns the difference of two Legendre series `c1` - `c2`. The + sequences of coefficients are from lowest order term to highest, i.e., + [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-d arrays of Legendre series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Of Legendre series coefficients representing their difference. + + See Also + -------- + legadd, legmul, legdiv, legpow + + Notes + ----- + Unlike multiplication, division, etc., the difference of two Legendre + series is a Legendre series (without having to "reproject" the result + onto the basis set) so subtraction, just like that of "standard" + polynomials, is simply "component-wise." + + Examples + -------- + >>> from numpy.polynomial import legendre as L + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> L.legsub(c1,c2) + array([-2., 0., 2.]) + >>> L.legsub(c2,c1) # -C.legsub(c1,c2) + array([ 2., 0., -2.]) + + """ + # c1, c2 are trimmed copies + [c1, c2] = pu.as_series([c1, c2]) + if len(c1) > len(c2) : + c1[:c2.size] -= c2 + ret = c1 + else : + c2 = -c2 + c2[:c1.size] += c1 + ret = c2 + return pu.trimseq(ret) + + +def legmulx(cs): + """Multiply a Legendre series by x. + + Multiply the Legendre series `cs` by x, where x is the independent + variable. + + + Parameters + ---------- + cs : array_like + 1-d array of Legendre series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Array representing the result of the multiplication. + + Notes + ----- + The multiplication uses the recursion relationship for Legendre + polynomials in the form + + .. math:: + + xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1) + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + # The zero series needs special treatment + if len(cs) == 1 and cs[0] == 0: + return cs + + prd = np.empty(len(cs) + 1, dtype=cs.dtype) + prd[0] = cs[0]*0 + prd[1] = cs[0] + for i in range(1, len(cs)): + j = i + 1 + k = i - 1 + s = i + j + prd[j] = (cs[i]*j)/s + prd[k] += (cs[i]*i)/s + return prd + + +def legmul(c1, c2): + """ + Multiply one Legendre series by another. + + Returns the product of two Legendre series `c1` * `c2`. The arguments + are sequences of coefficients, from lowest order "term" to highest, + e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-d arrays of Legendre series coefficients ordered from low to + high. + + Returns + ------- + out : ndarray + Of Legendre series coefficients representing their product. + + See Also + -------- + legadd, legsub, legdiv, legpow + + Notes + ----- + In general, the (polynomial) product of two C-series results in terms + that are not in the Chebyshev polynomial basis set. Thus, to express + the product as a C-series, it is typically necessary to "re-project" + the product onto said basis set, which typically produces + "un-intuitive" (but correct) results; see Examples section below. + + Examples + -------- + >>> from numpy.polynomial import legendre as P + >>> c1 = (1,2,3) + >>> c2 = (3,2) + >>> P.legmul(c1,c2) # multiplication requires "reprojection" + array([ 4.33333333, 10.4 , 11.66666667, 3.6 ]) + + """ + # s1, s2 are trimmed copies + [c1, c2] = pu.as_series([c1, c2]) + + if len(c1) > len(c2): + cs = c2 + xs = c1 + else: + cs = c1 + xs = c2 + + if len(cs) == 1: + c0 = cs[0]*xs + c1 = 0 + elif len(cs) == 2: + c0 = cs[0]*xs + c1 = cs[1]*xs + else : + nd = len(cs) + c0 = cs[-2]*xs + c1 = cs[-1]*xs + for i in range(3, len(cs) + 1) : + tmp = c0 + nd = nd - 1 + c0 = legsub(cs[-i]*xs, (c1*(nd - 1))/nd) + c1 = legadd(tmp, (legmulx(c1)*(2*nd - 1))/nd) + return legadd(c0, legmulx(c1)) + + +def legdiv(c1, c2): + """ + Divide one Legendre series by another. + + Returns the quotient-with-remainder of two Legendre series + `c1` / `c2`. The arguments are sequences of coefficients from lowest + order "term" to highest, e.g., [1,2,3] represents the series + ``P_0 + 2*P_1 + 3*P_2``. + + Parameters + ---------- + c1, c2 : array_like + 1-d arrays of Legendre series coefficients ordered from low to + high. + + Returns + ------- + [quo, rem] : ndarrays + Of Legendre series coefficients representing the quotient and + remainder. + + See Also + -------- + legadd, legsub, legmul, legpow + + Notes + ----- + In general, the (polynomial) division of one Legendre series by another + results in quotient and remainder terms that are not in the Legendre + polynomial basis set. Thus, to express these results as a Legendre + series, it is necessary to "re-project" the results onto the Legendre + basis set, which may produce "un-intuitive" (but correct) results; see + Examples section below. + + Examples + -------- + >>> from numpy.polynomial import legendre as L + >>> c1 = (1,2,3) + >>> c2 = (3,2,1) + >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not + (array([ 3.]), array([-8., -4.])) + >>> c2 = (0,1,2,3) + >>> L.legdiv(c2,c1) # neither "intuitive" + (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852])) + + """ + # c1, c2 are trimmed copies + [c1, c2] = pu.as_series([c1, c2]) + if c2[-1] == 0 : + raise ZeroDivisionError() + + lc1 = len(c1) + lc2 = len(c2) + if lc1 < lc2 : + return c1[:1]*0, c1 + elif lc2 == 1 : + return c1/c2[-1], c1[:1]*0 + else : + quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) + rem = c1 + for i in range(lc1 - lc2, - 1, -1): + p = legmul([0]*i + [1], c2) + q = rem[-1]/p[-1] + rem = rem[:-1] - q*p[:-1] + quo[i] = q + return quo, pu.trimseq(rem) + + +def legpow(cs, pow, maxpower=16) : + """Raise a Legendre series to a power. + + Returns the Legendre series `cs` raised to the power `pow`. The + arguement `cs` is a sequence of coefficients ordered from low to high. + i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.`` + + Parameters + ---------- + cs : array_like + 1d array of Legendre series coefficients ordered from low to + high. + pow : integer + Power to which the series will be raised + maxpower : integer, optional + Maximum power allowed. This is mainly to limit growth of the series + to umanageable size. Default is 16 + + Returns + ------- + coef : ndarray + Legendre series of power. + + See Also + -------- + legadd, legsub, legmul, legdiv + + Examples + -------- + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + power = int(pow) + if power != pow or power < 0 : + raise ValueError("Power must be a non-negative integer.") + elif maxpower is not None and power > maxpower : + raise ValueError("Power is too large") + elif power == 0 : + return np.array([1], dtype=cs.dtype) + elif power == 1 : + return cs + else : + # This can be made more efficient by using powers of two + # in the usual way. + prd = cs + for i in range(2, power + 1) : + prd = legmul(prd, cs) + return prd + + +def legder(cs, m=1, scl=1) : + """ + Differentiate a Legendre series. + + Returns the series `cs` differentiated `m` times. At each iteration the + result is multiplied by `scl` (the scaling factor is for use in a linear + change of variable). The argument `cs` is the sequence of coefficients + from lowest order "term" to highest, e.g., [1,2,3] represents the series + ``P_0 + 2*P_1 + 3*P_2``. + + Parameters + ---------- + cs: array_like + 1-d array of Legendre series coefficients ordered from low to high. + m : int, optional + Number of derivatives taken, must be non-negative. (Default: 1) + scl : scalar, optional + Each differentiation is multiplied by `scl`. The end result is + multiplication by ``scl**m``. This is for use in a linear change of + variable. (Default: 1) + + Returns + ------- + der : ndarray + Legendre series of the derivative. + + See Also + -------- + legint + + Notes + ----- + In general, the result of differentiating a Legendre series does not + resemble the same operation on a power series. Thus the result of this + function may be "un-intuitive," albeit correct; see Examples section + below. + + Examples + -------- + >>> from numpy.polynomial import legendre as L + >>> cs = (1,2,3,4) + >>> L.legder(cs) + array([ 6., 9., 20.]) + >>> L.legder(cs,3) + array([ 60.]) + >>> L.legder(cs,scl=-1) + array([ -6., -9., -20.]) + >>> L.legder(cs,2,-1) + array([ 9., 60.]) + + """ + cnt = int(m) + + if cnt != m: + raise ValueError, "The order of derivation must be integer" + if cnt < 0 : + raise ValueError, "The order of derivation must be non-negative" + + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + if cnt == 0: + return cs + elif cnt >= len(cs): + return cs[:1]*0 + else : + for i in range(cnt): + n = len(cs) - 1 + cs *= scl + der = np.empty(n, dtype=cs.dtype) + for j in range(n, 0, -1): + der[j - 1] = (2*j - 1)*cs[j] + cs[j - 2] += cs[j] + cs = der + return cs + + +def legint(cs, m=1, k=[], lbnd=0, scl=1): + """ + Integrate a Legendre series. + + Returns a Legendre series that is the Legendre series `cs`, integrated + `m` times from `lbnd` to `x`. At each iteration the resulting series + is **multiplied** by `scl` and an integration constant, `k`, is added. + The scaling factor is for use in a linear change of variable. ("Buyer + beware": note that, depending on what one is doing, one may want `scl` + to be the reciprocal of what one might expect; for more information, + see the Notes section below.) The argument `cs` is a sequence of + coefficients, from lowest order Legendre series "term" to highest, + e.g., [1,2,3] represents the series :math:`P_0(x) + 2P_1(x) + 3P_2(x)`. + + Parameters + ---------- + cs : array_like + 1-d array of Legendre series coefficients, ordered from low to high. + m : int, optional + Order of integration, must be positive. (Default: 1) + k : {[], list, scalar}, optional + Integration constant(s). The value of the first integral at + ``lbnd`` is the first value in the list, the value of the second + integral at ``lbnd`` is the second value, etc. If ``k == []`` (the + default), all constants are set to zero. If ``m == 1``, a single + scalar can be given instead of a list. + lbnd : scalar, optional + The lower bound of the integral. (Default: 0) + scl : scalar, optional + Following each integration the result is *multiplied* by `scl` + before the integration constant is added. (Default: 1) + + Returns + ------- + S : ndarray + Legendre series coefficients of the integral. + + Raises + ------ + ValueError + If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or + ``np.isscalar(scl) == False``. + + See Also + -------- + legder + + Notes + ----- + Note that the result of each integration is *multiplied* by `scl`. + Why is this important to note? Say one is making a linear change of + variable :math:`u = ax + b` in an integral relative to `x`. Then + :math:`dx = du/a`, so one will need to set `scl` equal to :math:`1/a` + - perhaps not what one would have first thought. + + Also note that, in general, the result of integrating a C-series needs + to be "re-projected" onto the C-series basis set. Thus, typically, + the result of this function is "un-intuitive," albeit correct; see + Examples section below. + + Examples + -------- + >>> from numpy.polynomial import legyshev as L + >>> cs = (1,2,3) + >>> L.legint(cs) + array([ 0.5, -0.5, 0.5, 0.5]) + >>> L.legint(cs,3) + array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, + 0.00625 ]) + >>> L.legint(cs, k=3) + array([ 3.5, -0.5, 0.5, 0.5]) + >>> L.legint(cs,lbnd=-2) + array([ 8.5, -0.5, 0.5, 0.5]) + >>> L.legint(cs,scl=-2) + array([-1., 1., -1., -1.]) + + """ + cnt = int(m) + if np.isscalar(k) : + k = [k] + + if cnt != m: + raise ValueError, "The order of integration must be integer" + if cnt < 0 : + raise ValueError, "The order of integration must be non-negative" + if len(k) > cnt : + raise ValueError, "Too many integration constants" + + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + if cnt == 0: + return cs + + k = list(k) + [0]*(cnt - len(k)) + for i in range(cnt) : + n = len(cs) + cs *= scl + if n == 1 and cs[0] == 0: + cs[0] += k[i] + else: + tmp = np.empty(n + 1, dtype=cs.dtype) + tmp[0] = cs[0]*0 + tmp[1] = cs[0] + for j in range(1, n): + t = cs[j]/(2*j + 1) + tmp[j + 1] = t + tmp[j - 1] -= t + tmp[0] += k[i] - legval(lbnd, tmp) + cs = tmp + return cs + + +def legval(x, cs): + """Evaluate a Legendre series. + + If `cs` is of length `n`, this function returns : + + ``p(x) = cs[0]*P_0(x) + cs[1]*P_1(x) + ... + cs[n-1]*P_{n-1}(x)`` + + If x is a sequence or array then p(x) will have the same shape as x. + If r is a ring_like object that supports multiplication and addition + by the values in `cs`, then an object of the same type is returned. + + Parameters + ---------- + x : array_like, ring_like + Array of numbers or objects that support multiplication and + addition with themselves and with the elements of `cs`. + cs : array_like + 1-d array of Chebyshev coefficients ordered from low to high. + + Returns + ------- + values : ndarray, ring_like + If the return is an ndarray then it has the same shape as `x`. + + See Also + -------- + legfit + + Examples + -------- + + Notes + ----- + The evaluation uses Clenshaw recursion, aka synthetic division. + + Examples + -------- + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + if isinstance(x, tuple) or isinstance(x, list) : + x = np.asarray(x) + + if len(cs) == 1 : + c0 = cs[0] + c1 = 0 + elif len(cs) == 2 : + c0 = cs[0] + c1 = cs[1] + else : + nd = len(cs) + c0 = cs[-2] + c1 = cs[-1] + for i in range(3, len(cs) + 1) : + tmp = c0 + nd = nd - 1 + c0 = cs[-i] - (c1*(nd - 1))/nd + c1 = tmp + (c1*x*(2*nd - 1))/nd + return c0 + c1*x + + +def legvander(x, deg) : + """Vandermonde matrix of given degree. + + Returns the Vandermonde matrix of degree `deg` and sample points `x`. + This isn't a true Vandermonde matrix because `x` can be an arbitrary + ndarray and the Legendre polynomials aren't powers. If ``V`` is the + returned matrix and `x` is a 2d array, then the elements of ``V`` are + ``V[i,j,k] = P_k(x[i,j])``, where ``P_k`` is the Legendre polynomial + of degree ``k``. + + Parameters + ---------- + x : array_like + Array of points. The values are converted to double or complex + doubles. If x is scalar it is converted to a 1D array. + deg : integer + Degree of the resulting matrix. + + Returns + ------- + vander : Vandermonde matrix. + The shape of the returned matrix is ``x.shape + (deg+1,)``. The last + index is the degree. + + """ + ideg = int(deg) + if ideg != deg: + raise ValueError("deg must be integer") + if ideg < 0: + raise ValueError("deg must be non-negative") + + x = np.array(x, copy=0, ndmin=1) + 0.0 + v = np.empty((ideg + 1,) + x.shape, dtype=x.dtype) + # Use forward recursion to generate the entries. This is not as accurate + # as reverse recursion in this application but it is more efficient. + v[0] = x*0 + 1 + if ideg > 0 : + v[1] = x + for i in range(2, ideg + 1) : + v[i] = (v[i-1]*x*(2*i - 1) - v[i-2]*(i - 1))/i + return np.rollaxis(v, 0, v.ndim) + + +def legfit(x, y, deg, rcond=None, full=False, w=None): + """ + Least squares fit of Legendre series to data. + + Fit a Legendre series ``p(x) = p[0] * P_{0}(x) + ... + p[deg] * + P_{deg}(x)`` of degree `deg` to points `(x, y)`. Returns a vector of + coefficients `p` that minimises the squared error. + + Parameters + ---------- + x : array_like, shape (M,) + x-coordinates of the M sample points ``(x[i], y[i])``. + y : array_like, shape (M,) or (M, K) + y-coordinates of the sample points. Several data sets of sample + points sharing the same x-coordinates can be fitted at once by + passing in a 2D-array that contains one dataset per column. + deg : int + Degree of the fitting polynomial + rcond : float, optional + Relative condition number of the fit. Singular values smaller than + this relative to the largest singular value will be ignored. The + default value is len(x)*eps, where eps is the relative precision of + the float type, about 2e-16 in most cases. + full : bool, optional + Switch determining nature of return value. When it is False (the + default) just the coefficients are returned, when True diagnostic + information from the singular value decomposition is also returned. + w : array_like, shape (`M`,), optional + Weights. If not None, the contribution of each point + ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the + weights are chosen so that the errors of the products ``w[i]*y[i]`` + all have the same variance. The default value is None. + + Returns + ------- + coef : ndarray, shape (M,) or (M, K) + Legendre coefficients ordered from low to high. If `y` was 2-D, + the coefficients for the data in column k of `y` are in column + `k`. + + [residuals, rank, singular_values, rcond] : present when `full` = True + Residuals of the least-squares fit, the effective rank of the + scaled Vandermonde matrix and its singular values, and the + specified value of `rcond`. For more details, see `linalg.lstsq`. + + Warns + ----- + RankWarning + The rank of the coefficient matrix in the least-squares fit is + deficient. The warning is only raised if `full` = False. The + warnings can be turned off by + + >>> import warnings + >>> warnings.simplefilter('ignore', RankWarning) + + See Also + -------- + legval : Evaluates a Legendre series. + legvander : Vandermonde matrix of Legendre series. + polyfit : least squares fit using polynomials. + chebfit : least squares fit using Chebyshev series. + linalg.lstsq : Computes a least-squares fit from the matrix. + scipy.interpolate.UnivariateSpline : Computes spline fits. + + Notes + ----- + The solution are the coefficients ``c[i]`` of the Legendre series + ``P(x)`` that minimizes the squared error + + ``E = \\sum_j |y_j - P(x_j)|^2``. + + This problem is solved by setting up as the overdetermined matrix + equation + + ``V(x)*c = y``, + + where ``V`` is the Vandermonde matrix of `x`, the elements of ``c`` are + the coefficients to be solved for, and the elements of `y` are the + observed values. This equation is then solved using the singular value + decomposition of ``V``. + + If some of the singular values of ``V`` are so small that they are + neglected, then a `RankWarning` will be issued. This means that the + coeficient values may be poorly determined. Using a lower order fit + will usually get rid of the warning. The `rcond` parameter can also be + set to a value smaller than its default, but the resulting fit may be + spurious and have large contributions from roundoff error. + + Fits using Legendre series are usually better conditioned than fits + using power series, but much can depend on the distribution of the + sample points and the smoothness of the data. If the quality of the fit + is inadequate splines may be a good alternative. + + References + ---------- + .. [1] Wikipedia, "Curve fitting", + http://en.wikipedia.org/wiki/Curve_fitting + + Examples + -------- + + """ + order = int(deg) + 1 + x = np.asarray(x) + 0.0 + y = np.asarray(y) + 0.0 + + # check arguments. + if deg < 0 : + raise ValueError, "expected deg >= 0" + if x.ndim != 1: + raise TypeError, "expected 1D vector for x" + if x.size == 0: + raise TypeError, "expected non-empty vector for x" + if y.ndim < 1 or y.ndim > 2 : + raise TypeError, "expected 1D or 2D array for y" + if len(x) != len(y): + raise TypeError, "expected x and y to have same length" + + # set up the least squares matrices + lhs = legvander(x, deg) + rhs = y + if w is not None: + w = np.asarray(w) + 0.0 + if w.ndim != 1: + raise TypeError, "expected 1D vector for w" + if len(x) != len(w): + raise TypeError, "expected x and w to have same length" + # apply weights + if rhs.ndim == 2: + lhs *= w[:, np.newaxis] + rhs *= w[:, np.newaxis] + else: + lhs *= w[:, np.newaxis] + rhs *= w + + # set rcond + if rcond is None : + rcond = len(x)*np.finfo(x.dtype).eps + + # scale the design matrix and solve the least squares equation + scl = np.sqrt((lhs*lhs).sum(0)) + c, resids, rank, s = la.lstsq(lhs/scl, rhs, rcond) + c = (c.T/scl).T + + # warn on rank reduction + if rank != order and not full: + msg = "The fit may be poorly conditioned" + warnings.warn(msg, pu.RankWarning) + + if full : + return c, [resids, rank, s, rcond] + else : + return c + + +def legroots(cs): + """ + Compute the roots of a Chebyshev series. + + Return the roots (a.k.a "zeros") of the Legendre series represented by + `cs`, which is the sequence of the C-series' coefficients from lowest + order "term" to highest, e.g., [1,2,3] represents the Legendre series + ``P_0 + 2*P_1 + 3*P_2``. + + Parameters + ---------- + cs : array_like + 1-d array of Legendre series coefficients ordered from low to high. + + Returns + ------- + out : ndarray + Array of the roots. If all the roots are real, then so is the + dtype of ``out``; otherwise, ``out``'s dtype is complex. + + See Also + -------- + polyroots + chebroots + + Notes + ----- + Algorithm(s) used: + + Remember: because the Legendre series basis set is different from the + "standard" basis set, the results of this function *may* not be what + one is expecting. + + Examples + -------- + >>> import numpy.polynomial as P + >>> import numpy.polynomial.Legendre as L + >>> P.polyroots((-1,1,-1,1)) # x^3 - x^2 + x - 1 has two complex roots + array([ -4.99600361e-16-1.j, -4.99600361e-16+1.j, 1.00000e+00+0.j]) + >>> L.legroots((-1,1,-1,1)) # T3 - T2 + T1 - T0 has only real roots + array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) + + """ + # cs is a trimmed copy + [cs] = pu.as_series([cs]) + if len(cs) <= 1 : + return np.array([], dtype=cs.dtype) + if len(cs) == 2 : + return np.array([-cs[0]/cs[1]]) + + n = len(cs) - 1 + cs /= cs[-1] + cmat = np.zeros((n,n), dtype=cs.dtype) + cmat[1, 0] = 1 + for i in range(1, n): + tmp = 2*i + 1 + cmat[i - 1, i] = i/tmp + if i != n - 1: + cmat[i + 1, i] = (i + 1)/tmp + else: + cmat[:, i] -= cs[:-1]*(i + 1)/tmp + roots = la.eigvals(cmat) + roots.sort() + return roots + + +# +# Legendre series class +# + +exec polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]') Modified: trunk/numpy/polynomial/tests/test_chebyshev.py =================================================================== --- trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-16 00:10:29 UTC (rev 8645) +++ trunk/numpy/polynomial/tests/test_chebyshev.py 2010-08-17 01:52:11 UTC (rev 8646) @@ -339,11 +339,11 @@ def test_cheb2poly(self) : for i in range(10) : - assert_equal(ch.cheb2poly([0]*i + [1]), Tlist[i]) + assert_almost_equal(ch.cheb2poly([0]*i + [1]), Tlist[i]) def test_poly2cheb(self) : for i in range(10) : - assert_equal(ch.poly2cheb(Tlist[i]), [0]*i + [1]) + assert_almost_equal(ch.poly2cheb(Tlist[i]), [0]*i + [1]) def test_chebpts1(self): #test exceptions Copied: trunk/numpy/polynomial/tests/test_legendre.py (from rev 8645, trunk/numpy/polynomial/tests/test_chebyshev.py) =================================================================== --- trunk/numpy/polynomial/tests/test_legendre.py (rev 0) +++ trunk/numpy/polynomial/tests/test_legendre.py 2010-08-17 01:52:11 UTC (rev 8646) @@ -0,0 +1,533 @@ +"""Tests for legendre module. + +""" +from __future__ import division + +import numpy as np +import numpy.polynomial.legendre as leg +import numpy.polynomial.polynomial as poly +from numpy.testing import * + +P0 = np.array([ 1]) +P1 = np.array([ 0, 1]) +P2 = np.array([-1, 0, 3])/2 +P3 = np.array([ 0, -3, 0, 5])/2 +P4 = np.array([ 3, 0, -30, 0, 35])/8 +P5 = np.array([ 0, 15, 0, -70, 0, 63])/8 +P6 = np.array([-5, 0, 105, 0,-315, 0, 231])/16 +P7 = np.array([ 0,-35, 0, 315, 0, -693, 0, 429])/16 +P8 = np.array([35, 0,-1260, 0,6930, 0,-12012, 0,6435])/128 +P9 = np.array([ 0,315, 0,-4620, 0,18018, 0,-25740, 0,12155])/128 + +Plist = [P0, P1, P2, P3, P4, P5, P6, P7, P8, P9] + +def trim(x) : + return leg.legtrim(x, tol=1e-6) + + +class TestConstants(TestCase) : + + def test_legdomain(self) : + assert_equal(leg.legdomain, [-1, 1]) + + def test_legzero(self) : + assert_equal(leg.legzero, [0]) + + def test_legone(self) : + assert_equal(leg.legone, [1]) + + def test_legx(self) : + assert_equal(leg.legx, [0, 1]) + + +class TestArithmetic(TestCase) : + x = np.linspace(-1, 1, 100) + y0 = poly.polyval(x, P0) + y1 = poly.polyval(x, P1) + y2 = poly.polyval(x, P2) + y3 = poly.polyval(x, P3) + y4 = poly.polyval(x, P4) + y5 = poly.polyval(x, P5) + y6 = poly.polyval(x, P6) + y7 = poly.polyval(x, P7) + y8 = poly.polyval(x, P8) + y9 = poly.polyval(x, P9) + y = [y0, y1, y2, y3, y4, y5, y6, y7, y8, y9] + + def test_legval(self) : + def f(x) : + return x*(x**2 - 1) + + #check empty input + assert_equal(leg.legval([], [1]).size, 0) + + #check normal input) + for i in range(10) : + msg = "At i=%d" % i + ser = np.zeros + tgt = self.y[i] + res = leg.legval(self.x, [0]*i + [1]) + assert_almost_equal(res, tgt, err_msg=msg) + + #check that shape is preserved + for i in range(3) : + dims = [2]*i + x = np.zeros(dims) + assert_equal(leg.legval(x, [1]).shape, dims) + assert_equal(leg.legval(x, [1,0]).shape, dims) + assert_equal(leg.legval(x, [1,0,0]).shape, dims) + + def test_legadd(self) : + for i in range(5) : + for j in range(5) : + msg = "At i=%d, j=%d" % (i,j) + tgt = np.zeros(max(i,j) + 1) + tgt[i] += 1 + tgt[j] += 1 + res = leg.legadd([0]*i + [1], [0]*j + [1]) + assert_equal(trim(res), trim(tgt), err_msg=msg) + + def test_legsub(self) : + for i in range(5) : + for j in range(5) : + msg = "At i=%d, j=%d" % (i,j) + tgt = np.zeros(max(i,j) + 1) + tgt[i] += 1 + tgt[j] -= 1 + res = leg.legsub([0]*i + [1], [0]*j + [1]) + assert_equal(trim(res), trim(tgt), err_msg=msg) + + def test_legmulx(self): + assert_equal(leg.legmulx([0]), [0]) + assert_equal(leg.legmulx([1]), [0,1]) + for i in range(1, 5): + tmp = 2*i + 1 + ser = [0]*i + [1] + tgt = [0]*(i - 1) + [i/tmp, 0, (i + 1)/tmp] + assert_equal(leg.legmulx(ser), tgt) + + def test_legmul(self) : + # check values of result + for i in range(5) : + pol1 = [0]*i + [1] + val1 = leg.legval(self.x, pol1) + for j in range(5) : + msg = "At i=%d, j=%d" % (i,j) + pol2 = [0]*j + [1] + val2 = leg.legval(self.x, pol2) + pol3 = leg.legmul(pol1, pol2) + val3 = leg.legval(self.x, pol3) + assert_(len(pol3) == i + j + 1, msg) + assert_almost_equal(val3, val1*val2, err_msg=msg) + + def test_legdiv(self) : + for i in range(5) : + for j in range(5) : + msg = "At i=%d, j=%d" % (i,j) + ci = [0]*i + [1] + cj = [0]*j + [1] + tgt = leg.legadd(ci, cj) + quo, rem = leg.legdiv(tgt, ci) + res = leg.legadd(leg.legmul(quo, ci), rem) + assert_equal(trim(res), trim(tgt), err_msg=msg) + + +class TestCalculus(TestCase) : + + def test_legint(self) : + # check exceptions + assert_raises(ValueError, leg.legint, [0], .5) + assert_raises(ValueError, leg.legint, [0], -1) + assert_raises(ValueError, leg.legint, [0], 1, [0,0]) + + # test integration of zero polynomial + for i in range(2, 5): + k = [0]*(i - 2) + [1] + res = leg.legint([0], m=i, k=k) + assert_almost_equal(res, [0, 1]) + + # check single integration with integration constant + for i in range(5) : + scl = i + 1 + pol = [0]*i + [1] + tgt = [i] + [0]*i + [1/scl] + legpol = leg.poly2leg(pol) + legint = leg.legint(legpol, m=1, k=[i]) + res = leg.leg2poly(legint) + assert_almost_equal(trim(res), trim(tgt)) + + # check single integration with integration constant and lbnd + for i in range(5) : + scl = i + 1 + pol = [0]*i + [1] + legpol = leg.poly2leg(pol) + legint = leg.legint(legpol, m=1, k=[i], lbnd=-1) + assert_almost_equal(leg.legval(-1, legint), i) + + # check single integration with integration constant and scaling + for i in range(5) : + scl = i + 1 + pol = [0]*i + [1] + tgt = [i] + [0]*i + [2/scl] + legpol = leg.poly2leg(pol) + legint = leg.legint(legpol, m=1, k=[i], scl=2) + res = leg.leg2poly(legint) + assert_almost_equal(trim(res), trim(tgt)) + + # check multiple integrations with default k + for i in range(5) : + for j in range(2,5) : + pol = [0]*i + [1] + tgt = pol[:] + for k in range(j) : + tgt = leg.legint(tgt, m=1) + res = leg.legint(pol, m=j) + assert_almost_equal(trim(res), trim(tgt)) + + # check multiple integrations with defined k + for i in range(5) : + for j in range(2,5) : + pol = [0]*i + [1] + tgt = pol[:] + for k in range(j) : + tgt = leg.legint(tgt, m=1, k=[k]) + res = leg.legint(pol, m=j, k=range(j)) + assert_almost_equal(trim(res), trim(tgt)) + + # check multiple integrations with lbnd + for i in range(5) : + for j in range(2,5) : + pol = [0]*i + [1] + tgt = pol[:] + for k in range(j) : + tgt = leg.legint(tgt, m=1, k=[k], lbnd=-1) + res = leg.legint(pol, m=j, k=range(j), lbnd=-1) + assert_almost_equal(trim(res), trim(tgt)) + + # check multiple integrations with scaling + for i in range(5) : + for j in range(2,5) : + pol = [0]*i + [1] + tgt = pol[:] + for k in range(j) : + tgt = leg.legint(tgt, m=1, k=[k], scl=2) + res = leg.legint(pol, m=j, k=range(j), scl=2) + assert_almost_equal(trim(res), trim(tgt)) + + def test_legder(self) : + # check exceptions + assert_raises(ValueError, leg.legder, [0], .5) + assert_raises(ValueError, leg.legder, [0], -1) + + # check that zeroth deriviative does nothing + for i in range(5) : + tgt = [1] + [0]*i + res = leg.legder(tgt, m=0) + assert_equal(trim(res), trim(tgt)) + + # check that derivation is the inverse of integration + for i in range(5) : + for j in range(2,5) : + tgt = [1] + [0]*i + res = leg.legder(leg.legint(tgt, m=j), m=j) + assert_almost_equal(trim(res), trim(tgt)) + + # check derivation with scaling + for i in range(5) : + for j in range(2,5) : + tgt = [1] + [0]*i + res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5) + assert_almost_equal(trim(res), trim(tgt)) + + +class TestMisc(TestCase) : + + def test_legfromroots(self) : + res = leg.legfromroots([]) + assert_almost_equal(trim(res), [1]) + for i in range(1,5) : + roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2]) + pol = leg.legfromroots(roots) + res = leg.legval(roots, pol) + tgt = 0 + assert_(len(pol) == i + 1) + assert_almost_equal(leg.leg2poly(pol)[-1], 1) + assert_almost_equal(res, tgt) + + def test_legroots(self) : + assert_almost_equal(leg.legroots([1]), []) + assert_almost_equal(leg.legroots([1, 2]), [-.5]) + for i in range(2,5) : + tgt = np.linspace(-1, 1, i) + res = leg.legroots(leg.legfromroots(tgt)) + assert_almost_equal(trim(res), trim(tgt)) + + def test_legvander(self) : + # check for 1d x + x = np.arange(3) + v = leg.legvander(x, 3) + assert_(v.shape == (3,4)) + for i in range(4) : + coef = [0]*i + [1] + assert_almost_equal(v[...,i], leg.legval(x, coef)) + + # check for 2d x + x = np.array([[1,2],[3,4],[5,6]]) + v = leg.legvander(x, 3) + assert_(v.shape == (3,2,4)) + for i in range(4) : + coef = [0]*i + [1] + assert_almost_equal(v[...,i], leg.legval(x, coef)) + + def test_legfit(self) : + def f(x) : + return x*(x - 1)*(x - 2) + + # Test exceptions + assert_raises(ValueError, leg.legfit, [1], [1], -1) + assert_raises(TypeError, leg.legfit, [[1]], [1], 0) + assert_raises(TypeError, leg.legfit, [], [1], 0) + assert_raises(TypeError, leg.legfit, [1], [[[1]]], 0) + assert_raises(TypeError, leg.legfit, [1, 2], [1], 0) + assert_raises(TypeError, leg.legfit, [1], [1, 2], 0) + assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[[1]]) + assert_raises(TypeError, leg.legfit, [1], [1], 0, w=[1,1]) + + # Test fit + x = np.linspace(0,2) + y = f(x) + # + coef3 = leg.legfit(x, y, 3) + assert_equal(len(coef3), 4) + assert_almost_equal(leg.legval(x, coef3), y) + # + coef4 = leg.legfit(x, y, 4) + assert_equal(len(coef4), 5) + assert_almost_equal(leg.legval(x, coef4), y) + # + coef2d = leg.legfit(x, np.array([y,y]).T, 3) + assert_almost_equal(coef2d, np.array([coef3,coef3]).T) + # test weighting + w = np.zeros_like(x) + yw = y.copy() + w[1::2] = 1 + y[0::2] = 0 + wcoef3 = leg.legfit(x, yw, 3, w=w) + assert_almost_equal(wcoef3, coef3) + # + wcoef2d = leg.legfit(x, np.array([yw,yw]).T, 3, w=w) + assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T) + + def test_legtrim(self) : + coef = [2, -1, 1, 0] + + # Test exceptions + assert_raises(ValueError, leg.legtrim, coef, -1) + + # Test results + assert_equal(leg.legtrim(coef), coef[:-1]) + assert_equal(leg.legtrim(coef, 1), coef[:-3]) + assert_equal(leg.legtrim(coef, 2), [0]) + + def test_legline(self) : + assert_equal(leg.legline(3,4), [3, 4]) + + def test_leg2poly(self) : + for i in range(10) : + assert_almost_equal(leg.leg2poly([0]*i + [1]), Plist[i]) + + def test_poly2leg(self) : + for i in range(10) : + assert_almost_equal(leg.poly2leg(Plist[i]), [0]*i + [1]) + + +def assert_poly_almost_equal(p1, p2): + assert_almost_equal(p1.coef, p2.coef) + assert_equal(p1.domain, p2.domain) + + +class TestLegendreClass(TestCase) : + + p1 = leg.Legendre([1,2,3]) + p2 = leg.Legendre([1,2,3], [0,1]) + p3 = leg.Legendre([1,2]) + p4 = leg.Legendre([2,2,3]) + p5 = leg.Legendre([3,2,3]) + + def test_equal(self) : + assert_(self.p1 == self.p1) + assert_(self.p2 == self.p2) + assert_(not self.p1 == self.p2) + assert_(not self.p1 == self.p3) + assert_(not self.p1 == [1,2,3]) + + def test_not_equal(self) : + assert_(not self.p1 != self.p1) + assert_(not self.p2 != self.p2) + assert_(self.p1 != self.p2) + assert_(self.p1 != self.p3) + assert_(self.p1 != [1,2,3]) + + def test_add(self) : + tgt = leg.Legendre([2,4,6]) + assert_(self.p1 + self.p1 == tgt) + assert_(self.p1 + [1,2,3] == tgt) + assert_([1,2,3] + self.p1 == tgt) + + def test_sub(self) : + tgt = leg.Legendre([1]) + assert_(self.p4 - self.p1 == tgt) + assert_(self.p4 - [1,2,3] == tgt) + assert_([2,2,3] - self.p1 == tgt) + + def test_mul(self) : + tgt = leg.Legendre([4.13333333, 8.8, 11.23809524, 7.2, 4.62857143]) + assert_poly_almost_equal(self.p1 * self.p1, tgt) + assert_poly_almost_equal(self.p1 * [1,2,3], tgt) + assert_poly_almost_equal([1,2,3] * self.p1, tgt) + + def test_floordiv(self) : + tgt = leg.Legendre([1]) + assert_(self.p4 // self.p1 == tgt) + assert_(self.p4 // [1,2,3] == tgt) + assert_([2,2,3] // self.p1 == tgt) + + def test_mod(self) : + tgt = leg.Legendre([1]) + assert_((self.p4 % self.p1) == tgt) + assert_((self.p4 % [1,2,3]) == tgt) + assert_(([2,2,3] % self.p1) == tgt) + + def test_divmod(self) : + tquo = leg.Legendre([1]) + trem = leg.Legendre([2]) + quo, rem = divmod(self.p5, self.p1) + assert_(quo == tquo and rem == trem) + quo, rem = divmod(self.p5, [1,2,3]) + assert_(quo == tquo and rem == trem) + quo, rem = divmod([3,2,3], self.p1) + assert_(quo == tquo and rem == trem) + + def test_pow(self) : + tgt = leg.Legendre([1]) + for i in range(5) : + res = self.p1**i + assert_(res == tgt) + tgt = tgt*self.p1 + + def test_call(self) : + # domain = [-1, 1] + x = np.linspace(-1, 1) + tgt = 3*(1.5*x**2 - .5) + 2*x + 1 + assert_almost_equal(self.p1(x), tgt) + + # domain = [0, 1] + x = np.linspace(0, 1) + xx = 2*x - 1 + assert_almost_equal(self.p2(x), self.p1(xx)) + + def test_degree(self) : + assert_equal(self.p1.degree(), 2) + + def test_trimdeg(self) : + assert_raises(ValueError, self.p1.cutdeg, .5) + assert_raises(ValueError, self.p1.cutdeg, -1) + assert_equal(len(self.p1.cutdeg(3)), 3) + assert_equal(len(self.p1.cutdeg(2)), 3) + assert_equal(len(self.p1.cutdeg(1)), 2) + assert_equal(len(self.p1.cutdeg(0)), 1) + + def test_convert(self) : + x = np.linspace(-1,1) + p = self.p1.convert(domain=[0,1]) + assert_almost_equal(p(x), self.p1(x)) + + def test_mapparms(self) : + parms = self.p2.mapparms() + assert_almost_equal(parms, [-1, 2]) + + def test_trim(self) : + coef = [1, 1e-6, 1e-12, 0] + p = leg.Legendre(coef) + assert_equal(p.trim().coef, coef[:3]) + assert_equal(p.trim(1e-10).coef, coef[:2]) + assert_equal(p.trim(1e-5).coef, coef[:1]) + + def test_truncate(self) : + assert_raises(ValueError, self.p1.truncate, .5) + assert_raises(ValueError, self.p1.truncate, 0) + assert_equal(len(self.p1.truncate(4)), 3) + assert_equal(len(self.p1.truncate(3)), 3) + assert_equal(len(self.p1.truncate(2)), 2) + assert_equal(len(self.p1.truncate(1)), 1) + + def test_copy(self) : + p = self.p1.copy() + assert_(self.p1 == p) + + def test_integ(self) : + p = self.p2.integ() + assert_almost_equal(p.coef, leg.legint([1,2,3], 1, 0, scl=.5)) + p = self.p2.integ(lbnd=0) + assert_almost_equal(p(0), 0) + p = self.p2.integ(1, 1) + assert_almost_equal(p.coef, leg.legint([1,2,3], 1, 1, scl=.5)) + p = self.p2.integ(2, [1, 2]) + assert_almost_equal(p.coef, leg.legint([1,2,3], 2, [1,2], scl=.5)) + + def test_deriv(self) : + p = self.p2.integ(2, [1, 2]) + assert_almost_equal(p.deriv(1).coef, self.p2.integ(1, [1]).coef) + assert_almost_equal(p.deriv(2).coef, self.p2.coef) + + def test_roots(self) : + p = leg.Legendre(leg.poly2leg([0, -1, 0, 1]), [0, 1]) + res = p.roots() + tgt = [0, .5, 1] + assert_almost_equal(res, tgt) + + def test_linspace(self): + xdes = np.linspace(0, 1, 20) + ydes = self.p2(xdes) + xres, yres = self.p2.linspace(20) + assert_almost_equal(xres, xdes) + assert_almost_equal(yres, ydes) + + def test_fromroots(self) : + roots = [0, .5, 1] + p = leg.Legendre.fromroots(roots, domain=[0, 1]) + res = p.coef + tgt = leg.poly2leg([0, -1, 0, 1]) + assert_almost_equal(res, tgt) + + def test_fit(self) : + def f(x) : + return x*(x - 1)*(x - 2) + x = np.linspace(0,3) + y = f(x) + + # test default value of domain + p = leg.Legendre.fit(x, y, 3) + assert_almost_equal(p.domain, [0,3]) + + # test that fit works in given domains + p = leg.Legendre.fit(x, y, 3, None) + assert_almost_equal(p(x), y) + assert_almost_equal(p.domain, [0,3]) + p = leg.Legendre.fit(x, y, 3, []) + assert_almost_equal(p(x), y) + assert_almost_equal(p.domain, [-1, 1]) + # test that fit accepts weights. + w = np.zeros_like(x) + yw = y.copy() + w[1::2] = 1 + yw[0::2] = 0 + p = leg.Legendre.fit(x, yw, 3, w=w) + assert_almost_equal(p(x), y) + + def test_identity(self) : + x = np.linspace(0,3) + p = leg.Legendre.identity() + assert_almost_equal(p(x), x) + p = leg.Legendre.identity([1,3]) + assert_almost_equal(p(x), x) From numpy-svn at scipy.org Mon Aug 16 22:39:06 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 16 Aug 2010 21:39:06 -0500 (CDT) Subject: [Numpy-svn] r8647 - trunk/numpy/polynomial Message-ID: <20100817023906.DD9EC39CB4B@scipy.org> Author: charris Date: 2010-08-16 21:39:06 -0500 (Mon, 16 Aug 2010) New Revision: 8647 Modified: trunk/numpy/polynomial/legendre.py Log: DOC: Fix documentation and examples in legendre.py. Modified: trunk/numpy/polynomial/legendre.py =================================================================== --- trunk/numpy/polynomial/legendre.py 2010-08-17 01:52:11 UTC (rev 8646) +++ trunk/numpy/polynomial/legendre.py 2010-08-17 02:39:06 UTC (rev 8647) @@ -47,29 +47,6 @@ -------- `numpy.polynomial` -Notes ------ -The implementations of multiplication, division, integration, and -differentiation use the algebraic identities [1]_: - -.. math :: - T_n(x) = \\frac{z^n + z^{-n}}{2} \\\\ - z\\frac{dx}{dz} = \\frac{z - z^{-1}}{2}. - -where - -.. math :: x = \\frac{z + z^{-1}}{2}. - -These identities allow a Chebyshev series to be expressed as a finite, -symmetric Laurent series. In this module, this sort of Laurent series -is referred to as a "z-series." - -References ----------- -.. [1] A. T. Benjamin, et al., "Combinatorial Trigonometry with Chebyshev - Polynomials," *Journal of Statistical Planning and Inference 14*, 2008 - (preprint: http://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) - """ from __future__ import division @@ -169,14 +146,16 @@ Examples -------- - >>> from numpy import polynomial as P - >>> c = P.Chebyshev(np.arange(4)) + >>> c = P.Legendre(range(4)) >>> c - Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) - >>> p = P.Polynomial(P.cheb2poly(c.coef)) + Legendre([ 0., 1., 2., 3.], [-1., 1.]) + >>> p = c.convert(kind=P.Polynomial) >>> p - Polynomial([ -2., -8., 4., 12.], [-1., 1.]) + Polynomial([-1. , -3.5, 3. , 7.5], [-1., 1.]) + >>> P.leg2poly(range(4)) + array([-1. , -3.5, 3. , 7.5]) + """ from polynomial import polyadd, polysub, polymulx @@ -238,7 +217,7 @@ >>> import numpy.polynomial.legendre as L >>> L.legline(3,2) array([3, 2]) - >>> L.legval(-3, L.chebline(3,2)) # should be -3 + >>> L.legval(-3, L.legline(3,2)) # should be -3 -3.0 """ @@ -294,42 +273,6 @@ return prd -def chebline(off, scl) : - """ - Chebyshev series whose graph is a straight line. - - - - Parameters - ---------- - off, scl : scalars - The specified line is given by ``off + scl*x``. - - Returns - ------- - y : ndarray - This module's representation of the Chebyshev series for - ``off + scl*x``. - - See Also - -------- - polyline - - Examples - -------- - >>> import numpy.polynomial.chebyshev as C - >>> C.chebline(3,2) - array([3, 2]) - >>> C.chebval(-3, C.chebline(3,2)) # should be -3 - -3.0 - - """ - if scl != 0 : - return np.array([off,scl]) - else : - return np.array([off]) - - def legfromroots(roots) : """ Generate a Legendre series with the given roots. @@ -567,14 +510,14 @@ Notes ----- In general, the (polynomial) product of two C-series results in terms - that are not in the Chebyshev polynomial basis set. Thus, to express - the product as a C-series, it is typically necessary to "re-project" - the product onto said basis set, which typically produces - "un-intuitive" (but correct) results; see Examples section below. + that are not in the Legendre polynomial basis set. Thus, to express + the product as a Legendre series, it is necessary to "re-project" the + product onto said basis set, which may produce "un-intuitive" (but + correct) results; see Examples section below. Examples -------- - >>> from numpy.polynomial import legendre as P + >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2) >>> P.legmul(c1,c2) # multiplication requires "reprojection" @@ -866,19 +809,19 @@ Examples -------- - >>> from numpy.polynomial import legyshev as L + >>> from numpy.polynomial import legendre as L >>> cs = (1,2,3) >>> L.legint(cs) - array([ 0.5, -0.5, 0.5, 0.5]) + array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) >>> L.legint(cs,3) - array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, - 0.00625 ]) + array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, + -1.73472348e-18, 1.90476190e-02, 9.52380952e-03]) >>> L.legint(cs, k=3) - array([ 3.5, -0.5, 0.5, 0.5]) - >>> L.legint(cs,lbnd=-2) - array([ 8.5, -0.5, 0.5, 0.5]) - >>> L.legint(cs,scl=-2) - array([-1., 1., -1., -1.]) + array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) + >>> L.legint(cs, lbnd=-2) + array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) + >>> L.legint(cs, scl=2) + array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) """ cnt = int(m) @@ -933,7 +876,7 @@ Array of numbers or objects that support multiplication and addition with themselves and with the elements of `cs`. cs : array_like - 1-d array of Chebyshev coefficients ordered from low to high. + 1-d array of Legendre coefficients ordered from low to high. Returns ------- @@ -1178,12 +1121,11 @@ def legroots(cs): """ - Compute the roots of a Chebyshev series. + Compute the roots of a Legendre series. Return the roots (a.k.a "zeros") of the Legendre series represented by - `cs`, which is the sequence of the C-series' coefficients from lowest - order "term" to highest, e.g., [1,2,3] represents the Legendre series - ``P_0 + 2*P_1 + 3*P_2``. + `cs`, which is the sequence of coefficients from lowest order "term" + to highest, e.g., [1,2,3] is the series ``L_0 + 2*L_1 + 3*L_2``. Parameters ---------- @@ -1212,11 +1154,11 @@ Examples -------- >>> import numpy.polynomial as P - >>> import numpy.polynomial.Legendre as L - >>> P.polyroots((-1,1,-1,1)) # x^3 - x^2 + x - 1 has two complex roots - array([ -4.99600361e-16-1.j, -4.99600361e-16+1.j, 1.00000e+00+0.j]) - >>> L.legroots((-1,1,-1,1)) # T3 - T2 + T1 - T0 has only real roots - array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) + >>> P.polyroots((1, 2, 3, 4)) # 4x^3 + 3x^2 + 2x + 1 has two complex roots + array([-0.60582959+0.j , -0.07208521-0.63832674j, + -0.07208521+0.63832674j]) + >>> P.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0 has only real roots + array([-0.85099543, -0.11407192, 0.51506735]) """ # cs is a trimmed copy From numpy-svn at scipy.org Tue Aug 17 07:43:44 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 06:43:44 -0500 (CDT) Subject: [Numpy-svn] r8648 - branches/1.5.x/numpy/core/tests Message-ID: <20100817114344.4724B39CD48@scipy.org> Author: rgommers Date: 2010-08-17 06:43:44 -0500 (Tue, 17 Aug 2010) New Revision: 8648 Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py Log: TST: (backport of r8623) skip C99 nan/inf tests on Windows. Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-17 02:39:06 UTC (rev 8647) +++ branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-17 11:43:44 UTC (rev 8648) @@ -1,3 +1,5 @@ +import sys + from numpy.testing import * import numpy.core.umath as ncu import numpy as np @@ -6,6 +8,20 @@ # TODO: conj 'symmetry' # TODO: FPU exceptions +# At least on Windows the results of many complex functions are not conforming +# to the C99 standard. See ticket 1574. +functions_seem_flaky = (np.exp(complex(np.inf, 0)).imag != 0) +# TODO: replace with a check on whether platform-provided C99 funcs are used +have_platform_functions = (sys.platform == 'win32') +skip_complex_tests = have_platform_functions and functions_seem_flaky + +def platform_skip(func): + return dec.skipif(skip_complex_tests, + "Numpy is using complex functions (e.g. sqrt) provided by your" + "platform's C library. However, they do not seem to behave according" + "to C99 -- so C99 tests are skipped.")(func) + + class TestCexp(object): def test_simple(self): check = check_complex_value @@ -17,6 +33,7 @@ ref = np.exp(1) * np.complex(np.cos(1), np.sin(1)) yield check, f, 1, 1, ref.real, ref.imag, False + @platform_skip def test_special_values(self): # C99: Section G 6.3.1 @@ -127,6 +144,7 @@ for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) + @platform_skip def test_special_values(self): xl = [] yl = [] @@ -297,6 +315,7 @@ #def test_branch_cut(self): # _check_branch_cut(f, -1, 0, 1, -1) + @platform_skip def test_special_values(self): check = check_complex_value f = np.sqrt From numpy-svn at scipy.org Tue Aug 17 07:46:32 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 06:46:32 -0500 (CDT) Subject: [Numpy-svn] r8649 - branches/1.5.x Message-ID: <20100817114632.9ABFE39CD48@scipy.org> Author: rgommers Date: 2010-08-17 06:46:32 -0500 (Tue, 17 Aug 2010) New Revision: 8649 Modified: branches/1.5.x/release.sh branches/1.5.x/setup.py Log: REL: set version to 1.5.0b2, and add 3.1 superpack to release script. Modified: branches/1.5.x/release.sh =================================================================== --- branches/1.5.x/release.sh 2010-08-17 11:43:44 UTC (rev 8648) +++ branches/1.5.x/release.sh 2010-08-17 11:46:32 UTC (rev 8649) @@ -7,6 +7,7 @@ paver dmg -p 2.7 paver dmg -p 2.6 paver dmg -p 2.5 +paver bdist_superpack -p 3.1 paver bdist_superpack -p 2.7 paver bdist_superpack -p 2.6 paver bdist_superpack -p 2.5 Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-17 11:43:44 UTC (rev 8648) +++ branches/1.5.x/setup.py 2010-08-17 11:46:32 UTC (rev 8649) @@ -56,8 +56,8 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = False -VERSION = '%d.%d.%db1' % (MAJOR, MINOR, MICRO) +ISRELEASED = True +VERSION = '%d.%d.%db2' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise def svn_version(): From numpy-svn at scipy.org Tue Aug 17 07:48:07 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 06:48:07 -0500 (CDT) Subject: [Numpy-svn] r8650 - tags Message-ID: <20100817114807.4341F39CD48@scipy.org> Author: rgommers Date: 2010-08-17 06:48:07 -0500 (Tue, 17 Aug 2010) New Revision: 8650 Added: tags/1.5.0b2/ Log: Create tag 1.5.0b2 Copied: tags/1.5.0b2 (from rev 8649, branches/1.5.x) From numpy-svn at scipy.org Tue Aug 17 07:49:43 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 06:49:43 -0500 (CDT) Subject: [Numpy-svn] r8651 - branches/1.5.x Message-ID: <20100817114943.26FFC39CD48@scipy.org> Author: rgommers Date: 2010-08-17 06:49:43 -0500 (Tue, 17 Aug 2010) New Revision: 8651 Modified: branches/1.5.x/setup.py Log: REL: set released=False again. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-17 11:48:07 UTC (rev 8650) +++ branches/1.5.x/setup.py 2010-08-17 11:49:43 UTC (rev 8651) @@ -56,7 +56,7 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = True +ISRELEASED = False VERSION = '%d.%d.%db2' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise From numpy-svn at scipy.org Tue Aug 17 12:10:14 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 11:10:14 -0500 (CDT) Subject: [Numpy-svn] r8652 - in branches/1.5.x: . tools/numpy-macosx-installer Message-ID: <20100817161014.82A3D39CCFF@scipy.org> Author: rgommers Date: 2010-08-17 11:10:14 -0500 (Tue, 17 Aug 2010) New Revision: 8652 Modified: branches/1.5.x/pavement.py branches/1.5.x/release.sh branches/1.5.x/tools/numpy-macosx-installer/new-create-dmg Log: REL: Some more changes to release scripts. Modified: branches/1.5.x/pavement.py =================================================================== --- branches/1.5.x/pavement.py 2010-08-17 11:49:43 UTC (rev 8651) +++ branches/1.5.x/pavement.py 2010-08-17 16:10:14 UTC (rev 8652) @@ -202,7 +202,7 @@ pyver = options.python_version def copy_bdist(arch): # Copy the wininst in dist into the release directory - if pyver[0] >= 3: + if int(pyver[0]) >= 3: source = os.path.join('build', 'py3k', 'dist', wininst_name(pyver)) else: source = os.path.join('dist', wininst_name(pyver)) Modified: branches/1.5.x/release.sh =================================================================== --- branches/1.5.x/release.sh 2010-08-17 11:49:43 UTC (rev 8651) +++ branches/1.5.x/release.sh 2010-08-17 16:10:14 UTC (rev 8652) @@ -4,9 +4,11 @@ source bootstrap/bin/activate python setupsconsegg.py install paver sdist -paver dmg -p 2.7 paver dmg -p 2.6 paver dmg -p 2.5 +export MACOSX_DEPLOYMENT_TARGET=10.6 +paver dmg -p 2.7 + paver bdist_superpack -p 3.1 paver bdist_superpack -p 2.7 paver bdist_superpack -p 2.6 Modified: branches/1.5.x/tools/numpy-macosx-installer/new-create-dmg =================================================================== --- branches/1.5.x/tools/numpy-macosx-installer/new-create-dmg 2010-08-17 11:49:43 UTC (rev 8651) +++ branches/1.5.x/tools/numpy-macosx-installer/new-create-dmg 2010-08-17 16:10:14 UTC (rev 8652) @@ -58,7 +58,7 @@ DMG_NAME="$(basename "$DMG_PATH")" DMG_TEMP_NAME="$DMG_DIR/rw.${DMG_NAME}" SRC_FOLDER="$(cd "$2" > /dev/null; pwd)" -DMG_SIZE=11m +DMG_SIZE=12m test -z "$VOLUME_NAME" && VOLUME_NAME="$(basename "$DMG_PATH" .dmg)" # AUX_PATH="$(cd "$(dirname $0)"; pwd)/support" From numpy-svn at scipy.org Tue Aug 17 14:22:26 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 13:22:26 -0500 (CDT) Subject: [Numpy-svn] r8653 - trunk/numpy/polynomial Message-ID: <20100817182226.7226539CD24@scipy.org> Author: charris Date: 2010-08-17 13:22:25 -0500 (Tue, 17 Aug 2010) New Revision: 8653 Modified: trunk/numpy/polynomial/polytemplate.py Log: Merge branch 'poly' Modified: trunk/numpy/polynomial/polytemplate.py =================================================================== --- trunk/numpy/polynomial/polytemplate.py 2010-08-17 16:10:14 UTC (rev 8652) +++ trunk/numpy/polynomial/polytemplate.py 2010-08-17 18:22:25 UTC (rev 8653) @@ -545,7 +545,7 @@ roots = ${nick}roots(self.coef) return pu.mapdomain(roots, $domain, self.domain) - def linspace(self, n): + def linspace(self, n=100): """Return x,y values at equally spaced points in domain. Returns x, y values at `n` equally spaced points across domain. @@ -554,8 +554,8 @@ Paramters --------- - n : int - Number of point pairs to return. + n : int, optional + Number of point pairs to return. The default value is 100. Returns ------- From numpy-svn at scipy.org Tue Aug 17 21:26:02 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 17 Aug 2010 20:26:02 -0500 (CDT) Subject: [Numpy-svn] r8654 - branches/1.5.x/numpy/polynomial Message-ID: <20100818012602.B4F0D39CCFF@scipy.org> Author: charris Date: 2010-08-17 20:26:02 -0500 (Tue, 17 Aug 2010) New Revision: 8654 Modified: branches/1.5.x/numpy/polynomial/polytemplate.py Log: BCK: Backport r8653 from trunk. Modified: branches/1.5.x/numpy/polynomial/polytemplate.py =================================================================== --- branches/1.5.x/numpy/polynomial/polytemplate.py 2010-08-17 18:22:25 UTC (rev 8653) +++ branches/1.5.x/numpy/polynomial/polytemplate.py 2010-08-18 01:26:02 UTC (rev 8654) @@ -545,7 +545,7 @@ roots = ${nick}roots(self.coef) return pu.mapdomain(roots, $domain, self.domain) - def linspace(self, n): + def linspace(self, n=100): """Return x,y values at equally spaced points in domain. Returns x, y values at `n` equally spaced points across domain. @@ -554,8 +554,8 @@ Paramters --------- - n : int - Number of point pairs to return. + n : int, optional + Number of point pairs to return. The default value is 100. Returns ------- From numpy-svn at scipy.org Fri Aug 20 06:48:41 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 20 Aug 2010 05:48:41 -0500 (CDT) Subject: [Numpy-svn] r8655 - trunk Message-ID: <20100820104841.A76FF39CD25@scipy.org> Author: rgommers Date: 2010-08-20 05:48:41 -0500 (Fri, 20 Aug 2010) New Revision: 8655 Modified: trunk/setupegg.py Log: 3K: make setupegg.py work through imp. Necessary because execfile() has disappeared in py3k. None of this works with bdist_mpkg at the moment, but that's a separate problem. Modified: trunk/setupegg.py =================================================================== --- trunk/setupegg.py 2010-08-18 01:26:02 UTC (rev 8654) +++ trunk/setupegg.py 2010-08-20 10:48:41 UTC (rev 8655) @@ -1,7 +1,24 @@ #!/usr/bin/env python """ A setup.py script to use setuptools, which gives egg goodness, etc. + +This is used to build installers for OS X through bdist_mpkg. + +Notes +----- +Using ``python setupegg.py install`` directly results in file permissions being +set wrong, with nose refusing to run any tests. To run the tests anyway, use:: + + >>> np.test(extra_argv=['--exe']) + """ +import sys from setuptools import setup -execfile('setup.py') + +if sys.version_info[0] >= 3: + import imp + setupfile = imp.load_source('setupfile', 'setup.py') + setupfile.setup_package() +else: + execfile('setup.py') From numpy-svn at scipy.org Fri Aug 20 22:01:23 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 20 Aug 2010 21:01:23 -0500 (CDT) Subject: [Numpy-svn] r8656 - trunk/doc Message-ID: <20100821020123.DEE4239CC7C@scipy.org> Author: rgommers Date: 2010-08-20 21:01:23 -0500 (Fri, 20 Aug 2010) New Revision: 8656 Modified: trunk/doc/HOWTO_RELEASE.txt Log: DOC: update release howto with notes on PyPi and python-announce list. Modified: trunk/doc/HOWTO_RELEASE.txt =================================================================== --- trunk/doc/HOWTO_RELEASE.txt 2010-08-20 10:48:41 UTC (rev 8655) +++ trunk/doc/HOWTO_RELEASE.txt 2010-08-21 02:01:23 UTC (rev 8656) @@ -243,6 +243,7 @@ Update PyPi ----------- +The final release (not betas or release candidates) should be uploaded to PyPi. There are two ways to update PyPi, the first one is:: $ python setup.py sdist upload @@ -261,7 +262,8 @@ Announce to the lists --------------------- The release should be announced on the mailing lists of -NumPy and SciPy, and possibly also those of Matplotlib,IPython and/or Pygame. +NumPy and SciPy, to python-announce, and possibly also those of +Matplotlib,IPython and/or Pygame. During the beta/RC phase an explicit request for testing the binaries with several other libraries (SciPy/Matplotlib/Pygame) should be posted on the From numpy-svn at scipy.org Fri Aug 20 22:32:19 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 20 Aug 2010 21:32:19 -0500 (CDT) Subject: [Numpy-svn] r8657 - trunk/numpy/core Message-ID: <20100821023219.1A3F739CC7C@scipy.org> Author: cdavid Date: 2010-08-20 21:32:18 -0500 (Fri, 20 Aug 2010) New Revision: 8657 Modified: trunk/numpy/core/setup.py Log: BUG: fix re-declaration of already defined macros in python.h. Modified: trunk/numpy/core/setup.py =================================================================== --- trunk/numpy/core/setup.py 2010-08-21 02:01:23 UTC (rev 8656) +++ trunk/numpy/core/setup.py 2010-08-21 02:32:18 UTC (rev 8657) @@ -215,12 +215,12 @@ _macros = ["isnan", "isinf", "signbit", "isfinite"] if sys.version_info[:2] >= (2, 6): for f in _macros: - st = config.check_decl(fname2def("decl_%s" % f), + already_declared = config.check_decl(fname2def("decl_%s" % f), headers=["Python.h", "math.h"]) - if not st: + if already_declared: + pub.append('NPY_%s' % fname2def("decl_%s" % f)) + else: macros.append(f) - else: - _add_decl(f) else: macros = _macros[:] # Normally, isnan and isinf are macro (C99), but some platforms only have From numpy-svn at scipy.org Sun Aug 22 01:25:08 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 22 Aug 2010 00:25:08 -0500 (CDT) Subject: [Numpy-svn] r8658 - in branches/1.5.x/numpy: core/tests lib/tests ma/tests Message-ID: <20100822052508.150CB39CD18@scipy.org> Author: rgommers Date: 2010-08-22 00:25:08 -0500 (Sun, 22 Aug 2010) New Revision: 8658 Modified: branches/1.5.x/numpy/core/tests/test_multiarray.py branches/1.5.x/numpy/core/tests/test_regression.py branches/1.5.x/numpy/core/tests/test_umath.py branches/1.5.x/numpy/core/tests/test_umath_complex.py branches/1.5.x/numpy/lib/tests/test_io.py branches/1.5.x/numpy/ma/tests/test_core.py branches/1.5.x/numpy/ma/tests/test_subclassing.py Log: TST: silence NaN related test warnings. See #1587. The final decision on what to do with this issue still has to be made, so this patch is only applied to 1.5.x now. Thanks to Christoph Gohlke for the patch. Modified: branches/1.5.x/numpy/core/tests/test_multiarray.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_multiarray.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/core/tests/test_multiarray.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -702,9 +702,13 @@ assert all(amax == aargmax.choose(*a.transpose(i,*axes))) def test_combinations(self): - for arr, pos in self.nan_arr: - assert_equal(np.argmax(arr), pos, err_msg="%r"%arr) - assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr) + err = np.seterr(invalid="ignore") + try: + for arr, pos in self.nan_arr: + assert_equal(np.argmax(arr), pos, err_msg="%r"%arr) + assert_equal(arr[np.argmax(arr)], np.max(arr), err_msg="%r"%arr) + finally: + np.seterr(**err) class TestMinMax(TestCase): Modified: branches/1.5.x/numpy/core/tests/test_regression.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -1008,7 +1008,11 @@ def test_sign_for_complex_nan(self, level=rlevel): """Ticket 794.""" C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan]) - have = np.sign(C) + err = np.seterr(invalid="ignore") + try: + have = np.sign(C) + finally: + np.seterr(**err) want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan]) assert_equal(have, want) Modified: branches/1.5.x/numpy/core/tests/test_umath.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_umath.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/core/tests/test_umath.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -170,11 +170,15 @@ np.seterr(**err) def test_nan(self): - assert np.isnan(np.logaddexp2(np.nan, np.inf)) - assert np.isnan(np.logaddexp2(np.inf, np.nan)) - assert np.isnan(np.logaddexp2(np.nan, 0)) - assert np.isnan(np.logaddexp2(0, np.nan)) - assert np.isnan(np.logaddexp2(np.nan, np.nan)) + err = np.seterr(invalid="ignore") + try: + assert np.isnan(np.logaddexp2(np.nan, np.inf)) + assert np.isnan(np.logaddexp2(np.inf, np.nan)) + assert np.isnan(np.logaddexp2(np.nan, 0)) + assert np.isnan(np.logaddexp2(0, np.nan)) + assert np.isnan(np.logaddexp2(np.nan, np.nan)) + finally: + np.seterr(**err) class TestLog(TestCase): @@ -236,11 +240,15 @@ np.seterr(**err) def test_nan(self): - assert np.isnan(np.logaddexp(np.nan, np.inf)) - assert np.isnan(np.logaddexp(np.inf, np.nan)) - assert np.isnan(np.logaddexp(np.nan, 0)) - assert np.isnan(np.logaddexp(0, np.nan)) - assert np.isnan(np.logaddexp(np.nan, np.nan)) + err = np.seterr(invalid="ignore") + try: + assert np.isnan(np.logaddexp(np.nan, np.inf)) + assert np.isnan(np.logaddexp(np.inf, np.nan)) + assert np.isnan(np.logaddexp(np.nan, 0)) + assert np.isnan(np.logaddexp(0, np.nan)) + assert np.isnan(np.logaddexp(np.nan, np.nan)) + finally: + np.seterr(**err) class TestLog1p(TestCase): @@ -399,15 +407,23 @@ arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) - assert_equal(np.maximum(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + assert_equal(np.maximum(arg1, arg2), out) + finally: + np.seterr(**err) def test_complex_nans(self): nan = np.nan - for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : - arg1 = np.array([0, cnan, cnan], dtype=np.complex) - arg2 = np.array([cnan, 0, cnan], dtype=np.complex) - out = np.array([nan, nan, nan], dtype=np.complex) - assert_equal(np.maximum(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : + arg1 = np.array([0, cnan, cnan], dtype=np.complex) + arg2 = np.array([cnan, 0, cnan], dtype=np.complex) + out = np.array([nan, nan, nan], dtype=np.complex) + assert_equal(np.maximum(arg1, arg2), out) + finally: + np.seterr(**err) class TestMinimum(TestCase): @@ -420,15 +436,23 @@ arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) - assert_equal(np.minimum(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + assert_equal(np.minimum(arg1, arg2), out) + finally: + np.seterr(**err) def test_complex_nans(self): nan = np.nan - for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : - arg1 = np.array([0, cnan, cnan], dtype=np.complex) - arg2 = np.array([cnan, 0, cnan], dtype=np.complex) - out = np.array([nan, nan, nan], dtype=np.complex) - assert_equal(np.minimum(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : + arg1 = np.array([0, cnan, cnan], dtype=np.complex) + arg2 = np.array([cnan, 0, cnan], dtype=np.complex) + out = np.array([nan, nan, nan], dtype=np.complex) + assert_equal(np.minimum(arg1, arg2), out) + finally: + np.seterr(**err) class TestFmax(TestCase): @@ -441,15 +465,23 @@ arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) - assert_equal(np.fmax(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + assert_equal(np.fmax(arg1, arg2), out) + finally: + np.seterr(**err) def test_complex_nans(self): nan = np.nan - for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : - arg1 = np.array([0, cnan, cnan], dtype=np.complex) - arg2 = np.array([cnan, 0, cnan], dtype=np.complex) - out = np.array([0, 0, nan], dtype=np.complex) - assert_equal(np.fmax(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]: + arg1 = np.array([0, cnan, cnan], dtype=np.complex) + arg2 = np.array([cnan, 0, cnan], dtype=np.complex) + out = np.array([0, 0, nan], dtype=np.complex) + assert_equal(np.fmax(arg1, arg2), out) + finally: + np.seterr(**err) class TestFmin(TestCase): @@ -462,15 +494,23 @@ arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) - assert_equal(np.fmin(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + assert_equal(np.fmin(arg1, arg2), out) + finally: + np.seterr(**err) def test_complex_nans(self): nan = np.nan - for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : - arg1 = np.array([0, cnan, cnan], dtype=np.complex) - arg2 = np.array([cnan, 0, cnan], dtype=np.complex) - out = np.array([0, 0, nan], dtype=np.complex) - assert_equal(np.fmin(arg1, arg2), out) + err = np.seterr(invalid="ignore") + try: + for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)]: + arg1 = np.array([0, cnan, cnan], dtype=np.complex) + arg2 = np.array([cnan, 0, cnan], dtype=np.complex) + out = np.array([0, 0, nan], dtype=np.complex) + assert_equal(np.fmin(arg1, arg2), out) + finally: + np.seterr(**err) class TestFloatingPoint(TestCase): @@ -1080,19 +1120,23 @@ fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1), complex(1, 1), complex(-1, -1), complex(0, 0)] - for x in nans + fins: - x = np.array([x]) - for y in nans + fins: - y = np.array([y]) + err = np.seterr(invalid="ignore") + try: + for x in nans + fins: + x = np.array([x]) + for y in nans + fins: + y = np.array([y]) + + if np.isfinite(x) and np.isfinite(y): + continue + + assert_equal(x < y, False, err_msg="%r < %r" % (x, y)) + assert_equal(x > y, False, err_msg="%r > %r" % (x, y)) + assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y)) + assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y)) + assert_equal(x == y, False, err_msg="%r == %r" % (x, y)) + finally: + np.seterr(**err) - if np.isfinite(x) and np.isfinite(y): - continue - - assert_equal(x < y, False, err_msg="%r < %r" % (x, y)) - assert_equal(x > y, False, err_msg="%r > %r" % (x, y)) - assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y)) - assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y)) - assert_equal(x == y, False, err_msg="%r == %r" % (x, y)) - if __name__ == "__main__": run_module_suite() Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -239,7 +239,11 @@ # clog(- inf + i inf) returns +inf + i3pi /4. x = np.array([complex(-np.inf, np.inf)], dtype=np.complex) y = np.complex(np.inf, 0.75 * np.pi) - assert_almost_equal(np.log(x), y) + err = np.seterr(invalid="ignore") + try: + assert_almost_equal(np.log(x), y) + finally: + np.seterr(**err) xl.append(x) yl.append(y) @@ -424,9 +428,13 @@ def test_simple(self): x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan]) + err = np.seterr(invalid="ignore") y = np.abs(x) - for i in range(len(x)): - assert_almost_equal(y[i], y_r[i]) + try: + for i in range(len(x)): + assert_almost_equal(y[i], y_r[i]) + finally: + np.seterr(**err) def test_fabs(self): # Test that np.abs(x +- 0j) == np.abs(x) (as mandated by C99 for cabs) @@ -437,7 +445,11 @@ assert_array_equal(np.abs(x), np.real(x)) x = np.array([complex(np.inf, np.NZERO)], dtype=np.complex) - assert_array_equal(np.abs(x), np.real(x)) + err = np.seterr(invalid="ignore") + try: + assert_array_equal(np.abs(x), np.real(x)) + finally: + np.seterr(**err) x = np.array([complex(np.nan, np.NZERO)], dtype=np.complex) assert_array_equal(np.abs(x), np.real(x)) Modified: branches/1.5.x/numpy/lib/tests/test_io.py =================================================================== --- branches/1.5.x/numpy/lib/tests/test_io.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/lib/tests/test_io.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -849,7 +849,11 @@ def test_withmissing(self): data = StringIO('A,B\n0,1\n2,N/A') kwargs = dict(delimiter=",", missing_values="N/A", names=True) - test = np.mafromtxt(data, dtype=None, **kwargs) + err = np.seterr(invalid='ignore') + try: + test = np.mafromtxt(data, dtype=None, **kwargs) + finally: + np.seterr(**err) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], dtype=[('A', np.int), ('B', np.int)]) @@ -857,7 +861,11 @@ assert_equal(test.mask, control.mask) # data.seek(0) - test = np.mafromtxt(data, **kwargs) + err = np.seterr(invalid='ignore') + try: + test = np.mafromtxt(data, **kwargs) + finally: + np.seterr(**err) control = ma.array([(0, 1), (2, -1)], mask=[(False, False), (False, True)], dtype=[('A', np.float), ('B', np.float)]) @@ -870,8 +878,12 @@ basekwargs = dict(dtype=None, delimiter=",", names=True,) mdtype = [('A', int), ('B', float), ('C', complex)] # - test = np.mafromtxt(StringIO(data), missing_values="N/A", - **basekwargs) + err = np.seterr(invalid='ignore') + try: + test = np.mafromtxt(StringIO(data), missing_values="N/A", + **basekwargs) + finally: + np.seterr(**err) control = ma.array([(0, 0.0, 0j), (1, -999, 1j), (-9, 2.2, -999j), (3, -99, 3j)], mask=[(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)], @@ -879,17 +891,26 @@ assert_equal(test, control) # basekwargs['dtype'] = mdtype - test = np.mafromtxt(StringIO(data), - missing_values={0:-9, 1:-99, 2:-999j}, **basekwargs) + err = np.seterr(invalid='ignore') + try: + test = np.mafromtxt(StringIO(data), + missing_values={0:-9, 1:-99, 2:-999j}, + **basekwargs) + finally: + np.seterr(**err) control = ma.array([(0, 0.0, 0j), (1, -999, 1j), (-9, 2.2, -999j), (3, -99, 3j)], mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)], dtype=mdtype) assert_equal(test, control) # - test = np.mafromtxt(StringIO(data), - missing_values={0:-9, 'B':-99, 'C':-999j}, - **basekwargs) + err = np.seterr(invalid='ignore') + try: + test = np.mafromtxt(StringIO(data), + missing_values={0:-9, 'B':-99, 'C':-999j}, + **basekwargs) + finally: + np.seterr(**err) control = ma.array([(0, 0.0, 0j), (1, -999, 1j), (-9, 2.2, -999j), (3, -99, 3j)], mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)], Modified: branches/1.5.x/numpy/ma/tests/test_core.py =================================================================== --- branches/1.5.x/numpy/ma/tests/test_core.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/ma/tests/test_core.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -2702,8 +2702,12 @@ _ = method(out=mout) self.assertTrue(mout is not masked) assert_equal(mout.mask, True) - # Using a ndarray as explicit output - _ = method(out=nout) + err = np.seterr(invalid="ignore") + try: + # Using a ndarray as explicit output + _ = method(out=nout) + finally: + np.seterr(**err) self.assertTrue(np.isnan(nout)) # x = array(arange(10), mask=True) @@ -2717,8 +2721,12 @@ _ = method(out=mout, ddof=1) self.assertTrue(mout is not masked) assert_equal(mout.mask, True) - # Using a ndarray as explicit output - _ = method(out=nout, ddof=1) + err = np.seterr(invalid="ignore") + try: + # Using a ndarray as explicit output + _ = method(out=nout, ddof=1) + finally: + np.seterr(**err) self.assertTrue(np.isnan(nout)) Modified: branches/1.5.x/numpy/ma/tests/test_subclassing.py =================================================================== --- branches/1.5.x/numpy/ma/tests/test_subclassing.py 2010-08-21 02:32:18 UTC (rev 8657) +++ branches/1.5.x/numpy/ma/tests/test_subclassing.py 2010-08-22 05:25:08 UTC (rev 8658) @@ -94,7 +94,11 @@ "Tests masked_unary_operation" (x, mx) = self.data self.assertTrue(isinstance(log(mx), mmatrix)) - assert_equal(log(x), np.log(x)) + err = np.seterr(divide="ignore") + try: + assert_equal(log(x), np.log(x)) + finally: + np.seterr(**err) def test_masked_binary_operations(self): "Tests masked_binary_operation" From numpy-svn at scipy.org Sun Aug 22 01:25:27 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 22 Aug 2010 00:25:27 -0500 (CDT) Subject: [Numpy-svn] r8659 - branches/1.5.x/numpy/core/tests Message-ID: <20100822052527.D347F39CD18@scipy.org> Author: rgommers Date: 2010-08-22 00:25:27 -0500 (Sun, 22 Aug 2010) New Revision: 8659 Modified: branches/1.5.x/numpy/core/tests/test_regression.py Log: TST: mark test for #99 as knownfail for 64 bit Windows. Thanks to Christoph Gohkle. Modified: branches/1.5.x/numpy/core/tests/test_regression.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-22 05:25:08 UTC (rev 8658) +++ branches/1.5.x/numpy/core/tests/test_regression.py 2010-08-22 05:25:27 UTC (rev 8659) @@ -136,7 +136,8 @@ self.assertRaises(TypeError,np.dtype, {'names':['a'],'formats':['foo']},align=1) - @dec.knownfailureif(sys.version_info[0] >= 3, + @dec.knownfailureif(sys.version_info[0] >= 3 or ( + sys.platform == 'win32' and '64 bit' in sys.version), "numpy.intp('0xff', 16) not supported on Py3, " "as it does not inherit from Python int") def test_intp(self,level=rlevel): From numpy-svn at scipy.org Sun Aug 22 01:25:46 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 22 Aug 2010 00:25:46 -0500 (CDT) Subject: [Numpy-svn] r8660 - branches/1.5.x/numpy/core/tests Message-ID: <20100822052546.AB51739CD18@scipy.org> Author: rgommers Date: 2010-08-22 00:25:46 -0500 (Sun, 22 Aug 2010) New Revision: 8660 Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py Log: TST: Mark Clog test as knownfail on Windows. On 64-bit Windows builds the platform_skip decorator didn't take effect because "(np.exp(complex(np.inf, 0)).imag != 0)" correctly evaluates to False. But the test was failing anyway. Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-22 05:25:27 UTC (rev 8659) +++ branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-22 05:25:46 UTC (rev 8660) @@ -144,7 +144,12 @@ for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) - @platform_skip + #@platform_skip + # Clog tests have been failing for a long time on Windows, so always skip + # on that platform. In 1.5.x the platform_skip decorator is Windows-only + # anyway. + @dec.knownfailureif(sys.platform == 'win32', + "clog(- inf + i inf) fails on Windows.") def test_special_values(self): xl = [] yl = [] From numpy-svn at scipy.org Sun Aug 22 01:37:21 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 22 Aug 2010 00:37:21 -0500 (CDT) Subject: [Numpy-svn] r8661 - branches/1.5.x/doc/release Message-ID: <20100822053721.377A539CC9C@scipy.org> Author: rgommers Date: 2010-08-22 00:37:21 -0500 (Sun, 22 Aug 2010) New Revision: 8661 Modified: branches/1.5.x/doc/release/1.5.0-notes.rst Log: DOC: add note on py3k-compatible nose branch. Modified: branches/1.5.x/doc/release/1.5.0-notes.rst =================================================================== --- branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-22 05:25:46 UTC (rev 8660) +++ branches/1.5.x/doc/release/1.5.0-notes.rst 2010-08-22 05:37:21 UTC (rev 8661) @@ -12,8 +12,12 @@ This is the first NumPy release which is compatible with Python 3. Support for Python 3 and Python 2 is done from a single code base. Extensive notes on changes can be found at -``_. +``_. +Note that the Numpy testing framework relies on nose, which does not have a +Python 3 compatible release yet. A working Python 3 branch of nose can be found +at ``_ however. + Porting of SciPy to Python 3 is expected to be completed soon. :pep:`3118` compatibility From numpy-svn at scipy.org Wed Aug 25 03:22:41 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 02:22:41 -0500 (CDT) Subject: [Numpy-svn] r8662 - trunk/numpy/distutils/command Message-ID: <20100825072241.0385239CCAA@scipy.org> Author: pearu Date: 2010-08-25 02:22:40 -0500 (Wed, 25 Aug 2010) New Revision: 8662 Modified: trunk/numpy/distutils/command/build_src.py Log: Make extension swig_opts effective to build_src command. Modified: trunk/numpy/distutils/command/build_src.py =================================================================== --- trunk/numpy/distutils/command/build_src.py 2010-08-22 05:37:21 UTC (rev 8661) +++ trunk/numpy/distutils/command/build_src.py 2010-08-25 07:22:40 UTC (rev 8662) @@ -640,9 +640,13 @@ target_dirs = [] py_files = [] # swig generated .py files target_ext = '.c' - if self.swig_cpp: + if '-c++' in extension.swig_opts: typ = 'c++' is_cpp = True + extension.swig_opts.remove('-c++') + elif self.swig_cpp: + typ = 'c++' + is_cpp = True else: typ = None is_cpp = False @@ -716,7 +720,7 @@ self.mkpath(d) swig = self.swig or self.find_swig() - swig_cmd = [swig, "-python"] + swig_cmd = [swig, "-python"] + extension.swig_opts if is_cpp: swig_cmd.append('-c++') for d in extension.include_dirs: From numpy-svn at scipy.org Wed Aug 25 04:41:58 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 03:41:58 -0500 (CDT) Subject: [Numpy-svn] r8663 - trunk/numpy/distutils/command Message-ID: <20100825084158.00AE039CCAA@scipy.org> Author: pearu Date: 2010-08-25 03:41:58 -0500 (Wed, 25 Aug 2010) New Revision: 8663 Modified: trunk/numpy/distutils/command/build_src.py Log: Fix swig target extension when swig target is not defined by the .i file but should be c++. Modified: trunk/numpy/distutils/command/build_src.py =================================================================== --- trunk/numpy/distutils/command/build_src.py 2010-08-25 07:22:40 UTC (rev 8662) +++ trunk/numpy/distutils/command/build_src.py 2010-08-25 08:41:58 UTC (rev 8663) @@ -656,6 +656,8 @@ for source in sources: (base, ext) = os.path.splitext(source) if ext == '.i': # SWIG interface file + # the code below assumes that the sources list + # contains not more than one .i SWIG interface file if self.inplace: target_dir = os.path.dirname(base) py_target_dir = self.ext_target_dir @@ -671,10 +673,16 @@ if typ is None: typ = get_swig_target(source) is_cpp = typ=='c++' - if is_cpp: target_ext = '.cpp' + if is_cpp: + target_ext = '.cpp' else: typ2 = get_swig_target(source) - if typ!=typ2: + if typ2 is None: + log.warn('source %r does not define swig target, assuming %s swig target' \ + % (source, typ)) + if is_cpp: + target_ext = '.cpp' + elif typ!=typ2: log.warn('expected %r but source %r defines %r swig target' \ % (typ, source, typ2)) if typ2=='c++': @@ -750,7 +758,7 @@ def get_swig_target(source): f = open(source,'r') - result = 'c' + result = None line = f.readline() if _has_cpp_header(line): result = 'c++' From numpy-svn at scipy.org Wed Aug 25 07:23:07 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 06:23:07 -0500 (CDT) Subject: [Numpy-svn] r8664 - trunk/numpy/distutils/command Message-ID: <20100825112307.26C7239CCAA@scipy.org> Author: pearu Date: 2010-08-25 06:23:07 -0500 (Wed, 25 Aug 2010) New Revision: 8664 Modified: trunk/numpy/distutils/command/__init__.py trunk/numpy/distutils/command/build_py.py Log: Fix bug to ensure that swig generated .py files are installed. Modified: trunk/numpy/distutils/command/__init__.py =================================================================== --- trunk/numpy/distutils/command/__init__.py 2010-08-25 08:41:58 UTC (rev 8663) +++ trunk/numpy/distutils/command/__init__.py 2010-08-25 11:23:07 UTC (rev 8664) @@ -5,7 +5,7 @@ __revision__ = "$Id: __init__.py,v 1.3 2005/05/16 11:08:49 pearu Exp $" -distutils_all = [ 'build_py', +distutils_all = [ #'build_py', 'clean', 'install_clib', 'install_scripts', @@ -20,6 +20,7 @@ 'config_compiler', 'config', 'build_src', + 'build_py', 'build_ext', 'build_clib', 'build_scripts', Modified: trunk/numpy/distutils/command/build_py.py =================================================================== --- trunk/numpy/distutils/command/build_py.py 2010-08-25 08:41:58 UTC (rev 8663) +++ trunk/numpy/distutils/command/build_py.py 2010-08-25 11:23:07 UTC (rev 8664) @@ -4,6 +4,12 @@ class build_py(old_build_py): + def run(self): + build_src = self.get_finalized_command('build_src') + if build_src.py_modules_dict and self.packages is None: + self.packages = build_src.py_modules_dict.keys () + old_build_py.run(self) + def find_package_modules(self, package, package_dir): modules = old_build_py.find_package_modules(self, package, package_dir) @@ -19,6 +25,7 @@ self.py_modules[:] = new_py_modules modules = old_build_py.find_modules(self) self.py_modules[:] = old_py_modules + return modules # XXX: Fix find_source_files for item in py_modules such that item is 3-tuple From numpy-svn at scipy.org Wed Aug 25 08:30:32 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:30:32 -0500 (CDT) Subject: [Numpy-svn] r8665 - trunk/numpy/core/include/numpy Message-ID: <20100825123032.78FD639CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:30:32 -0500 (Wed, 25 Aug 2010) New Revision: 8665 Modified: trunk/numpy/core/include/numpy/npy_3kcompat.h Log: BUG: Fix bug on Windows in fromfile/tofile. Closes #1583. Thanks to C. Gohkle. Modified: trunk/numpy/core/include/numpy/npy_3kcompat.h =================================================================== --- trunk/numpy/core/include/numpy/npy_3kcompat.h 2010-08-25 11:23:07 UTC (rev 8664) +++ trunk/numpy/core/include/numpy/npy_3kcompat.h 2010-08-25 12:30:32 UTC (rev 8665) @@ -178,7 +178,11 @@ } fd2 = PyNumber_AsSsize_t(ret, NULL); Py_DECREF(ret); +#ifdef _WIN32 + return _fdopen(fd2, mode); +#else return fdopen(fd2, mode); +#endif } #endif From numpy-svn at scipy.org Wed Aug 25 08:33:54 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:33:54 -0500 (CDT) Subject: [Numpy-svn] r8666 - branches/1.5.x/numpy/core/include/numpy Message-ID: <20100825123354.25E8639CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:33:53 -0500 (Wed, 25 Aug 2010) New Revision: 8666 Modified: branches/1.5.x/numpy/core/include/numpy/npy_3kcompat.h Log: BUG: (backport of r8665) Fix bug on Windows in fromfile/tofile. Closes #1583. Thanks to C. Gohkle. Modified: branches/1.5.x/numpy/core/include/numpy/npy_3kcompat.h =================================================================== --- branches/1.5.x/numpy/core/include/numpy/npy_3kcompat.h 2010-08-25 12:30:32 UTC (rev 8665) +++ branches/1.5.x/numpy/core/include/numpy/npy_3kcompat.h 2010-08-25 12:33:53 UTC (rev 8666) @@ -178,7 +178,11 @@ } fd2 = PyNumber_AsSsize_t(ret, NULL); Py_DECREF(ret); +#ifdef _WIN32 + return _fdopen(fd2, mode); +#else return fdopen(fd2, mode); +#endif } #endif From numpy-svn at scipy.org Wed Aug 25 08:35:05 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:35:05 -0500 (CDT) Subject: [Numpy-svn] r8667 - branches/1.5.x/numpy/core/tests Message-ID: <20100825123505.DA9A739CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:35:05 -0500 (Wed, 25 Aug 2010) New Revision: 8667 Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py Log: TST: clean up invalid value warning emitted from test. Modified: branches/1.5.x/numpy/core/tests/test_umath_complex.py =================================================================== --- branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-25 12:33:53 UTC (rev 8666) +++ branches/1.5.x/numpy/core/tests/test_umath_complex.py 2010-08-25 12:35:05 UTC (rev 8667) @@ -10,7 +10,11 @@ # At least on Windows the results of many complex functions are not conforming # to the C99 standard. See ticket 1574. -functions_seem_flaky = (np.exp(complex(np.inf, 0)).imag != 0) +err = np.seterr(invalid='ignore') +try: + functions_seem_flaky = (np.exp(complex(np.inf, 0)).imag != 0) +finally: + np.seterr(**err) # TODO: replace with a check on whether platform-provided C99 funcs are used have_platform_functions = (sys.platform == 'win32') skip_complex_tests = have_platform_functions and functions_seem_flaky From numpy-svn at scipy.org Wed Aug 25 08:40:23 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:40:23 -0500 (CDT) Subject: [Numpy-svn] r8668 - branches/1.5.x Message-ID: <20100825124023.E88B439CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:40:23 -0500 (Wed, 25 Aug 2010) New Revision: 8668 Modified: branches/1.5.x/setupegg.py Log: 3K: (backport of r8655) make setupegg.py work through imp. Necessary because execfile() has disappeared in py3k. None of this works with bdist_mpkg at the moment, but that's a separate problem. Modified: branches/1.5.x/setupegg.py =================================================================== --- branches/1.5.x/setupegg.py 2010-08-25 12:35:05 UTC (rev 8667) +++ branches/1.5.x/setupegg.py 2010-08-25 12:40:23 UTC (rev 8668) @@ -1,7 +1,24 @@ #!/usr/bin/env python """ A setup.py script to use setuptools, which gives egg goodness, etc. + +This is used to build installers for OS X through bdist_mpkg. + +Notes +----- +Using ``python setupegg.py install`` directly results in file permissions being +set wrong, with nose refusing to run any tests. To run the tests anyway, use:: + + >>> np.test(extra_argv=['--exe']) + """ +import sys from setuptools import setup -execfile('setup.py') + +if sys.version_info[0] >= 3: + import imp + setupfile = imp.load_source('setupfile', 'setup.py') + setupfile.setup_package() +else: + execfile('setup.py') From numpy-svn at scipy.org Wed Aug 25 08:47:52 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:47:52 -0500 (CDT) Subject: [Numpy-svn] r8669 - branches/1.5.x Message-ID: <20100825124752.0696A39CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:47:51 -0500 (Wed, 25 Aug 2010) New Revision: 8669 Modified: branches/1.5.x/setup.py Log: REL: set version to 1.5.0rc1, released=True. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-25 12:40:23 UTC (rev 8668) +++ branches/1.5.x/setup.py 2010-08-25 12:47:51 UTC (rev 8669) @@ -56,8 +56,8 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = False -VERSION = '%d.%d.%db2' % (MAJOR, MINOR, MICRO) +ISRELEASED = True +VERSION = '%d.%d.%drc1' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise def svn_version(): From numpy-svn at scipy.org Wed Aug 25 08:50:31 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:50:31 -0500 (CDT) Subject: [Numpy-svn] r8670 - tags Message-ID: <20100825125031.3C76439CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:50:31 -0500 (Wed, 25 Aug 2010) New Revision: 8670 Added: tags/1.5.0rc1/ Log: Create tag 1.5.0rc1 Copied: tags/1.5.0rc1 (from rev 8669, branches/1.5.x) From numpy-svn at scipy.org Wed Aug 25 08:51:28 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 25 Aug 2010 07:51:28 -0500 (CDT) Subject: [Numpy-svn] r8671 - branches/1.5.x Message-ID: <20100825125128.BDC0539CC70@scipy.org> Author: rgommers Date: 2010-08-25 07:51:28 -0500 (Wed, 25 Aug 2010) New Revision: 8671 Modified: branches/1.5.x/setup.py Log: REL: Set released=False again. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-25 12:50:31 UTC (rev 8670) +++ branches/1.5.x/setup.py 2010-08-25 12:51:28 UTC (rev 8671) @@ -56,7 +56,7 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = True +ISRELEASED = False VERSION = '%d.%d.%drc1' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise From numpy-svn at scipy.org Fri Aug 27 16:21:22 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 27 Aug 2010 15:21:22 -0500 (CDT) Subject: [Numpy-svn] r8672 - in trunk/numpy/lib: . tests Message-ID: <20100827202122.EBD2839CD44@scipy.org> Author: dhuard Date: 2010-08-27 15:21:22 -0500 (Fri, 27 Aug 2010) New Revision: 8672 Modified: trunk/numpy/lib/function_base.py trunk/numpy/lib/tests/test_function_base.py Log: Fixed bug in histogram for non-uniform bin widths and normed=True. Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2010-08-25 12:51:28 UTC (rev 8671) +++ trunk/numpy/lib/function_base.py 2010-08-27 20:21:22 UTC (rev 8672) @@ -191,7 +191,7 @@ if normed: db = array(np.diff(bins), float) - return n/(n*db).sum(), bins + return n/db/n.sum(), bins else: return n, bins Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2010-08-25 12:51:28 UTC (rev 8671) +++ trunk/numpy/lib/tests/test_function_base.py 2010-08-27 20:21:22 UTC (rev 8672) @@ -565,13 +565,25 @@ area = sum(a * diff(b)) assert_almost_equal(area, 1) - # Check with non constant bin width - v = rand(n) * 10 - bins = [0, 1, 5, 9, 10] + # Check with non-constant bin widths + v = np.arange(10) + bins = [0,1,3,6,10] a, b = histogram(v, bins, normed=True) - area = sum(a * diff(b)) - assert_almost_equal(area, 1) - + assert_array_equal(a, .1) + assert_equal(sum(a*diff(b)), 1) + + # Variale bin widths are especially useful to deal with + # infinities. + v = np.arange(10) + bins = [0,1,3,6,np.inf] + a, b = histogram(v, bins, normed=True) + assert_array_equal(a, [.1,.1,.1,0.]) + + # Taken from a bug report from N. Becker on the numpy-discussion + # mailing list Aug. 6, 2010. + counts, dmy = np.histogram([1,2,3,4], [0.5,1.5,np.inf], normed=True) + assert_equal(counts, [.25, 0]) + def test_outliers(self): # Check that outliers are not tallied a = arange(10) + .5 @@ -631,9 +643,14 @@ wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1]) assert_array_equal(wa, [4, 5, 0, 1]) wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1], normed=True) - assert_array_equal(wa, array([4, 5, 0, 1]) / 10. / 3. * 4) + assert_array_almost_equal(wa, array([4, 5, 0, 1]) / 10. / 3. * 4) + # Check weights with non-uniform bin widths + a,b = histogram(np.arange(9), [0,1,3,6,10], \ + weights=[2,1,1,1,1,1,1,1,1], normed=True) + assert_almost_equal(a, [.2, .1, .1, .075]) + class TestHistogramdd(TestCase): def test_simple(self): x = array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \ From numpy-svn at scipy.org Mon Aug 30 06:56:17 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 30 Aug 2010 05:56:17 -0500 (CDT) Subject: [Numpy-svn] r8673 - in trunk/numpy/distutils: . command Message-ID: <20100830105617.714EE39CD02@scipy.org> Author: pearu Date: 2010-08-30 05:56:17 -0500 (Mon, 30 Aug 2010) New Revision: 8673 Modified: trunk/numpy/distutils/command/config.py trunk/numpy/distutils/system_info.py Log: Implemented detection of gfortran usage for ATLAS linkage. get_atlas_version returns now a tuple (version_str, info_dict). Nice thing about the patch is that specifying gnu95 compiler is not needed anymore for numpy (neither for scipy) build when using ATLAS containing gfortran compiled blas/lapack. Modified: trunk/numpy/distutils/command/config.py =================================================================== --- trunk/numpy/distutils/command/config.py 2010-08-27 20:21:22 UTC (rev 8672) +++ trunk/numpy/distutils/command/config.py 2010-08-30 10:56:17 UTC (rev 8673) @@ -399,8 +399,15 @@ self._check_compiler() exitcode, output = 255, '' try: - src, obj, exe = self._link(body, headers, include_dirs, - libraries, library_dirs, lang) + grabber = GrabStdout() + try: + src, obj, exe = self._link(body, headers, include_dirs, + libraries, library_dirs, lang) + grabber.restore() + except: + output = grabber.data + grabber.restore() + raise exe = os.path.join('.', exe) exitstatus, output = exec_command(exe, execute_in='.') if hasattr(os, 'WEXITSTATUS'): @@ -416,6 +423,22 @@ log.info("success!") except (CompileError, LinkError): log.info("failure.") - self._clean() return exitcode, output + +class GrabStdout(object): + + def __init__(self): + self.sys_stdout = sys.stdout + self.data = '' + sys.stdout = self + + def write (self, data): + self.sys_stdout.write(data) + self.data += data + + def flush (self): + self.sys_stdout.flush() + + def restore(self): + sys.stdout = self.sys_stdout Modified: trunk/numpy/distutils/system_info.py =================================================================== --- trunk/numpy/distutils/system_info.py 2010-08-27 20:21:22 UTC (rev 8672) +++ trunk/numpy/distutils/system_info.py 2010-08-30 10:56:17 UTC (rev 8673) @@ -1011,6 +1011,9 @@ else: info['language'] = 'f77' + atlas_version, atlas_extra_info = get_atlas_version(**atlas) + dict_append(info, **atlas_extra_info) + self.set_info(**info) class atlas_blas_info(atlas_info): @@ -1035,6 +1038,9 @@ dict_append(info,include_dirs=[h]) info['language'] = 'c' + atlas_version, atlas_extra_info = get_atlas_version(**atlas) + dict_append(atlas, **atlas_extra_info) + dict_append(info,**atlas) self.set_info(**info) @@ -1209,22 +1215,44 @@ return _cached_atlas_version[key] c = cmd_config(Distribution()) atlas_version = None + info = {} try: s, o = c.get_output(atlas_version_c_text, libraries=libraries, library_dirs=library_dirs) - except: # failed to get version from file -- maybe on Windows + if s and re.search (r'undefined reference to `_gfortran', o, re.M): + s, o = c.get_output(atlas_version_c_text, + libraries=libraries + ['gfortran'], library_dirs=library_dirs) + if not s: + warnings.warn(""" +***************************************************** +Linkage with ATLAS requires gfortran. Use + + python setup.py config_fc --fcompiler=gnu95 ... + +when building extension libraries that use ATLAS. +Make sure that -lgfortran is used for C++ extensions. +***************************************************** +""") + dict_append(info, language='f90', + define_macros = [('ATLAS_REQUIRES_GFORTRAN', None)]) + except Exception, msg: # failed to get version from file -- maybe on Windows # look at directory name for o in library_dirs: m = re.search(r'ATLAS_(?P\d+[.]\d+[.]\d+)_',o) if m: atlas_version = m.group('version') if atlas_version is not None: + break # final choice --- look at ATLAS_VERSION environment # variable if atlas_version is None: atlas_version = os.environ.get('ATLAS_VERSION',None) - return atlas_version or '?.?.?' + if atlas_version: + dict_append(info, define_macros = [('ATLAS_INFO','"\\"%s\\""' % atlas_version)]) + else: + dict_append(info, define_macros = [('NO_ATLAS_INFO',-1)]) + return atlas_version or '?.?.?', info if not s: m = re.search(r'ATLAS version (?P\d+[.]\d+[.]\d+)',o) @@ -1236,9 +1264,14 @@ else: log.info('Status: %d', s) log.info('Output: %s', o) - _cached_atlas_version[key] = atlas_version - return atlas_version + if atlas_version=='3.2.1_pre3.3.6': + dict_append(info, define_macros = [('NO_ATLAS_INFO',-2)]) + else: + dict_append(info, define_macros = [('ATLAS_INFO','"\\"%s\\""' % atlas_version)]) + result = _cached_atlas_version[key] = atlas_version, info + return result + from distutils.util import get_platform class lapack_opt_info(system_info): @@ -1286,22 +1319,12 @@ need_blas = 0 info = {} if atlas_info: - version_info = atlas_info.copy() - atlas_version = get_atlas_version(**version_info) - if 'define_macros' not in atlas_info: - atlas_info['define_macros'] = [] - if atlas_version is None: - atlas_info['define_macros'].append(('NO_ATLAS_INFO',2)) - else: - atlas_info['define_macros'].append(('ATLAS_INFO', - '"\\"%s\\""' % atlas_version)) - if atlas_version=='3.2.1_pre3.3.6': - atlas_info['define_macros'].append(('NO_ATLAS_INFO',4)) - l = atlas_info.get('define_macros',[]) + l = atlas_info.get ('define_macros', []) if ('ATLAS_WITH_LAPACK_ATLAS',None) in l \ or ('ATLAS_WITHOUT_LAPACK',None) in l: need_lapack = 1 info = atlas_info + else: warnings.warn(AtlasNotFoundError.__doc__) need_blas = 1 @@ -1385,15 +1408,6 @@ need_blas = 0 info = {} if atlas_info: - version_info = atlas_info.copy() - atlas_version = get_atlas_version(**version_info) - if 'define_macros' not in atlas_info: - atlas_info['define_macros'] = [] - if atlas_version is None: - atlas_info['define_macros'].append(('NO_ATLAS_INFO',2)) - else: - atlas_info['define_macros'].append(('ATLAS_INFO', - '"\\"%s\\""' % atlas_version)) info = atlas_info else: warnings.warn(AtlasNotFoundError.__doc__) From numpy-svn at scipy.org Mon Aug 30 13:24:58 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 30 Aug 2010 12:24:58 -0500 (CDT) Subject: [Numpy-svn] r8674 - in trunk/numpy/lib: . tests Message-ID: <20100830172458.03FD039CCEE@scipy.org> Author: dhuard Date: 2010-08-30 12:24:57 -0500 (Mon, 30 Aug 2010) New Revision: 8674 Modified: trunk/numpy/lib/function_base.py trunk/numpy/lib/tests/test_function_base.py Log: added a warning concerning the buggy normalization in histogram with non-uniform bin widths Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2010-08-30 10:56:17 UTC (rev 8673) +++ trunk/numpy/lib/function_base.py 2010-08-30 17:24:57 UTC (rev 8674) @@ -155,8 +155,10 @@ mn -= 0.5 mx += 0.5 bins = linspace(mn, mx, bins+1, endpoint=True) + uniform = True else: bins = asarray(bins) + uniform = False if (np.diff(bins) < 0).any(): raise AttributeError( 'bins must increase monotonically.') @@ -191,7 +193,16 @@ if normed: db = array(np.diff(bins), float) + if not uniform: + warnings.warn(""" + This release of NumPy fixes a normalization bug in histogram + function occuring with non-uniform bin widths. The returned + value is now a density: n / (N * bin width), where n is the + bin count and N the total number of points. + """) return n/db/n.sum(), bins + + else: return n, bins Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2010-08-30 10:56:17 UTC (rev 8673) +++ trunk/numpy/lib/tests/test_function_base.py 2010-08-30 17:24:57 UTC (rev 8674) @@ -565,6 +565,7 @@ area = sum(a * diff(b)) assert_almost_equal(area, 1) + warnings.simplefilter('ignore', Warning) # Check with non-constant bin widths v = np.arange(10) bins = [0,1,3,6,10] @@ -583,6 +584,7 @@ # mailing list Aug. 6, 2010. counts, dmy = np.histogram([1,2,3,4], [0.5,1.5,np.inf], normed=True) assert_equal(counts, [.25, 0]) + warnings.resetwarnings() def test_outliers(self): # Check that outliers are not tallied @@ -645,12 +647,13 @@ wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1], normed=True) assert_array_almost_equal(wa, array([4, 5, 0, 1]) / 10. / 3. * 4) + warnings.simplefilter('ignore', Warning) # Check weights with non-uniform bin widths a,b = histogram(np.arange(9), [0,1,3,6,10], \ weights=[2,1,1,1,1,1,1,1,1], normed=True) assert_almost_equal(a, [.2, .1, .1, .075]) + warnings.resetwarnings() - class TestHistogramdd(TestCase): def test_simple(self): x = array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \ From numpy-svn at scipy.org Tue Aug 31 08:30:01 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 31 Aug 2010 07:30:01 -0500 (CDT) Subject: [Numpy-svn] r8675 - branches/1.5.x Message-ID: <20100831123001.9645F39CCFC@scipy.org> Author: rgommers Date: 2010-08-31 07:30:01 -0500 (Tue, 31 Aug 2010) New Revision: 8675 Modified: branches/1.5.x/setup.py Log: REL: set version to 1.5.0, released=True. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-30 17:24:57 UTC (rev 8674) +++ branches/1.5.x/setup.py 2010-08-31 12:30:01 UTC (rev 8675) @@ -56,8 +56,8 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = False -VERSION = '%d.%d.%drc1' % (MAJOR, MINOR, MICRO) +ISRELEASED = True +VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise def svn_version(): From numpy-svn at scipy.org Tue Aug 31 08:31:32 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 31 Aug 2010 07:31:32 -0500 (CDT) Subject: [Numpy-svn] r8676 - tags Message-ID: <20100831123132.5B23E39CCFC@scipy.org> Author: rgommers Date: 2010-08-31 07:31:32 -0500 (Tue, 31 Aug 2010) New Revision: 8676 Added: tags/1.5.0/ Log: Create tag 1.5.0 Copied: tags/1.5.0 (from rev 8675, branches/1.5.x) From numpy-svn at scipy.org Tue Aug 31 08:33:02 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 31 Aug 2010 07:33:02 -0500 (CDT) Subject: [Numpy-svn] r8677 - branches/1.5.x Message-ID: <20100831123302.15B7E39CCFC@scipy.org> Author: rgommers Date: 2010-08-31 07:33:02 -0500 (Tue, 31 Aug 2010) New Revision: 8677 Modified: branches/1.5.x/setup.py Log: REL: set released=False again in setup.py. Modified: branches/1.5.x/setup.py =================================================================== --- branches/1.5.x/setup.py 2010-08-31 12:31:32 UTC (rev 8676) +++ branches/1.5.x/setup.py 2010-08-31 12:33:02 UTC (rev 8677) @@ -56,7 +56,7 @@ MAJOR = 1 MINOR = 5 MICRO = 0 -ISRELEASED = True +ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # Return the svn version as a string, raise a ValueError otherwise From numpy-svn at scipy.org Tue Aug 31 10:02:59 2010 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 31 Aug 2010 09:02:59 -0500 (CDT) Subject: [Numpy-svn] r8678 - trunk/numpy/lib/tests Message-ID: <20100831140259.7A90D39CCFC@scipy.org> Author: dhuard Date: 2010-08-31 09:02:59 -0500 (Tue, 31 Aug 2010) New Revision: 8678 Modified: trunk/numpy/lib/tests/test_arraysetops.py trunk/numpy/lib/tests/test_function_base.py Log: Made sure the warning filters in test_function_base and test_arraysetops do not modify user defined filters. Modified: trunk/numpy/lib/tests/test_arraysetops.py =================================================================== --- trunk/numpy/lib/tests/test_arraysetops.py 2010-08-31 12:33:02 UTC (rev 8677) +++ trunk/numpy/lib/tests/test_arraysetops.py 2010-08-31 14:02:59 UTC (rev 8678) @@ -16,18 +16,16 @@ c = unique( a ) assert_array_equal( c, ec ) - warnings.simplefilter('ignore', Warning) vals, indices = unique( a, return_index=True ) - warnings.resetwarnings() + ed = np.array( [2, 3, 0, 1] ) assert_array_equal(vals, ec) assert_array_equal(indices, ed) - warnings.simplefilter('ignore', Warning) vals, ind0, ind1 = unique( a, return_index=True, return_inverse=True ) - warnings.resetwarnings() + ee = np.array( [2, 3, 0, 1, 0, 2, 3] ) assert_array_equal(vals, ec) @@ -61,13 +59,15 @@ b = np.array( [2, 1, 4, 3, 3, 1, 5] ) ec = np.array( [1, 2, 5] ) - warnings.simplefilter('ignore', Warning) - c = intersect1d_nu( a, b ) - warnings.resetwarnings() + warnings.filterwarnings('ignore', message='\s*`intersect1d_nu` is deprecated!') + warnings.filterwarnings('ignore', message='\s*`unique1d` is deprecated!') + c = intersect1d_nu( a, b ) assert_array_equal( c, ec ) - assert_array_equal([], intersect1d_nu([],[])) + warnings.filters.pop(0) + warnings.filters.pop(0) + def test_setxor1d( self ): a = np.array( [5, 7, 1, 2] ) b = np.array( [2, 4, 3, 1, 5] ) @@ -110,9 +110,9 @@ b = np.array( [2, 4, 3, 1, 5] ) ec = np.array( [True, False, True, True] ) - warnings.simplefilter('ignore', Warning) + warnings.filterwarnings('ignore', '\s*`setmember1d` is deprecated!') c = setmember1d( a, b ) - warnings.resetwarnings() + assert_array_equal( c, ec ) a[0] = 8 @@ -126,6 +126,7 @@ assert_array_equal( c, ec ) assert_array_equal([], setmember1d([],[])) + warnings.filters.pop(0) def test_in1d(self): a = np.array( [5, 7, 1, 2] ) Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2010-08-31 12:33:02 UTC (rev 8677) +++ trunk/numpy/lib/tests/test_function_base.py 2010-08-31 14:02:59 UTC (rev 8678) @@ -565,7 +565,8 @@ area = sum(a * diff(b)) assert_almost_equal(area, 1) - warnings.simplefilter('ignore', Warning) + warnings.filterwarnings('ignore', + message="\s*This release of NumPy fixes a normalization bug") # Check with non-constant bin widths v = np.arange(10) bins = [0,1,3,6,10] @@ -584,7 +585,7 @@ # mailing list Aug. 6, 2010. counts, dmy = np.histogram([1,2,3,4], [0.5,1.5,np.inf], normed=True) assert_equal(counts, [.25, 0]) - warnings.resetwarnings() + warnings.filters.pop(0) def test_outliers(self): # Check that outliers are not tallied @@ -647,12 +648,14 @@ wa, wb = histogram([1, 2, 2, 4], bins=4, weights=[4, 3, 2, 1], normed=True) assert_array_almost_equal(wa, array([4, 5, 0, 1]) / 10. / 3. * 4) - warnings.simplefilter('ignore', Warning) + warnings.filterwarnings('ignore', \ + message="\s*This release of NumPy fixes a normalization bug") # Check weights with non-uniform bin widths a,b = histogram(np.arange(9), [0,1,3,6,10], \ weights=[2,1,1,1,1,1,1,1,1], normed=True) assert_almost_equal(a, [.2, .1, .1, .075]) - warnings.resetwarnings() + warnings.filters.pop(0) + class TestHistogramdd(TestCase): def test_simple(self):