From scipy-svn at scipy.org Sat Nov 1 06:57:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 05:57:00 -0500 (CDT) Subject: [Scipy-svn] r4863 - in trunk/scipy/integrate: . tests Message-ID: <20081101105700.11DD239C05F@scipy.org> Author: stefan Date: 2008-11-01 05:56:47 -0500 (Sat, 01 Nov 2008) New Revision: 4863 Modified: trunk/scipy/integrate/quadrature.py trunk/scipy/integrate/tests/test_quadrature.py Log: Fix internally used vectorize1 to work with functions that return floats [patch by Neil Muller]. Closes #288. Modified: trunk/scipy/integrate/quadrature.py =================================================================== --- trunk/scipy/integrate/quadrature.py 2008-10-29 22:42:23 UTC (rev 4862) +++ trunk/scipy/integrate/quadrature.py 2008-11-01 10:56:47 UTC (rev 4863) @@ -59,7 +59,10 @@ # call with first point to get output type y0 = func(x[0], *args) n = len(x) - output = empty((n,), dtype=y0.dtype) + if hasattr(y0, 'dtype'): + output = empty((n,), dtype=y0.dtype) + else: + output = empty((n,), dtype=type(y0)) output[0] = y0 for i in xrange(1, n): output[i] = func(x[i], *args) Modified: trunk/scipy/integrate/tests/test_quadrature.py =================================================================== --- trunk/scipy/integrate/tests/test_quadrature.py 2008-10-29 22:42:23 UTC (rev 4862) +++ trunk/scipy/integrate/tests/test_quadrature.py 2008-11-01 10:56:47 UTC (rev 4863) @@ -28,5 +28,13 @@ def test_romb(self): assert_equal(romb(numpy.arange(17)),128) + def test_non_dtype(self): + # Check that we work fine with functions returning float + import math + valmath = romberg(math.sin, 0, 1) + expected_val = 0.45969769413185085 + assert_almost_equal(valmath, expected_val, decimal=7) + + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Sat Nov 1 07:11:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 06:11:11 -0500 (CDT) Subject: [Scipy-svn] r4864 - trunk/scipy/integrate Message-ID: <20081101111111.0A79039C088@scipy.org> Author: stefan Date: 2008-11-01 06:11:05 -0500 (Sat, 01 Nov 2008) New Revision: 4864 Modified: trunk/scipy/integrate/quadrature.py Log: Add docstring to `vectorize1` [patch by Neil Muller]. Modified: trunk/scipy/integrate/quadrature.py =================================================================== --- trunk/scipy/integrate/quadrature.py 2008-11-01 10:56:47 UTC (rev 4863) +++ trunk/scipy/integrate/quadrature.py 2008-11-01 11:11:05 UTC (rev 4864) @@ -48,6 +48,30 @@ return (b-a)/2.0*sum(w*func(y,*args),0), None def vectorize1(func, args=(), vec_func=False): + """Vectorize the call to a function. + + This is an internal utility function used by `romberg` and + `quadrature` to create a vectorized version of a function. + + If `vec_func` is True, the function `func` is assumed to take vector + arguments. + + Parameters + ---------- + func : callable + User defined function. + args : tuple + Extra arguments for the function. + vec_func : bool + True if the function func takes vector arguments. + + Returns + ------- + vfunc : callable + A function that will take a vector argument and return the + result. + + """ if vec_func: def vfunc(x): return func(x, *args) From scipy-svn at scipy.org Sat Nov 1 07:27:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 06:27:49 -0500 (CDT) Subject: [Scipy-svn] r4865 - in trunk/scipy/stats: . tests Message-ID: <20081101112749.E679639C2EA@scipy.org> Author: stefan Date: 2008-11-01 06:27:41 -0500 (Sat, 01 Nov 2008) New Revision: 4865 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_stats.py Log: `skew` should return float for 1-d input [patch by Pieter Rautenbach]. Closes #771. Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-01 11:11:05 UTC (rev 4864) +++ trunk/scipy/stats/stats.py 2008-11-01 11:27:41 UTC (rev 4865) @@ -757,6 +757,8 @@ m3 = np.extract(can_correct, m3) nval = np.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5 np.place(vals, can_correct, nval) + if vals.ndim == 0: + return vals.item() return vals def kurtosis(a, axis=0, fisher=True, bias=True): Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-01 11:11:05 UTC (rev 4864) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-01 11:27:41 UTC (rev 4865) @@ -820,7 +820,8 @@ def test_skewness(self): """ - sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0)/((sqrt(var(testmathworks)*4/5))**3)/5 + sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0)/ + ((sqrt(var(testmathworks)*4/5))**3)/5 """ y = stats.skew(self.testmathworks) assert_approx_equal(y,-0.29322304336607,10) @@ -828,6 +829,13 @@ assert_approx_equal(y,-0.437111105023940,10) y = stats.skew(self.testcase) assert_approx_equal(y,0.0,10) + + def test_skewness_scalar(self): + """ + `skew` must return a scalar for 1-dim input + """ + assert_equal(stats.skew(arange(10)), 0.0) + def test_kurtosis(self): """ sum((testcase-mean(testcase,axis=0))**4,axis=0)/((sqrt(var(testcase)*3/4))**4)/4 From scipy-svn at scipy.org Sat Nov 1 07:35:07 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 06:35:07 -0500 (CDT) Subject: [Scipy-svn] r4866 - trunk/scipy/ndimage Message-ID: <20081101113507.EDA5339C2EA@scipy.org> Author: stefan Date: 2008-11-01 06:35:01 -0500 (Sat, 01 Nov 2008) New Revision: 4866 Modified: trunk/scipy/ndimage/morphology.py Log: Remove unused code generate_binary_structure [patch by Pieter Holtzhausen]. Modified: trunk/scipy/ndimage/morphology.py =================================================================== --- trunk/scipy/ndimage/morphology.py 2008-11-01 11:27:41 UTC (rev 4865) +++ trunk/scipy/ndimage/morphology.py 2008-11-01 11:35:01 UTC (rev 4866) @@ -78,7 +78,6 @@ return numpy.array(0, dtype = bool) else: return numpy.array(1, dtype = bool) - output = numpy.zeros([3] * rank, bool) output = numpy.fabs(numpy.indices([3] * rank) - 1) output = numpy.add.reduce(output, 0) return numpy.asarray(output <= connectivity, dtype = bool) From scipy-svn at scipy.org Sat Nov 1 07:59:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 06:59:49 -0500 (CDT) Subject: [Scipy-svn] r4867 - trunk/scipy/interpolate Message-ID: <20081101115949.28C6E39C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 06:59:38 -0500 (Sat, 01 Nov 2008) New Revision: 4867 Modified: trunk/scipy/interpolate/rbf.py Log: Fix interpolate.Rbf docstring, and move it to a class docstring. Modified: trunk/scipy/interpolate/rbf.py =================================================================== --- trunk/scipy/interpolate/rbf.py 2008-11-01 11:35:01 UTC (rev 4866) +++ trunk/scipy/interpolate/rbf.py 2008-11-01 11:59:38 UTC (rev 4867) @@ -46,10 +46,54 @@ from scipy import linalg class Rbf(object): - """ A class for radial basis function approximation/interpolation of - n-dimensional scattered data. """ + Rbf(*args) + + A class for radial basis function approximation/interpolation of + n-dimensional scattered data. + Parameters + ---------- + *args : arrays + x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes + and d is the array of values at the nodes + function : str, optional + The radial basis function, based on the radius, r, given by the norm + (defult is Euclidean distance); the default is 'multiquadric':: + + 'multiquadric': sqrt((r/self.epsilon)**2 + 1) + 'inverse multiquadric': 1.0/sqrt((r/self.epsilon)**2 + 1) + 'gaussian': exp(-(self.epsilon*r)**2) + 'cubic': r**3 + 'quintic': r**5 + 'thin-plate': r**2 * log(r) + + epsilon : float, optional + Adjustable constant for gaussian or multiquadrics functions + - defaults to approximate average distance between nodes (which is + a good start). + smooth : float, optional + Values greater than zero increase the smoothness of the + approximation. 0 is for interpolation (default), the function will + always go through the nodal points in this case. + norm : callable, optional + A function that returns the 'distance' between two points, with + inputs as arrays of positions (x, y, z, ...), and an output as an + array of distance. E.g, the default:: + + def euclidean_norm(x1, x2): + return sqrt( ((x1 - x2)**2).sum(axis=0) ) + + which is called with x1=x1[ndims,newaxis,:] and + x2=x2[ndims,:,newaxis] such that the result is a symmetric, square + matrix of the distances between each point to each other point. + + Examples + -------- + >>> rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance + >>> di = rbfi(xi, yi, zi) # interpolated values + """ + def _euclidean_norm(self, x1, x2): return sqrt( ((x1 - x2)**2).sum(axis=0) ) @@ -70,54 +114,6 @@ raise ValueError, 'Invalid basis function name' def __init__(self, *args, **kwargs): - """ Constructor for Rbf class. - - Parameters - ---------- - *args : arrays - x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes - and d is the array of values at the nodes - function : str, optional - The radial basis function, based on the radius, r, given by the norm - (defult is Euclidean distance); the default is 'multiquadratic'. - - :: - 'multiquadric': sqrt((self.epsilon*r)**2 + 1) - 'inverse multiquadric': 1.0/sqrt((self.epsilon*r)**2 + 1) - 'gaussian': exp(-(self.epsilon*r)**2) - 'cubic': r**3 - 'quintic': r**5 - 'thin-plate': r**2 * log(r) - epsilon : float, optional - Adjustable constant for gaussian or multiquadrics functions - - defaults to approximate average distance between nodes (which is - a good start). - smooth : float, optional - Values greater than zero increase the smoothness of the - approximation. 0 is for interpolation (default), the function will - always go through the nodal points in this case. - norm : callable, optional - A function that returns the 'distance' between two points, with - inputs as arrays of positions (x, y, z, ...), and an output as an - array of distance. E.g, the default:: - - def euclidean_norm(x1, x2): - return sqrt( ((x1 - x2)**2).sum(axis=0) ) - - which is called with x1=x1[ndims,newaxis,:] and - x2=x2[ndims,:,newaxis] such that the result is a symetric, square - matrix of the distances between each point to each other point. - - Returns - ------- - rbf : Rbf - Interpolator object that returns interpolated values at new positions. - - Examples - -------- - >>> rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance - >>> di = rbfi(xi, yi, zi) # interpolated values - """ self.xi = asarray([asarray(a, dtype=float64).flatten() for a in args[:-1]]) self.N = self.xi.shape[-1] self.di = asarray(args[-1], dtype=float64).flatten() From scipy-svn at scipy.org Sat Nov 1 08:00:24 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 07:00:24 -0500 (CDT) Subject: [Scipy-svn] r4868 - trunk/scipy/interpolate Message-ID: <20081101120024.596B639C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 07:00:05 -0500 (Sat, 01 Nov 2008) New Revision: 4868 Modified: trunk/scipy/interpolate/rbf.py Log: interpolate.Rbf: fix thin-plate spline interpolation Modified: trunk/scipy/interpolate/rbf.py =================================================================== --- trunk/scipy/interpolate/rbf.py 2008-11-01 11:59:38 UTC (rev 4867) +++ trunk/scipy/interpolate/rbf.py 2008-11-01 12:00:05 UTC (rev 4868) @@ -42,7 +42,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -from numpy import sqrt, log, asarray, newaxis, all, dot, float64, exp, eye +from numpy import (sqrt, log, asarray, newaxis, all, dot, float64, exp, eye, + isnan) from scipy import linalg class Rbf(object): @@ -109,7 +110,9 @@ elif self.function.lower() == 'quintic': return r**5 elif self.function.lower() == 'thin-plate': - return r**2 * log(r) + result = r**2 * log(r) + result[r == 0] = 0 # the spline is zero at zero + return result else: raise ValueError, 'Invalid basis function name' From scipy-svn at scipy.org Sat Nov 1 08:01:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 07:01:10 -0500 (CDT) Subject: [Scipy-svn] r4869 - trunk/scipy/interpolate/tests Message-ID: <20081101120110.B1AB239C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 07:00:34 -0500 (Sat, 01 Nov 2008) New Revision: 4869 Modified: trunk/scipy/interpolate/tests/test_rbf.py Log: interpolate.Rbf: Test all available basis functions Modified: trunk/scipy/interpolate/tests/test_rbf.py =================================================================== --- trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 12:00:05 UTC (rev 4868) +++ trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 12:00:34 UTC (rev 4869) @@ -4,36 +4,39 @@ from numpy.testing import assert_array_almost_equal from numpy import linspace, sin, random, exp - - from scipy.interpolate.rbf import Rbf +FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', + 'cubic', 'quintic', 'thin-plate') -def test_rbf1d(): +def check_rbf1d(function): x = linspace(0,10,9) y = sin(x) - rbf = Rbf(x, y) + rbf = Rbf(x, y, function=function) yi = rbf(x) assert_array_almost_equal(y, yi) -def test_rbf2d(): +def check_rbf2d(function): x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 z = x*exp(-x**2-y**2) - rbf = Rbf(x, y, z ,epsilon=2) + rbf = Rbf(x, y, z, epsilon=2, function=function) zi = rbf(x, y) zi.shape = x.shape assert_array_almost_equal(z, zi) -def test_rbf3d(): +def check_rbf3d(function): x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 z = random.rand(50,1)*4-2 d = x*exp(-x**2-y**2) - rbf = Rbf(x, y, z, d ,epsilon=2) + rbf = Rbf(x, y, z, d, epsilon=2, function=function) di = rbf(x, y, z) di.shape = x.shape assert_array_almost_equal(di, d) -if __name__ == "__main__": - run_module_suite() +def test_rbf_interpolation(): + for function in FUNCTIONS: + yield check_rbf1d, function + yield check_rbf2d, function + yield check_rbf3d, function From scipy-svn at scipy.org Sat Nov 1 08:30:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 07:30:08 -0500 (CDT) Subject: [Scipy-svn] r4870 - in trunk/scipy/interpolate: . tests Message-ID: <20081101123008.EB3A939C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 07:29:56 -0500 (Sat, 01 Nov 2008) New Revision: 4870 Modified: trunk/scipy/interpolate/rbf.py trunk/scipy/interpolate/tests/test_rbf.py Log: interpolate.Rbf: accept array-like inputs in __call__. Accept complex data vector in __init__ Modified: trunk/scipy/interpolate/rbf.py =================================================================== --- trunk/scipy/interpolate/rbf.py 2008-11-01 12:00:34 UTC (rev 4869) +++ trunk/scipy/interpolate/rbf.py 2008-11-01 12:29:56 UTC (rev 4870) @@ -43,7 +43,7 @@ """ from numpy import (sqrt, log, asarray, newaxis, all, dot, float64, exp, eye, - isnan) + isnan, float_) from scipy import linalg class Rbf(object): @@ -117,9 +117,10 @@ raise ValueError, 'Invalid basis function name' def __init__(self, *args, **kwargs): - self.xi = asarray([asarray(a, dtype=float64).flatten() for a in args[:-1]]) + self.xi = asarray([asarray(a, dtype=float_).flatten() + for a in args[:-1]]) self.N = self.xi.shape[-1] - self.di = asarray(args[-1], dtype=float64).flatten() + self.di = asarray(args[-1]).flatten() assert [x.size==self.di.size for x in self.xi], \ 'All arrays must be equal length' @@ -143,10 +144,11 @@ return self.norm(x1, x2) def __call__(self, *args): + args = [asarray(x) for x in args] assert all([x.shape == y.shape \ for x in args \ for y in args]), 'Array lengths must be equal' shp = args[0].shape - self.xa = asarray([a.flatten() for a in args], dtype=float64) + self.xa = asarray([a.flatten() for a in args], dtype=float_) r = self._call_norm(self.xa, self.xi) return dot(self._function(r), self.nodes).reshape(shp) Modified: trunk/scipy/interpolate/tests/test_rbf.py =================================================================== --- trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 12:00:34 UTC (rev 4869) +++ trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 12:29:56 UTC (rev 4870) @@ -2,7 +2,7 @@ # Created by John Travers, Robert Hetland, 2007 """ Test functions for rbf module """ -from numpy.testing import assert_array_almost_equal +from numpy.testing import assert_array_almost_equal, assert_almost_equal from numpy import linspace, sin, random, exp from scipy.interpolate.rbf import Rbf @@ -15,11 +15,12 @@ rbf = Rbf(x, y, function=function) yi = rbf(x) assert_array_almost_equal(y, yi) + assert_almost_equal(rbf(float(x[0])), y[0]) def check_rbf2d(function): x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 - z = x*exp(-x**2-y**2) + z = x*exp(-x**2-1j*y**2) rbf = Rbf(x, y, z, epsilon=2, function=function) zi = rbf(x, y) zi.shape = x.shape From scipy-svn at scipy.org Sat Nov 1 08:30:31 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 07:30:31 -0500 (CDT) Subject: [Scipy-svn] r4871 - in trunk/scipy/interpolate: . tests Message-ID: <20081101123031.317AA39C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 07:30:19 -0500 (Sat, 01 Nov 2008) New Revision: 4871 Modified: trunk/scipy/interpolate/rbf.py trunk/scipy/interpolate/tests/test_rbf.py Log: interpolate.Rbf: add linear basis function Modified: trunk/scipy/interpolate/rbf.py =================================================================== --- trunk/scipy/interpolate/rbf.py 2008-11-01 12:29:56 UTC (rev 4870) +++ trunk/scipy/interpolate/rbf.py 2008-11-01 12:30:19 UTC (rev 4871) @@ -65,6 +65,7 @@ 'multiquadric': sqrt((r/self.epsilon)**2 + 1) 'inverse multiquadric': 1.0/sqrt((r/self.epsilon)**2 + 1) 'gaussian': exp(-(self.epsilon*r)**2) + 'linear': r 'cubic': r**3 'quintic': r**5 'thin-plate': r**2 * log(r) @@ -105,6 +106,8 @@ return 1.0/sqrt((1.0/self.epsilon*r)**2 + 1) elif self.function.lower() == 'gaussian': return exp(-(self.epsilon*r)**2) + elif self.function.lower() == 'linear': + return r elif self.function.lower() == 'cubic': return r**3 elif self.function.lower() == 'quintic': Modified: trunk/scipy/interpolate/tests/test_rbf.py =================================================================== --- trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 12:29:56 UTC (rev 4870) +++ trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 12:30:19 UTC (rev 4871) @@ -7,7 +7,7 @@ from scipy.interpolate.rbf import Rbf FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', - 'cubic', 'quintic', 'thin-plate') + 'cubic', 'quintic', 'thin-plate', 'linear') def check_rbf1d(function): x = linspace(0,10,9) From scipy-svn at scipy.org Sat Nov 1 09:21:42 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:21:42 -0500 (CDT) Subject: [Scipy-svn] r4872 - branches Message-ID: <20081101132142.BD47E39C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:21:35 -0500 (Sat, 01 Nov 2008) New Revision: 4872 Added: branches/remove_fft_backends/ Log: Creating a short-lived branch to remove all fft backends but fftpack Copied: branches/remove_fft_backends (from rev 4871, trunk) From scipy-svn at scipy.org Sat Nov 1 09:24:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:24:43 -0500 (CDT) Subject: [Scipy-svn] r4873 - branches/remove_fft_backends Message-ID: <20081101132443.015CA39C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:24:40 -0500 (Sat, 01 Nov 2008) New Revision: 4873 Modified: branches/remove_fft_backends/ Log: Initialized merge tracking via "svnmerge" with revisions "1-4871" from http://svn.scipy.org/svn/scipy/trunk Property changes on: branches/remove_fft_backends ___________________________________________________________________ Name: svnmerge-integrated - /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 + /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 /trunk:1-4871 From scipy-svn at scipy.org Sat Nov 1 09:29:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:29:29 -0500 (CDT) Subject: [Scipy-svn] r4874 - branches/remove_fft_backends/scipy/fftpack Message-ID: <20081101132929.9B73139C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:29:25 -0500 (Sat, 01 Nov 2008) New Revision: 4874 Modified: branches/remove_fft_backends/scipy/fftpack/setup.py Log: Do not look for fftw and other backends anymore in distutils build. Modified: branches/remove_fft_backends/scipy/fftpack/setup.py =================================================================== --- branches/remove_fft_backends/scipy/fftpack/setup.py 2008-11-01 13:24:40 UTC (rev 4873) +++ branches/remove_fft_backends/scipy/fftpack/setup.py 2008-11-01 13:29:25 UTC (rev 4874) @@ -5,19 +5,9 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration - from numpy.distutils.system_info import get_info + config = Configuration('fftpack',parent_package, top_path) - djbfft_info = {} - mkl_info = get_info('mkl') - if mkl_info: - mkl_info.setdefault('define_macros', []).append(('SCIPY_MKL_H', None)) - fft_opt_info = mkl_info - else: - fft_opt_info = get_info('fftw3') or get_info('fftw2') \ - or get_info('dfftw') - djbfft_info = get_info('djbfft') - config.add_data_dir('tests') config.add_data_dir('benchmarks') @@ -30,7 +20,6 @@ config.add_extension('_fftpack', sources=sources, libraries=['dfftpack'], - extra_info=[fft_opt_info, djbfft_info], depends=['src/zfft_djbfft.c', 'src/zfft_fftpack.c', 'src/zfft_fftw.c', 'src/zfft_fftw3.c', 'src/zfft_mkl.c', 'src/drfft_djbfft.c', 'src/drfft_fftpack.c', @@ -43,7 +32,6 @@ config.add_extension('convolve', sources=['convolve.pyf','src/convolve.c'], libraries=['dfftpack'], - extra_info=[fft_opt_info, djbfft_info], ) return config From scipy-svn at scipy.org Sat Nov 1 09:30:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:30:09 -0500 (CDT) Subject: [Scipy-svn] r4875 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101133009.6A09A39C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:30:05 -0500 (Sat, 01 Nov 2008) New Revision: 4875 Removed: branches/remove_fft_backends/scipy/fftpack/src/drfft_djbfft.c branches/remove_fft_backends/scipy/fftpack/src/zfft_djbfft.c Log: Remove djbfft wrappers. Deleted: branches/remove_fft_backends/scipy/fftpack/src/drfft_djbfft.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/drfft_djbfft.c 2008-11-01 13:29:25 UTC (rev 4874) +++ branches/remove_fft_backends/scipy/fftpack/src/drfft_djbfft.c 2008-11-01 13:30:05 UTC (rev 4875) @@ -1,131 +0,0 @@ -/* - * Last Change: Wed Aug 01 08:00 PM 2007 J - * - * Original code by Pearu Peterson. - */ - -/* - * DJBFFT only implements size 2^N ! - * - * drfft_def and drfft_def_destroy_cache are the functions used for size different - * than 2^N - */ -#ifdef WITH_FFTW3 -#define drfft_def drfft_fftw3 -#define drfft_def_destroy_cache destroy_drfftw3_caches -#elif defined WITH_FFTW -#define drfft_def drfft_fftw -#define drfft_def_destroy_cache destroy_drfftw_caches -#else -#define drfft_def drfft_fftpack -#define drfft_def_destroy_cache destroy_drfftpack_caches -#endif - -GEN_CACHE(drdjbfft, (int n) - , unsigned int *f; - double *ptr;, - caches_drdjbfft[i].n == n, - caches_drdjbfft[id].f = (unsigned int *) malloc(sizeof(unsigned int) * (n)); - caches_drdjbfft[id].ptr = (double *) malloc(sizeof(double) * n); - fftfreq_rtable(caches_drdjbfft[id].f, n);, - free(caches_drdjbfft[id].f); - free(caches_drdjbfft[id].ptr);, - 10) - -/**************** ZFFT function **********************/ -static void drfft_djbfft(double * inout, - int n, int direction, int howmany, int normalize) -{ - int i; - double *ptr = inout; - double *ptrc = NULL; - unsigned int *f = NULL; - - switch (n) { - case 2:; - case 4:; - case 8:; - case 16:; - case 32:; - case 64:; - case 128:; - case 256:; - case 512:; - case 1024:; - case 2048:; - case 4096:; - case 8192: - i = get_cache_id_drdjbfft(n); - f = caches_drdjbfft[i].f; - ptrc = caches_drdjbfft[i].ptr; - } - if (f == NULL) { - drfft_def(inout, n, direction, howmany, normalize); - } - - switch (direction) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - if (f != NULL) { - COPYSTD2DJB(ptr, ptrc, n); - switch (n) { -#define TMPCASE(N) case N: fftr8_##N(ptrc); break - TMPCASE(2); - TMPCASE(4); - TMPCASE(8); - TMPCASE(16); - TMPCASE(32); - TMPCASE(64); - TMPCASE(128); - TMPCASE(256); - TMPCASE(512); - TMPCASE(1024); - TMPCASE(2048); - TMPCASE(4096); - TMPCASE(8192); -#undef TMPCASE - } - COPYDJB2STD(ptrc, ptr, f, n); - } - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - if (f != NULL) { - COPYINVSTD2DJB(ptr, ptrc, normalize, f, n); - switch (n) { - -#define TMPCASE(N)case N:if(normalize)fftr8_scale##N(ptrc);fftr8_un##N(ptrc);break - TMPCASE(2); - TMPCASE(4); - TMPCASE(8); - TMPCASE(16); - TMPCASE(32); - TMPCASE(64); - TMPCASE(128); - TMPCASE(256); - TMPCASE(512); - TMPCASE(1024); - TMPCASE(2048); - TMPCASE(4096); - TMPCASE(8192); -#undef TMPCASE - } - COPYINVDJB2STD(ptrc, ptr, n); - } - } - break; - - default: - fprintf(stderr, "drfft: invalid direction=%d\n", direction); - } - - if (normalize && f != NULL && direction == 1) { - double d = 1.0 / n; - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - (*(ptr++)) *= d; - } - } -} Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfft_djbfft.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfft_djbfft.c 2008-11-01 13:29:25 UTC (rev 4874) +++ branches/remove_fft_backends/scipy/fftpack/src/zfft_djbfft.c 2008-11-01 13:30:05 UTC (rev 4875) @@ -1,151 +0,0 @@ -/* -* DJBFFT only implements size 2^N ! -* -* zfft_def and zfft_def_destroy_cache are the functions -* used for size different than 2^N -*/ -#ifdef WITH_FFTWORK -#define zfft_def zfft_fftwork -#define zfft_def_destroy_cache destroy_zfftwork_cache -#elif defined WITH_FFTW3 -#define zfft_def zfft_fftw3 -#define zfft_def_destroy_cache destroy_zfftw3_caches -#elif defined WITH_FFTW -#define zfft_def zfft_fftw -#define zfft_def_destroy_cache destroy_zfftw_caches -#else -#define zfft_def zfft_fftpack -#define zfft_def_destroy_cache destroy_zfftpack_caches -#endif - -GEN_CACHE(zdjbfft,(int n) - ,unsigned int* f; - double* ptr; - ,caches_zdjbfft[i].n==n - ,caches_zdjbfft[id].f = (unsigned int*)malloc(sizeof(unsigned int)*(n)); - caches_zdjbfft[id].ptr = (double*)malloc(sizeof(double)*(2*n)); - fftfreq_ctable(caches_zdjbfft[id].f,n); - for(i=0;i Author: cdavid Date: 2008-11-01 08:30:16 -0500 (Sat, 01 Nov 2008) New Revision: 4876 Removed: branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw3.c branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw3.c branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw3.c Log: Remove fftw3 wrappers. Deleted: branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw3.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw3.c 2008-11-01 13:30:05 UTC (rev 4875) +++ branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw3.c 2008-11-01 13:30:16 UTC (rev 4876) @@ -1,65 +0,0 @@ -/* - * Last Change: Wed Aug 01 07:00 PM 2007 J - * - * FFTW3 implementation - * - * Original code by Pearu Peterson. - */ - -GEN_CACHE(drfftw3, (int n, int d, int flags) - , int direction; - int flags; - fftw_plan plan; - double *ptr;, ((caches_drfftw3[i].n == n) && - (caches_drfftw3[i].direction == d) && - (caches_drfftw3[i].flags == flags)) - , caches_drfftw3[id].direction = d; - caches_drfftw3[id].flags = flags; - caches_drfftw3[id].ptr = - (double *) fftw_malloc(sizeof(double) * (n)); - caches_drfftw3[id].plan = - fftw_plan_r2r_1d(n, caches_drfftw3[id].ptr, caches_drfftw3[id].ptr, - (d > 0 ? FFTW_R2HC : FFTW_HC2R), flags);, - fftw_destroy_plan(caches_drfftw3[id].plan); - fftw_free(caches_drfftw3[id].ptr);, 10) - -static void drfft_fftw3(double *inout, int n, int direction, int - howmany, int normalize) -{ - int i; - double *ptr = inout; - - double *ptrc = NULL; - fftw_plan plan = NULL; - - i = get_cache_id_drfftw3(n, direction, FFTW_ESTIMATE); - plan = caches_drfftw3[i].plan; - ptrc = caches_drfftw3[i].ptr; - switch (direction) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - memcpy(ptrc, ptr, sizeof(double) * n); - fftw_execute(plan); - COPYRFFTW2STD(ptrc, ptr, n); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - COPYINVRFFTW2STD(ptr, ptrc, n); - fftw_execute(plan); - memcpy(ptr, ptrc, sizeof(double) * n); - } - break; - default: - fprintf(stderr, "drfft: invalid direction=%d\n", direction); - } - - if (normalize) { - double d = 1.0 / n; - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - (*(ptr++)) *= d; - } - } -} Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw3.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw3.c 2008-11-01 13:30:05 UTC (rev 4875) +++ branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw3.c 2008-11-01 13:30:16 UTC (rev 4876) @@ -1,121 +0,0 @@ - -/* This cache uses FFTW_MEASURE for the plans, and do not copy the data. */ -GEN_CACHE(zfftw3,(int n,int d) - ,int direction; - fftw_plan plan; - fftw_complex *wrk; - ,((caches_zfftw3[i].n==n) && - (caches_zfftw3[i].direction==d)) - ,caches_zfftw3[id].direction = d; - /* This working buffer is only used to compute the plan: we need it - since FFTW_MEASURE destroys its input when computing a plan */ - caches_zfftw3[id].wrk = fftw_malloc(n * sizeof(double) * 2); - caches_zfftw3[id].plan = fftw_plan_dft_1d(n, - caches_zfftw3[id].wrk, - caches_zfftw3[id].wrk, - (d>0?FFTW_FORWARD:FFTW_BACKWARD), - FFTW_ESTIMATE | FFTW_UNALIGNED); - , - fftw_destroy_plan(caches_zfftw3[id].plan); - fftw_free(caches_zfftw3[id].wrk); - ,10) - -static void zfft_fftw3(complex_double * inout, int n, int dir, int -howmany, int normalize) -{ - fftw_complex *ptr = (fftw_complex*)inout; - fftw_complex *ptrm; - fftw_plan plan = NULL; - double factor = 1./n; - - int i; - - plan = caches_zfftw3[get_cache_id_zfftw3(n, dir)].plan; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_execute_dft(plan, ptr, ptr); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_execute_dft(plan, ptr, ptr); - } - break; - - default: - fprintf(stderr, "zfft: invalid dir=%d\n", dir); - } - - if (normalize) { - ptr =(fftw_complex*)inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) *= factor; - *((double *) (ptr++) + 1) *= factor; - } - } -} -#if 0 -GEN_CACHE(zfftw3,(int n,int d) - ,int direction; - fftw_plan plan; - fftw_complex* ptr; - ,((caches_zfftw3[i].n==n) && - (caches_zfftw3[i].direction==d)) - ,caches_zfftw3[id].direction = d; - caches_zfftw3[id].ptr = fftw_malloc(sizeof(fftw_complex)*(n)); - caches_zfftw3[id].plan = fftw_plan_dft_1d(n, caches_zfftw3[id].ptr, - caches_zfftw3[id].ptr, - (d>0?FFTW_FORWARD:FFTW_BACKWARD), - FFTW_ESTIMATE); - ,fftw_destroy_plan(caches_zfftw3[id].plan); - fftw_free(caches_zfftw3[id].ptr); - ,10) - -static void zfft_fftw3(complex_double * inout, int n, int dir, int -howmany, int normalize) -{ - complex_double *ptr = inout; - fftw_complex *ptrm = NULL; - fftw_plan plan = NULL; - - int i; - - plan = caches_zfftw3[get_cache_id_zfftw3(n, dir)].plan; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - ptrm = - caches_zfftw3[get_cache_id_zfftw3(n, dir)].ptr; - memcpy(ptrm, ptr, sizeof(double) * 2 * n); - fftw_execute(plan); - memcpy(ptr, ptrm, sizeof(double) * 2 * n); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - ptrm = - caches_zfftw3[get_cache_id_zfftw3(n, dir)].ptr; - memcpy(ptrm, ptr, sizeof(double) * 2 * n); - fftw_execute(plan); - memcpy(ptr, ptrm, sizeof(double) * 2 * n); - } - break; - - default: - fprintf(stderr, "zfft: invalid dir=%d\n", dir); - } - - if (normalize) { - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= n; - *((double *) (ptr++) + 1) /= n; - } - } -} -#endif Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw3.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw3.c 2008-11-01 13:30:05 UTC (rev 4875) +++ branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw3.c 2008-11-01 13:30:16 UTC (rev 4876) @@ -1,40 +0,0 @@ -/* - * fftw3 backend for multi dimensional fft - * - * Original code by Pearu Peaterson - * - * Last Change: Wed Aug 08 02:00 PM 2007 J - */ - -/* stub because fftw3 has no cache mechanism (yet) */ -static void destroy_zfftnd_fftw3_caches(void) {} - -extern void zfftnd_fftw3(complex_double * inout, int rank, - int *dims, int direction, int howmany, - int normalize) -{ - int i, sz; - complex_double *ptr = inout; - - fftw_plan plan = NULL; - sz = 1; - for (i = 0; i < rank; ++i) { - sz *= dims[i]; - } - plan = fftw_plan_many_dft(rank, dims, howmany, - (fftw_complex *) ptr, NULL, 1, sz, - (fftw_complex *) ptr, NULL, 1, sz, - (direction > - 0 ? FFTW_FORWARD : FFTW_BACKWARD), - FFTW_ESTIMATE); - fftw_execute(plan); - fftw_destroy_plan(plan); - - if (normalize) { - ptr = inout; - for (i = sz * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= sz; - *((double *) (ptr++) + 1) /= sz; - } - } -} From scipy-svn at scipy.org Sat Nov 1 09:30:31 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:30:31 -0500 (CDT) Subject: [Scipy-svn] r4877 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101133031.0620039C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:30:27 -0500 (Sat, 01 Nov 2008) New Revision: 4877 Removed: branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw.c branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw.c branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw.c Log: Remove fftw2 wrappers. Deleted: branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw.c 2008-11-01 13:30:16 UTC (rev 4876) +++ branches/remove_fft_backends/scipy/fftpack/src/drfft_fftw.c 2008-11-01 13:30:27 UTC (rev 4877) @@ -1,70 +0,0 @@ -/* - * Last Change: Wed Aug 01 07:00 PM 2007 J - * - * FFTW2 implementation - * - * Original code by Pearu Peterson. - */ - -GEN_CACHE(drfftw, (int n, int d, int flags) - , int direction; - int flags; - rfftw_plan plan; - double *ptr;, ((caches_drfftw[i].n == n) && - (caches_drfftw[i].direction == d) && - (caches_drfftw[i].flags == flags)) - , caches_drfftw[id].direction = d; - caches_drfftw[id].flags = flags; - caches_drfftw[id].plan = rfftw_create_plan(n, - (d > - 0 ? - FFTW_REAL_TO_COMPLEX - : - FFTW_COMPLEX_TO_REAL), - flags); - caches_drfftw[id].ptr = - (double *) malloc(sizeof(double) * (n));, - rfftw_destroy_plan(caches_drfftw[id].plan); - free(caches_drfftw[id].ptr);, 10) - -static void drfft_fftw(double *inout, int n, int dir, int - howmany, int normalize) -{ - int i; - double *ptr = inout; - double *ptrc = NULL; - rfftw_plan plan = NULL; - - i = get_cache_id_drfftw(n, dir, FFTW_IN_PLACE | FFTW_ESTIMATE); - plan = caches_drfftw[i].plan; - ptrc = caches_drfftw[i].ptr; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - memcpy(ptrc, ptr, sizeof(double) * n); - rfftw(plan, 1, (fftw_real *) ptrc, 1, 1, NULL, 1, 1); - COPYRFFTW2STD(ptrc, ptr, n); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - COPYINVRFFTW2STD(ptr, ptrc, n); - rfftw(plan, 1, (fftw_real *) ptrc, 1, 1, NULL, 1, 1); - memcpy(ptr, ptrc, sizeof(double) * n); - } - break; - - default: - fprintf(stderr, "drfft: invalid direction=%d\n", dir); - } - - if (normalize) { - double d = 1.0 / n; - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - (*(ptr++)) *= d; - } - } -} Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw.c 2008-11-01 13:30:16 UTC (rev 4876) +++ branches/remove_fft_backends/scipy/fftpack/src/zfft_fftw.c 2008-11-01 13:30:27 UTC (rev 4877) @@ -1,43 +0,0 @@ -GEN_CACHE(zfftw,(int n,int d) - ,int direction; - fftw_plan plan; - ,((caches_zfftw[i].n==n) && - (caches_zfftw[i].direction==d)) - ,caches_zfftw[id].direction = d; - caches_zfftw[id].plan = fftw_create_plan(n, - (d>0?FFTW_FORWARD:FFTW_BACKWARD), - FFTW_IN_PLACE|FFTW_ESTIMATE); - ,fftw_destroy_plan(caches_zfftw[id].plan); - ,10) - -extern void zfft_fftw(complex_double * inout, int n, - int dir, int howmany, int normalize) -{ - int i; - complex_double *ptr = inout; - fftw_plan plan = NULL; - plan = caches_zfftw[get_cache_id_zfftw(n, dir)].plan; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_one(plan, (fftw_complex *) ptr, NULL); - } - break; - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_one(plan, (fftw_complex *) ptr, NULL); - } - break; - default: - fprintf(stderr, "zfft: invalid dir=%d\n", dir); - } - - if (normalize) { - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= n; - *((double *) (ptr++) + 1) /= n; - } - } -} Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw.c 2008-11-01 13:30:16 UTC (rev 4876) +++ branches/remove_fft_backends/scipy/fftpack/src/zfftnd_fftw.c 2008-11-01 13:30:27 UTC (rev 4877) @@ -1,53 +0,0 @@ -/* - * fftw2 backend for multi dimensional fft - * - * Original code by Pearu Peaterson - * - * Last Change: Thu Sep 06 05:00 PM 2007 J - */ - -GEN_CACHE(zfftnd_fftw, (int n, int *dims, int d, int flags) - , int direction; - int *dims; - fftwnd_plan plan;, ((caches_zfftnd_fftw[i].n == n) && - (caches_zfftnd_fftw[i].direction == d) && - (equal_dims - (n, caches_zfftnd_fftw[i].dims, dims))) - , caches_zfftnd_fftw[id].direction = d; - caches_zfftnd_fftw[id].n = n; - caches_zfftnd_fftw[id].dims = (int *) malloc(sizeof(int) * n); - memcpy(caches_zfftnd_fftw[id].dims, dims, sizeof(int) * n); - caches_zfftnd_fftw[id].plan = - fftwnd_create_plan(n, dims, - (d > 0 ? FFTW_FORWARD : FFTW_BACKWARD), - flags);, - fftwnd_destroy_plan(caches_zfftnd_fftw[id].plan); - free(caches_zfftnd_fftw[id].dims);, 10) - - -extern void zfftnd_fftw(complex_double * inout, int rank, - int *dims, int direction, int howmany, - int normalize) -{ - int i, sz; - complex_double *ptr = inout; - fftwnd_plan plan = NULL; - - sz = 1; - for (i = 0; i < rank; ++i) { - sz *= dims[i]; - } - i = get_cache_id_zfftnd_fftw(rank, dims, direction, - FFTW_IN_PLACE | FFTW_ESTIMATE); - plan = caches_zfftnd_fftw[i].plan; - for (i = 0; i < howmany; ++i, ptr += sz) { - fftwnd_one(plan, (fftw_complex *) ptr, NULL); - } - if (normalize) { - ptr = inout; - for (i = sz * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= sz; - *((double *) (ptr++) + 1) /= sz; - } - } -} From scipy-svn at scipy.org Sat Nov 1 09:30:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:30:48 -0500 (CDT) Subject: [Scipy-svn] r4878 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101133048.9E5A539C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:30:40 -0500 (Sat, 01 Nov 2008) New Revision: 4878 Removed: branches/remove_fft_backends/scipy/fftpack/src/zfft_mkl.c branches/remove_fft_backends/scipy/fftpack/src/zfftnd_mkl.c Log: Remove MKL wrappers. Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfft_mkl.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfft_mkl.c 2008-11-01 13:30:27 UTC (rev 4877) +++ branches/remove_fft_backends/scipy/fftpack/src/zfft_mkl.c 2008-11-01 13:30:40 UTC (rev 4878) @@ -1,42 +0,0 @@ -GEN_CACHE(zmkl,(int n) - ,DFTI_DESCRIPTOR_HANDLE desc_handle; - ,(caches_zmkl[i].n==n) - ,DftiCreateDescriptor(&caches_zmkl[id].desc_handle, DFTI_DOUBLE, DFTI_COMPLEX, 1, (long)n); - DftiCommitDescriptor(caches_zmkl[id].desc_handle); - ,DftiFreeDescriptor(&caches_zmkl[id].desc_handle); - ,10) - -static void zfft_mkl(complex_double * inout, - int n, int direction, int howmany, int normalize) -{ - int i; - complex_double *ptr = inout; - DFTI_DESCRIPTOR_HANDLE desc_handle; - desc_handle = caches_zmkl[get_cache_id_zmkl(n)].desc_handle; - - switch (direction) { - - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - DftiComputeForward(desc_handle, (double *) ptr); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - DftiComputeBackward(desc_handle, (double *) ptr); - } - break; - - default: - fprintf(stderr, "zfft: invalid direction=%d\n", direction); - } - - if (normalize) { - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= n; - *((double *) (ptr++) + 1) /= n; - } - } -} Deleted: branches/remove_fft_backends/scipy/fftpack/src/zfftnd_mkl.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfftnd_mkl.c 2008-11-01 13:30:27 UTC (rev 4877) +++ branches/remove_fft_backends/scipy/fftpack/src/zfftnd_mkl.c 2008-11-01 13:30:40 UTC (rev 4878) @@ -1,66 +0,0 @@ -/* - * MKL backend for multi dimensional fft - * - * Original code by David M. Cooke - * - * Last Change: Wed Aug 08 03:00 PM 2007 J - */ - -static long *convert_dims(int n, int *dims) -{ - long *ndim; - int i; - ndim = (long *) malloc(sizeof(long) * n); - for (i = 0; i < n; i++) { - ndim[i] = (long) dims[i]; - } - return ndim; -} - -GEN_CACHE(zfftnd_mkl, (int n, int *dims) - , DFTI_DESCRIPTOR_HANDLE desc_handle; - int *dims; - long *ndims;, ((caches_zfftnd_mkl[i].n == n) && - (equal_dims(n, caches_zfftnd_mkl[i].dims, dims))) - , caches_zfftnd_mkl[id].ndims = convert_dims(n, dims); - caches_zfftnd_mkl[id].n = n; - caches_zfftnd_mkl[id].dims = (int *) malloc(sizeof(int) * n); - memcpy(caches_zfftnd_mkl[id].dims, dims, sizeof(int) * n); - DftiCreateDescriptor(&caches_zfftnd_mkl[id].desc_handle, - DFTI_DOUBLE, DFTI_COMPLEX, (long) n, - caches_zfftnd_mkl[id].ndims); - DftiCommitDescriptor(caches_zfftnd_mkl[id].desc_handle);, - DftiFreeDescriptor(&caches_zfftnd_mkl[id].desc_handle); - free(caches_zfftnd_mkl[id].dims); - free(caches_zfftnd_mkl[id].ndims);, 10) - -extern void zfftnd_mkl(complex_double * inout, int rank, - int *dims, int direction, int howmany, - int normalize) -{ - int i, sz; - complex_double *ptr = inout; - - DFTI_DESCRIPTOR_HANDLE desc_handle; - sz = 1; - for (i = 0; i < rank; ++i) { - sz *= dims[i]; - } - - desc_handle = - caches_zfftnd_mkl[get_cache_id_zfftnd_mkl(rank, dims)].desc_handle; - for (i = 0; i < howmany; ++i, ptr += sz) { - if (direction == 1) { - DftiComputeForward(desc_handle, (double *) ptr); - } else if (direction == -1) { - DftiComputeBackward(desc_handle, (double *) ptr); - } - } - if (normalize) { - ptr = inout; - for (i = sz * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= sz; - *((double *) (ptr++) + 1) /= sz; - } - } -} From scipy-svn at scipy.org Sat Nov 1 09:33:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:33:48 -0500 (CDT) Subject: [Scipy-svn] r4879 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101133348.38A7139C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:33:43 -0500 (Sat, 01 Nov 2008) New Revision: 4879 Modified: branches/remove_fft_backends/scipy/fftpack/src/zfft.c Log: Remove any non-fftpack code for complex, one-dimensions fft. Modified: branches/remove_fft_backends/scipy/fftpack/src/zfft.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfft.c 2008-11-01 13:30:40 UTC (rev 4878) +++ branches/remove_fft_backends/scipy/fftpack/src/zfft.c 2008-11-01 13:33:43 UTC (rev 4879) @@ -20,57 +20,5 @@ zfft_##name(inout, n, direction, howmany, normalize);\ } -/* ************** Definition of backend specific functions ********* */ - -/* - * To add a backend : - * - create a file zfft_name.c, where you define a function zfft_name where - * name is the name of your backend. If you do not use the GEN_CACHE macro, - * you will need to define a function void destroy_zname_caches(void), - * which can do nothing - * - in zfft.c, include the zfft_name.c file, and add the 3 following lines - * just after it: - * #ifndef WITH_DJBFFT - * GEN_PUBLIC_API(name) - * #endif - */ - -#ifdef WITH_FFTW3 - #include "zfft_fftw3.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftw3) - #endif -#elif defined WITH_FFTW - #include "zfft_fftw.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftw) - #endif -#elif defined WITH_MKL - #include "zfft_mkl.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(mkl) - #endif -#else /* Use fftpack by default */ - #include "zfft_fftpack.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftpack) - #endif -#endif - -/* - * djbfft must be used at the end, because it needs another backend (defined - * above) for non 2^n * size - */ -#ifdef WITH_DJBFFT - #include "zfft_djbfft.c" - void destroy_zfft_cache(void) - { - destroy_zdjbfft_caches(); - zfft_def_destroy_cache(); - } - void zfft(complex_double *inout, int n, - int direction, int howmany, int normalize) - { - zfft_djbfft(inout, n, direction, howmany, normalize); - } -#endif +#include "zfft_fftpack.c" +GEN_PUBLIC_API(fftpack) From scipy-svn at scipy.org Sat Nov 1 09:34:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:34:38 -0500 (CDT) Subject: [Scipy-svn] r4880 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101133438.6B9C139C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:34:29 -0500 (Sat, 01 Nov 2008) New Revision: 4880 Modified: branches/remove_fft_backends/scipy/fftpack/src/zfftnd.c Log: Remove any non-fftpack code for complex, multi-dimension fft. Modified: branches/remove_fft_backends/scipy/fftpack/src/zfftnd.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfftnd.c 2008-11-01 13:33:43 UTC (rev 4879) +++ branches/remove_fft_backends/scipy/fftpack/src/zfftnd.c 2008-11-01 13:34:29 UTC (rev 4880) @@ -19,27 +19,5 @@ zfftnd_##name(inout, rank, dims, direction, howmany, normalize);\ } -#if defined(WITH_FFTW) || defined(WITH_MKL) -static -int equal_dims(int rank,int *dims1,int *dims2) { - int i; - for (i=0;i Author: cdavid Date: 2008-11-01 08:36:08 -0500 (Sat, 01 Nov 2008) New Revision: 4881 Modified: branches/remove_fft_backends/scipy/fftpack/src/fftpack.h Log: Remove any non-fftpack code in fftpack header. Modified: branches/remove_fft_backends/scipy/fftpack/src/fftpack.h =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack.h 2008-11-01 13:34:29 UTC (rev 4880) +++ branches/remove_fft_backends/scipy/fftpack/src/fftpack.h 2008-11-01 13:36:08 UTC (rev 4881) @@ -25,42 +25,6 @@ extern int ispow2le2e30(int n); extern int ispow2le2e13(int n); -#ifdef SCIPY_FFTWORK_H -#define WITH_FFTWORK -#include "fftwork/fast_header.h" -#endif - -#ifdef SCIPY_DJBFFT_H -#define WITH_DJBFFT -#define complex8 complex_double -#define COMPLEX8_H -#include -#include -#include -#endif - -#ifdef SCIPY_MKL_H -#define WITH_MKL -#include -#endif - -#ifdef SCIPY_FFTW3_H -#define WITH_FFTW3 -#include -#endif - -#ifdef SCIPY_DFFTW_H -#define WITH_FFTW -#include -#include -#endif - -#ifdef SCIPY_FFTW_H -#define WITH_FFTW -#include -#include -#endif - #if defined(NO_APPEND_FORTRAN) #if defined(UPPERCASE_FORTRAN) #define F_FUNC(f,F) F From scipy-svn at scipy.org Sat Nov 1 09:37:30 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 08:37:30 -0500 (CDT) Subject: [Scipy-svn] r4882 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101133730.7333A39C05F@scipy.org> Author: cdavid Date: 2008-11-01 08:37:23 -0500 (Sat, 01 Nov 2008) New Revision: 4882 Modified: branches/remove_fft_backends/scipy/fftpack/src/drfft.c Log: Remove any non-fftpack code for real, one-dimension fft. Modified: branches/remove_fft_backends/scipy/fftpack/src/drfft.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/drfft.c 2008-11-01 13:36:08 UTC (rev 4881) +++ branches/remove_fft_backends/scipy/fftpack/src/drfft.c 2008-11-01 13:37:23 UTC (rev 4882) @@ -20,52 +20,5 @@ drfft_##name(inout, n, direction, howmany, normalize);\ } -/* ************** Definition of backend specific functions ********* */ - -/* - * To add a backend : - * - create a file drfft_name.c, where you define a function drfft_name where - * name is the name of your backend. If you do not use the GEN_CACHE macro, - * you will need to define a function void destroy_drname_caches(void), - * which can do nothing - * - in drfft.c, include the drfft_name.c file, and add the 3 following lines - * just after it: - * #ifndef WITH_DJBFFT - * GEN_PUBLIC_API(name) - * #endif - */ - -#ifdef WITH_FFTW3 - #include "drfft_fftw3.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftw3) - #endif -#elif defined WITH_FFTW - #include "drfft_fftw.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftw) - #endif -#else /* Use fftpack by default */ - #include "drfft_fftpack.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftpack) - #endif -#endif - -/* - * djbfft must be used at the end, because it needs another backend (defined - * above) for non 2^n * size - */ -#ifdef WITH_DJBFFT - #include "drfft_djbfft.c" - void destroy_drfft_cache(void) - { - destroy_drdjbfft_caches(); - drfft_def_destroy_cache(); - } - void drfft(double *inout, int n, - int direction, int howmany, int normalize) - { - drfft_djbfft(inout, n, direction, howmany, normalize); - } -#endif +#include "drfft_fftpack.c" +GEN_PUBLIC_API(fftpack) From scipy-svn at scipy.org Sat Nov 1 10:00:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:00:16 -0500 (CDT) Subject: [Scipy-svn] r4883 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101140016.4ED6D39C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:00:07 -0500 (Sat, 01 Nov 2008) New Revision: 4883 Modified: branches/remove_fft_backends/scipy/fftpack/src/convolve.c Log: Remove non-fftpack reference on convolve code. Modified: branches/remove_fft_backends/scipy/fftpack/src/convolve.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/convolve.c 2008-11-01 13:37:23 UTC (rev 4882) +++ branches/remove_fft_backends/scipy/fftpack/src/convolve.c 2008-11-01 14:00:07 UTC (rev 4883) @@ -11,32 +11,6 @@ #include "fftpack.h" -/**************** DJBFFT *****************************/ -#ifdef WITH_DJBFFT -GEN_CACHE(ddjbfft,(int n) - ,double* ptr; - ,(caches_ddjbfft[i].n==n) - ,caches_ddjbfft[id].ptr = (double*)malloc(sizeof(double)*n); - ,free(caches_ddjbfft[id].ptr); - ,20) -#endif - -/**************** FFTW *****************************/ -#ifdef WITH_FFTW -GEN_CACHE(drfftw,(int n) - ,rfftw_plan plan1; - rfftw_plan plan2; - ,(caches_drfftw[i].n==n) - ,caches_drfftw[id].plan1 = rfftw_create_plan(n, - FFTW_REAL_TO_COMPLEX, - FFTW_IN_PLACE|FFTW_ESTIMATE); - caches_drfftw[id].plan2 = rfftw_create_plan(n, - FFTW_COMPLEX_TO_REAL, - FFTW_IN_PLACE|FFTW_ESTIMATE); - ,rfftw_destroy_plan(caches_drfftw[id].plan1); - rfftw_destroy_plan(caches_drfftw[id].plan2); - ,20) -#else /**************** FFTPACK ZFFT **********************/ extern void F_FUNC(dfftf,DFFTF)(int*,double*,double*); extern void F_FUNC(dfftb,DFFTB)(int*,double*,double*); @@ -48,93 +22,16 @@ F_FUNC(dffti,DFFTI)(&n,caches_dfftpack[id].wsave); ,free(caches_dfftpack[id].wsave); ,20) -#endif extern void destroy_convolve_cache(void) { -#ifdef WITH_DJBFFT - destroy_ddjbfft_caches(); -#endif -#ifdef WITH_FFTW - destroy_drfftw_caches(); -#else - destroy_dfftpack_caches(); -#endif + destroy_dfftpack_caches(); } /**************** convolve **********************/ extern void convolve(int n,double* inout,double* omega,int swap_real_imag) { int i; -#ifdef WITH_DJBFFT - double* ptr = NULL; -#endif -#ifdef WITH_FFTW - rfftw_plan plan1 = NULL; - rfftw_plan plan2 = NULL; -#else double* wsave = NULL; -#endif -#ifdef WITH_DJBFFT - switch (n) { - case 2:;case 4:;case 8:;case 16:;case 32:;case 64:;case 128:;case 256:; - case 512:;case 1024:;case 2048:;case 4096:;case 8192: - i = get_cache_id_ddjbfft(n); - ptr = caches_ddjbfft[i].ptr; - COPYSTD2DJB(inout,ptr,n); - switch (n) { -#define TMPCASE(N) case N: fftr8_##N(ptr); break - TMPCASE(2);TMPCASE(4);TMPCASE(8);TMPCASE(16);TMPCASE(32); - TMPCASE(64);TMPCASE(128);TMPCASE(256);TMPCASE(512); - TMPCASE(1024);TMPCASE(2048);TMPCASE(4096);TMPCASE(8192); -#undef TMPCASE - } - if (swap_real_imag) { - int n1 = n-1; - double c; - ptr[0] *= omega[0]; - ptr[1] *= omega[1]; - for(i=2;in2) f[k] -= n; - omega[0] = (*kernel_func)(0)/n; - switch (d%4) { - case 0: - for (k=2;k Author: cdavid Date: 2008-11-01 09:04:16 -0500 (Sat, 01 Nov 2008) New Revision: 4884 Modified: branches/remove_fft_backends/scipy/fftpack/src/convolve.c Log: Update convolve C code to PEP-7. Modified: branches/remove_fft_backends/scipy/fftpack/src/convolve.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/convolve.c 2008-11-01 14:00:07 UTC (rev 4883) +++ branches/remove_fft_backends/scipy/fftpack/src/convolve.c 2008-11-01 14:04:16 UTC (rev 4884) @@ -12,115 +12,120 @@ #include "fftpack.h" /**************** FFTPACK ZFFT **********************/ -extern void F_FUNC(dfftf,DFFTF)(int*,double*,double*); -extern void F_FUNC(dfftb,DFFTB)(int*,double*,double*); -extern void F_FUNC(dffti,DFFTI)(int*,double*); -GEN_CACHE(dfftpack,(int n) - ,double* wsave; - ,(caches_dfftpack[i].n==n) - ,caches_dfftpack[id].wsave = (double*)malloc(sizeof(double)*(2*n+15)); - F_FUNC(dffti,DFFTI)(&n,caches_dfftpack[id].wsave); - ,free(caches_dfftpack[id].wsave); - ,20) -extern void destroy_convolve_cache(void) { - destroy_dfftpack_caches(); +extern void F_FUNC(dfftf, DFFTF) (int *, double *, double *); +extern void F_FUNC(dfftb, DFFTB) (int *, double *, double *); +extern void F_FUNC(dffti, DFFTI) (int *, double *); +GEN_CACHE(dfftpack, (int n) + , double *wsave;, (caches_dfftpack[i].n == n) + , caches_dfftpack[id].wsave = + (double *) malloc(sizeof(double) * (2 * n + 15)); + F_FUNC(dffti, DFFTI) (&n, caches_dfftpack[id].wsave);, + free(caches_dfftpack[id].wsave);, 20) + +extern void destroy_convolve_cache(void) +{ + destroy_dfftpack_caches(); } /**************** convolve **********************/ -extern -void convolve(int n,double* inout,double* omega,int swap_real_imag) { - int i; - double* wsave = NULL; +extern void +convolve(int n, double *inout, double *omega, int swap_real_imag) +{ + int i; + double *wsave = NULL; i = get_cache_id_dfftpack(n); wsave = caches_dfftpack[i].wsave; - F_FUNC(dfftf,DFFTF)(&n,inout,wsave); + F_FUNC(dfftf, DFFTF) (&n, inout, wsave); if (swap_real_imag) { - double c; - int n1 = n-1; - inout[0] *= omega[0]; - if (!(n%2)) - inout[n-1] *= omega[n-1]; - for(i=1;i Author: cdavid Date: 2008-11-01 09:06:57 -0500 (Sat, 01 Nov 2008) New Revision: 4885 Modified: branches/remove_fft_backends/scipy/fftpack/src/fftpack.h Log: Remove unused convertion code for djbfft and fftw backends. Modified: branches/remove_fft_backends/scipy/fftpack/src/fftpack.h =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack.h 2008-11-01 14:04:16 UTC (rev 4884) +++ branches/remove_fft_backends/scipy/fftpack/src/fftpack.h 2008-11-01 14:06:57 UTC (rev 4885) @@ -82,100 +82,4 @@ nof_in_cache_##name = last_cache_id_##name = 0;\ } -#define COPYSTD2DJB(SRC,DEST,N) { \ - int n2 = (N)/2,k,j; \ - *(DEST) = *(SRC); \ - *(DEST+1) = *(SRC+n2); \ - for (j=(N)/2-1,k=2;j>0;--j,k+=2) { \ - *(DEST+k) = *(SRC+n2+j); \ - *(DEST+k+1) = *(SRC+j); \ - } \ -} - -#define COPYINVDJB2STD(SRC,DEST,N) { \ - int n2 = (N)/2,k,j; \ - *(DEST) = *(SRC); \ - *(DEST+n2) = *(SRC+1); \ - for (j=(N)/2-1,k=2;j>0;--j,k+=2) { \ - *(DEST+n2+j) = *(SRC+k); \ - *(DEST+j) = *(SRC+k+1); \ - } \ -} - -#define COPYINVDJB2STD2(SRC,DEST,N) { \ - int n2 = (N)/2,k,j; \ - *(DEST) = *(SRC); \ - *(DEST+(N)-1) = *(SRC+(N)-1); \ - for (j=1,k=1;jn2) { \ - j = 2*(N-j); \ - *(DEST+j-1) = *(SRC+k); \ - *(DEST+j) = -*(SRC+k+1); \ - } else { \ - j *= 2; \ - *(DEST+j-1) = *(SRC+k); \ - *(DEST+j) = *(SRC+k+1); \ - } \ - } \ -} -#define COPYINVSTD2DJB(SRC,DEST,NORMALIZE,FRQ,N) { \ - int n2 = (N)/2,k,j; \ - if (NORMALIZE) { \ - *(DEST) = *(SRC); \ - *(DEST+1) = *(SRC+N-1); \ - } else { \ - *(DEST) = (*(SRC))*0.5; \ - *(DEST+1) = (*(SRC+N-1))*0.5; \ - } \ - for (k=2;kn2) { \ - j = 2*(N-j); \ - *(DEST+k) = *(SRC+j-1); \ - *(DEST+k+1) = -*(SRC+j); \ - } else { \ - j *= 2; \ - *(DEST+k) = *(SRC+j-1); \ - *(DEST+k+1) = *(SRC+j); \ - } \ - } \ -} -#define COPYRFFTW2STD(SRC,DEST,N) { \ - int j,n2=(N)/2; \ - *(DEST) = *(SRC); \ - for (j=1;j1) { \ - *(DEST+2*n2-1) = *(SRC+n2); \ - if ((N)%2) \ - *(DEST+2*n2) = *(SRC+(N)-n2); \ - } \ -} -#define COPYINVRFFTW2STD(SRC,DEST,N) { \ - int j,n2=(N)/2; \ - *(DEST) = *(SRC); \ - for (j=1;j1) {\ - *(DEST+n2) = *(SRC+2*n2-1); \ - if ((N)%2) \ - *(DEST+(N)-n2) = *(SRC+2*n2); \ - } \ -} - #endif From scipy-svn at scipy.org Sat Nov 1 10:08:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:08:57 -0500 (CDT) Subject: [Scipy-svn] r4886 - branches/remove_fft_backends/scipy/fftpack/src Message-ID: <20081101140857.5B89239C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:08:51 -0500 (Sat, 01 Nov 2008) New Revision: 4886 Modified: branches/remove_fft_backends/scipy/fftpack/src/zfft_fftpack.c Log: remove unused variables in zfft wrapper for fftpack. Modified: branches/remove_fft_backends/scipy/fftpack/src/zfft_fftpack.c =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/zfft_fftpack.c 2008-11-01 14:06:57 UTC (rev 4885) +++ branches/remove_fft_backends/scipy/fftpack/src/zfft_fftpack.c 2008-11-01 14:08:51 UTC (rev 4886) @@ -15,9 +15,6 @@ int i; complex_double *ptr = inout; double *wsave = NULL; - int j; - complex_double *ptrc = NULL; - unsigned int *f = NULL; wsave = caches_zfftpack[get_cache_id_zfftpack(n)].wsave; From scipy-svn at scipy.org Sat Nov 1 10:11:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:11:40 -0500 (CDT) Subject: [Scipy-svn] r4887 - branches/remove_fft_backends/scipy/fftpack Message-ID: <20081101141140.24F3F39C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:11:36 -0500 (Sat, 01 Nov 2008) New Revision: 4887 Modified: branches/remove_fft_backends/scipy/fftpack/setup.py Log: Update dependencies list for _fftpack. Modified: branches/remove_fft_backends/scipy/fftpack/setup.py =================================================================== --- branches/remove_fft_backends/scipy/fftpack/setup.py 2008-11-01 14:08:51 UTC (rev 4886) +++ branches/remove_fft_backends/scipy/fftpack/setup.py 2008-11-01 14:11:36 UTC (rev 4887) @@ -20,14 +20,8 @@ config.add_extension('_fftpack', sources=sources, libraries=['dfftpack'], - depends=['src/zfft_djbfft.c', 'src/zfft_fftpack.c', 'src/zfft_fftw.c', - 'src/zfft_fftw3.c', 'src/zfft_mkl.c', - 'src/drfft_djbfft.c', 'src/drfft_fftpack.c', - 'src/drfft_fftw3.c', 'src/drfft_fftw.c', - 'src/zfftnd_fftpack.c', 'src/zfftnd_fftw.c', - 'src/zfftnd_fftw3.c', 'src/zfftnd_mkl.c', - ], - ) + depends=['src/zfft_fftpack.c', 'src/drfft_fftpack.c', + 'src/zfftnd_fftpack.c']) config.add_extension('convolve', sources=['convolve.pyf','src/convolve.c'], From scipy-svn at scipy.org Sat Nov 1 10:13:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:13:38 -0500 (CDT) Subject: [Scipy-svn] r4888 - in branches/remove_fft_backends/scipy/fftpack: . src Message-ID: <20081101141338.D04E539C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:13:25 -0500 (Sat, 01 Nov 2008) New Revision: 4888 Added: branches/remove_fft_backends/scipy/fftpack/src/dfftpack/ branches/remove_fft_backends/scipy/fftpack/src/fftpack/ Removed: branches/remove_fft_backends/scipy/fftpack/dfftpack/ branches/remove_fft_backends/scipy/fftpack/fftpack/ Modified: branches/remove_fft_backends/scipy/fftpack/setup.py Log: Move fftpack backend sources into src. Modified: branches/remove_fft_backends/scipy/fftpack/setup.py =================================================================== --- branches/remove_fft_backends/scipy/fftpack/setup.py 2008-11-01 14:11:36 UTC (rev 4887) +++ branches/remove_fft_backends/scipy/fftpack/setup.py 2008-11-01 14:13:25 UTC (rev 4888) @@ -12,7 +12,7 @@ config.add_data_dir('benchmarks') config.add_library('dfftpack', - sources=[join('dfftpack','*.f')]) + sources=[join('src/dfftpack','*.f')]) sources = ['fftpack.pyf','src/zfft.c','src/drfft.c','src/zrfft.c', 'src/zfftnd.c'] Copied: branches/remove_fft_backends/scipy/fftpack/src/dfftpack (from rev 4886, branches/remove_fft_backends/scipy/fftpack/dfftpack) Copied: branches/remove_fft_backends/scipy/fftpack/src/fftpack (from rev 4886, branches/remove_fft_backends/scipy/fftpack/fftpack) From scipy-svn at scipy.org Sat Nov 1 10:20:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:20:43 -0500 (CDT) Subject: [Scipy-svn] r4889 - branches/remove_fft_backends/scipy/fftpack Message-ID: <20081101142043.F092039C2EA@scipy.org> Author: cdavid Date: 2008-11-01 09:20:37 -0500 (Sat, 01 Nov 2008) New Revision: 4889 Modified: branches/remove_fft_backends/scipy/fftpack/NOTES.txt branches/remove_fft_backends/scipy/fftpack/SConscript Log: Update NOTEST. Modified: branches/remove_fft_backends/scipy/fftpack/NOTES.txt =================================================================== --- branches/remove_fft_backends/scipy/fftpack/NOTES.txt 2008-11-01 14:13:25 UTC (rev 4888) +++ branches/remove_fft_backends/scipy/fftpack/NOTES.txt 2008-11-01 14:20:37 UTC (rev 4889) @@ -27,76 +27,14 @@ :: - python tests/test_basic.py -l 10 - python tests/test_pseudo_diffs.py -l 10 - python tests/test_helper.py -l 10 + python -c "import scipy.fftpack; scipy.fftpack.test()" or from python ->>> import fftpack ->>> fftpack.test(10) +>>> import scipy.fftpack +>>> scipy.fftpack.test(10) -Building with high-performance FFT libraries -============================================ - -fftpack uses optimal combination of FFT libraries for different -jobs. Currently, Fortran FFTPACK, FFTW, and DJBFFT libraries are -supported. The last two are optional and used only if -scipy/distutils/system_info.py detects them. -If they are available, then the output of - -:: - - python scipy/distutils/system_info.py - -should show, for example - -:: - - dfftw_info: - FOUND: - libraries = ['drfftw', 'dfftw'] - library_dirs = ['/path/to/lib'] - define_macros = [('SCIPY_DFFTW_H', None)] - include_dirs = ['/path/to/include'] - - djbfft_info: - FOUND: - extra_objects = ['/path/to/lib/djbfft.a'] - define_macros = [('SCIPY_DJBFFT_H', None)] - include_dirs = ['/path/to/include'] - -Note that when using fftw libraries provided by a Linux distribution -then fftw-dev (or fftw-devel or similar) must be installed as well, -otherwise system_info.py won't detect fftw libraries. - -DJBFFT library is fastest for power-of-two (<=8192) Fourier -transforms. FFTW is superior for non-power-of-two transforms and -multi-dimensional transforms. - -Building notes for FFTW_ ------------------------- -Follow the instructions in - - http://www.fftw.org/doc/fftw_6.html - -Note that fftpack uses double-precision FFTW. So, if you build -libfftw.a, then it is assumed that it contains double-precision code. - -.. _FFTW: http://www.fftw.org - -Building notes for DJBFFT_ --------------------------- -.. _DJBFFT: http://cr.yp.to/djbfft.html - -Follow the installation instructions in - - http://cr.yp.to/djbfft/install.html - -If djbfft is installed under these instructions then scipy_distutils -picks up it for fftpack automatically. - Differences between fftpack and FFT from Numeric ================================================ Modified: branches/remove_fft_backends/scipy/fftpack/SConscript =================================================================== --- branches/remove_fft_backends/scipy/fftpack/SConscript 2008-11-01 14:13:25 UTC (rev 4888) +++ branches/remove_fft_backends/scipy/fftpack/SConscript 2008-11-01 14:20:37 UTC (rev 4889) @@ -1,32 +1,14 @@ -# Last Change: Thu Jun 12 07:00 PM 2008 J +# Last Change: Sat Nov 01 10:00 PM 2008 J # vim:syntax=python from os.path import join as pjoin -from numscons import GetNumpyEnvironment, write_info -from numscons import CheckFFT, IsMKL, IsFFTW2, IsFFTW3 +from numscons import GetNumpyEnvironment env = GetNumpyEnvironment(ARGUMENTS) env.Tool('f2py') -# Check fft implementation -config = env.NumpyConfigure(custom_tests = {'CheckFFT': CheckFFT}) -has_fft = config.CheckFFT() -config.Finish() -write_info(env) - -# Tweak defineds depending on the fft used -if has_fft: - if IsMKL(env, 'fft'): - env.Append(CPPDEFINES = "SCIPY_MKL_H") - elif IsFFTW3(env, 'fft'): - env.Append(CPPDEFINES = "SCIPY_FFTW3_H") - elif IsFFTW2(env, 'fft'): - env.Append(CPPDEFINES = "SCIPY_FFTW2_H") - else: - pass - # Build dfftpack -src = [pjoin("dfftpack", i) for i in [ "dcosqb.f", "dcosqf.f", "dcosqi.f", +src = [pjoin("src/dfftpack", i) for i in [ "dcosqb.f", "dcosqf.f", "dcosqi.f", "dcost.f", "dcosti.f", "dfftb.f", "dfftb1.f", "dfftf.f", "dfftf1.f", "dffti.f", "dffti1.f", "dsinqb.f", "dsinqf.f", "dsinqi.f", "dsint.f", "dsint1.f", "dsinti.f", "zfftb.f", "zfftb1.f", "zfftf.f", "zfftf1.f", "zffti.f", From scipy-svn at scipy.org Sat Nov 1 10:28:44 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:28:44 -0500 (CDT) Subject: [Scipy-svn] r4890 - branches/remove_fft_backends/scipy/fftpack/benchmarks Message-ID: <20081101142844.7644039C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:28:39 -0500 (Sat, 01 Nov 2008) New Revision: 4890 Modified: branches/remove_fft_backends/scipy/fftpack/benchmarks/bench_basic.py Log: Forgot rfft import when going to nose frameworks for benchmarks of fft. Modified: branches/remove_fft_backends/scipy/fftpack/benchmarks/bench_basic.py =================================================================== --- branches/remove_fft_backends/scipy/fftpack/benchmarks/bench_basic.py 2008-11-01 14:20:37 UTC (rev 4889) +++ branches/remove_fft_backends/scipy/fftpack/benchmarks/bench_basic.py 2008-11-01 14:28:39 UTC (rev 4890) @@ -2,7 +2,7 @@ """ import sys from numpy.testing import * -from scipy.fftpack import ifft, fft, fftn, irfft +from scipy.fftpack import ifft, fft, fftn, irfft, rfft from numpy import arange, asarray, zeros, dot, exp, pi, double, cdouble import numpy.fft From scipy-svn at scipy.org Sat Nov 1 10:39:05 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:39:05 -0500 (CDT) Subject: [Scipy-svn] r4891 - trunk Message-ID: <20081101143905.4E7DC39C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:39:02 -0500 (Sat, 01 Nov 2008) New Revision: 4891 Modified: trunk/ Log: Initialized merge tracking via "svnmerge" with revisions "1-4890" from http://svn.scipy.org/svn/scipy/branches/remove_fft_backends Property changes on: trunk ___________________________________________________________________ Name: svnmerge-integrated - /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 + /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/remove_fft_backends:1-4890 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 From scipy-svn at scipy.org Sat Nov 1 10:42:42 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:42:42 -0500 (CDT) Subject: [Scipy-svn] r4892 - trunk Message-ID: <20081101144242.C89B139C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:42:39 -0500 (Sat, 01 Nov 2008) New Revision: 4892 Modified: trunk/ Log: Removed merge tracking for "svnmerge" for http://svn.scipy.org/svn/scipy/branches/remove_fft_backends Property changes on: trunk ___________________________________________________________________ Name: svnmerge-integrated - /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/remove_fft_backends:1-4890 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 + /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 From scipy-svn at scipy.org Sat Nov 1 10:51:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 09:51:10 -0500 (CDT) Subject: [Scipy-svn] r4893 - in trunk: . scipy/fftpack scipy/fftpack/benchmarks scipy/fftpack/src scipy/fftpack/src/dfftpack scipy/fftpack/src/fftpack Message-ID: <20081101145110.DF47439C05F@scipy.org> Author: cdavid Date: 2008-11-01 09:49:49 -0500 (Sat, 01 Nov 2008) New Revision: 4893 Added: trunk/scipy/fftpack/src/dfftpack/ trunk/scipy/fftpack/src/dfftpack/dcosqb.f trunk/scipy/fftpack/src/dfftpack/dcosqf.f trunk/scipy/fftpack/src/dfftpack/dcosqi.f trunk/scipy/fftpack/src/dfftpack/dcost.f trunk/scipy/fftpack/src/dfftpack/dcosti.f trunk/scipy/fftpack/src/dfftpack/dfftb.f trunk/scipy/fftpack/src/dfftpack/dfftb1.f trunk/scipy/fftpack/src/dfftpack/dfftf.f trunk/scipy/fftpack/src/dfftpack/dfftf1.f trunk/scipy/fftpack/src/dfftpack/dffti.f trunk/scipy/fftpack/src/dfftpack/dffti1.f trunk/scipy/fftpack/src/dfftpack/doc trunk/scipy/fftpack/src/dfftpack/doc.double trunk/scipy/fftpack/src/dfftpack/dsinqb.f trunk/scipy/fftpack/src/dfftpack/dsinqf.f trunk/scipy/fftpack/src/dfftpack/dsinqi.f trunk/scipy/fftpack/src/dfftpack/dsint.f trunk/scipy/fftpack/src/dfftpack/dsint1.f trunk/scipy/fftpack/src/dfftpack/dsinti.f trunk/scipy/fftpack/src/dfftpack/zfftb.f trunk/scipy/fftpack/src/dfftpack/zfftb1.f trunk/scipy/fftpack/src/dfftpack/zfftf.f trunk/scipy/fftpack/src/dfftpack/zfftf1.f trunk/scipy/fftpack/src/dfftpack/zffti.f trunk/scipy/fftpack/src/dfftpack/zffti1.f trunk/scipy/fftpack/src/fftpack/ trunk/scipy/fftpack/src/fftpack/cfftb.f trunk/scipy/fftpack/src/fftpack/cfftb1.f trunk/scipy/fftpack/src/fftpack/cfftf.f trunk/scipy/fftpack/src/fftpack/cfftf1.f trunk/scipy/fftpack/src/fftpack/cffti.f trunk/scipy/fftpack/src/fftpack/cffti1.f trunk/scipy/fftpack/src/fftpack/cosqb.f trunk/scipy/fftpack/src/fftpack/cosqf.f trunk/scipy/fftpack/src/fftpack/cosqi.f trunk/scipy/fftpack/src/fftpack/cost.f trunk/scipy/fftpack/src/fftpack/costi.f trunk/scipy/fftpack/src/fftpack/doc trunk/scipy/fftpack/src/fftpack/rfftb.f trunk/scipy/fftpack/src/fftpack/rfftb1.f trunk/scipy/fftpack/src/fftpack/rfftf.f trunk/scipy/fftpack/src/fftpack/rfftf1.f trunk/scipy/fftpack/src/fftpack/rffti.f trunk/scipy/fftpack/src/fftpack/rffti1.f trunk/scipy/fftpack/src/fftpack/sinqb.f trunk/scipy/fftpack/src/fftpack/sinqf.f trunk/scipy/fftpack/src/fftpack/sinqi.f trunk/scipy/fftpack/src/fftpack/sint.f trunk/scipy/fftpack/src/fftpack/sint1.f trunk/scipy/fftpack/src/fftpack/sinti.f Removed: trunk/scipy/fftpack/dfftpack/ trunk/scipy/fftpack/fftpack/ trunk/scipy/fftpack/src/dfftpack/dcosqb.f trunk/scipy/fftpack/src/dfftpack/dcosqf.f trunk/scipy/fftpack/src/dfftpack/dcosqi.f trunk/scipy/fftpack/src/dfftpack/dcost.f trunk/scipy/fftpack/src/dfftpack/dcosti.f trunk/scipy/fftpack/src/dfftpack/dfftb.f trunk/scipy/fftpack/src/dfftpack/dfftb1.f trunk/scipy/fftpack/src/dfftpack/dfftf.f trunk/scipy/fftpack/src/dfftpack/dfftf1.f trunk/scipy/fftpack/src/dfftpack/dffti.f trunk/scipy/fftpack/src/dfftpack/dffti1.f trunk/scipy/fftpack/src/dfftpack/doc trunk/scipy/fftpack/src/dfftpack/doc.double trunk/scipy/fftpack/src/dfftpack/dsinqb.f trunk/scipy/fftpack/src/dfftpack/dsinqf.f trunk/scipy/fftpack/src/dfftpack/dsinqi.f trunk/scipy/fftpack/src/dfftpack/dsint.f trunk/scipy/fftpack/src/dfftpack/dsint1.f trunk/scipy/fftpack/src/dfftpack/dsinti.f trunk/scipy/fftpack/src/dfftpack/zfftb.f trunk/scipy/fftpack/src/dfftpack/zfftb1.f trunk/scipy/fftpack/src/dfftpack/zfftf.f trunk/scipy/fftpack/src/dfftpack/zfftf1.f trunk/scipy/fftpack/src/dfftpack/zffti.f trunk/scipy/fftpack/src/dfftpack/zffti1.f trunk/scipy/fftpack/src/drfft_djbfft.c trunk/scipy/fftpack/src/drfft_fftw.c trunk/scipy/fftpack/src/drfft_fftw3.c trunk/scipy/fftpack/src/fftpack/cfftb.f trunk/scipy/fftpack/src/fftpack/cfftb1.f trunk/scipy/fftpack/src/fftpack/cfftf.f trunk/scipy/fftpack/src/fftpack/cfftf1.f trunk/scipy/fftpack/src/fftpack/cffti.f trunk/scipy/fftpack/src/fftpack/cffti1.f trunk/scipy/fftpack/src/fftpack/cosqb.f trunk/scipy/fftpack/src/fftpack/cosqf.f trunk/scipy/fftpack/src/fftpack/cosqi.f trunk/scipy/fftpack/src/fftpack/cost.f trunk/scipy/fftpack/src/fftpack/costi.f trunk/scipy/fftpack/src/fftpack/doc trunk/scipy/fftpack/src/fftpack/rfftb.f trunk/scipy/fftpack/src/fftpack/rfftb1.f trunk/scipy/fftpack/src/fftpack/rfftf.f trunk/scipy/fftpack/src/fftpack/rfftf1.f trunk/scipy/fftpack/src/fftpack/rffti.f trunk/scipy/fftpack/src/fftpack/rffti1.f trunk/scipy/fftpack/src/fftpack/sinqb.f trunk/scipy/fftpack/src/fftpack/sinqf.f trunk/scipy/fftpack/src/fftpack/sinqi.f trunk/scipy/fftpack/src/fftpack/sint.f trunk/scipy/fftpack/src/fftpack/sint1.f trunk/scipy/fftpack/src/fftpack/sinti.f trunk/scipy/fftpack/src/zfft_djbfft.c trunk/scipy/fftpack/src/zfft_fftw.c trunk/scipy/fftpack/src/zfft_fftw3.c trunk/scipy/fftpack/src/zfft_mkl.c trunk/scipy/fftpack/src/zfftnd_fftw.c trunk/scipy/fftpack/src/zfftnd_fftw3.c trunk/scipy/fftpack/src/zfftnd_mkl.c Modified: trunk/ trunk/scipy/fftpack/NOTES.txt trunk/scipy/fftpack/SConscript trunk/scipy/fftpack/benchmarks/bench_basic.py trunk/scipy/fftpack/setup.py trunk/scipy/fftpack/src/convolve.c trunk/scipy/fftpack/src/drfft.c trunk/scipy/fftpack/src/fftpack.h trunk/scipy/fftpack/src/zfft.c trunk/scipy/fftpack/src/zfft_fftpack.c trunk/scipy/fftpack/src/zfftnd.c Log: Merge the remove_fft_backends branch. Property changes on: trunk ___________________________________________________________________ Name: svnmerge-integrated - /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 + /branches/build_with_scons:1-3868 /branches/refactor_fft:1-4210 /branches/scipy.scons:1-3533 /branches/sparse_build_reduce_mem:1-4005 /branches/testing_cleanup:1-3662 /trunk:1-4871 Modified: trunk/scipy/fftpack/NOTES.txt =================================================================== --- trunk/scipy/fftpack/NOTES.txt 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/NOTES.txt 2008-11-01 14:49:49 UTC (rev 4893) @@ -27,76 +27,14 @@ :: - python tests/test_basic.py -l 10 - python tests/test_pseudo_diffs.py -l 10 - python tests/test_helper.py -l 10 + python -c "import scipy.fftpack; scipy.fftpack.test()" or from python ->>> import fftpack ->>> fftpack.test(10) +>>> import scipy.fftpack +>>> scipy.fftpack.test(10) -Building with high-performance FFT libraries -============================================ - -fftpack uses optimal combination of FFT libraries for different -jobs. Currently, Fortran FFTPACK, FFTW, and DJBFFT libraries are -supported. The last two are optional and used only if -scipy/distutils/system_info.py detects them. -If they are available, then the output of - -:: - - python scipy/distutils/system_info.py - -should show, for example - -:: - - dfftw_info: - FOUND: - libraries = ['drfftw', 'dfftw'] - library_dirs = ['/path/to/lib'] - define_macros = [('SCIPY_DFFTW_H', None)] - include_dirs = ['/path/to/include'] - - djbfft_info: - FOUND: - extra_objects = ['/path/to/lib/djbfft.a'] - define_macros = [('SCIPY_DJBFFT_H', None)] - include_dirs = ['/path/to/include'] - -Note that when using fftw libraries provided by a Linux distribution -then fftw-dev (or fftw-devel or similar) must be installed as well, -otherwise system_info.py won't detect fftw libraries. - -DJBFFT library is fastest for power-of-two (<=8192) Fourier -transforms. FFTW is superior for non-power-of-two transforms and -multi-dimensional transforms. - -Building notes for FFTW_ ------------------------- -Follow the instructions in - - http://www.fftw.org/doc/fftw_6.html - -Note that fftpack uses double-precision FFTW. So, if you build -libfftw.a, then it is assumed that it contains double-precision code. - -.. _FFTW: http://www.fftw.org - -Building notes for DJBFFT_ --------------------------- -.. _DJBFFT: http://cr.yp.to/djbfft.html - -Follow the installation instructions in - - http://cr.yp.to/djbfft/install.html - -If djbfft is installed under these instructions then scipy_distutils -picks up it for fftpack automatically. - Differences between fftpack and FFT from Numeric ================================================ Modified: trunk/scipy/fftpack/SConscript =================================================================== --- trunk/scipy/fftpack/SConscript 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/SConscript 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,32 +1,14 @@ -# Last Change: Thu Jun 12 07:00 PM 2008 J +# Last Change: Sat Nov 01 10:00 PM 2008 J # vim:syntax=python from os.path import join as pjoin -from numscons import GetNumpyEnvironment, write_info -from numscons import CheckFFT, IsMKL, IsFFTW2, IsFFTW3 +from numscons import GetNumpyEnvironment env = GetNumpyEnvironment(ARGUMENTS) env.Tool('f2py') -# Check fft implementation -config = env.NumpyConfigure(custom_tests = {'CheckFFT': CheckFFT}) -has_fft = config.CheckFFT() -config.Finish() -write_info(env) - -# Tweak defineds depending on the fft used -if has_fft: - if IsMKL(env, 'fft'): - env.Append(CPPDEFINES = "SCIPY_MKL_H") - elif IsFFTW3(env, 'fft'): - env.Append(CPPDEFINES = "SCIPY_FFTW3_H") - elif IsFFTW2(env, 'fft'): - env.Append(CPPDEFINES = "SCIPY_FFTW2_H") - else: - pass - # Build dfftpack -src = [pjoin("dfftpack", i) for i in [ "dcosqb.f", "dcosqf.f", "dcosqi.f", +src = [pjoin("src/dfftpack", i) for i in [ "dcosqb.f", "dcosqf.f", "dcosqi.f", "dcost.f", "dcosti.f", "dfftb.f", "dfftb1.f", "dfftf.f", "dfftf1.f", "dffti.f", "dffti1.f", "dsinqb.f", "dsinqf.f", "dsinqi.f", "dsint.f", "dsint1.f", "dsinti.f", "zfftb.f", "zfftb1.f", "zfftf.f", "zfftf1.f", "zffti.f", Modified: trunk/scipy/fftpack/benchmarks/bench_basic.py =================================================================== --- trunk/scipy/fftpack/benchmarks/bench_basic.py 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/benchmarks/bench_basic.py 2008-11-01 14:49:49 UTC (rev 4893) @@ -2,7 +2,7 @@ """ import sys from numpy.testing import * -from scipy.fftpack import ifft, fft, fftn, irfft +from scipy.fftpack import ifft, fft, fftn, irfft, rfft from numpy import arange, asarray, zeros, dot, exp, pi, double, cdouble import numpy.fft Modified: trunk/scipy/fftpack/setup.py =================================================================== --- trunk/scipy/fftpack/setup.py 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/setup.py 2008-11-01 14:49:49 UTC (rev 4893) @@ -5,24 +5,14 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration - from numpy.distutils.system_info import get_info + config = Configuration('fftpack',parent_package, top_path) - djbfft_info = {} - mkl_info = get_info('mkl') - if mkl_info: - mkl_info.setdefault('define_macros', []).append(('SCIPY_MKL_H', None)) - fft_opt_info = mkl_info - else: - fft_opt_info = get_info('fftw3') or get_info('fftw2') \ - or get_info('dfftw') - djbfft_info = get_info('djbfft') - config.add_data_dir('tests') config.add_data_dir('benchmarks') config.add_library('dfftpack', - sources=[join('dfftpack','*.f')]) + sources=[join('src/dfftpack','*.f')]) sources = ['fftpack.pyf','src/zfft.c','src/drfft.c','src/zrfft.c', 'src/zfftnd.c'] @@ -30,20 +20,12 @@ config.add_extension('_fftpack', sources=sources, libraries=['dfftpack'], - extra_info=[fft_opt_info, djbfft_info], - depends=['src/zfft_djbfft.c', 'src/zfft_fftpack.c', 'src/zfft_fftw.c', - 'src/zfft_fftw3.c', 'src/zfft_mkl.c', - 'src/drfft_djbfft.c', 'src/drfft_fftpack.c', - 'src/drfft_fftw3.c', 'src/drfft_fftw.c', - 'src/zfftnd_fftpack.c', 'src/zfftnd_fftw.c', - 'src/zfftnd_fftw3.c', 'src/zfftnd_mkl.c', - ], - ) + depends=['src/zfft_fftpack.c', 'src/drfft_fftpack.c', + 'src/zfftnd_fftpack.c']) config.add_extension('convolve', sources=['convolve.pyf','src/convolve.c'], libraries=['dfftpack'], - extra_info=[fft_opt_info, djbfft_info], ) return config Modified: trunk/scipy/fftpack/src/convolve.c =================================================================== --- trunk/scipy/fftpack/src/convolve.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/convolve.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -11,367 +11,121 @@ #include "fftpack.h" -/**************** DJBFFT *****************************/ -#ifdef WITH_DJBFFT -GEN_CACHE(ddjbfft,(int n) - ,double* ptr; - ,(caches_ddjbfft[i].n==n) - ,caches_ddjbfft[id].ptr = (double*)malloc(sizeof(double)*n); - ,free(caches_ddjbfft[id].ptr); - ,20) -#endif - -/**************** FFTW *****************************/ -#ifdef WITH_FFTW -GEN_CACHE(drfftw,(int n) - ,rfftw_plan plan1; - rfftw_plan plan2; - ,(caches_drfftw[i].n==n) - ,caches_drfftw[id].plan1 = rfftw_create_plan(n, - FFTW_REAL_TO_COMPLEX, - FFTW_IN_PLACE|FFTW_ESTIMATE); - caches_drfftw[id].plan2 = rfftw_create_plan(n, - FFTW_COMPLEX_TO_REAL, - FFTW_IN_PLACE|FFTW_ESTIMATE); - ,rfftw_destroy_plan(caches_drfftw[id].plan1); - rfftw_destroy_plan(caches_drfftw[id].plan2); - ,20) -#else /**************** FFTPACK ZFFT **********************/ -extern void F_FUNC(dfftf,DFFTF)(int*,double*,double*); -extern void F_FUNC(dfftb,DFFTB)(int*,double*,double*); -extern void F_FUNC(dffti,DFFTI)(int*,double*); -GEN_CACHE(dfftpack,(int n) - ,double* wsave; - ,(caches_dfftpack[i].n==n) - ,caches_dfftpack[id].wsave = (double*)malloc(sizeof(double)*(2*n+15)); - F_FUNC(dffti,DFFTI)(&n,caches_dfftpack[id].wsave); - ,free(caches_dfftpack[id].wsave); - ,20) -#endif -extern void destroy_convolve_cache(void) { -#ifdef WITH_DJBFFT - destroy_ddjbfft_caches(); -#endif -#ifdef WITH_FFTW - destroy_drfftw_caches(); -#else - destroy_dfftpack_caches(); -#endif +extern void F_FUNC(dfftf, DFFTF) (int *, double *, double *); +extern void F_FUNC(dfftb, DFFTB) (int *, double *, double *); +extern void F_FUNC(dffti, DFFTI) (int *, double *); +GEN_CACHE(dfftpack, (int n) + , double *wsave;, (caches_dfftpack[i].n == n) + , caches_dfftpack[id].wsave = + (double *) malloc(sizeof(double) * (2 * n + 15)); + F_FUNC(dffti, DFFTI) (&n, caches_dfftpack[id].wsave);, + free(caches_dfftpack[id].wsave);, 20) + +extern void destroy_convolve_cache(void) +{ + destroy_dfftpack_caches(); } /**************** convolve **********************/ -extern -void convolve(int n,double* inout,double* omega,int swap_real_imag) { - int i; -#ifdef WITH_DJBFFT - double* ptr = NULL; -#endif -#ifdef WITH_FFTW - rfftw_plan plan1 = NULL; - rfftw_plan plan2 = NULL; -#else - double* wsave = NULL; -#endif -#ifdef WITH_DJBFFT - switch (n) { - case 2:;case 4:;case 8:;case 16:;case 32:;case 64:;case 128:;case 256:; - case 512:;case 1024:;case 2048:;case 4096:;case 8192: - i = get_cache_id_ddjbfft(n); - ptr = caches_ddjbfft[i].ptr; - COPYSTD2DJB(inout,ptr,n); - switch (n) { -#define TMPCASE(N) case N: fftr8_##N(ptr); break - TMPCASE(2);TMPCASE(4);TMPCASE(8);TMPCASE(16);TMPCASE(32); - TMPCASE(64);TMPCASE(128);TMPCASE(256);TMPCASE(512); - TMPCASE(1024);TMPCASE(2048);TMPCASE(4096);TMPCASE(8192); -#undef TMPCASE - } - if (swap_real_imag) { - int n1 = n-1; - double c; - ptr[0] *= omega[0]; - ptr[1] *= omega[1]; - for(i=2;in2) f[k] -= n; - omega[0] = (*kernel_func)(0)/n; - switch (d%4) { - case 0: - for (k=2;k= 0; --i) { - (*(ptr++)) *= d; - } - } -} Deleted: trunk/scipy/fftpack/src/drfft_fftw.c =================================================================== --- trunk/scipy/fftpack/src/drfft_fftw.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/drfft_fftw.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,70 +0,0 @@ -/* - * Last Change: Wed Aug 01 07:00 PM 2007 J - * - * FFTW2 implementation - * - * Original code by Pearu Peterson. - */ - -GEN_CACHE(drfftw, (int n, int d, int flags) - , int direction; - int flags; - rfftw_plan plan; - double *ptr;, ((caches_drfftw[i].n == n) && - (caches_drfftw[i].direction == d) && - (caches_drfftw[i].flags == flags)) - , caches_drfftw[id].direction = d; - caches_drfftw[id].flags = flags; - caches_drfftw[id].plan = rfftw_create_plan(n, - (d > - 0 ? - FFTW_REAL_TO_COMPLEX - : - FFTW_COMPLEX_TO_REAL), - flags); - caches_drfftw[id].ptr = - (double *) malloc(sizeof(double) * (n));, - rfftw_destroy_plan(caches_drfftw[id].plan); - free(caches_drfftw[id].ptr);, 10) - -static void drfft_fftw(double *inout, int n, int dir, int - howmany, int normalize) -{ - int i; - double *ptr = inout; - double *ptrc = NULL; - rfftw_plan plan = NULL; - - i = get_cache_id_drfftw(n, dir, FFTW_IN_PLACE | FFTW_ESTIMATE); - plan = caches_drfftw[i].plan; - ptrc = caches_drfftw[i].ptr; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - memcpy(ptrc, ptr, sizeof(double) * n); - rfftw(plan, 1, (fftw_real *) ptrc, 1, 1, NULL, 1, 1); - COPYRFFTW2STD(ptrc, ptr, n); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - COPYINVRFFTW2STD(ptr, ptrc, n); - rfftw(plan, 1, (fftw_real *) ptrc, 1, 1, NULL, 1, 1); - memcpy(ptr, ptrc, sizeof(double) * n); - } - break; - - default: - fprintf(stderr, "drfft: invalid direction=%d\n", dir); - } - - if (normalize) { - double d = 1.0 / n; - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - (*(ptr++)) *= d; - } - } -} Deleted: trunk/scipy/fftpack/src/drfft_fftw3.c =================================================================== --- trunk/scipy/fftpack/src/drfft_fftw3.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/drfft_fftw3.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,65 +0,0 @@ -/* - * Last Change: Wed Aug 01 07:00 PM 2007 J - * - * FFTW3 implementation - * - * Original code by Pearu Peterson. - */ - -GEN_CACHE(drfftw3, (int n, int d, int flags) - , int direction; - int flags; - fftw_plan plan; - double *ptr;, ((caches_drfftw3[i].n == n) && - (caches_drfftw3[i].direction == d) && - (caches_drfftw3[i].flags == flags)) - , caches_drfftw3[id].direction = d; - caches_drfftw3[id].flags = flags; - caches_drfftw3[id].ptr = - (double *) fftw_malloc(sizeof(double) * (n)); - caches_drfftw3[id].plan = - fftw_plan_r2r_1d(n, caches_drfftw3[id].ptr, caches_drfftw3[id].ptr, - (d > 0 ? FFTW_R2HC : FFTW_HC2R), flags);, - fftw_destroy_plan(caches_drfftw3[id].plan); - fftw_free(caches_drfftw3[id].ptr);, 10) - -static void drfft_fftw3(double *inout, int n, int direction, int - howmany, int normalize) -{ - int i; - double *ptr = inout; - - double *ptrc = NULL; - fftw_plan plan = NULL; - - i = get_cache_id_drfftw3(n, direction, FFTW_ESTIMATE); - plan = caches_drfftw3[i].plan; - ptrc = caches_drfftw3[i].ptr; - switch (direction) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - memcpy(ptrc, ptr, sizeof(double) * n); - fftw_execute(plan); - COPYRFFTW2STD(ptrc, ptr, n); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - COPYINVRFFTW2STD(ptr, ptrc, n); - fftw_execute(plan); - memcpy(ptr, ptrc, sizeof(double) * n); - } - break; - default: - fprintf(stderr, "drfft: invalid direction=%d\n", direction); - } - - if (normalize) { - double d = 1.0 / n; - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - (*(ptr++)) *= d; - } - } -} Copied: trunk/scipy/fftpack/src/fftpack (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack) Property changes on: trunk/scipy/fftpack/src/fftpack ___________________________________________________________________ Name: svn:ignore + *.pyc *.swp *.pyd *.so Deleted: trunk/scipy/fftpack/src/fftpack/cfftb.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftb.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cfftb.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,8 +0,0 @@ - SUBROUTINE CFFTB (N,C,WSAVE) - DIMENSION C(*) ,WSAVE(*) - IF (N .EQ. 1) RETURN - IW1 = N+N+1 - IW2 = IW1+N+N - CALL CFFTB1 (N,C,WSAVE,WSAVE(IW1),WSAVE(IW2)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cfftb.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftb.f) Deleted: trunk/scipy/fftpack/src/fftpack/cfftb1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftb1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cfftb1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,368 +0,0 @@ - SUBROUTINE CFFTB1 (N,C,CH,WA,IFAC) - DIMENSION CH(*) ,C(*) ,WA(*) ,IFAC(*) - NF = IFAC(2) - NA = 0 - L1 = 1 - IW = 1 - DO 116 K1=1,NF - IP = IFAC(K1+2) - L2 = IP*L1 - IDO = N/L2 - IDOT = IDO+IDO - IDL1 = IDOT*L1 - IF (IP .NE. 4) GO TO 103 - IX2 = IW+IDOT - IX3 = IX2+IDOT - IF (NA .NE. 0) GO TO 101 - CALL PASSB4 (IDOT,L1,C,CH,WA(IW),WA(IX2),WA(IX3)) - GO TO 102 - 101 CALL PASSB4 (IDOT,L1,CH,C,WA(IW),WA(IX2),WA(IX3)) - 102 NA = 1-NA - GO TO 115 - 103 IF (IP .NE. 2) GO TO 106 - IF (NA .NE. 0) GO TO 104 - CALL PASSB2 (IDOT,L1,C,CH,WA(IW)) - GO TO 105 - 104 CALL PASSB2 (IDOT,L1,CH,C,WA(IW)) - 105 NA = 1-NA - GO TO 115 - 106 IF (IP .NE. 3) GO TO 109 - IX2 = IW+IDOT - IF (NA .NE. 0) GO TO 107 - CALL PASSB3 (IDOT,L1,C,CH,WA(IW),WA(IX2)) - GO TO 108 - 107 CALL PASSB3 (IDOT,L1,CH,C,WA(IW),WA(IX2)) - 108 NA = 1-NA - GO TO 115 - 109 IF (IP .NE. 5) GO TO 112 - IX2 = IW+IDOT - IX3 = IX2+IDOT - IX4 = IX3+IDOT - IF (NA .NE. 0) GO TO 110 - CALL PASSB5 (IDOT,L1,C,CH,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - GO TO 111 - 110 CALL PASSB5 (IDOT,L1,CH,C,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - 111 NA = 1-NA - GO TO 115 - 112 IF (NA .NE. 0) GO TO 113 - CALL PASSB (NAC,IDOT,IP,L1,IDL1,C,C,C,CH,CH,WA(IW)) - GO TO 114 - 113 CALL PASSB (NAC,IDOT,IP,L1,IDL1,CH,CH,CH,C,C,WA(IW)) - 114 IF (NAC .NE. 0) NA = 1-NA - 115 L1 = L2 - IW = IW+(IP-1)*IDOT - 116 CONTINUE - IF (NA .EQ. 0) RETURN - N2 = N+N - DO 117 I=1,N2 - C(I) = CH(I) - 117 CONTINUE - RETURN - END - SUBROUTINE PASSB2 (IDO,L1,CC,CH,WA1) - DIMENSION CC(IDO,2,L1) ,CH(IDO,L1,2) , - 1 WA1(*) - IF (IDO .GT. 2) GO TO 102 - DO 101 K=1,L1 - CH(1,K,1) = CC(1,1,K)+CC(1,2,K) - CH(1,K,2) = CC(1,1,K)-CC(1,2,K) - CH(2,K,1) = CC(2,1,K)+CC(2,2,K) - CH(2,K,2) = CC(2,1,K)-CC(2,2,K) - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - CH(I-1,K,1) = CC(I-1,1,K)+CC(I-1,2,K) - TR2 = CC(I-1,1,K)-CC(I-1,2,K) - CH(I,K,1) = CC(I,1,K)+CC(I,2,K) - TI2 = CC(I,1,K)-CC(I,2,K) - CH(I,K,2) = WA1(I-1)*TI2+WA1(I)*TR2 - CH(I-1,K,2) = WA1(I-1)*TR2-WA1(I)*TI2 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSB3 (IDO,L1,CC,CH,WA1,WA2) - DIMENSION CC(IDO,3,L1) ,CH(IDO,L1,3) , - 1 WA1(*) ,WA2(*) - DATA TAUR,TAUI /-.5,.866025403784439/ - IF (IDO .NE. 2) GO TO 102 - DO 101 K=1,L1 - TR2 = CC(1,2,K)+CC(1,3,K) - CR2 = CC(1,1,K)+TAUR*TR2 - CH(1,K,1) = CC(1,1,K)+TR2 - TI2 = CC(2,2,K)+CC(2,3,K) - CI2 = CC(2,1,K)+TAUR*TI2 - CH(2,K,1) = CC(2,1,K)+TI2 - CR3 = TAUI*(CC(1,2,K)-CC(1,3,K)) - CI3 = TAUI*(CC(2,2,K)-CC(2,3,K)) - CH(1,K,2) = CR2-CI3 - CH(1,K,3) = CR2+CI3 - CH(2,K,2) = CI2+CR3 - CH(2,K,3) = CI2-CR3 - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - TR2 = CC(I-1,2,K)+CC(I-1,3,K) - CR2 = CC(I-1,1,K)+TAUR*TR2 - CH(I-1,K,1) = CC(I-1,1,K)+TR2 - TI2 = CC(I,2,K)+CC(I,3,K) - CI2 = CC(I,1,K)+TAUR*TI2 - CH(I,K,1) = CC(I,1,K)+TI2 - CR3 = TAUI*(CC(I-1,2,K)-CC(I-1,3,K)) - CI3 = TAUI*(CC(I,2,K)-CC(I,3,K)) - DR2 = CR2-CI3 - DR3 = CR2+CI3 - DI2 = CI2+CR3 - DI3 = CI2-CR3 - CH(I,K,2) = WA1(I-1)*DI2+WA1(I)*DR2 - CH(I-1,K,2) = WA1(I-1)*DR2-WA1(I)*DI2 - CH(I,K,3) = WA2(I-1)*DI3+WA2(I)*DR3 - CH(I-1,K,3) = WA2(I-1)*DR3-WA2(I)*DI3 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSB4 (IDO,L1,CC,CH,WA1,WA2,WA3) - DIMENSION CC(IDO,4,L1) ,CH(IDO,L1,4) , - 1 WA1(*) ,WA2(*) ,WA3(*) - IF (IDO .NE. 2) GO TO 102 - DO 101 K=1,L1 - TI1 = CC(2,1,K)-CC(2,3,K) - TI2 = CC(2,1,K)+CC(2,3,K) - TR4 = CC(2,4,K)-CC(2,2,K) - TI3 = CC(2,2,K)+CC(2,4,K) - TR1 = CC(1,1,K)-CC(1,3,K) - TR2 = CC(1,1,K)+CC(1,3,K) - TI4 = CC(1,2,K)-CC(1,4,K) - TR3 = CC(1,2,K)+CC(1,4,K) - CH(1,K,1) = TR2+TR3 - CH(1,K,3) = TR2-TR3 - CH(2,K,1) = TI2+TI3 - CH(2,K,3) = TI2-TI3 - CH(1,K,2) = TR1+TR4 - CH(1,K,4) = TR1-TR4 - CH(2,K,2) = TI1+TI4 - CH(2,K,4) = TI1-TI4 - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - TI1 = CC(I,1,K)-CC(I,3,K) - TI2 = CC(I,1,K)+CC(I,3,K) - TI3 = CC(I,2,K)+CC(I,4,K) - TR4 = CC(I,4,K)-CC(I,2,K) - TR1 = CC(I-1,1,K)-CC(I-1,3,K) - TR2 = CC(I-1,1,K)+CC(I-1,3,K) - TI4 = CC(I-1,2,K)-CC(I-1,4,K) - TR3 = CC(I-1,2,K)+CC(I-1,4,K) - CH(I-1,K,1) = TR2+TR3 - CR3 = TR2-TR3 - CH(I,K,1) = TI2+TI3 - CI3 = TI2-TI3 - CR2 = TR1+TR4 - CR4 = TR1-TR4 - CI2 = TI1+TI4 - CI4 = TI1-TI4 - CH(I-1,K,2) = WA1(I-1)*CR2-WA1(I)*CI2 - CH(I,K,2) = WA1(I-1)*CI2+WA1(I)*CR2 - CH(I-1,K,3) = WA2(I-1)*CR3-WA2(I)*CI3 - CH(I,K,3) = WA2(I-1)*CI3+WA2(I)*CR3 - CH(I-1,K,4) = WA3(I-1)*CR4-WA3(I)*CI4 - CH(I,K,4) = WA3(I-1)*CI4+WA3(I)*CR4 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSB5 (IDO,L1,CC,CH,WA1,WA2,WA3,WA4) - DIMENSION CC(IDO,5,L1) ,CH(IDO,L1,5) , - 1 WA1(*) ,WA2(*) ,WA3(*) ,WA4(*) - DATA TR11,TI11,TR12,TI12 /.309016994374947,.951056516295154, - 1-.809016994374947,.587785252292473/ - IF (IDO .NE. 2) GO TO 102 - DO 101 K=1,L1 - TI5 = CC(2,2,K)-CC(2,5,K) - TI2 = CC(2,2,K)+CC(2,5,K) - TI4 = CC(2,3,K)-CC(2,4,K) - TI3 = CC(2,3,K)+CC(2,4,K) - TR5 = CC(1,2,K)-CC(1,5,K) - TR2 = CC(1,2,K)+CC(1,5,K) - TR4 = CC(1,3,K)-CC(1,4,K) - TR3 = CC(1,3,K)+CC(1,4,K) - CH(1,K,1) = CC(1,1,K)+TR2+TR3 - CH(2,K,1) = CC(2,1,K)+TI2+TI3 - CR2 = CC(1,1,K)+TR11*TR2+TR12*TR3 - CI2 = CC(2,1,K)+TR11*TI2+TR12*TI3 - CR3 = CC(1,1,K)+TR12*TR2+TR11*TR3 - CI3 = CC(2,1,K)+TR12*TI2+TR11*TI3 - CR5 = TI11*TR5+TI12*TR4 - CI5 = TI11*TI5+TI12*TI4 - CR4 = TI12*TR5-TI11*TR4 - CI4 = TI12*TI5-TI11*TI4 - CH(1,K,2) = CR2-CI5 - CH(1,K,5) = CR2+CI5 - CH(2,K,2) = CI2+CR5 - CH(2,K,3) = CI3+CR4 - CH(1,K,3) = CR3-CI4 - CH(1,K,4) = CR3+CI4 - CH(2,K,4) = CI3-CR4 - CH(2,K,5) = CI2-CR5 - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - TI5 = CC(I,2,K)-CC(I,5,K) - TI2 = CC(I,2,K)+CC(I,5,K) - TI4 = CC(I,3,K)-CC(I,4,K) - TI3 = CC(I,3,K)+CC(I,4,K) - TR5 = CC(I-1,2,K)-CC(I-1,5,K) - TR2 = CC(I-1,2,K)+CC(I-1,5,K) - TR4 = CC(I-1,3,K)-CC(I-1,4,K) - TR3 = CC(I-1,3,K)+CC(I-1,4,K) - CH(I-1,K,1) = CC(I-1,1,K)+TR2+TR3 - CH(I,K,1) = CC(I,1,K)+TI2+TI3 - CR2 = CC(I-1,1,K)+TR11*TR2+TR12*TR3 - CI2 = CC(I,1,K)+TR11*TI2+TR12*TI3 - CR3 = CC(I-1,1,K)+TR12*TR2+TR11*TR3 - CI3 = CC(I,1,K)+TR12*TI2+TR11*TI3 - CR5 = TI11*TR5+TI12*TR4 - CI5 = TI11*TI5+TI12*TI4 - CR4 = TI12*TR5-TI11*TR4 - CI4 = TI12*TI5-TI11*TI4 - DR3 = CR3-CI4 - DR4 = CR3+CI4 - DI3 = CI3+CR4 - DI4 = CI3-CR4 - DR5 = CR2+CI5 - DR2 = CR2-CI5 - DI5 = CI2-CR5 - DI2 = CI2+CR5 - CH(I-1,K,2) = WA1(I-1)*DR2-WA1(I)*DI2 - CH(I,K,2) = WA1(I-1)*DI2+WA1(I)*DR2 - CH(I-1,K,3) = WA2(I-1)*DR3-WA2(I)*DI3 - CH(I,K,3) = WA2(I-1)*DI3+WA2(I)*DR3 - CH(I-1,K,4) = WA3(I-1)*DR4-WA3(I)*DI4 - CH(I,K,4) = WA3(I-1)*DI4+WA3(I)*DR4 - CH(I-1,K,5) = WA4(I-1)*DR5-WA4(I)*DI5 - CH(I,K,5) = WA4(I-1)*DI5+WA4(I)*DR5 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSB (NAC,IDO,IP,L1,IDL1,CC,C1,C2,CH,CH2,WA) - DIMENSION CH(IDO,L1,IP) ,CC(IDO,IP,L1) , - 1 C1(IDO,L1,IP) ,WA(*) ,C2(IDL1,IP), - 2 CH2(IDL1,IP) - IDOT = IDO/2 - NT = IP*IDL1 - IPP2 = IP+2 - IPPH = (IP+1)/2 - IDP = IP*IDO -C - IF (IDO .LT. L1) GO TO 106 - DO 103 J=2,IPPH - JC = IPP2-J - DO 102 K=1,L1 - DO 101 I=1,IDO - CH(I,K,J) = CC(I,J,K)+CC(I,JC,K) - CH(I,K,JC) = CC(I,J,K)-CC(I,JC,K) - 101 CONTINUE - 102 CONTINUE - 103 CONTINUE - DO 105 K=1,L1 - DO 104 I=1,IDO - CH(I,K,1) = CC(I,1,K) - 104 CONTINUE - 105 CONTINUE - GO TO 112 - 106 DO 109 J=2,IPPH - JC = IPP2-J - DO 108 I=1,IDO - DO 107 K=1,L1 - CH(I,K,J) = CC(I,J,K)+CC(I,JC,K) - CH(I,K,JC) = CC(I,J,K)-CC(I,JC,K) - 107 CONTINUE - 108 CONTINUE - 109 CONTINUE - DO 111 I=1,IDO - DO 110 K=1,L1 - CH(I,K,1) = CC(I,1,K) - 110 CONTINUE - 111 CONTINUE - 112 IDL = 2-IDO - INC = 0 - DO 116 L=2,IPPH - LC = IPP2-L - IDL = IDL+IDO - DO 113 IK=1,IDL1 - C2(IK,L) = CH2(IK,1)+WA(IDL-1)*CH2(IK,2) - C2(IK,LC) = WA(IDL)*CH2(IK,IP) - 113 CONTINUE - IDLJ = IDL - INC = INC+IDO - DO 115 J=3,IPPH - JC = IPP2-J - IDLJ = IDLJ+INC - IF (IDLJ .GT. IDP) IDLJ = IDLJ-IDP - WAR = WA(IDLJ-1) - WAI = WA(IDLJ) - DO 114 IK=1,IDL1 - C2(IK,L) = C2(IK,L)+WAR*CH2(IK,J) - C2(IK,LC) = C2(IK,LC)+WAI*CH2(IK,JC) - 114 CONTINUE - 115 CONTINUE - 116 CONTINUE - DO 118 J=2,IPPH - DO 117 IK=1,IDL1 - CH2(IK,1) = CH2(IK,1)+CH2(IK,J) - 117 CONTINUE - 118 CONTINUE - DO 120 J=2,IPPH - JC = IPP2-J - DO 119 IK=2,IDL1,2 - CH2(IK-1,J) = C2(IK-1,J)-C2(IK,JC) - CH2(IK-1,JC) = C2(IK-1,J)+C2(IK,JC) - CH2(IK,J) = C2(IK,J)+C2(IK-1,JC) - CH2(IK,JC) = C2(IK,J)-C2(IK-1,JC) - 119 CONTINUE - 120 CONTINUE - NAC = 1 - IF (IDO .EQ. 2) RETURN - NAC = 0 - DO 121 IK=1,IDL1 - C2(IK,1) = CH2(IK,1) - 121 CONTINUE - DO 123 J=2,IP - DO 122 K=1,L1 - C1(1,K,J) = CH(1,K,J) - C1(2,K,J) = CH(2,K,J) - 122 CONTINUE - 123 CONTINUE - IF (IDOT .GT. L1) GO TO 127 - IDIJ = 0 - DO 126 J=2,IP - IDIJ = IDIJ+2 - DO 125 I=4,IDO,2 - IDIJ = IDIJ+2 - DO 124 K=1,L1 - C1(I-1,K,J) = WA(IDIJ-1)*CH(I-1,K,J)-WA(IDIJ)*CH(I,K,J) - C1(I,K,J) = WA(IDIJ-1)*CH(I,K,J)+WA(IDIJ)*CH(I-1,K,J) - 124 CONTINUE - 125 CONTINUE - 126 CONTINUE - RETURN - 127 IDJ = 2-IDO - DO 130 J=2,IP - IDJ = IDJ+IDO - DO 129 K=1,L1 - IDIJ = IDJ - DO 128 I=4,IDO,2 - IDIJ = IDIJ+2 - C1(I-1,K,J) = WA(IDIJ-1)*CH(I-1,K,J)-WA(IDIJ)*CH(I,K,J) - C1(I,K,J) = WA(IDIJ-1)*CH(I,K,J)+WA(IDIJ)*CH(I-1,K,J) - 128 CONTINUE - 129 CONTINUE - 130 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cfftb1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftb1.f) Deleted: trunk/scipy/fftpack/src/fftpack/cfftf.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftf.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cfftf.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,8 +0,0 @@ - SUBROUTINE CFFTF (N,C,WSAVE) - DIMENSION C(*) ,WSAVE(*) - IF (N .EQ. 1) RETURN - IW1 = N+N+1 - IW2 = IW1+N+N - CALL CFFTF1 (N,C,WSAVE,WSAVE(IW1),WSAVE(IW2)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cfftf.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftf.f) Deleted: trunk/scipy/fftpack/src/fftpack/cfftf1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftf1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cfftf1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,368 +0,0 @@ - SUBROUTINE CFFTF1 (N,C,CH,WA,IFAC) - DIMENSION CH(*) ,C(*) ,WA(*) ,IFAC(*) - NF = IFAC(2) - NA = 0 - L1 = 1 - IW = 1 - DO 116 K1=1,NF - IP = IFAC(K1+2) - L2 = IP*L1 - IDO = N/L2 - IDOT = IDO+IDO - IDL1 = IDOT*L1 - IF (IP .NE. 4) GO TO 103 - IX2 = IW+IDOT - IX3 = IX2+IDOT - IF (NA .NE. 0) GO TO 101 - CALL PASSF4 (IDOT,L1,C,CH,WA(IW),WA(IX2),WA(IX3)) - GO TO 102 - 101 CALL PASSF4 (IDOT,L1,CH,C,WA(IW),WA(IX2),WA(IX3)) - 102 NA = 1-NA - GO TO 115 - 103 IF (IP .NE. 2) GO TO 106 - IF (NA .NE. 0) GO TO 104 - CALL PASSF2 (IDOT,L1,C,CH,WA(IW)) - GO TO 105 - 104 CALL PASSF2 (IDOT,L1,CH,C,WA(IW)) - 105 NA = 1-NA - GO TO 115 - 106 IF (IP .NE. 3) GO TO 109 - IX2 = IW+IDOT - IF (NA .NE. 0) GO TO 107 - CALL PASSF3 (IDOT,L1,C,CH,WA(IW),WA(IX2)) - GO TO 108 - 107 CALL PASSF3 (IDOT,L1,CH,C,WA(IW),WA(IX2)) - 108 NA = 1-NA - GO TO 115 - 109 IF (IP .NE. 5) GO TO 112 - IX2 = IW+IDOT - IX3 = IX2+IDOT - IX4 = IX3+IDOT - IF (NA .NE. 0) GO TO 110 - CALL PASSF5 (IDOT,L1,C,CH,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - GO TO 111 - 110 CALL PASSF5 (IDOT,L1,CH,C,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - 111 NA = 1-NA - GO TO 115 - 112 IF (NA .NE. 0) GO TO 113 - CALL PASSF (NAC,IDOT,IP,L1,IDL1,C,C,C,CH,CH,WA(IW)) - GO TO 114 - 113 CALL PASSF (NAC,IDOT,IP,L1,IDL1,CH,CH,CH,C,C,WA(IW)) - 114 IF (NAC .NE. 0) NA = 1-NA - 115 L1 = L2 - IW = IW+(IP-1)*IDOT - 116 CONTINUE - IF (NA .EQ. 0) RETURN - N2 = N+N - DO 117 I=1,N2 - C(I) = CH(I) - 117 CONTINUE - RETURN - END - SUBROUTINE PASSF2 (IDO,L1,CC,CH,WA1) - DIMENSION CC(IDO,2,L1) ,CH(IDO,L1,2) , - 1 WA1(*) - IF (IDO .GT. 2) GO TO 102 - DO 101 K=1,L1 - CH(1,K,1) = CC(1,1,K)+CC(1,2,K) - CH(1,K,2) = CC(1,1,K)-CC(1,2,K) - CH(2,K,1) = CC(2,1,K)+CC(2,2,K) - CH(2,K,2) = CC(2,1,K)-CC(2,2,K) - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - CH(I-1,K,1) = CC(I-1,1,K)+CC(I-1,2,K) - TR2 = CC(I-1,1,K)-CC(I-1,2,K) - CH(I,K,1) = CC(I,1,K)+CC(I,2,K) - TI2 = CC(I,1,K)-CC(I,2,K) - CH(I,K,2) = WA1(I-1)*TI2-WA1(I)*TR2 - CH(I-1,K,2) = WA1(I-1)*TR2+WA1(I)*TI2 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSF3 (IDO,L1,CC,CH,WA1,WA2) - DIMENSION CC(IDO,3,L1) ,CH(IDO,L1,3) , - 1 WA1(*) ,WA2(*) - DATA TAUR,TAUI /-.5,-.866025403784439/ - IF (IDO .NE. 2) GO TO 102 - DO 101 K=1,L1 - TR2 = CC(1,2,K)+CC(1,3,K) - CR2 = CC(1,1,K)+TAUR*TR2 - CH(1,K,1) = CC(1,1,K)+TR2 - TI2 = CC(2,2,K)+CC(2,3,K) - CI2 = CC(2,1,K)+TAUR*TI2 - CH(2,K,1) = CC(2,1,K)+TI2 - CR3 = TAUI*(CC(1,2,K)-CC(1,3,K)) - CI3 = TAUI*(CC(2,2,K)-CC(2,3,K)) - CH(1,K,2) = CR2-CI3 - CH(1,K,3) = CR2+CI3 - CH(2,K,2) = CI2+CR3 - CH(2,K,3) = CI2-CR3 - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - TR2 = CC(I-1,2,K)+CC(I-1,3,K) - CR2 = CC(I-1,1,K)+TAUR*TR2 - CH(I-1,K,1) = CC(I-1,1,K)+TR2 - TI2 = CC(I,2,K)+CC(I,3,K) - CI2 = CC(I,1,K)+TAUR*TI2 - CH(I,K,1) = CC(I,1,K)+TI2 - CR3 = TAUI*(CC(I-1,2,K)-CC(I-1,3,K)) - CI3 = TAUI*(CC(I,2,K)-CC(I,3,K)) - DR2 = CR2-CI3 - DR3 = CR2+CI3 - DI2 = CI2+CR3 - DI3 = CI2-CR3 - CH(I,K,2) = WA1(I-1)*DI2-WA1(I)*DR2 - CH(I-1,K,2) = WA1(I-1)*DR2+WA1(I)*DI2 - CH(I,K,3) = WA2(I-1)*DI3-WA2(I)*DR3 - CH(I-1,K,3) = WA2(I-1)*DR3+WA2(I)*DI3 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSF4 (IDO,L1,CC,CH,WA1,WA2,WA3) - DIMENSION CC(IDO,4,L1) ,CH(IDO,L1,4) , - 1 WA1(*) ,WA2(*) ,WA3(*) - IF (IDO .NE. 2) GO TO 102 - DO 101 K=1,L1 - TI1 = CC(2,1,K)-CC(2,3,K) - TI2 = CC(2,1,K)+CC(2,3,K) - TR4 = CC(2,2,K)-CC(2,4,K) - TI3 = CC(2,2,K)+CC(2,4,K) - TR1 = CC(1,1,K)-CC(1,3,K) - TR2 = CC(1,1,K)+CC(1,3,K) - TI4 = CC(1,4,K)-CC(1,2,K) - TR3 = CC(1,2,K)+CC(1,4,K) - CH(1,K,1) = TR2+TR3 - CH(1,K,3) = TR2-TR3 - CH(2,K,1) = TI2+TI3 - CH(2,K,3) = TI2-TI3 - CH(1,K,2) = TR1+TR4 - CH(1,K,4) = TR1-TR4 - CH(2,K,2) = TI1+TI4 - CH(2,K,4) = TI1-TI4 - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - TI1 = CC(I,1,K)-CC(I,3,K) - TI2 = CC(I,1,K)+CC(I,3,K) - TI3 = CC(I,2,K)+CC(I,4,K) - TR4 = CC(I,2,K)-CC(I,4,K) - TR1 = CC(I-1,1,K)-CC(I-1,3,K) - TR2 = CC(I-1,1,K)+CC(I-1,3,K) - TI4 = CC(I-1,4,K)-CC(I-1,2,K) - TR3 = CC(I-1,2,K)+CC(I-1,4,K) - CH(I-1,K,1) = TR2+TR3 - CR3 = TR2-TR3 - CH(I,K,1) = TI2+TI3 - CI3 = TI2-TI3 - CR2 = TR1+TR4 - CR4 = TR1-TR4 - CI2 = TI1+TI4 - CI4 = TI1-TI4 - CH(I-1,K,2) = WA1(I-1)*CR2+WA1(I)*CI2 - CH(I,K,2) = WA1(I-1)*CI2-WA1(I)*CR2 - CH(I-1,K,3) = WA2(I-1)*CR3+WA2(I)*CI3 - CH(I,K,3) = WA2(I-1)*CI3-WA2(I)*CR3 - CH(I-1,K,4) = WA3(I-1)*CR4+WA3(I)*CI4 - CH(I,K,4) = WA3(I-1)*CI4-WA3(I)*CR4 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSF5 (IDO,L1,CC,CH,WA1,WA2,WA3,WA4) - DIMENSION CC(IDO,5,L1) ,CH(IDO,L1,5) , - 1 WA1(*) ,WA2(*) ,WA3(*) ,WA4(*) - DATA TR11,TI11,TR12,TI12 /.309016994374947,-.951056516295154, - 1-.809016994374947,-.587785252292473/ - IF (IDO .NE. 2) GO TO 102 - DO 101 K=1,L1 - TI5 = CC(2,2,K)-CC(2,5,K) - TI2 = CC(2,2,K)+CC(2,5,K) - TI4 = CC(2,3,K)-CC(2,4,K) - TI3 = CC(2,3,K)+CC(2,4,K) - TR5 = CC(1,2,K)-CC(1,5,K) - TR2 = CC(1,2,K)+CC(1,5,K) - TR4 = CC(1,3,K)-CC(1,4,K) - TR3 = CC(1,3,K)+CC(1,4,K) - CH(1,K,1) = CC(1,1,K)+TR2+TR3 - CH(2,K,1) = CC(2,1,K)+TI2+TI3 - CR2 = CC(1,1,K)+TR11*TR2+TR12*TR3 - CI2 = CC(2,1,K)+TR11*TI2+TR12*TI3 - CR3 = CC(1,1,K)+TR12*TR2+TR11*TR3 - CI3 = CC(2,1,K)+TR12*TI2+TR11*TI3 - CR5 = TI11*TR5+TI12*TR4 - CI5 = TI11*TI5+TI12*TI4 - CR4 = TI12*TR5-TI11*TR4 - CI4 = TI12*TI5-TI11*TI4 - CH(1,K,2) = CR2-CI5 - CH(1,K,5) = CR2+CI5 - CH(2,K,2) = CI2+CR5 - CH(2,K,3) = CI3+CR4 - CH(1,K,3) = CR3-CI4 - CH(1,K,4) = CR3+CI4 - CH(2,K,4) = CI3-CR4 - CH(2,K,5) = CI2-CR5 - 101 CONTINUE - RETURN - 102 DO 104 K=1,L1 - DO 103 I=2,IDO,2 - TI5 = CC(I,2,K)-CC(I,5,K) - TI2 = CC(I,2,K)+CC(I,5,K) - TI4 = CC(I,3,K)-CC(I,4,K) - TI3 = CC(I,3,K)+CC(I,4,K) - TR5 = CC(I-1,2,K)-CC(I-1,5,K) - TR2 = CC(I-1,2,K)+CC(I-1,5,K) - TR4 = CC(I-1,3,K)-CC(I-1,4,K) - TR3 = CC(I-1,3,K)+CC(I-1,4,K) - CH(I-1,K,1) = CC(I-1,1,K)+TR2+TR3 - CH(I,K,1) = CC(I,1,K)+TI2+TI3 - CR2 = CC(I-1,1,K)+TR11*TR2+TR12*TR3 - CI2 = CC(I,1,K)+TR11*TI2+TR12*TI3 - CR3 = CC(I-1,1,K)+TR12*TR2+TR11*TR3 - CI3 = CC(I,1,K)+TR12*TI2+TR11*TI3 - CR5 = TI11*TR5+TI12*TR4 - CI5 = TI11*TI5+TI12*TI4 - CR4 = TI12*TR5-TI11*TR4 - CI4 = TI12*TI5-TI11*TI4 - DR3 = CR3-CI4 - DR4 = CR3+CI4 - DI3 = CI3+CR4 - DI4 = CI3-CR4 - DR5 = CR2+CI5 - DR2 = CR2-CI5 - DI5 = CI2-CR5 - DI2 = CI2+CR5 - CH(I-1,K,2) = WA1(I-1)*DR2+WA1(I)*DI2 - CH(I,K,2) = WA1(I-1)*DI2-WA1(I)*DR2 - CH(I-1,K,3) = WA2(I-1)*DR3+WA2(I)*DI3 - CH(I,K,3) = WA2(I-1)*DI3-WA2(I)*DR3 - CH(I-1,K,4) = WA3(I-1)*DR4+WA3(I)*DI4 - CH(I,K,4) = WA3(I-1)*DI4-WA3(I)*DR4 - CH(I-1,K,5) = WA4(I-1)*DR5+WA4(I)*DI5 - CH(I,K,5) = WA4(I-1)*DI5-WA4(I)*DR5 - 103 CONTINUE - 104 CONTINUE - RETURN - END - SUBROUTINE PASSF (NAC,IDO,IP,L1,IDL1,CC,C1,C2,CH,CH2,WA) - DIMENSION CH(IDO,L1,IP) ,CC(IDO,IP,L1) , - 1 C1(IDO,L1,IP) ,WA(*) ,C2(IDL1,IP), - 2 CH2(IDL1,IP) - IDOT = IDO/2 - NT = IP*IDL1 - IPP2 = IP+2 - IPPH = (IP+1)/2 - IDP = IP*IDO -C - IF (IDO .LT. L1) GO TO 106 - DO 103 J=2,IPPH - JC = IPP2-J - DO 102 K=1,L1 - DO 101 I=1,IDO - CH(I,K,J) = CC(I,J,K)+CC(I,JC,K) - CH(I,K,JC) = CC(I,J,K)-CC(I,JC,K) - 101 CONTINUE - 102 CONTINUE - 103 CONTINUE - DO 105 K=1,L1 - DO 104 I=1,IDO - CH(I,K,1) = CC(I,1,K) - 104 CONTINUE - 105 CONTINUE - GO TO 112 - 106 DO 109 J=2,IPPH - JC = IPP2-J - DO 108 I=1,IDO - DO 107 K=1,L1 - CH(I,K,J) = CC(I,J,K)+CC(I,JC,K) - CH(I,K,JC) = CC(I,J,K)-CC(I,JC,K) - 107 CONTINUE - 108 CONTINUE - 109 CONTINUE - DO 111 I=1,IDO - DO 110 K=1,L1 - CH(I,K,1) = CC(I,1,K) - 110 CONTINUE - 111 CONTINUE - 112 IDL = 2-IDO - INC = 0 - DO 116 L=2,IPPH - LC = IPP2-L - IDL = IDL+IDO - DO 113 IK=1,IDL1 - C2(IK,L) = CH2(IK,1)+WA(IDL-1)*CH2(IK,2) - C2(IK,LC) = -WA(IDL)*CH2(IK,IP) - 113 CONTINUE - IDLJ = IDL - INC = INC+IDO - DO 115 J=3,IPPH - JC = IPP2-J - IDLJ = IDLJ+INC - IF (IDLJ .GT. IDP) IDLJ = IDLJ-IDP - WAR = WA(IDLJ-1) - WAI = WA(IDLJ) - DO 114 IK=1,IDL1 - C2(IK,L) = C2(IK,L)+WAR*CH2(IK,J) - C2(IK,LC) = C2(IK,LC)-WAI*CH2(IK,JC) - 114 CONTINUE - 115 CONTINUE - 116 CONTINUE - DO 118 J=2,IPPH - DO 117 IK=1,IDL1 - CH2(IK,1) = CH2(IK,1)+CH2(IK,J) - 117 CONTINUE - 118 CONTINUE - DO 120 J=2,IPPH - JC = IPP2-J - DO 119 IK=2,IDL1,2 - CH2(IK-1,J) = C2(IK-1,J)-C2(IK,JC) - CH2(IK-1,JC) = C2(IK-1,J)+C2(IK,JC) - CH2(IK,J) = C2(IK,J)+C2(IK-1,JC) - CH2(IK,JC) = C2(IK,J)-C2(IK-1,JC) - 119 CONTINUE - 120 CONTINUE - NAC = 1 - IF (IDO .EQ. 2) RETURN - NAC = 0 - DO 121 IK=1,IDL1 - C2(IK,1) = CH2(IK,1) - 121 CONTINUE - DO 123 J=2,IP - DO 122 K=1,L1 - C1(1,K,J) = CH(1,K,J) - C1(2,K,J) = CH(2,K,J) - 122 CONTINUE - 123 CONTINUE - IF (IDOT .GT. L1) GO TO 127 - IDIJ = 0 - DO 126 J=2,IP - IDIJ = IDIJ+2 - DO 125 I=4,IDO,2 - IDIJ = IDIJ+2 - DO 124 K=1,L1 - C1(I-1,K,J) = WA(IDIJ-1)*CH(I-1,K,J)+WA(IDIJ)*CH(I,K,J) - C1(I,K,J) = WA(IDIJ-1)*CH(I,K,J)-WA(IDIJ)*CH(I-1,K,J) - 124 CONTINUE - 125 CONTINUE - 126 CONTINUE - RETURN - 127 IDJ = 2-IDO - DO 130 J=2,IP - IDJ = IDJ+IDO - DO 129 K=1,L1 - IDIJ = IDJ - DO 128 I=4,IDO,2 - IDIJ = IDIJ+2 - C1(I-1,K,J) = WA(IDIJ-1)*CH(I-1,K,J)+WA(IDIJ)*CH(I,K,J) - C1(I,K,J) = WA(IDIJ-1)*CH(I,K,J)-WA(IDIJ)*CH(I-1,K,J) - 128 CONTINUE - 129 CONTINUE - 130 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cfftf1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cfftf1.f) Deleted: trunk/scipy/fftpack/src/fftpack/cffti.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cffti.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cffti.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,8 +0,0 @@ - SUBROUTINE CFFTI (N,WSAVE) - DIMENSION WSAVE(*) - IF (N .EQ. 1) RETURN - IW1 = N+N+1 - IW2 = IW1+N+N - CALL CFFTI1 (N,WSAVE(IW1),WSAVE(IW2)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cffti.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cffti.f) Deleted: trunk/scipy/fftpack/src/fftpack/cffti1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cffti1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cffti1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,62 +0,0 @@ - SUBROUTINE CFFTI1 (N,WA,IFAC) - DIMENSION WA(*) ,IFAC(*) ,NTRYH(4) - DATA NTRYH(1),NTRYH(2),NTRYH(3),NTRYH(4)/3,4,2,5/ - NL = N - NF = 0 - J = 0 - 101 J = J+1 - IF (J.le.4) GO TO 102 - GO TO 103 - 102 NTRY = NTRYH(J) - GO TO 104 - 103 NTRY = NTRY+2 - 104 NQ = NL/NTRY - NR = NL-NTRY*NQ - IF (NR.eq.0) GO TO 105 - GO TO 101 - 105 NF = NF+1 - IFAC(NF+2) = NTRY - NL = NQ - IF (NTRY .NE. 2) GO TO 107 - IF (NF .EQ. 1) GO TO 107 - DO 106 I=2,NF - IB = NF-I+2 - IFAC(IB+2) = IFAC(IB+1) - 106 CONTINUE - IFAC(3) = 2 - 107 IF (NL .NE. 1) GO TO 104 - IFAC(1) = N - IFAC(2) = NF - TPI = 6.28318530717959 - ARGH = TPI/FLOAT(N) - I = 2 - L1 = 1 - DO 110 K1=1,NF - IP = IFAC(K1+2) - LD = 0 - L2 = L1*IP - IDO = N/L2 - IDOT = IDO+IDO+2 - IPM = IP-1 - DO 109 J=1,IPM - I1 = I - WA(I-1) = 1. - WA(I) = 0. - LD = LD+L1 - FI = 0. - ARGLD = FLOAT(LD)*ARGH - DO 108 II=4,IDOT,2 - I = I+2 - FI = FI+1. - ARG = FI*ARGLD - WA(I-1) = COS(ARG) - WA(I) = SIN(ARG) - 108 CONTINUE - IF (IP .LE. 5) GO TO 109 - WA(I1-1) = WA(I-1) - WA(I1) = WA(I) - 109 CONTINUE - L1 = L2 - 110 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cffti1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cffti1.f) Deleted: trunk/scipy/fftpack/src/fftpack/cosqb.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cosqb.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cosqb.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,42 +0,0 @@ - SUBROUTINE COSQB (N,X,WSAVE) - DIMENSION X(*) ,WSAVE(*) - DATA TSQRT2 /2.82842712474619/ - IF (N.lt.2) GO TO 101 - IF (N.eq.2) GO TO 102 - GO TO 103 - 101 X(1) = 4.*X(1) - RETURN - 102 X1 = 4.*(X(1)+X(2)) - X(2) = TSQRT2*(X(1)-X(2)) - X(1) = X1 - RETURN - 103 CALL COSQB1 (N,X,WSAVE,WSAVE(N+1)) - RETURN - END - SUBROUTINE COSQB1 (N,X,W,XH) - DIMENSION X(1) ,W(1) ,XH(1) - NS2 = (N+1)/2 - NP2 = N+2 - DO 101 I=3,N,2 - XIM1 = X(I-1)+X(I) - X(I) = X(I)-X(I-1) - X(I-1) = XIM1 - 101 CONTINUE - X(1) = X(1)+X(1) - MODN = MOD(N,2) - IF (MODN .EQ. 0) X(N) = X(N)+X(N) - CALL RFFTB (N,X,XH) - DO 102 K=2,NS2 - KC = NP2-K - XH(K) = W(K-1)*X(KC)+W(KC-1)*X(K) - XH(KC) = W(K-1)*X(K)-W(KC-1)*X(KC) - 102 CONTINUE - IF (MODN .EQ. 0) X(NS2+1) = W(NS2)*(X(NS2+1)+X(NS2+1)) - DO 103 K=2,NS2 - KC = NP2-K - X(K) = XH(K)+XH(KC) - X(KC) = XH(K)-XH(KC) - 103 CONTINUE - X(1) = X(1)+X(1) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cosqb.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cosqb.f) Deleted: trunk/scipy/fftpack/src/fftpack/cosqf.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cosqf.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cosqf.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,38 +0,0 @@ - SUBROUTINE COSQF (N,X,WSAVE) - DIMENSION X(*) ,WSAVE(*) - DATA SQRT2 /1.4142135623731/ - IF (N.lt.2) GO TO 102 - IF (N.eq.2) GO TO 101 - GO TO 103 - 101 TSQX = SQRT2*X(2) - X(2) = X(1)-TSQX - X(1) = X(1)+TSQX - 102 RETURN - 103 CALL COSQF1 (N,X,WSAVE,WSAVE(N+1)) - RETURN - END - SUBROUTINE COSQF1 (N,X,W,XH) - DIMENSION X(1) ,W(1) ,XH(1) - NS2 = (N+1)/2 - NP2 = N+2 - DO 101 K=2,NS2 - KC = NP2-K - XH(K) = X(K)+X(KC) - XH(KC) = X(K)-X(KC) - 101 CONTINUE - MODN = MOD(N,2) - IF (MODN .EQ. 0) XH(NS2+1) = X(NS2+1)+X(NS2+1) - DO 102 K=2,NS2 - KC = NP2-K - X(K) = W(K-1)*XH(KC)+W(KC-1)*XH(K) - X(KC) = W(K-1)*XH(K)-W(KC-1)*XH(KC) - 102 CONTINUE - IF (MODN .EQ. 0) X(NS2+1) = W(NS2)*XH(NS2+1) - CALL RFFTF (N,X,XH) - DO 103 I=3,N,2 - XIM1 = X(I-1)-X(I) - X(I) = X(I-1)+X(I) - X(I-1) = XIM1 - 103 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cosqf.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cosqf.f) Deleted: trunk/scipy/fftpack/src/fftpack/cosqi.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cosqi.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cosqi.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,12 +0,0 @@ - SUBROUTINE COSQI (N,WSAVE) - DIMENSION WSAVE(*) - DATA PIH /1.57079632679491/ - DT = PIH/FLOAT(N) - FK = 0. - DO 101 K=1,N - FK = FK+1. - WSAVE(K) = COS(FK*DT) - 101 CONTINUE - CALL RFFTI (N,WSAVE(N+1)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cosqi.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cosqi.f) Deleted: trunk/scipy/fftpack/src/fftpack/cost.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/cost.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/cost.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,44 +0,0 @@ - SUBROUTINE COST (N,X,WSAVE) - DIMENSION X(*) ,WSAVE(*) - NM1 = N-1 - NP1 = N+1 - NS2 = N/2 - IF (N.lt.2) GO TO 106 - IF (N.eq.2) GO TO 101 - GO TO 102 - 101 X1H = X(1)+X(2) - X(2) = X(1)-X(2) - X(1) = X1H - RETURN - 102 IF (N .GT. 3) GO TO 103 - X1P3 = X(1)+X(3) - TX2 = X(2)+X(2) - X(2) = X(1)-X(3) - X(1) = X1P3+TX2 - X(3) = X1P3-TX2 - RETURN - 103 C1 = X(1)-X(N) - X(1) = X(1)+X(N) - DO 104 K=2,NS2 - KC = NP1-K - T1 = X(K)+X(KC) - T2 = X(K)-X(KC) - C1 = C1+WSAVE(KC)*T2 - T2 = WSAVE(K)*T2 - X(K) = T1-T2 - X(KC) = T1+T2 - 104 CONTINUE - MODN = MOD(N,2) - IF (MODN .NE. 0) X(NS2+1) = X(NS2+1)+X(NS2+1) - CALL RFFTF (NM1,X,WSAVE(N+1)) - XIM2 = X(2) - X(2) = C1 - DO 105 I=4,N,2 - XI = X(I) - X(I) = X(I-2)-X(I-1) - X(I-1) = XIM2 - XIM2 = XI - 105 CONTINUE - IF (MODN .NE. 0) X(N) = XIM2 - 106 RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/cost.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/cost.f) Deleted: trunk/scipy/fftpack/src/fftpack/costi.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/costi.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/costi.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,18 +0,0 @@ - SUBROUTINE COSTI (N,WSAVE) - DIMENSION WSAVE(*) - DATA PI /3.14159265358979/ - IF (N .LE. 3) RETURN - NM1 = N-1 - NP1 = N+1 - NS2 = N/2 - DT = PI/FLOAT(NM1) - FK = 0. - DO 101 K=2,NS2 - KC = NP1-K - FK = FK+1. - WSAVE(K) = 2.*SIN(FK*DT) - WSAVE(KC) = 2.*COS(FK*DT) - 101 CONTINUE - CALL RFFTI (NM1,WSAVE(N+1)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/costi.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/costi.f) Deleted: trunk/scipy/fftpack/src/fftpack/doc =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/doc 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/doc 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,866 +0,0 @@ - - FFTPACK - -* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - - version 4 april 1985 - - a package of fortran subprograms for the fast fourier - transform of periodic and other symmetric sequences - - by - - paul n swarztrauber - - national center for atmospheric research boulder,colorado 80307 - - which is sponsored by the national science foundation - -* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - - -this package consists of programs which perform fast fourier -transforms for both complex and real periodic sequences and -certain other symmetric sequences that are listed below. - -1. rffti initialize rfftf and rfftb -2. rfftf forward transform of a real periodic sequence -3. rfftb backward transform of a real coefficient array - -4. ezffti initialize ezfftf and ezfftb -5. ezfftf a simplified real periodic forward transform -6. ezfftb a simplified real periodic backward transform - -7. sinti initialize sint -8. sint sine transform of a real odd sequence - -9. costi initialize cost -10. cost cosine transform of a real even sequence - -11. sinqi initialize sinqf and sinqb -12. sinqf forward sine transform with odd wave numbers -13. sinqb unnormalized inverse of sinqf - -14. cosqi initialize cosqf and cosqb -15. cosqf forward cosine transform with odd wave numbers -16. cosqb unnormalized inverse of cosqf - -17. cffti initialize cfftf and cfftb -18. cfftf forward transform of a complex periodic sequence -19. cfftb unnormalized inverse of cfftf - - -****************************************************************** - -subroutine rffti(n,wsave) - - **************************************************************** - -subroutine rffti initializes the array wsave which is used in -both rfftf and rfftb. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the sequence to be transformed. - -output parameter - -wsave a work array which must be dimensioned at least 2*n+15. - the same work array can be used for both rfftf and rfftb - as long as n remains unchanged. different wsave arrays - are required for different values of n. the contents of - wsave must not be changed between calls of rfftf or rfftb. - -****************************************************************** - -subroutine rfftf(n,r,wsave) - -****************************************************************** - -subroutine rfftf computes the fourier coefficients of a real -perodic sequence (fourier analysis). the transform is defined -below at output parameter r. - -input parameters - -n the length of the array r to be transformed. the method - is most efficient when n is a product of small primes. - n may change so long as different work arrays are provided - -r a real array of length n which contains the sequence - to be transformed - -wsave a work array which must be dimensioned at least 2*n+15. - in the program that calls rfftf. the wsave array must be - initialized by calling subroutine rffti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - the same wsave array can be used by rfftf and rfftb. - - -output parameters - -r r(1) = the sum from i=1 to i=n of r(i) - - if n is even set l =n/2 , if n is odd set l = (n+1)/2 - - then for k = 2,...,l - - r(2*k-2) = the sum from i = 1 to i = n of - - r(i)*cos((k-1)*(i-1)*2*pi/n) - - r(2*k-1) = the sum from i = 1 to i = n of - - -r(i)*sin((k-1)*(i-1)*2*pi/n) - - if n is even - - r(n) = the sum from i = 1 to i = n of - - (-1)**(i-1)*r(i) - - ***** note - this transform is unnormalized since a call of rfftf - followed by a call of rfftb will multiply the input - sequence by n. - -wsave contains results which must not be destroyed between - calls of rfftf or rfftb. - - -****************************************************************** - -subroutine rfftb(n,r,wsave) - -****************************************************************** - -subroutine rfftb computes the real perodic sequence from its -fourier coefficients (fourier synthesis). the transform is defined -below at output parameter r. - -input parameters - -n the length of the array r to be transformed. the method - is most efficient when n is a product of small primes. - n may change so long as different work arrays are provided - -r a real array of length n which contains the sequence - to be transformed - -wsave a work array which must be dimensioned at least 2*n+15. - in the program that calls rfftb. the wsave array must be - initialized by calling subroutine rffti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - the same wsave array can be used by rfftf and rfftb. - - -output parameters - -r for n even and for i = 1,...,n - - r(i) = r(1)+(-1)**(i-1)*r(n) - - plus the sum from k=2 to k=n/2 of - - 2.*r(2*k-2)*cos((k-1)*(i-1)*2*pi/n) - - -2.*r(2*k-1)*sin((k-1)*(i-1)*2*pi/n) - - for n odd and for i = 1,...,n - - r(i) = r(1) plus the sum from k=2 to k=(n+1)/2 of - - 2.*r(2*k-2)*cos((k-1)*(i-1)*2*pi/n) - - -2.*r(2*k-1)*sin((k-1)*(i-1)*2*pi/n) - - ***** note - this transform is unnormalized since a call of rfftf - followed by a call of rfftb will multiply the input - sequence by n. - -wsave contains results which must not be destroyed between - calls of rfftb or rfftf. - - -****************************************************************** - -subroutine ezffti(n,wsave) - -****************************************************************** - -subroutine ezffti initializes the array wsave which is used in -both ezfftf and ezfftb. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the sequence to be transformed. - -output parameter - -wsave a work array which must be dimensioned at least 3*n+15. - the same work array can be used for both ezfftf and ezfftb - as long as n remains unchanged. different wsave arrays - are required for different values of n. - - -****************************************************************** - -subroutine ezfftf(n,r,azero,a,b,wsave) - -****************************************************************** - -subroutine ezfftf computes the fourier coefficients of a real -perodic sequence (fourier analysis). the transform is defined -below at output parameters azero,a and b. ezfftf is a simplified -but slower version of rfftf. - -input parameters - -n the length of the array r to be transformed. the method - is must efficient when n is the product of small primes. - -r a real array of length n which contains the sequence - to be transformed. r is not destroyed. - - -wsave a work array which must be dimensioned at least 3*n+15. - in the program that calls ezfftf. the wsave array must be - initialized by calling subroutine ezffti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - the same wsave array can be used by ezfftf and ezfftb. - -output parameters - -azero the sum from i=1 to i=n of r(i)/n - -a,b for n even b(n/2)=0. and a(n/2) is the sum from i=1 to - i=n of (-1)**(i-1)*r(i)/n - - for n even define kmax=n/2-1 - for n odd define kmax=(n-1)/2 - - then for k=1,...,kmax - - a(k) equals the sum from i=1 to i=n of - - 2./n*r(i)*cos(k*(i-1)*2*pi/n) - - b(k) equals the sum from i=1 to i=n of - - 2./n*r(i)*sin(k*(i-1)*2*pi/n) - - -****************************************************************** - -subroutine ezfftb(n,r,azero,a,b,wsave) - -****************************************************************** - -subroutine ezfftb computes a real perodic sequence from its -fourier coefficients (fourier synthesis). the transform is -defined below at output parameter r. ezfftb is a simplified -but slower version of rfftb. - -input parameters - -n the length of the output array r. the method is most - efficient when n is the product of small primes. - -azero the constant fourier coefficient - -a,b arrays which contain the remaining fourier coefficients - these arrays are not destroyed. - - the length of these arrays depends on whether n is even or - odd. - - if n is even n/2 locations are required - if n is odd (n-1)/2 locations are required - -wsave a work array which must be dimensioned at least 3*n+15. - in the program that calls ezfftb. the wsave array must be - initialized by calling subroutine ezffti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - the same wsave array can be used by ezfftf and ezfftb. - - -output parameters - -r if n is even define kmax=n/2 - if n is odd define kmax=(n-1)/2 - - then for i=1,...,n - - r(i)=azero plus the sum from k=1 to k=kmax of - - a(k)*cos(k*(i-1)*2*pi/n)+b(k)*sin(k*(i-1)*2*pi/n) - -********************* complex notation ************************** - - for j=1,...,n - - r(j) equals the sum from k=-kmax to k=kmax of - - c(k)*exp(i*k*(j-1)*2*pi/n) - - where - - c(k) = .5*cmplx(a(k),-b(k)) for k=1,...,kmax - - c(-k) = conjg(c(k)) - - c(0) = azero - - and i=sqrt(-1) - -*************** amplitude - phase notation *********************** - - for i=1,...,n - - r(i) equals azero plus the sum from k=1 to k=kmax of - - alpha(k)*cos(k*(i-1)*2*pi/n+beta(k)) - - where - - alpha(k) = sqrt(a(k)*a(k)+b(k)*b(k)) - - cos(beta(k))=a(k)/alpha(k) - - sin(beta(k))=-b(k)/alpha(k) - -****************************************************************** - -subroutine sinti(n,wsave) - -****************************************************************** - -subroutine sinti initializes the array wsave which is used in -subroutine sint. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the sequence to be transformed. the method - is most efficient when n+1 is a product of small primes. - -output parameter - -wsave a work array with at least int(2.5*n+15) locations. - different wsave arrays are required for different values - of n. the contents of wsave must not be changed between - calls of sint. - -****************************************************************** - -subroutine sint(n,x,wsave) - -****************************************************************** - -subroutine sint computes the discrete fourier sine transform -of an odd sequence x(i). the transform is defined below at -output parameter x. - -sint is the unnormalized inverse of itself since a call of sint -followed by another call of sint will multiply the input sequence -x by 2*(n+1). - -the array wsave which is used by subroutine sint must be -initialized by calling subroutine sinti(n,wsave). - -input parameters - -n the length of the sequence to be transformed. the method - is most efficient when n+1 is the product of small primes. - -x an array which contains the sequence to be transformed - - -wsave a work array with dimension at least int(2.5*n+15) - in the program that calls sint. the wsave array must be - initialized by calling subroutine sinti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - -output parameters - -x for i=1,...,n - - x(i)= the sum from k=1 to k=n - - 2*x(k)*sin(k*i*pi/(n+1)) - - a call of sint followed by another call of - sint will multiply the sequence x by 2*(n+1). - hence sint is the unnormalized inverse - of itself. - -wsave contains initialization calculations which must not be - destroyed between calls of sint. - -****************************************************************** - -subroutine costi(n,wsave) - -****************************************************************** - -subroutine costi initializes the array wsave which is used in -subroutine cost. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the sequence to be transformed. the method - is most efficient when n-1 is a product of small primes. - -output parameter - -wsave a work array which must be dimensioned at least 3*n+15. - different wsave arrays are required for different values - of n. the contents of wsave must not be changed between - calls of cost. - -****************************************************************** - -subroutine cost(n,x,wsave) - -****************************************************************** - -subroutine cost computes the discrete fourier cosine transform -of an even sequence x(i). the transform is defined below at output -parameter x. - -cost is the unnormalized inverse of itself since a call of cost -followed by another call of cost will multiply the input sequence -x by 2*(n-1). the transform is defined below at output parameter x - -the array wsave which is used by subroutine cost must be -initialized by calling subroutine costi(n,wsave). - -input parameters - -n the length of the sequence x. n must be greater than 1. - the method is most efficient when n-1 is a product of - small primes. - -x an array which contains the sequence to be transformed - -wsave a work array which must be dimensioned at least 3*n+15 - in the program that calls cost. the wsave array must be - initialized by calling subroutine costi(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - -output parameters - -x for i=1,...,n - - x(i) = x(1)+(-1)**(i-1)*x(n) - - + the sum from k=2 to k=n-1 - - 2*x(k)*cos((k-1)*(i-1)*pi/(n-1)) - - a call of cost followed by another call of - cost will multiply the sequence x by 2*(n-1) - hence cost is the unnormalized inverse - of itself. - -wsave contains initialization calculations which must not be - destroyed between calls of cost. - -****************************************************************** - -subroutine sinqi(n,wsave) - -****************************************************************** - -subroutine sinqi initializes the array wsave which is used in -both sinqf and sinqb. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the sequence to be transformed. the method - is most efficient when n is a product of small primes. - -output parameter - -wsave a work array which must be dimensioned at least 3*n+15. - the same work array can be used for both sinqf and sinqb - as long as n remains unchanged. different wsave arrays - are required for different values of n. the contents of - wsave must not be changed between calls of sinqf or sinqb. - -****************************************************************** - -subroutine sinqf(n,x,wsave) - -****************************************************************** - -subroutine sinqf computes the fast fourier transform of quarter -wave data. that is , sinqf computes the coefficients in a sine -series representation with only odd wave numbers. the transform -is defined below at output parameter x. - -sinqb is the unnormalized inverse of sinqf since a call of sinqf -followed by a call of sinqb will multiply the input sequence x -by 4*n. - -the array wsave which is used by subroutine sinqf must be -initialized by calling subroutine sinqi(n,wsave). - - -input parameters - -n the length of the array x to be transformed. the method - is most efficient when n is a product of small primes. - -x an array which contains the sequence to be transformed - -wsave a work array which must be dimensioned at least 3*n+15. - in the program that calls sinqf. the wsave array must be - initialized by calling subroutine sinqi(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - -output parameters - -x for i=1,...,n - - x(i) = (-1)**(i-1)*x(n) - - + the sum from k=1 to k=n-1 of - - 2*x(k)*sin((2*i-1)*k*pi/(2*n)) - - a call of sinqf followed by a call of - sinqb will multiply the sequence x by 4*n. - therefore sinqb is the unnormalized inverse - of sinqf. - -wsave contains initialization calculations which must not - be destroyed between calls of sinqf or sinqb. - -****************************************************************** - -subroutine sinqb(n,x,wsave) - -****************************************************************** - -subroutine sinqb computes the fast fourier transform of quarter -wave data. that is , sinqb computes a sequence from its -representation in terms of a sine series with odd wave numbers. -the transform is defined below at output parameter x. - -sinqf is the unnormalized inverse of sinqb since a call of sinqb -followed by a call of sinqf will multiply the input sequence x -by 4*n. - -the array wsave which is used by subroutine sinqb must be -initialized by calling subroutine sinqi(n,wsave). - - -input parameters - -n the length of the array x to be transformed. the method - is most efficient when n is a product of small primes. - -x an array which contains the sequence to be transformed - -wsave a work array which must be dimensioned at least 3*n+15. - in the program that calls sinqb. the wsave array must be - initialized by calling subroutine sinqi(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - -output parameters - -x for i=1,...,n - - x(i)= the sum from k=1 to k=n of - - 4*x(k)*sin((2k-1)*i*pi/(2*n)) - - a call of sinqb followed by a call of - sinqf will multiply the sequence x by 4*n. - therefore sinqf is the unnormalized inverse - of sinqb. - -wsave contains initialization calculations which must not - be destroyed between calls of sinqb or sinqf. - -****************************************************************** - -subroutine cosqi(n,wsave) - -****************************************************************** - -subroutine cosqi initializes the array wsave which is used in -both cosqf and cosqb. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the array to be transformed. the method - is most efficient when n is a product of small primes. - -output parameter - -wsave a work array which must be dimensioned at least 3*n+15. - the same work array can be used for both cosqf and cosqb - as long as n remains unchanged. different wsave arrays - are required for different values of n. the contents of - wsave must not be changed between calls of cosqf or cosqb. - -****************************************************************** - -subroutine cosqf(n,x,wsave) - -****************************************************************** - -subroutine cosqf computes the fast fourier transform of quarter -wave data. that is , cosqf computes the coefficients in a cosine -series representation with only odd wave numbers. the transform -is defined below at output parameter x - -cosqf is the unnormalized inverse of cosqb since a call of cosqf -followed by a call of cosqb will multiply the input sequence x -by 4*n. - -the array wsave which is used by subroutine cosqf must be -initialized by calling subroutine cosqi(n,wsave). - - -input parameters - -n the length of the array x to be transformed. the method - is most efficient when n is a product of small primes. - -x an array which contains the sequence to be transformed - -wsave a work array which must be dimensioned at least 3*n+15 - in the program that calls cosqf. the wsave array must be - initialized by calling subroutine cosqi(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - -output parameters - -x for i=1,...,n - - x(i) = x(1) plus the sum from k=2 to k=n of - - 2*x(k)*cos((2*i-1)*(k-1)*pi/(2*n)) - - a call of cosqf followed by a call of - cosqb will multiply the sequence x by 4*n. - therefore cosqb is the unnormalized inverse - of cosqf. - -wsave contains initialization calculations which must not - be destroyed between calls of cosqf or cosqb. - -****************************************************************** - -subroutine cosqb(n,x,wsave) - -****************************************************************** - -subroutine cosqb computes the fast fourier transform of quarter -wave data. that is , cosqb computes a sequence from its -representation in terms of a cosine series with odd wave numbers. -the transform is defined below at output parameter x. - -cosqb is the unnormalized inverse of cosqf since a call of cosqb -followed by a call of cosqf will multiply the input sequence x -by 4*n. - -the array wsave which is used by subroutine cosqb must be -initialized by calling subroutine cosqi(n,wsave). - - -input parameters - -n the length of the array x to be transformed. the method - is most efficient when n is a product of small primes. - -x an array which contains the sequence to be transformed - -wsave a work array that must be dimensioned at least 3*n+15 - in the program that calls cosqb. the wsave array must be - initialized by calling subroutine cosqi(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - -output parameters - -x for i=1,...,n - - x(i)= the sum from k=1 to k=n of - - 4*x(k)*cos((2*k-1)*(i-1)*pi/(2*n)) - - a call of cosqb followed by a call of - cosqf will multiply the sequence x by 4*n. - therefore cosqf is the unnormalized inverse - of cosqb. - -wsave contains initialization calculations which must not - be destroyed between calls of cosqb or cosqf. - -****************************************************************** - -subroutine cffti(n,wsave) - -****************************************************************** - -subroutine cffti initializes the array wsave which is used in -both cfftf and cfftb. the prime factorization of n together with -a tabulation of the trigonometric functions are computed and -stored in wsave. - -input parameter - -n the length of the sequence to be transformed - -output parameter - -wsave a work array which must be dimensioned at least 4*n+15 - the same work array can be used for both cfftf and cfftb - as long as n remains unchanged. different wsave arrays - are required for different values of n. the contents of - wsave must not be changed between calls of cfftf or cfftb. - -****************************************************************** - -subroutine cfftf(n,c,wsave) - -****************************************************************** - -subroutine cfftf computes the forward complex discrete fourier -transform (the fourier analysis). equivalently , cfftf computes -the fourier coefficients of a complex periodic sequence. -the transform is defined below at output parameter c. - -the transform is not normalized. to obtain a normalized transform -the output must be divided by n. otherwise a call of cfftf -followed by a call of cfftb will multiply the sequence by n. - -the array wsave which is used by subroutine cfftf must be -initialized by calling subroutine cffti(n,wsave). - -input parameters - - -n the length of the complex sequence c. the method is - more efficient when n is the product of small primes. n - -c a complex array of length n which contains the sequence - -wsave a real work array which must be dimensioned at least 4n+15 - in the program that calls cfftf. the wsave array must be - initialized by calling subroutine cffti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - the same wsave array can be used by cfftf and cfftb. - -output parameters - -c for j=1,...,n - - c(j)=the sum from k=1,...,n of - - c(k)*exp(-i*(j-1)*(k-1)*2*pi/n) - - where i=sqrt(-1) - -wsave contains initialization calculations which must not be - destroyed between calls of subroutine cfftf or cfftb - -****************************************************************** - -subroutine cfftb(n,c,wsave) - -****************************************************************** - -subroutine cfftb computes the backward complex discrete fourier -transform (the fourier synthesis). equivalently , cfftb computes -a complex periodic sequence from its fourier coefficients. -the transform is defined below at output parameter c. - -a call of cfftf followed by a call of cfftb will multiply the -sequence by n. - -the array wsave which is used by subroutine cfftb must be -initialized by calling subroutine cffti(n,wsave). - -input parameters - - -n the length of the complex sequence c. the method is - more efficient when n is the product of small primes. - -c a complex array of length n which contains the sequence - -wsave a real work array which must be dimensioned at least 4n+15 - in the program that calls cfftb. the wsave array must be - initialized by calling subroutine cffti(n,wsave) and a - different wsave array must be used for each different - value of n. this initialization does not have to be - repeated so long as n remains unchanged thus subsequent - transforms can be obtained faster than the first. - the same wsave array can be used by cfftf and cfftb. - -output parameters - -c for j=1,...,n - - c(j)=the sum from k=1,...,n of - - c(k)*exp(i*(j-1)*(k-1)*2*pi/n) - - where i=sqrt(-1) - -wsave contains initialization calculations which must not be - destroyed between calls of subroutine cfftf or cfftb - - - -["send index for vfftpk" describes a vectorized version of fftpack] - Copied: trunk/scipy/fftpack/src/fftpack/doc (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/doc) Deleted: trunk/scipy/fftpack/src/fftpack/rfftb.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftb.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/rfftb.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,6 +0,0 @@ - SUBROUTINE RFFTB (N,R,WSAVE) - DIMENSION R(*) ,WSAVE(*) - IF (N .EQ. 1) RETURN - CALL RFFTB1 (N,R,WSAVE,WSAVE(N+1),WSAVE(2*N+1)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/rfftb.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftb.f) Deleted: trunk/scipy/fftpack/src/fftpack/rfftb1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftb1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/rfftb1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,407 +0,0 @@ - SUBROUTINE RFFTB1 (N,C,CH,WA,IFAC) - DIMENSION CH(*) ,C(*) ,WA(*) ,IFAC(*) - NF = IFAC(2) - NA = 0 - L1 = 1 - IW = 1 - DO 116 K1=1,NF - IP = IFAC(K1+2) - L2 = IP*L1 - IDO = N/L2 - IDL1 = IDO*L1 - IF (IP .NE. 4) GO TO 103 - IX2 = IW+IDO - IX3 = IX2+IDO - IF (NA .NE. 0) GO TO 101 - CALL RADB4 (IDO,L1,C,CH,WA(IW),WA(IX2),WA(IX3)) - GO TO 102 - 101 CALL RADB4 (IDO,L1,CH,C,WA(IW),WA(IX2),WA(IX3)) - 102 NA = 1-NA - GO TO 115 - 103 IF (IP .NE. 2) GO TO 106 - IF (NA .NE. 0) GO TO 104 - CALL RADB2 (IDO,L1,C,CH,WA(IW)) - GO TO 105 - 104 CALL RADB2 (IDO,L1,CH,C,WA(IW)) - 105 NA = 1-NA - GO TO 115 - 106 IF (IP .NE. 3) GO TO 109 - IX2 = IW+IDO - IF (NA .NE. 0) GO TO 107 - CALL RADB3 (IDO,L1,C,CH,WA(IW),WA(IX2)) - GO TO 108 - 107 CALL RADB3 (IDO,L1,CH,C,WA(IW),WA(IX2)) - 108 NA = 1-NA - GO TO 115 - 109 IF (IP .NE. 5) GO TO 112 - IX2 = IW+IDO - IX3 = IX2+IDO - IX4 = IX3+IDO - IF (NA .NE. 0) GO TO 110 - CALL RADB5 (IDO,L1,C,CH,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - GO TO 111 - 110 CALL RADB5 (IDO,L1,CH,C,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - 111 NA = 1-NA - GO TO 115 - 112 IF (NA .NE. 0) GO TO 113 - CALL RADBG (IDO,IP,L1,IDL1,C,C,C,CH,CH,WA(IW)) - GO TO 114 - 113 CALL RADBG (IDO,IP,L1,IDL1,CH,CH,CH,C,C,WA(IW)) - 114 IF (IDO .EQ. 1) NA = 1-NA - 115 L1 = L2 - IW = IW+(IP-1)*IDO - 116 CONTINUE - IF (NA .EQ. 0) RETURN - DO 117 I=1,N - C(I) = CH(I) - 117 CONTINUE - RETURN - END - SUBROUTINE RADB2 (IDO,L1,CC,CH,WA1) - DIMENSION CC(IDO,2,L1) ,CH(IDO,L1,2) , - 1 WA1(*) - DO 101 K=1,L1 - CH(1,K,1) = CC(1,1,K)+CC(IDO,2,K) - CH(1,K,2) = CC(1,1,K)-CC(IDO,2,K) - 101 CONTINUE - IF (IDO.lt.2) GO TO 107 - IF (IDO.eq.2) GO TO 105 - GO TO 102 - 102 IDP2 = IDO+2 - DO 104 K=1,L1 - DO 103 I=3,IDO,2 - IC = IDP2-I - CH(I-1,K,1) = CC(I-1,1,K)+CC(IC-1,2,K) - TR2 = CC(I-1,1,K)-CC(IC-1,2,K) - CH(I,K,1) = CC(I,1,K)-CC(IC,2,K) - TI2 = CC(I,1,K)+CC(IC,2,K) - CH(I-1,K,2) = WA1(I-2)*TR2-WA1(I-1)*TI2 - CH(I,K,2) = WA1(I-2)*TI2+WA1(I-1)*TR2 - 103 CONTINUE - 104 CONTINUE - IF (MOD(IDO,2) .EQ. 1) RETURN - 105 DO 106 K=1,L1 - CH(IDO,K,1) = CC(IDO,1,K)+CC(IDO,1,K) - CH(IDO,K,2) = -(CC(1,2,K)+CC(1,2,K)) - 106 CONTINUE - 107 RETURN - END - SUBROUTINE RADB3 (IDO,L1,CC,CH,WA1,WA2) - DIMENSION CC(IDO,3,L1) ,CH(IDO,L1,3) , - 1 WA1(*) ,WA2(*) - DATA TAUR,TAUI /-.5,.866025403784439/ - DO 101 K=1,L1 - TR2 = CC(IDO,2,K)+CC(IDO,2,K) - CR2 = CC(1,1,K)+TAUR*TR2 - CH(1,K,1) = CC(1,1,K)+TR2 - CI3 = TAUI*(CC(1,3,K)+CC(1,3,K)) - CH(1,K,2) = CR2-CI3 - CH(1,K,3) = CR2+CI3 - 101 CONTINUE - IF (IDO .EQ. 1) RETURN - IDP2 = IDO+2 - DO 103 K=1,L1 - DO 102 I=3,IDO,2 - IC = IDP2-I - TR2 = CC(I-1,3,K)+CC(IC-1,2,K) - CR2 = CC(I-1,1,K)+TAUR*TR2 - CH(I-1,K,1) = CC(I-1,1,K)+TR2 - TI2 = CC(I,3,K)-CC(IC,2,K) - CI2 = CC(I,1,K)+TAUR*TI2 - CH(I,K,1) = CC(I,1,K)+TI2 - CR3 = TAUI*(CC(I-1,3,K)-CC(IC-1,2,K)) - CI3 = TAUI*(CC(I,3,K)+CC(IC,2,K)) - DR2 = CR2-CI3 - DR3 = CR2+CI3 - DI2 = CI2+CR3 - DI3 = CI2-CR3 - CH(I-1,K,2) = WA1(I-2)*DR2-WA1(I-1)*DI2 - CH(I,K,2) = WA1(I-2)*DI2+WA1(I-1)*DR2 - CH(I-1,K,3) = WA2(I-2)*DR3-WA2(I-1)*DI3 - CH(I,K,3) = WA2(I-2)*DI3+WA2(I-1)*DR3 - 102 CONTINUE - 103 CONTINUE - RETURN - END - SUBROUTINE RADB4 (IDO,L1,CC,CH,WA1,WA2,WA3) - DIMENSION CC(IDO,4,L1) ,CH(IDO,L1,4) , - 1 WA1(*) ,WA2(*) ,WA3(*) - DATA SQRT2 /1.414213562373095/ - DO 101 K=1,L1 - TR1 = CC(1,1,K)-CC(IDO,4,K) - TR2 = CC(1,1,K)+CC(IDO,4,K) - TR3 = CC(IDO,2,K)+CC(IDO,2,K) - TR4 = CC(1,3,K)+CC(1,3,K) - CH(1,K,1) = TR2+TR3 - CH(1,K,2) = TR1-TR4 - CH(1,K,3) = TR2-TR3 - CH(1,K,4) = TR1+TR4 - 101 CONTINUE - IF (IDO.lt.2) GO TO 107 - IF (IDO.eq.2) GO TO 105 - GO TO 102 - 102 IDP2 = IDO+2 - DO 104 K=1,L1 - DO 103 I=3,IDO,2 - IC = IDP2-I - TI1 = CC(I,1,K)+CC(IC,4,K) - TI2 = CC(I,1,K)-CC(IC,4,K) - TI3 = CC(I,3,K)-CC(IC,2,K) - TR4 = CC(I,3,K)+CC(IC,2,K) - TR1 = CC(I-1,1,K)-CC(IC-1,4,K) - TR2 = CC(I-1,1,K)+CC(IC-1,4,K) - TI4 = CC(I-1,3,K)-CC(IC-1,2,K) - TR3 = CC(I-1,3,K)+CC(IC-1,2,K) - CH(I-1,K,1) = TR2+TR3 - CR3 = TR2-TR3 - CH(I,K,1) = TI2+TI3 - CI3 = TI2-TI3 - CR2 = TR1-TR4 - CR4 = TR1+TR4 - CI2 = TI1+TI4 - CI4 = TI1-TI4 - CH(I-1,K,2) = WA1(I-2)*CR2-WA1(I-1)*CI2 - CH(I,K,2) = WA1(I-2)*CI2+WA1(I-1)*CR2 - CH(I-1,K,3) = WA2(I-2)*CR3-WA2(I-1)*CI3 - CH(I,K,3) = WA2(I-2)*CI3+WA2(I-1)*CR3 - CH(I-1,K,4) = WA3(I-2)*CR4-WA3(I-1)*CI4 - CH(I,K,4) = WA3(I-2)*CI4+WA3(I-1)*CR4 - 103 CONTINUE - 104 CONTINUE - IF (MOD(IDO,2) .EQ. 1) RETURN - 105 CONTINUE - DO 106 K=1,L1 - TI1 = CC(1,2,K)+CC(1,4,K) - TI2 = CC(1,4,K)-CC(1,2,K) - TR1 = CC(IDO,1,K)-CC(IDO,3,K) - TR2 = CC(IDO,1,K)+CC(IDO,3,K) - CH(IDO,K,1) = TR2+TR2 - CH(IDO,K,2) = SQRT2*(TR1-TI1) - CH(IDO,K,3) = TI2+TI2 - CH(IDO,K,4) = -SQRT2*(TR1+TI1) - 106 CONTINUE - 107 RETURN - END - SUBROUTINE RADB5 (IDO,L1,CC,CH,WA1,WA2,WA3,WA4) - DIMENSION CC(IDO,5,L1) ,CH(IDO,L1,5) , - 1 WA1(*) ,WA2(*) ,WA3(*) ,WA4(*) - DATA TR11,TI11,TR12,TI12 /.309016994374947,.951056516295154, - 1-.809016994374947,.587785252292473/ - DO 101 K=1,L1 - TI5 = CC(1,3,K)+CC(1,3,K) - TI4 = CC(1,5,K)+CC(1,5,K) - TR2 = CC(IDO,2,K)+CC(IDO,2,K) - TR3 = CC(IDO,4,K)+CC(IDO,4,K) - CH(1,K,1) = CC(1,1,K)+TR2+TR3 - CR2 = CC(1,1,K)+TR11*TR2+TR12*TR3 - CR3 = CC(1,1,K)+TR12*TR2+TR11*TR3 - CI5 = TI11*TI5+TI12*TI4 - CI4 = TI12*TI5-TI11*TI4 - CH(1,K,2) = CR2-CI5 - CH(1,K,3) = CR3-CI4 - CH(1,K,4) = CR3+CI4 - CH(1,K,5) = CR2+CI5 - 101 CONTINUE - IF (IDO .EQ. 1) RETURN - IDP2 = IDO+2 - DO 103 K=1,L1 - DO 102 I=3,IDO,2 - IC = IDP2-I - TI5 = CC(I,3,K)+CC(IC,2,K) - TI2 = CC(I,3,K)-CC(IC,2,K) - TI4 = CC(I,5,K)+CC(IC,4,K) - TI3 = CC(I,5,K)-CC(IC,4,K) - TR5 = CC(I-1,3,K)-CC(IC-1,2,K) - TR2 = CC(I-1,3,K)+CC(IC-1,2,K) - TR4 = CC(I-1,5,K)-CC(IC-1,4,K) - TR3 = CC(I-1,5,K)+CC(IC-1,4,K) - CH(I-1,K,1) = CC(I-1,1,K)+TR2+TR3 - CH(I,K,1) = CC(I,1,K)+TI2+TI3 - CR2 = CC(I-1,1,K)+TR11*TR2+TR12*TR3 - CI2 = CC(I,1,K)+TR11*TI2+TR12*TI3 - CR3 = CC(I-1,1,K)+TR12*TR2+TR11*TR3 - CI3 = CC(I,1,K)+TR12*TI2+TR11*TI3 - CR5 = TI11*TR5+TI12*TR4 - CI5 = TI11*TI5+TI12*TI4 - CR4 = TI12*TR5-TI11*TR4 - CI4 = TI12*TI5-TI11*TI4 - DR3 = CR3-CI4 - DR4 = CR3+CI4 - DI3 = CI3+CR4 - DI4 = CI3-CR4 - DR5 = CR2+CI5 - DR2 = CR2-CI5 - DI5 = CI2-CR5 - DI2 = CI2+CR5 - CH(I-1,K,2) = WA1(I-2)*DR2-WA1(I-1)*DI2 - CH(I,K,2) = WA1(I-2)*DI2+WA1(I-1)*DR2 - CH(I-1,K,3) = WA2(I-2)*DR3-WA2(I-1)*DI3 - CH(I,K,3) = WA2(I-2)*DI3+WA2(I-1)*DR3 - CH(I-1,K,4) = WA3(I-2)*DR4-WA3(I-1)*DI4 - CH(I,K,4) = WA3(I-2)*DI4+WA3(I-1)*DR4 - CH(I-1,K,5) = WA4(I-2)*DR5-WA4(I-1)*DI5 - CH(I,K,5) = WA4(I-2)*DI5+WA4(I-1)*DR5 - 102 CONTINUE - 103 CONTINUE - RETURN - END - SUBROUTINE RADBG (IDO,IP,L1,IDL1,CC,C1,C2,CH,CH2,WA) - DIMENSION CH(IDO,L1,IP) ,CC(IDO,IP,L1) , - 1 C1(IDO,L1,IP) ,C2(IDL1,IP), - 2 CH2(IDL1,IP) ,WA(*) - DATA TPI/6.28318530717959/ - ARG = TPI/FLOAT(IP) - DCP = COS(ARG) - DSP = SIN(ARG) - IDP2 = IDO+2 - NBD = (IDO-1)/2 - IPP2 = IP+2 - IPPH = (IP+1)/2 - IF (IDO .LT. L1) GO TO 103 - DO 102 K=1,L1 - DO 101 I=1,IDO - CH(I,K,1) = CC(I,1,K) - 101 CONTINUE - 102 CONTINUE - GO TO 106 - 103 DO 105 I=1,IDO - DO 104 K=1,L1 - CH(I,K,1) = CC(I,1,K) - 104 CONTINUE - 105 CONTINUE - 106 DO 108 J=2,IPPH - JC = IPP2-J - J2 = J+J - DO 107 K=1,L1 - CH(1,K,J) = CC(IDO,J2-2,K)+CC(IDO,J2-2,K) - CH(1,K,JC) = CC(1,J2-1,K)+CC(1,J2-1,K) - 107 CONTINUE - 108 CONTINUE - IF (IDO .EQ. 1) GO TO 116 - IF (NBD .LT. L1) GO TO 112 - DO 111 J=2,IPPH - JC = IPP2-J - DO 110 K=1,L1 - DO 109 I=3,IDO,2 - IC = IDP2-I - CH(I-1,K,J) = CC(I-1,2*J-1,K)+CC(IC-1,2*J-2,K) - CH(I-1,K,JC) = CC(I-1,2*J-1,K)-CC(IC-1,2*J-2,K) - CH(I,K,J) = CC(I,2*J-1,K)-CC(IC,2*J-2,K) - CH(I,K,JC) = CC(I,2*J-1,K)+CC(IC,2*J-2,K) - 109 CONTINUE - 110 CONTINUE - 111 CONTINUE - GO TO 116 - 112 DO 115 J=2,IPPH - JC = IPP2-J - DO 114 I=3,IDO,2 - IC = IDP2-I - DO 113 K=1,L1 - CH(I-1,K,J) = CC(I-1,2*J-1,K)+CC(IC-1,2*J-2,K) - CH(I-1,K,JC) = CC(I-1,2*J-1,K)-CC(IC-1,2*J-2,K) - CH(I,K,J) = CC(I,2*J-1,K)-CC(IC,2*J-2,K) - CH(I,K,JC) = CC(I,2*J-1,K)+CC(IC,2*J-2,K) - 113 CONTINUE - 114 CONTINUE - 115 CONTINUE - 116 AR1 = 1. - AI1 = 0. - DO 120 L=2,IPPH - LC = IPP2-L - AR1H = DCP*AR1-DSP*AI1 - AI1 = DCP*AI1+DSP*AR1 - AR1 = AR1H - DO 117 IK=1,IDL1 - C2(IK,L) = CH2(IK,1)+AR1*CH2(IK,2) - C2(IK,LC) = AI1*CH2(IK,IP) - 117 CONTINUE - DC2 = AR1 - DS2 = AI1 - AR2 = AR1 - AI2 = AI1 - DO 119 J=3,IPPH - JC = IPP2-J - AR2H = DC2*AR2-DS2*AI2 - AI2 = DC2*AI2+DS2*AR2 - AR2 = AR2H - DO 118 IK=1,IDL1 - C2(IK,L) = C2(IK,L)+AR2*CH2(IK,J) - C2(IK,LC) = C2(IK,LC)+AI2*CH2(IK,JC) - 118 CONTINUE - 119 CONTINUE - 120 CONTINUE - DO 122 J=2,IPPH - DO 121 IK=1,IDL1 - CH2(IK,1) = CH2(IK,1)+CH2(IK,J) - 121 CONTINUE - 122 CONTINUE - DO 124 J=2,IPPH - JC = IPP2-J - DO 123 K=1,L1 - CH(1,K,J) = C1(1,K,J)-C1(1,K,JC) - CH(1,K,JC) = C1(1,K,J)+C1(1,K,JC) - 123 CONTINUE - 124 CONTINUE - IF (IDO .EQ. 1) GO TO 132 - IF (NBD .LT. L1) GO TO 128 - DO 127 J=2,IPPH - JC = IPP2-J - DO 126 K=1,L1 - DO 125 I=3,IDO,2 - CH(I-1,K,J) = C1(I-1,K,J)-C1(I,K,JC) - CH(I-1,K,JC) = C1(I-1,K,J)+C1(I,K,JC) - CH(I,K,J) = C1(I,K,J)+C1(I-1,K,JC) - CH(I,K,JC) = C1(I,K,J)-C1(I-1,K,JC) - 125 CONTINUE - 126 CONTINUE - 127 CONTINUE - GO TO 132 - 128 DO 131 J=2,IPPH - JC = IPP2-J - DO 130 I=3,IDO,2 - DO 129 K=1,L1 - CH(I-1,K,J) = C1(I-1,K,J)-C1(I,K,JC) - CH(I-1,K,JC) = C1(I-1,K,J)+C1(I,K,JC) - CH(I,K,J) = C1(I,K,J)+C1(I-1,K,JC) - CH(I,K,JC) = C1(I,K,J)-C1(I-1,K,JC) - 129 CONTINUE - 130 CONTINUE - 131 CONTINUE - 132 CONTINUE - IF (IDO .EQ. 1) RETURN - DO 133 IK=1,IDL1 - C2(IK,1) = CH2(IK,1) - 133 CONTINUE - DO 135 J=2,IP - DO 134 K=1,L1 - C1(1,K,J) = CH(1,K,J) - 134 CONTINUE - 135 CONTINUE - IF (NBD .GT. L1) GO TO 139 - IS = -IDO - DO 138 J=2,IP - IS = IS+IDO - IDIJ = IS - DO 137 I=3,IDO,2 - IDIJ = IDIJ+2 - DO 136 K=1,L1 - C1(I-1,K,J) = WA(IDIJ-1)*CH(I-1,K,J)-WA(IDIJ)*CH(I,K,J) - C1(I,K,J) = WA(IDIJ-1)*CH(I,K,J)+WA(IDIJ)*CH(I-1,K,J) - 136 CONTINUE - 137 CONTINUE - 138 CONTINUE - GO TO 143 - 139 IS = -IDO - DO 142 J=2,IP - IS = IS+IDO - DO 141 K=1,L1 - IDIJ = IS - DO 140 I=3,IDO,2 - IDIJ = IDIJ+2 - C1(I-1,K,J) = WA(IDIJ-1)*CH(I-1,K,J)-WA(IDIJ)*CH(I,K,J) - C1(I,K,J) = WA(IDIJ-1)*CH(I,K,J)+WA(IDIJ)*CH(I-1,K,J) - 140 CONTINUE - 141 CONTINUE - 142 CONTINUE - 143 RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/rfftb1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftb1.f) Deleted: trunk/scipy/fftpack/src/fftpack/rfftf.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftf.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/rfftf.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,6 +0,0 @@ - SUBROUTINE RFFTF (N,R,WSAVE) - DIMENSION R(*) ,WSAVE(*) - IF (N .EQ. 1) RETURN - CALL RFFTF1 (N,R,WSAVE,WSAVE(N+1),WSAVE(2*N+1)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/rfftf.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftf.f) Deleted: trunk/scipy/fftpack/src/fftpack/rfftf1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftf1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/rfftf1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,403 +0,0 @@ - SUBROUTINE RFFTF1 (N,C,CH,WA,IFAC) - DIMENSION CH(*) ,C(*) ,WA(*) ,IFAC(*) - NF = IFAC(2) - NA = 1 - L2 = N - IW = N - DO 111 K1=1,NF - KH = NF-K1 - IP = IFAC(KH+3) - L1 = L2/IP - IDO = N/L2 - IDL1 = IDO*L1 - IW = IW-(IP-1)*IDO - NA = 1-NA - IF (IP .NE. 4) GO TO 102 - IX2 = IW+IDO - IX3 = IX2+IDO - IF (NA .NE. 0) GO TO 101 - CALL RADF4 (IDO,L1,C,CH,WA(IW),WA(IX2),WA(IX3)) - GO TO 110 - 101 CALL RADF4 (IDO,L1,CH,C,WA(IW),WA(IX2),WA(IX3)) - GO TO 110 - 102 IF (IP .NE. 2) GO TO 104 - IF (NA .NE. 0) GO TO 103 - CALL RADF2 (IDO,L1,C,CH,WA(IW)) - GO TO 110 - 103 CALL RADF2 (IDO,L1,CH,C,WA(IW)) - GO TO 110 - 104 IF (IP .NE. 3) GO TO 106 - IX2 = IW+IDO - IF (NA .NE. 0) GO TO 105 - CALL RADF3 (IDO,L1,C,CH,WA(IW),WA(IX2)) - GO TO 110 - 105 CALL RADF3 (IDO,L1,CH,C,WA(IW),WA(IX2)) - GO TO 110 - 106 IF (IP .NE. 5) GO TO 108 - IX2 = IW+IDO - IX3 = IX2+IDO - IX4 = IX3+IDO - IF (NA .NE. 0) GO TO 107 - CALL RADF5 (IDO,L1,C,CH,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - GO TO 110 - 107 CALL RADF5 (IDO,L1,CH,C,WA(IW),WA(IX2),WA(IX3),WA(IX4)) - GO TO 110 - 108 IF (IDO .EQ. 1) NA = 1-NA - IF (NA .NE. 0) GO TO 109 - CALL RADFG (IDO,IP,L1,IDL1,C,C,C,CH,CH,WA(IW)) - NA = 1 - GO TO 110 - 109 CALL RADFG (IDO,IP,L1,IDL1,CH,CH,CH,C,C,WA(IW)) - NA = 0 - 110 L2 = L1 - 111 CONTINUE - IF (NA .EQ. 1) RETURN - DO 112 I=1,N - C(I) = CH(I) - 112 CONTINUE - RETURN - END - SUBROUTINE RADF2 (IDO,L1,CC,CH,WA1) - DIMENSION CH(IDO,2,L1) ,CC(IDO,L1,2) , - 1 WA1(*) - DO 101 K=1,L1 - CH(1,1,K) = CC(1,K,1)+CC(1,K,2) - CH(IDO,2,K) = CC(1,K,1)-CC(1,K,2) - 101 CONTINUE - IF (IDO.lt.2) GO TO 107 - IF (IDO.eq.2) GO TO 105 - GO TO 102 - 102 IDP2 = IDO+2 - DO 104 K=1,L1 - DO 103 I=3,IDO,2 - IC = IDP2-I - TR2 = WA1(I-2)*CC(I-1,K,2)+WA1(I-1)*CC(I,K,2) - TI2 = WA1(I-2)*CC(I,K,2)-WA1(I-1)*CC(I-1,K,2) - CH(I,1,K) = CC(I,K,1)+TI2 - CH(IC,2,K) = TI2-CC(I,K,1) - CH(I-1,1,K) = CC(I-1,K,1)+TR2 - CH(IC-1,2,K) = CC(I-1,K,1)-TR2 - 103 CONTINUE - 104 CONTINUE - IF (MOD(IDO,2) .EQ. 1) RETURN - 105 DO 106 K=1,L1 - CH(1,2,K) = -CC(IDO,K,2) - CH(IDO,1,K) = CC(IDO,K,1) - 106 CONTINUE - 107 RETURN - END - SUBROUTINE RADF3 (IDO,L1,CC,CH,WA1,WA2) - DIMENSION CH(IDO,3,L1) ,CC(IDO,L1,3) , - 1 WA1(*) ,WA2(*) - DATA TAUR,TAUI /-.5,.866025403784439/ - DO 101 K=1,L1 - CR2 = CC(1,K,2)+CC(1,K,3) - CH(1,1,K) = CC(1,K,1)+CR2 - CH(1,3,K) = TAUI*(CC(1,K,3)-CC(1,K,2)) - CH(IDO,2,K) = CC(1,K,1)+TAUR*CR2 - 101 CONTINUE - IF (IDO .EQ. 1) RETURN - IDP2 = IDO+2 - DO 103 K=1,L1 - DO 102 I=3,IDO,2 - IC = IDP2-I - DR2 = WA1(I-2)*CC(I-1,K,2)+WA1(I-1)*CC(I,K,2) - DI2 = WA1(I-2)*CC(I,K,2)-WA1(I-1)*CC(I-1,K,2) - DR3 = WA2(I-2)*CC(I-1,K,3)+WA2(I-1)*CC(I,K,3) - DI3 = WA2(I-2)*CC(I,K,3)-WA2(I-1)*CC(I-1,K,3) - CR2 = DR2+DR3 - CI2 = DI2+DI3 - CH(I-1,1,K) = CC(I-1,K,1)+CR2 - CH(I,1,K) = CC(I,K,1)+CI2 - TR2 = CC(I-1,K,1)+TAUR*CR2 - TI2 = CC(I,K,1)+TAUR*CI2 - TR3 = TAUI*(DI2-DI3) - TI3 = TAUI*(DR3-DR2) - CH(I-1,3,K) = TR2+TR3 - CH(IC-1,2,K) = TR2-TR3 - CH(I,3,K) = TI2+TI3 - CH(IC,2,K) = TI3-TI2 - 102 CONTINUE - 103 CONTINUE - RETURN - END - SUBROUTINE RADF4 (IDO,L1,CC,CH,WA1,WA2,WA3) - DIMENSION CC(IDO,L1,4) ,CH(IDO,4,L1) , - 1 WA1(*) ,WA2(*) ,WA3(*) - DATA HSQT2 /.7071067811865475/ - DO 101 K=1,L1 - TR1 = CC(1,K,2)+CC(1,K,4) - TR2 = CC(1,K,1)+CC(1,K,3) - CH(1,1,K) = TR1+TR2 - CH(IDO,4,K) = TR2-TR1 - CH(IDO,2,K) = CC(1,K,1)-CC(1,K,3) - CH(1,3,K) = CC(1,K,4)-CC(1,K,2) - 101 CONTINUE - IF (IDO.lt.2) GO TO 107 - IF (IDO.eq.2) GO TO 105 - GO TO 102 - 102 IDP2 = IDO+2 - DO 104 K=1,L1 - DO 103 I=3,IDO,2 - IC = IDP2-I - CR2 = WA1(I-2)*CC(I-1,K,2)+WA1(I-1)*CC(I,K,2) - CI2 = WA1(I-2)*CC(I,K,2)-WA1(I-1)*CC(I-1,K,2) - CR3 = WA2(I-2)*CC(I-1,K,3)+WA2(I-1)*CC(I,K,3) - CI3 = WA2(I-2)*CC(I,K,3)-WA2(I-1)*CC(I-1,K,3) - CR4 = WA3(I-2)*CC(I-1,K,4)+WA3(I-1)*CC(I,K,4) - CI4 = WA3(I-2)*CC(I,K,4)-WA3(I-1)*CC(I-1,K,4) - TR1 = CR2+CR4 - TR4 = CR4-CR2 - TI1 = CI2+CI4 - TI4 = CI2-CI4 - TI2 = CC(I,K,1)+CI3 - TI3 = CC(I,K,1)-CI3 - TR2 = CC(I-1,K,1)+CR3 - TR3 = CC(I-1,K,1)-CR3 - CH(I-1,1,K) = TR1+TR2 - CH(IC-1,4,K) = TR2-TR1 - CH(I,1,K) = TI1+TI2 - CH(IC,4,K) = TI1-TI2 - CH(I-1,3,K) = TI4+TR3 - CH(IC-1,2,K) = TR3-TI4 - CH(I,3,K) = TR4+TI3 - CH(IC,2,K) = TR4-TI3 - 103 CONTINUE - 104 CONTINUE - IF (MOD(IDO,2) .EQ. 1) RETURN - 105 CONTINUE - DO 106 K=1,L1 - TI1 = -HSQT2*(CC(IDO,K,2)+CC(IDO,K,4)) - TR1 = HSQT2*(CC(IDO,K,2)-CC(IDO,K,4)) - CH(IDO,1,K) = TR1+CC(IDO,K,1) - CH(IDO,3,K) = CC(IDO,K,1)-TR1 - CH(1,2,K) = TI1-CC(IDO,K,3) - CH(1,4,K) = TI1+CC(IDO,K,3) - 106 CONTINUE - 107 RETURN - END - SUBROUTINE RADF5 (IDO,L1,CC,CH,WA1,WA2,WA3,WA4) - DIMENSION CC(IDO,L1,5) ,CH(IDO,5,L1) , - 1 WA1(*) ,WA2(*) ,WA3(*) ,WA4(*) - DATA TR11,TI11,TR12,TI12 /.309016994374947,.951056516295154, - 1-.809016994374947,.587785252292473/ - DO 101 K=1,L1 - CR2 = CC(1,K,5)+CC(1,K,2) - CI5 = CC(1,K,5)-CC(1,K,2) - CR3 = CC(1,K,4)+CC(1,K,3) - CI4 = CC(1,K,4)-CC(1,K,3) - CH(1,1,K) = CC(1,K,1)+CR2+CR3 - CH(IDO,2,K) = CC(1,K,1)+TR11*CR2+TR12*CR3 - CH(1,3,K) = TI11*CI5+TI12*CI4 - CH(IDO,4,K) = CC(1,K,1)+TR12*CR2+TR11*CR3 - CH(1,5,K) = TI12*CI5-TI11*CI4 - 101 CONTINUE - IF (IDO .EQ. 1) RETURN - IDP2 = IDO+2 - DO 103 K=1,L1 - DO 102 I=3,IDO,2 - IC = IDP2-I - DR2 = WA1(I-2)*CC(I-1,K,2)+WA1(I-1)*CC(I,K,2) - DI2 = WA1(I-2)*CC(I,K,2)-WA1(I-1)*CC(I-1,K,2) - DR3 = WA2(I-2)*CC(I-1,K,3)+WA2(I-1)*CC(I,K,3) - DI3 = WA2(I-2)*CC(I,K,3)-WA2(I-1)*CC(I-1,K,3) - DR4 = WA3(I-2)*CC(I-1,K,4)+WA3(I-1)*CC(I,K,4) - DI4 = WA3(I-2)*CC(I,K,4)-WA3(I-1)*CC(I-1,K,4) - DR5 = WA4(I-2)*CC(I-1,K,5)+WA4(I-1)*CC(I,K,5) - DI5 = WA4(I-2)*CC(I,K,5)-WA4(I-1)*CC(I-1,K,5) - CR2 = DR2+DR5 - CI5 = DR5-DR2 - CR5 = DI2-DI5 - CI2 = DI2+DI5 - CR3 = DR3+DR4 - CI4 = DR4-DR3 - CR4 = DI3-DI4 - CI3 = DI3+DI4 - CH(I-1,1,K) = CC(I-1,K,1)+CR2+CR3 - CH(I,1,K) = CC(I,K,1)+CI2+CI3 - TR2 = CC(I-1,K,1)+TR11*CR2+TR12*CR3 - TI2 = CC(I,K,1)+TR11*CI2+TR12*CI3 - TR3 = CC(I-1,K,1)+TR12*CR2+TR11*CR3 - TI3 = CC(I,K,1)+TR12*CI2+TR11*CI3 - TR5 = TI11*CR5+TI12*CR4 - TI5 = TI11*CI5+TI12*CI4 - TR4 = TI12*CR5-TI11*CR4 - TI4 = TI12*CI5-TI11*CI4 - CH(I-1,3,K) = TR2+TR5 - CH(IC-1,2,K) = TR2-TR5 - CH(I,3,K) = TI2+TI5 - CH(IC,2,K) = TI5-TI2 - CH(I-1,5,K) = TR3+TR4 - CH(IC-1,4,K) = TR3-TR4 - CH(I,5,K) = TI3+TI4 - CH(IC,4,K) = TI4-TI3 - 102 CONTINUE - 103 CONTINUE - RETURN - END - SUBROUTINE RADFG (IDO,IP,L1,IDL1,CC,C1,C2,CH,CH2,WA) - DIMENSION CH(IDO,L1,IP) ,CC(IDO,IP,L1) , - 1 C1(IDO,L1,IP) ,C2(IDL1,IP), - 2 CH2(IDL1,IP) ,WA(*) - DATA TPI/6.28318530717959/ - ARG = TPI/FLOAT(IP) - DCP = COS(ARG) - DSP = SIN(ARG) - IPPH = (IP+1)/2 - IPP2 = IP+2 - IDP2 = IDO+2 - NBD = (IDO-1)/2 - IF (IDO .EQ. 1) GO TO 119 - DO 101 IK=1,IDL1 - CH2(IK,1) = C2(IK,1) - 101 CONTINUE - DO 103 J=2,IP - DO 102 K=1,L1 - CH(1,K,J) = C1(1,K,J) - 102 CONTINUE - 103 CONTINUE - IF (NBD .GT. L1) GO TO 107 - IS = -IDO - DO 106 J=2,IP - IS = IS+IDO - IDIJ = IS - DO 105 I=3,IDO,2 - IDIJ = IDIJ+2 - DO 104 K=1,L1 - CH(I-1,K,J) = WA(IDIJ-1)*C1(I-1,K,J)+WA(IDIJ)*C1(I,K,J) - CH(I,K,J) = WA(IDIJ-1)*C1(I,K,J)-WA(IDIJ)*C1(I-1,K,J) - 104 CONTINUE - 105 CONTINUE - 106 CONTINUE - GO TO 111 - 107 IS = -IDO - DO 110 J=2,IP - IS = IS+IDO - DO 109 K=1,L1 - IDIJ = IS - DO 108 I=3,IDO,2 - IDIJ = IDIJ+2 - CH(I-1,K,J) = WA(IDIJ-1)*C1(I-1,K,J)+WA(IDIJ)*C1(I,K,J) - CH(I,K,J) = WA(IDIJ-1)*C1(I,K,J)-WA(IDIJ)*C1(I-1,K,J) - 108 CONTINUE - 109 CONTINUE - 110 CONTINUE - 111 IF (NBD .LT. L1) GO TO 115 - DO 114 J=2,IPPH - JC = IPP2-J - DO 113 K=1,L1 - DO 112 I=3,IDO,2 - C1(I-1,K,J) = CH(I-1,K,J)+CH(I-1,K,JC) - C1(I-1,K,JC) = CH(I,K,J)-CH(I,K,JC) - C1(I,K,J) = CH(I,K,J)+CH(I,K,JC) - C1(I,K,JC) = CH(I-1,K,JC)-CH(I-1,K,J) - 112 CONTINUE - 113 CONTINUE - 114 CONTINUE - GO TO 121 - 115 DO 118 J=2,IPPH - JC = IPP2-J - DO 117 I=3,IDO,2 - DO 116 K=1,L1 - C1(I-1,K,J) = CH(I-1,K,J)+CH(I-1,K,JC) - C1(I-1,K,JC) = CH(I,K,J)-CH(I,K,JC) - C1(I,K,J) = CH(I,K,J)+CH(I,K,JC) - C1(I,K,JC) = CH(I-1,K,JC)-CH(I-1,K,J) - 116 CONTINUE - 117 CONTINUE - 118 CONTINUE - GO TO 121 - 119 DO 120 IK=1,IDL1 - C2(IK,1) = CH2(IK,1) - 120 CONTINUE - 121 DO 123 J=2,IPPH - JC = IPP2-J - DO 122 K=1,L1 - C1(1,K,J) = CH(1,K,J)+CH(1,K,JC) - C1(1,K,JC) = CH(1,K,JC)-CH(1,K,J) - 122 CONTINUE - 123 CONTINUE -C - AR1 = 1. - AI1 = 0. - DO 127 L=2,IPPH - LC = IPP2-L - AR1H = DCP*AR1-DSP*AI1 - AI1 = DCP*AI1+DSP*AR1 - AR1 = AR1H - DO 124 IK=1,IDL1 - CH2(IK,L) = C2(IK,1)+AR1*C2(IK,2) - CH2(IK,LC) = AI1*C2(IK,IP) - 124 CONTINUE - DC2 = AR1 - DS2 = AI1 - AR2 = AR1 - AI2 = AI1 - DO 126 J=3,IPPH - JC = IPP2-J - AR2H = DC2*AR2-DS2*AI2 - AI2 = DC2*AI2+DS2*AR2 - AR2 = AR2H - DO 125 IK=1,IDL1 - CH2(IK,L) = CH2(IK,L)+AR2*C2(IK,J) - CH2(IK,LC) = CH2(IK,LC)+AI2*C2(IK,JC) - 125 CONTINUE - 126 CONTINUE - 127 CONTINUE - DO 129 J=2,IPPH - DO 128 IK=1,IDL1 - CH2(IK,1) = CH2(IK,1)+C2(IK,J) - 128 CONTINUE - 129 CONTINUE -C - IF (IDO .LT. L1) GO TO 132 - DO 131 K=1,L1 - DO 130 I=1,IDO - CC(I,1,K) = CH(I,K,1) - 130 CONTINUE - 131 CONTINUE - GO TO 135 - 132 DO 134 I=1,IDO - DO 133 K=1,L1 - CC(I,1,K) = CH(I,K,1) - 133 CONTINUE - 134 CONTINUE - 135 DO 137 J=2,IPPH - JC = IPP2-J - J2 = J+J - DO 136 K=1,L1 - CC(IDO,J2-2,K) = CH(1,K,J) - CC(1,J2-1,K) = CH(1,K,JC) - 136 CONTINUE - 137 CONTINUE - IF (IDO .EQ. 1) RETURN - IF (NBD .LT. L1) GO TO 141 - DO 140 J=2,IPPH - JC = IPP2-J - J2 = J+J - DO 139 K=1,L1 - DO 138 I=3,IDO,2 - IC = IDP2-I - CC(I-1,J2-1,K) = CH(I-1,K,J)+CH(I-1,K,JC) - CC(IC-1,J2-2,K) = CH(I-1,K,J)-CH(I-1,K,JC) - CC(I,J2-1,K) = CH(I,K,J)+CH(I,K,JC) - CC(IC,J2-2,K) = CH(I,K,JC)-CH(I,K,J) - 138 CONTINUE - 139 CONTINUE - 140 CONTINUE - RETURN - 141 DO 144 J=2,IPPH - JC = IPP2-J - J2 = J+J - DO 143 I=3,IDO,2 - IC = IDP2-I - DO 142 K=1,L1 - CC(I-1,J2-1,K) = CH(I-1,K,J)+CH(I-1,K,JC) - CC(IC-1,J2-2,K) = CH(I-1,K,J)-CH(I-1,K,JC) - CC(I,J2-1,K) = CH(I,K,J)+CH(I,K,JC) - CC(IC,J2-2,K) = CH(I,K,JC)-CH(I,K,J) - 142 CONTINUE - 143 CONTINUE - 144 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/rfftf1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/rfftf1.f) Deleted: trunk/scipy/fftpack/src/fftpack/rffti.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/rffti.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/rffti.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,6 +0,0 @@ - SUBROUTINE RFFTI (N,WSAVE) - DIMENSION WSAVE(*) - IF (N .EQ. 1) RETURN - CALL RFFTI1 (N,WSAVE(N+1),WSAVE(2*N+1)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/rffti.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/rffti.f) Deleted: trunk/scipy/fftpack/src/fftpack/rffti1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/rffti1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/rffti1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,59 +0,0 @@ - SUBROUTINE RFFTI1 (N,WA,IFAC) - DIMENSION WA(*) ,IFAC(*) ,NTRYH(4) - DATA NTRYH(1),NTRYH(2),NTRYH(3),NTRYH(4)/4,2,3,5/ - NL = N - NF = 0 - J = 0 - 101 J = J+1 - IF (J.le.4) GO TO 102 - GO TO 103 - 102 NTRY = NTRYH(J) - GO TO 104 - 103 NTRY = NTRY+2 - 104 NQ = NL/NTRY - NR = NL-NTRY*NQ - IF (NR.eq.0) GO TO 105 - GO TO 101 - 105 NF = NF+1 - IFAC(NF+2) = NTRY - NL = NQ - IF (NTRY .NE. 2) GO TO 107 - IF (NF .EQ. 1) GO TO 107 - DO 106 I=2,NF - IB = NF-I+2 - IFAC(IB+2) = IFAC(IB+1) - 106 CONTINUE - IFAC(3) = 2 - 107 IF (NL .NE. 1) GO TO 104 - IFAC(1) = N - IFAC(2) = NF - TPI = 6.28318530717959 - ARGH = TPI/FLOAT(N) - IS = 0 - NFM1 = NF-1 - L1 = 1 - IF (NFM1 .EQ. 0) RETURN - DO 110 K1=1,NFM1 - IP = IFAC(K1+2) - LD = 0 - L2 = L1*IP - IDO = N/L2 - IPM = IP-1 - DO 109 J=1,IPM - LD = LD+L1 - I = IS - ARGLD = FLOAT(LD)*ARGH - FI = 0. - DO 108 II=3,IDO,2 - I = I+2 - FI = FI+1. - ARG = FI*ARGLD - WA(I-1) = COS(ARG) - WA(I) = SIN(ARG) - 108 CONTINUE - IS = IS+IDO - 109 CONTINUE - L1 = L2 - 110 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/rffti1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/rffti1.f) Deleted: trunk/scipy/fftpack/src/fftpack/sinqb.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinqb.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/sinqb.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,18 +0,0 @@ - SUBROUTINE SINQB (N,X,WSAVE) - DIMENSION X(*) ,WSAVE(*) - IF (N .GT. 1) GO TO 101 - X(1) = 4.*X(1) - RETURN - 101 NS2 = N/2 - DO 102 K=2,N,2 - X(K) = -X(K) - 102 CONTINUE - CALL COSQB (N,X,WSAVE) - DO 103 K=1,NS2 - KC = N-K - XHOLD = X(K) - X(K) = X(KC+1) - X(KC+1) = XHOLD - 103 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/sinqb.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinqb.f) Deleted: trunk/scipy/fftpack/src/fftpack/sinqf.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinqf.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/sinqf.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,16 +0,0 @@ - SUBROUTINE SINQF (N,X,WSAVE) - DIMENSION X(*) ,WSAVE(*) - IF (N .EQ. 1) RETURN - NS2 = N/2 - DO 101 K=1,NS2 - KC = N-K - XHOLD = X(K) - X(K) = X(KC+1) - X(KC+1) = XHOLD - 101 CONTINUE - CALL COSQF (N,X,WSAVE) - DO 102 K=2,N,2 - X(K) = -X(K) - 102 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/sinqf.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinqf.f) Deleted: trunk/scipy/fftpack/src/fftpack/sinqi.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinqi.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/sinqi.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,5 +0,0 @@ - SUBROUTINE SINQI (N,WSAVE) - DIMENSION WSAVE(*) - CALL COSQI (N,WSAVE) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/sinqi.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinqi.f) Deleted: trunk/scipy/fftpack/src/fftpack/sint.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/sint.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/sint.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,9 +0,0 @@ - SUBROUTINE SINT (N,X,WSAVE) - DIMENSION X(*) ,WSAVE(*) - NP1 = N+1 - IW1 = N/2+1 - IW2 = IW1+NP1 - IW3 = IW2+NP1 - CALL SINT1(N,X,WSAVE,WSAVE(IW1),WSAVE(IW2),WSAVE(IW3)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/sint.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/sint.f) Deleted: trunk/scipy/fftpack/src/fftpack/sint1.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/sint1.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/sint1.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,42 +0,0 @@ - SUBROUTINE SINT1(N,WAR,WAS,XH,X,IFAC) - DIMENSION WAR(*),WAS(*),X(*),XH(*),IFAC(*) - DATA SQRT3 /1.73205080756888/ - DO 100 I=1,N - XH(I) = WAR(I) - WAR(I) = X(I) - 100 CONTINUE - IF (N.lt.2) GO TO 101 - IF (N.eq.2) GO TO 102 - GO TO 103 - 101 XH(1) = XH(1)+XH(1) - GO TO 106 - 102 XHOLD = SQRT3*(XH(1)+XH(2)) - XH(2) = SQRT3*(XH(1)-XH(2)) - XH(1) = XHOLD - GO TO 106 - 103 NP1 = N+1 - NS2 = N/2 - X(1) = 0. - DO 104 K=1,NS2 - KC = NP1-K - T1 = XH(K)-XH(KC) - T2 = WAS(K)*(XH(K)+XH(KC)) - X(K+1) = T1+T2 - X(KC+1) = T2-T1 - 104 CONTINUE - MODN = MOD(N,2) - IF (MODN .NE. 0) X(NS2+2) = 4.*XH(NS2+1) - CALL RFFTF1 (NP1,X,XH,WAR,IFAC) - XH(1) = .5*X(1) - DO 105 I=3,N,2 - XH(I-1) = -X(I) - XH(I) = XH(I-2)+X(I-1) - 105 CONTINUE - IF (MODN .NE. 0) GO TO 106 - XH(N) = -X(N+1) - 106 DO 107 I=1,N - X(I) = WAR(I) - WAR(I) = XH(I) - 107 CONTINUE - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/sint1.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/sint1.f) Deleted: trunk/scipy/fftpack/src/fftpack/sinti.f =================================================================== --- branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinti.f 2008-11-01 14:28:39 UTC (rev 4890) +++ trunk/scipy/fftpack/src/fftpack/sinti.f 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,13 +0,0 @@ - SUBROUTINE SINTI (N,WSAVE) - DIMENSION WSAVE(*) - DATA PI /3.14159265358979/ - IF (N .LE. 1) RETURN - NS2 = N/2 - NP1 = N+1 - DT = PI/FLOAT(NP1) - DO 101 K=1,NS2 - WSAVE(K) = 2.*SIN(K*DT) - 101 CONTINUE - CALL RFFTI (NP1,WSAVE(NS2+1)) - RETURN - END Copied: trunk/scipy/fftpack/src/fftpack/sinti.f (from rev 4890, branches/remove_fft_backends/scipy/fftpack/src/fftpack/sinti.f) Modified: trunk/scipy/fftpack/src/fftpack.h =================================================================== --- trunk/scipy/fftpack/src/fftpack.h 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/fftpack.h 2008-11-01 14:49:49 UTC (rev 4893) @@ -25,42 +25,6 @@ extern int ispow2le2e30(int n); extern int ispow2le2e13(int n); -#ifdef SCIPY_FFTWORK_H -#define WITH_FFTWORK -#include "fftwork/fast_header.h" -#endif - -#ifdef SCIPY_DJBFFT_H -#define WITH_DJBFFT -#define complex8 complex_double -#define COMPLEX8_H -#include -#include -#include -#endif - -#ifdef SCIPY_MKL_H -#define WITH_MKL -#include -#endif - -#ifdef SCIPY_FFTW3_H -#define WITH_FFTW3 -#include -#endif - -#ifdef SCIPY_DFFTW_H -#define WITH_FFTW -#include -#include -#endif - -#ifdef SCIPY_FFTW_H -#define WITH_FFTW -#include -#include -#endif - #if defined(NO_APPEND_FORTRAN) #if defined(UPPERCASE_FORTRAN) #define F_FUNC(f,F) F @@ -118,100 +82,4 @@ nof_in_cache_##name = last_cache_id_##name = 0;\ } -#define COPYSTD2DJB(SRC,DEST,N) { \ - int n2 = (N)/2,k,j; \ - *(DEST) = *(SRC); \ - *(DEST+1) = *(SRC+n2); \ - for (j=(N)/2-1,k=2;j>0;--j,k+=2) { \ - *(DEST+k) = *(SRC+n2+j); \ - *(DEST+k+1) = *(SRC+j); \ - } \ -} - -#define COPYINVDJB2STD(SRC,DEST,N) { \ - int n2 = (N)/2,k,j; \ - *(DEST) = *(SRC); \ - *(DEST+n2) = *(SRC+1); \ - for (j=(N)/2-1,k=2;j>0;--j,k+=2) { \ - *(DEST+n2+j) = *(SRC+k); \ - *(DEST+j) = *(SRC+k+1); \ - } \ -} - -#define COPYINVDJB2STD2(SRC,DEST,N) { \ - int n2 = (N)/2,k,j; \ - *(DEST) = *(SRC); \ - *(DEST+(N)-1) = *(SRC+(N)-1); \ - for (j=1,k=1;jn2) { \ - j = 2*(N-j); \ - *(DEST+j-1) = *(SRC+k); \ - *(DEST+j) = -*(SRC+k+1); \ - } else { \ - j *= 2; \ - *(DEST+j-1) = *(SRC+k); \ - *(DEST+j) = *(SRC+k+1); \ - } \ - } \ -} -#define COPYINVSTD2DJB(SRC,DEST,NORMALIZE,FRQ,N) { \ - int n2 = (N)/2,k,j; \ - if (NORMALIZE) { \ - *(DEST) = *(SRC); \ - *(DEST+1) = *(SRC+N-1); \ - } else { \ - *(DEST) = (*(SRC))*0.5; \ - *(DEST+1) = (*(SRC+N-1))*0.5; \ - } \ - for (k=2;kn2) { \ - j = 2*(N-j); \ - *(DEST+k) = *(SRC+j-1); \ - *(DEST+k+1) = -*(SRC+j); \ - } else { \ - j *= 2; \ - *(DEST+k) = *(SRC+j-1); \ - *(DEST+k+1) = *(SRC+j); \ - } \ - } \ -} -#define COPYRFFTW2STD(SRC,DEST,N) { \ - int j,n2=(N)/2; \ - *(DEST) = *(SRC); \ - for (j=1;j1) { \ - *(DEST+2*n2-1) = *(SRC+n2); \ - if ((N)%2) \ - *(DEST+2*n2) = *(SRC+(N)-n2); \ - } \ -} -#define COPYINVRFFTW2STD(SRC,DEST,N) { \ - int j,n2=(N)/2; \ - *(DEST) = *(SRC); \ - for (j=1;j1) {\ - *(DEST+n2) = *(SRC+2*n2-1); \ - if ((N)%2) \ - *(DEST+(N)-n2) = *(SRC+2*n2); \ - } \ -} - #endif Modified: trunk/scipy/fftpack/src/zfft.c =================================================================== --- trunk/scipy/fftpack/src/zfft.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfft.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -20,57 +20,5 @@ zfft_##name(inout, n, direction, howmany, normalize);\ } -/* ************** Definition of backend specific functions ********* */ - -/* - * To add a backend : - * - create a file zfft_name.c, where you define a function zfft_name where - * name is the name of your backend. If you do not use the GEN_CACHE macro, - * you will need to define a function void destroy_zname_caches(void), - * which can do nothing - * - in zfft.c, include the zfft_name.c file, and add the 3 following lines - * just after it: - * #ifndef WITH_DJBFFT - * GEN_PUBLIC_API(name) - * #endif - */ - -#ifdef WITH_FFTW3 - #include "zfft_fftw3.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftw3) - #endif -#elif defined WITH_FFTW - #include "zfft_fftw.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftw) - #endif -#elif defined WITH_MKL - #include "zfft_mkl.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(mkl) - #endif -#else /* Use fftpack by default */ - #include "zfft_fftpack.c" - #ifndef WITH_DJBFFT - GEN_PUBLIC_API(fftpack) - #endif -#endif - -/* - * djbfft must be used at the end, because it needs another backend (defined - * above) for non 2^n * size - */ -#ifdef WITH_DJBFFT - #include "zfft_djbfft.c" - void destroy_zfft_cache(void) - { - destroy_zdjbfft_caches(); - zfft_def_destroy_cache(); - } - void zfft(complex_double *inout, int n, - int direction, int howmany, int normalize) - { - zfft_djbfft(inout, n, direction, howmany, normalize); - } -#endif +#include "zfft_fftpack.c" +GEN_PUBLIC_API(fftpack) Deleted: trunk/scipy/fftpack/src/zfft_djbfft.c =================================================================== --- trunk/scipy/fftpack/src/zfft_djbfft.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfft_djbfft.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,151 +0,0 @@ -/* -* DJBFFT only implements size 2^N ! -* -* zfft_def and zfft_def_destroy_cache are the functions -* used for size different than 2^N -*/ -#ifdef WITH_FFTWORK -#define zfft_def zfft_fftwork -#define zfft_def_destroy_cache destroy_zfftwork_cache -#elif defined WITH_FFTW3 -#define zfft_def zfft_fftw3 -#define zfft_def_destroy_cache destroy_zfftw3_caches -#elif defined WITH_FFTW -#define zfft_def zfft_fftw -#define zfft_def_destroy_cache destroy_zfftw_caches -#else -#define zfft_def zfft_fftpack -#define zfft_def_destroy_cache destroy_zfftpack_caches -#endif - -GEN_CACHE(zdjbfft,(int n) - ,unsigned int* f; - double* ptr; - ,caches_zdjbfft[i].n==n - ,caches_zdjbfft[id].f = (unsigned int*)malloc(sizeof(unsigned int)*(n)); - caches_zdjbfft[id].ptr = (double*)malloc(sizeof(double)*(2*n)); - fftfreq_ctable(caches_zdjbfft[id].f,n); - for(i=0;i0?FFTW_FORWARD:FFTW_BACKWARD), - FFTW_IN_PLACE|FFTW_ESTIMATE); - ,fftw_destroy_plan(caches_zfftw[id].plan); - ,10) - -extern void zfft_fftw(complex_double * inout, int n, - int dir, int howmany, int normalize) -{ - int i; - complex_double *ptr = inout; - fftw_plan plan = NULL; - plan = caches_zfftw[get_cache_id_zfftw(n, dir)].plan; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_one(plan, (fftw_complex *) ptr, NULL); - } - break; - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_one(plan, (fftw_complex *) ptr, NULL); - } - break; - default: - fprintf(stderr, "zfft: invalid dir=%d\n", dir); - } - - if (normalize) { - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= n; - *((double *) (ptr++) + 1) /= n; - } - } -} Deleted: trunk/scipy/fftpack/src/zfft_fftw3.c =================================================================== --- trunk/scipy/fftpack/src/zfft_fftw3.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfft_fftw3.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,121 +0,0 @@ - -/* This cache uses FFTW_MEASURE for the plans, and do not copy the data. */ -GEN_CACHE(zfftw3,(int n,int d) - ,int direction; - fftw_plan plan; - fftw_complex *wrk; - ,((caches_zfftw3[i].n==n) && - (caches_zfftw3[i].direction==d)) - ,caches_zfftw3[id].direction = d; - /* This working buffer is only used to compute the plan: we need it - since FFTW_MEASURE destroys its input when computing a plan */ - caches_zfftw3[id].wrk = fftw_malloc(n * sizeof(double) * 2); - caches_zfftw3[id].plan = fftw_plan_dft_1d(n, - caches_zfftw3[id].wrk, - caches_zfftw3[id].wrk, - (d>0?FFTW_FORWARD:FFTW_BACKWARD), - FFTW_ESTIMATE | FFTW_UNALIGNED); - , - fftw_destroy_plan(caches_zfftw3[id].plan); - fftw_free(caches_zfftw3[id].wrk); - ,10) - -static void zfft_fftw3(complex_double * inout, int n, int dir, int -howmany, int normalize) -{ - fftw_complex *ptr = (fftw_complex*)inout; - fftw_complex *ptrm; - fftw_plan plan = NULL; - double factor = 1./n; - - int i; - - plan = caches_zfftw3[get_cache_id_zfftw3(n, dir)].plan; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_execute_dft(plan, ptr, ptr); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - fftw_execute_dft(plan, ptr, ptr); - } - break; - - default: - fprintf(stderr, "zfft: invalid dir=%d\n", dir); - } - - if (normalize) { - ptr =(fftw_complex*)inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) *= factor; - *((double *) (ptr++) + 1) *= factor; - } - } -} -#if 0 -GEN_CACHE(zfftw3,(int n,int d) - ,int direction; - fftw_plan plan; - fftw_complex* ptr; - ,((caches_zfftw3[i].n==n) && - (caches_zfftw3[i].direction==d)) - ,caches_zfftw3[id].direction = d; - caches_zfftw3[id].ptr = fftw_malloc(sizeof(fftw_complex)*(n)); - caches_zfftw3[id].plan = fftw_plan_dft_1d(n, caches_zfftw3[id].ptr, - caches_zfftw3[id].ptr, - (d>0?FFTW_FORWARD:FFTW_BACKWARD), - FFTW_ESTIMATE); - ,fftw_destroy_plan(caches_zfftw3[id].plan); - fftw_free(caches_zfftw3[id].ptr); - ,10) - -static void zfft_fftw3(complex_double * inout, int n, int dir, int -howmany, int normalize) -{ - complex_double *ptr = inout; - fftw_complex *ptrm = NULL; - fftw_plan plan = NULL; - - int i; - - plan = caches_zfftw3[get_cache_id_zfftw3(n, dir)].plan; - - switch (dir) { - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - ptrm = - caches_zfftw3[get_cache_id_zfftw3(n, dir)].ptr; - memcpy(ptrm, ptr, sizeof(double) * 2 * n); - fftw_execute(plan); - memcpy(ptr, ptrm, sizeof(double) * 2 * n); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - ptrm = - caches_zfftw3[get_cache_id_zfftw3(n, dir)].ptr; - memcpy(ptrm, ptr, sizeof(double) * 2 * n); - fftw_execute(plan); - memcpy(ptr, ptrm, sizeof(double) * 2 * n); - } - break; - - default: - fprintf(stderr, "zfft: invalid dir=%d\n", dir); - } - - if (normalize) { - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= n; - *((double *) (ptr++) + 1) /= n; - } - } -} -#endif Deleted: trunk/scipy/fftpack/src/zfft_mkl.c =================================================================== --- trunk/scipy/fftpack/src/zfft_mkl.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfft_mkl.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,42 +0,0 @@ -GEN_CACHE(zmkl,(int n) - ,DFTI_DESCRIPTOR_HANDLE desc_handle; - ,(caches_zmkl[i].n==n) - ,DftiCreateDescriptor(&caches_zmkl[id].desc_handle, DFTI_DOUBLE, DFTI_COMPLEX, 1, (long)n); - DftiCommitDescriptor(caches_zmkl[id].desc_handle); - ,DftiFreeDescriptor(&caches_zmkl[id].desc_handle); - ,10) - -static void zfft_mkl(complex_double * inout, - int n, int direction, int howmany, int normalize) -{ - int i; - complex_double *ptr = inout; - DFTI_DESCRIPTOR_HANDLE desc_handle; - desc_handle = caches_zmkl[get_cache_id_zmkl(n)].desc_handle; - - switch (direction) { - - case 1: - for (i = 0; i < howmany; ++i, ptr += n) { - DftiComputeForward(desc_handle, (double *) ptr); - } - break; - - case -1: - for (i = 0; i < howmany; ++i, ptr += n) { - DftiComputeBackward(desc_handle, (double *) ptr); - } - break; - - default: - fprintf(stderr, "zfft: invalid direction=%d\n", direction); - } - - if (normalize) { - ptr = inout; - for (i = n * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= n; - *((double *) (ptr++) + 1) /= n; - } - } -} Modified: trunk/scipy/fftpack/src/zfftnd.c =================================================================== --- trunk/scipy/fftpack/src/zfftnd.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfftnd.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -19,27 +19,5 @@ zfftnd_##name(inout, rank, dims, direction, howmany, normalize);\ } -#if defined(WITH_FFTW) || defined(WITH_MKL) -static -int equal_dims(int rank,int *dims1,int *dims2) { - int i; - for (i=0;i 0 ? FFTW_FORWARD : FFTW_BACKWARD), - flags);, - fftwnd_destroy_plan(caches_zfftnd_fftw[id].plan); - free(caches_zfftnd_fftw[id].dims);, 10) - - -extern void zfftnd_fftw(complex_double * inout, int rank, - int *dims, int direction, int howmany, - int normalize) -{ - int i, sz; - complex_double *ptr = inout; - fftwnd_plan plan = NULL; - - sz = 1; - for (i = 0; i < rank; ++i) { - sz *= dims[i]; - } - i = get_cache_id_zfftnd_fftw(rank, dims, direction, - FFTW_IN_PLACE | FFTW_ESTIMATE); - plan = caches_zfftnd_fftw[i].plan; - for (i = 0; i < howmany; ++i, ptr += sz) { - fftwnd_one(plan, (fftw_complex *) ptr, NULL); - } - if (normalize) { - ptr = inout; - for (i = sz * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= sz; - *((double *) (ptr++) + 1) /= sz; - } - } -} Deleted: trunk/scipy/fftpack/src/zfftnd_fftw3.c =================================================================== --- trunk/scipy/fftpack/src/zfftnd_fftw3.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfftnd_fftw3.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,40 +0,0 @@ -/* - * fftw3 backend for multi dimensional fft - * - * Original code by Pearu Peaterson - * - * Last Change: Wed Aug 08 02:00 PM 2007 J - */ - -/* stub because fftw3 has no cache mechanism (yet) */ -static void destroy_zfftnd_fftw3_caches(void) {} - -extern void zfftnd_fftw3(complex_double * inout, int rank, - int *dims, int direction, int howmany, - int normalize) -{ - int i, sz; - complex_double *ptr = inout; - - fftw_plan plan = NULL; - sz = 1; - for (i = 0; i < rank; ++i) { - sz *= dims[i]; - } - plan = fftw_plan_many_dft(rank, dims, howmany, - (fftw_complex *) ptr, NULL, 1, sz, - (fftw_complex *) ptr, NULL, 1, sz, - (direction > - 0 ? FFTW_FORWARD : FFTW_BACKWARD), - FFTW_ESTIMATE); - fftw_execute(plan); - fftw_destroy_plan(plan); - - if (normalize) { - ptr = inout; - for (i = sz * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= sz; - *((double *) (ptr++) + 1) /= sz; - } - } -} Deleted: trunk/scipy/fftpack/src/zfftnd_mkl.c =================================================================== --- trunk/scipy/fftpack/src/zfftnd_mkl.c 2008-11-01 14:42:39 UTC (rev 4892) +++ trunk/scipy/fftpack/src/zfftnd_mkl.c 2008-11-01 14:49:49 UTC (rev 4893) @@ -1,66 +0,0 @@ -/* - * MKL backend for multi dimensional fft - * - * Original code by David M. Cooke - * - * Last Change: Wed Aug 08 03:00 PM 2007 J - */ - -static long *convert_dims(int n, int *dims) -{ - long *ndim; - int i; - ndim = (long *) malloc(sizeof(long) * n); - for (i = 0; i < n; i++) { - ndim[i] = (long) dims[i]; - } - return ndim; -} - -GEN_CACHE(zfftnd_mkl, (int n, int *dims) - , DFTI_DESCRIPTOR_HANDLE desc_handle; - int *dims; - long *ndims;, ((caches_zfftnd_mkl[i].n == n) && - (equal_dims(n, caches_zfftnd_mkl[i].dims, dims))) - , caches_zfftnd_mkl[id].ndims = convert_dims(n, dims); - caches_zfftnd_mkl[id].n = n; - caches_zfftnd_mkl[id].dims = (int *) malloc(sizeof(int) * n); - memcpy(caches_zfftnd_mkl[id].dims, dims, sizeof(int) * n); - DftiCreateDescriptor(&caches_zfftnd_mkl[id].desc_handle, - DFTI_DOUBLE, DFTI_COMPLEX, (long) n, - caches_zfftnd_mkl[id].ndims); - DftiCommitDescriptor(caches_zfftnd_mkl[id].desc_handle);, - DftiFreeDescriptor(&caches_zfftnd_mkl[id].desc_handle); - free(caches_zfftnd_mkl[id].dims); - free(caches_zfftnd_mkl[id].ndims);, 10) - -extern void zfftnd_mkl(complex_double * inout, int rank, - int *dims, int direction, int howmany, - int normalize) -{ - int i, sz; - complex_double *ptr = inout; - - DFTI_DESCRIPTOR_HANDLE desc_handle; - sz = 1; - for (i = 0; i < rank; ++i) { - sz *= dims[i]; - } - - desc_handle = - caches_zfftnd_mkl[get_cache_id_zfftnd_mkl(rank, dims)].desc_handle; - for (i = 0; i < howmany; ++i, ptr += sz) { - if (direction == 1) { - DftiComputeForward(desc_handle, (double *) ptr); - } else if (direction == -1) { - DftiComputeBackward(desc_handle, (double *) ptr); - } - } - if (normalize) { - ptr = inout; - for (i = sz * howmany - 1; i >= 0; --i) { - *((double *) (ptr)) /= sz; - *((double *) (ptr++) + 1) /= sz; - } - } -} From scipy-svn at scipy.org Sat Nov 1 11:00:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 10:00:58 -0500 (CDT) Subject: [Scipy-svn] r4894 - trunk/scipy/linalg Message-ID: <20081101150058.2633039C05F@scipy.org> Author: cdavid Date: 2008-11-01 10:00:54 -0500 (Sat, 01 Nov 2008) New Revision: 4894 Modified: trunk/scipy/linalg/SConscript Log: Fix scons script for linalg: did not use NumpyConfigure, hence putting scons stuff in top dir instead of build dir. Modified: trunk/scipy/linalg/SConscript =================================================================== --- trunk/scipy/linalg/SConscript 2008-11-01 14:49:49 UTC (rev 4893) +++ trunk/scipy/linalg/SConscript 2008-11-01 15:00:54 UTC (rev 4894) @@ -1,4 +1,4 @@ -# Last Change: Thu Jun 12 07:00 PM 2008 J +# Last Change: Sat Nov 01 11:00 PM 2008 J # vim:syntax=python import os @@ -39,8 +39,8 @@ #======================= # Starting Configuration #======================= -config = env.Configure(custom_tests = {'CheckCBLAS' : CheckCBLAS, - 'CheckCLAPACK' : CheckCLAPACK}) +config = env.NumpyConfigure(custom_tests = {'CheckCBLAS' : CheckCBLAS, + 'CheckCLAPACK' : CheckCLAPACK}) #------------------------- # Checking cblas/clapack @@ -67,9 +67,9 @@ #--------------------------- # Checking F77 blas/lapack #--------------------------- -fconfig = fenv.Configure(custom_tests = {'CheckBLAS' : CheckF77BLAS, - 'CheckLAPACK' : CheckF77LAPACK, - 'CheckF77Clib' : CheckF77Clib}) +fconfig = fenv.NumpyConfigure(custom_tests = {'CheckBLAS' : CheckF77BLAS, + 'CheckLAPACK' : CheckF77LAPACK, + 'CheckF77Clib' : CheckF77Clib}) if not fconfig.CheckF77Clib(): raise RuntimeError("Could not check F/C runtime library for %s/%s, " \ From scipy-svn at scipy.org Sat Nov 1 11:12:24 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 10:12:24 -0500 (CDT) Subject: [Scipy-svn] r4895 - in trunk/scipy/interpolate: . tests Message-ID: <20081101151224.F230439C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 10:12:11 -0500 (Sat, 01 Nov 2008) New Revision: 4895 Modified: trunk/scipy/interpolate/rbf.py trunk/scipy/interpolate/tests/test_rbf.py Log: interpolate.Rbf: make epsilon behave for 'gaussian' similarly as for multiquadrics Also add a test that checks that for a simple 1D smooth test case, Rbf builds a regular approximation that is valid also away from nodes. Modified: trunk/scipy/interpolate/rbf.py =================================================================== --- trunk/scipy/interpolate/rbf.py 2008-11-01 15:00:54 UTC (rev 4894) +++ trunk/scipy/interpolate/rbf.py 2008-11-01 15:12:11 UTC (rev 4895) @@ -64,7 +64,7 @@ 'multiquadric': sqrt((r/self.epsilon)**2 + 1) 'inverse multiquadric': 1.0/sqrt((r/self.epsilon)**2 + 1) - 'gaussian': exp(-(self.epsilon*r)**2) + 'gaussian': exp(-(r/self.epsilon)**2) 'linear': r 'cubic': r**3 'quintic': r**5 @@ -105,7 +105,7 @@ elif self.function.lower() == 'inverse multiquadric': return 1.0/sqrt((1.0/self.epsilon*r)**2 + 1) elif self.function.lower() == 'gaussian': - return exp(-(self.epsilon*r)**2) + return exp(-(1.0/self.epsilon*r)**2) elif self.function.lower() == 'linear': return r elif self.function.lower() == 'cubic': Modified: trunk/scipy/interpolate/tests/test_rbf.py =================================================================== --- trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 15:00:54 UTC (rev 4894) +++ trunk/scipy/interpolate/tests/test_rbf.py 2008-11-01 15:12:11 UTC (rev 4895) @@ -3,13 +3,14 @@ """ Test functions for rbf module """ from numpy.testing import assert_array_almost_equal, assert_almost_equal -from numpy import linspace, sin, random, exp +from numpy import linspace, sin, random, exp, log10 from scipy.interpolate.rbf import Rbf FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', 'cubic', 'quintic', 'thin-plate', 'linear') -def check_rbf1d(function): +def check_rbf1d_interpolation(function): + """Check that the Rbf function interpolates throught the nodes (1D)""" x = linspace(0,10,9) y = sin(x) rbf = Rbf(x, y, function=function) @@ -17,7 +18,8 @@ assert_array_almost_equal(y, yi) assert_almost_equal(rbf(float(x[0])), y[0]) -def check_rbf2d(function): +def check_rbf2d_interpolation(function): + """Check that the Rbf function interpolates throught the nodes (2D)""" x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 z = x*exp(-x**2-1j*y**2) @@ -26,7 +28,8 @@ zi.shape = x.shape assert_array_almost_equal(z, zi) -def check_rbf3d(function): +def check_rbf3d_interpolation(function): + """Check that the Rbf function interpolates throught the nodes (3D)""" x = random.rand(50,1)*4-2 y = random.rand(50,1)*4-2 z = random.rand(50,1)*4-2 @@ -38,6 +41,35 @@ def test_rbf_interpolation(): for function in FUNCTIONS: - yield check_rbf1d, function - yield check_rbf2d, function - yield check_rbf3d, function + yield check_rbf1d_interpolation, function + yield check_rbf2d_interpolation, function + yield check_rbf3d_interpolation, function + +def check_rbf1d_regularity(function, atol): + """Check that the Rbf function approximates a smooth function well away + from the nodes.""" + x = linspace(0, 10, 9) + y = sin(x) + rbf = Rbf(x, y, function=function) + xi = linspace(0, 10, 100) + yi = rbf(xi) + #import matplotlib.pyplot as plt + #plt.figure() + #plt.plot(x, y, 'o', xi, sin(xi), ':', xi, yi, '-') + #plt.title(function) + #plt.show() + assert_array_almost_equal(yi, sin(xi), decimal=-log10(atol), + err_msg="abs-diff: %f" % abs(yi - sin(xi)).max()) + +def test_rbf_regularity(): + tolerances = { + 'multiquadric': 0.05, + 'inverse multiquadric': 0.01, + 'gaussian': 0.01, + 'cubic': 0.1, + 'quintic': 0.1, + 'thin-plate': 0.1, + 'linear': 0.2 + } + for function in FUNCTIONS: + yield check_rbf1d_regularity, function, tolerances.get(function, 1e-2) From scipy-svn at scipy.org Sat Nov 1 11:17:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 10:17:39 -0500 (CDT) Subject: [Scipy-svn] r4896 - branches Message-ID: <20081101151739.CB6D539C05F@scipy.org> Author: cdavid Date: 2008-11-01 10:17:33 -0500 (Sat, 01 Nov 2008) New Revision: 4896 Removed: branches/remove_fft_backends/ Log: Remove integrated branch From scipy-svn at scipy.org Sat Nov 1 12:04:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 11:04:26 -0500 (CDT) Subject: [Scipy-svn] r4897 - in trunk/scipy/stats: . tests Message-ID: <20081101160426.3BD4F39C05F@scipy.org> Author: stefan Date: 2008-11-01 11:04:04 -0500 (Sat, 01 Nov 2008) New Revision: 4897 Modified: trunk/scipy/stats/distributions.py trunk/scipy/stats/tests/test_distributions.py Log: Fix a sign in `entropy` [patch by Herman Engelbrecht]. Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-01 15:17:33 UTC (rev 4896) +++ trunk/scipy/stats/distributions.py 2008-11-01 16:04:04 UTC (rev 4897) @@ -3180,10 +3180,10 @@ """S = entropy(pk,qk=None) calculate the entropy of a distribution given the p_k values - S = -sum(pk * log(pk),axis=0) + S = -sum(pk * log(pk), axis=0) If qk is not None, then compute a relative entropy - S = -sum(pk * log(pk / qk),axis=0) + S = sum(pk * log(pk / qk), axis=0) Routine will normalize pk and qk if they don't sum to 1 """ @@ -3200,7 +3200,7 @@ # too, the relative entropy is infinite. if any(take(pk,nonzero(qk==0.0),axis=0)!=0.0, 0): return inf - vec = where (pk == 0, 0.0, pk*log(pk / qk)) + vec = where (pk == 0, 0.0, -pk*log(pk / qk)) return -sum(vec,axis=0) Modified: trunk/scipy/stats/tests/test_distributions.py =================================================================== --- trunk/scipy/stats/tests/test_distributions.py 2008-11-01 15:17:33 UTC (rev 4896) +++ trunk/scipy/stats/tests/test_distributions.py 2008-11-01 16:04:04 UTC (rev 4897) @@ -224,5 +224,15 @@ if stats.bernoulli.__doc__ is not None: self.failUnless("bernoulli" in stats.bernoulli.__doc__.lower()) +class TestEntropy(TestCase): + def test_entropy_positive(self): + """See ticket #497""" + pk = [0.5,0.2,0.3] + qk = [0.1,0.25,0.65] + eself = stats.entropy(pk,pk) + edouble = stats.entropy(pk,qk) + assert(0.0 == eself) + assert(edouble >= 0.0) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Sat Nov 1 13:21:42 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 12:21:42 -0500 (CDT) Subject: [Scipy-svn] r4898 - trunk Message-ID: <20081101172142.AE18639C088@scipy.org> Author: stefan Date: 2008-11-01 12:21:33 -0500 (Sat, 01 Nov 2008) New Revision: 4898 Modified: trunk/README.txt Log: Corrected a reference to an outdated filename in the documentation Modified: trunk/README.txt =================================================================== --- trunk/README.txt 2008-11-01 16:04:04 UTC (rev 4897) +++ trunk/README.txt 2008-11-01 17:21:33 UTC (rev 4898) @@ -52,7 +52,7 @@ THANKS.txt SciPy developers and contributors. Please keep it up to date!! - DEVELOPERS.txt + README.txt SciPy structure (this document). setup.py From scipy-svn at scipy.org Sat Nov 1 14:08:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 13:08:46 -0500 (CDT) Subject: [Scipy-svn] r4899 - trunk Message-ID: <20081101180846.1336439C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 13:08:37 -0500 (Sat, 01 Nov 2008) New Revision: 4899 Added: trunk/Makefile Log: Add Makefile Added: trunk/Makefile =================================================================== --- trunk/Makefile 2008-11-01 17:21:33 UTC (rev 4898) +++ trunk/Makefile 2008-11-01 18:08:37 UTC (rev 4899) @@ -0,0 +1,35 @@ + +REVISION="$(shell svnversion ../trunk)" + +all: build test + +build: build-linux +test: test-linux + +test-all: test-linux test-wine +build-all: build-linux build-wine + +TEST_STANZA='import sys, os; sys.path.insert(0, os.path.join(os.getcwd(), "site-packages")); import scipy; sys.exit(scipy.test(verbose=2))' + +build-linux: + @echo "version = \"$(REVISION)\"" > scipy/__svn_version__.py + @echo "--- Building..." + python2.5 setup.py install --prefix=$$PWD/dist/linux \ + > build.log 2>&1 || { cat build.log; exit 1; } + +test-linux: + @echo "--- Testing in Linux" + (cd dist/linux/lib/python2.5 && python -c $(TEST_STANZA)) \ + > test.log 2>&1 || { cat test.log; exit 1; } + +build-wine: + @echo "--- Building..." + wine c:\\Python25\\python.exe setup.py build --compiler=mingw32 install --prefix="dist\\win32" \ + > build.log 2>&1 || { cat build.log; exit 1; } + +test-wine: + @echo "--- Testing in WINE" + (cd dist/win32/Lib && wine c:\\Python25\\python.exe -c $(TEST_STANZA)) \ + > test.log 2>&1 || { cat test.log; exit 1; } + +.PHONY: test build test-linux build-linux test-wine build-wine From scipy-svn at scipy.org Sat Nov 1 14:09:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 13:09:18 -0500 (CDT) Subject: [Scipy-svn] r4900 - trunk/scipy/stats Message-ID: <20081101180918.7AB7C39C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 13:08:58 -0500 (Sat, 01 Nov 2008) New Revision: 4900 Modified: trunk/scipy/stats/distributions.py Log: Fix scipy.stats.recipinvgauss docstring. Closes #757. Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-01 18:08:37 UTC (rev 4899) +++ trunk/scipy/stats/distributions.py 2008-11-01 18:08:58 UTC (rev 4900) @@ -2875,7 +2875,7 @@ Reciprocal inverse Gaussian -recipinvgauss.pdf(x, mu) = 1/sqrt(2*pi*x**3) * exp(-(x-mu)**2/(2*x*mu**2)) +recipinvgauss.pdf(x, mu) = 1/sqrt(2*pi*x) * exp(-(1-mu*x)**2/(2*x*mu**2)) for x >= 0. """ ) From scipy-svn at scipy.org Sat Nov 1 14:11:22 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 13:11:22 -0500 (CDT) Subject: [Scipy-svn] r4901 - trunk Message-ID: <20081101181122.EF2AC39C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 13:11:13 -0500 (Sat, 01 Nov 2008) New Revision: 4901 Removed: trunk/Makefile Log: Remove file added by mistake Deleted: trunk/Makefile =================================================================== --- trunk/Makefile 2008-11-01 18:08:58 UTC (rev 4900) +++ trunk/Makefile 2008-11-01 18:11:13 UTC (rev 4901) @@ -1,35 +0,0 @@ - -REVISION="$(shell svnversion ../trunk)" - -all: build test - -build: build-linux -test: test-linux - -test-all: test-linux test-wine -build-all: build-linux build-wine - -TEST_STANZA='import sys, os; sys.path.insert(0, os.path.join(os.getcwd(), "site-packages")); import scipy; sys.exit(scipy.test(verbose=2))' - -build-linux: - @echo "version = \"$(REVISION)\"" > scipy/__svn_version__.py - @echo "--- Building..." - python2.5 setup.py install --prefix=$$PWD/dist/linux \ - > build.log 2>&1 || { cat build.log; exit 1; } - -test-linux: - @echo "--- Testing in Linux" - (cd dist/linux/lib/python2.5 && python -c $(TEST_STANZA)) \ - > test.log 2>&1 || { cat test.log; exit 1; } - -build-wine: - @echo "--- Building..." - wine c:\\Python25\\python.exe setup.py build --compiler=mingw32 install --prefix="dist\\win32" \ - > build.log 2>&1 || { cat build.log; exit 1; } - -test-wine: - @echo "--- Testing in WINE" - (cd dist/win32/Lib && wine c:\\Python25\\python.exe -c $(TEST_STANZA)) \ - > test.log 2>&1 || { cat test.log; exit 1; } - -.PHONY: test build test-linux build-linux test-wine build-wine From scipy-svn at scipy.org Sat Nov 1 15:49:22 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 14:49:22 -0500 (CDT) Subject: [Scipy-svn] r4902 - scipy-docs/trunk Message-ID: <20081101194922.CC55439C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 14:49:07 -0500 (Sat, 01 Nov 2008) New Revision: 4902 Modified: scipy-docs/trunk/Makefile Log: Add upload command Modified: scipy-docs/trunk/Makefile =================================================================== --- scipy-docs/trunk/Makefile 2008-11-01 18:11:13 UTC (rev 4901) +++ scipy-docs/trunk/Makefile 2008-11-01 19:49:07 UTC (rev 4902) @@ -22,10 +22,17 @@ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview over all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" + @echo " upload USER=... to upload results to docs.scipy.org" clean: -rm -rf build/* source/generated +upload: + @test -e build/dist || { echo "make dist is required first"; exit 1; } + @test output-is-fine -nt build/dist || { \ + echo "Review the output in build/dist, and do 'touch output-is-fine' before uploading."; exit 1; } + rsync -r --delete-after -p build/dist/ $(USER)@docs.scipy.org:/home/docserver/www-root/doc/scipy/ + dist: html test -d build/latex || make latex -make -C build/latex all-pdf @@ -37,6 +44,8 @@ (cd build/html && zip -9qr ../dist/scipy-html.zip .) cp build/latex/*.pdf build/dist cd build/dist && tar czf ../dist.tar.gz * + chmod ug=rwX,o=rX -R build/dist + find build/dist -type d -print0 | xargs -0r chmod g+s generate: build/generate-stamp build/generate-stamp: $(wildcard source/*.rst) ext From scipy-svn at scipy.org Sat Nov 1 16:56:41 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 15:56:41 -0500 (CDT) Subject: [Scipy-svn] r4903 - trunk/scipy/ndimage Message-ID: <20081101205641.3992B39C088@scipy.org> Author: stefan Date: 2008-11-01 15:56:33 -0500 (Sat, 01 Nov 2008) New Revision: 4903 Modified: trunk/scipy/ndimage/morphology.py Log: Improve terminology in ndimage.distance_transform [patch by Pieter Holtzhausen]. Modified: trunk/scipy/ndimage/morphology.py =================================================================== --- trunk/scipy/ndimage/morphology.py 2008-11-01 19:49:07 UTC (rev 4902) +++ trunk/scipy/ndimage/morphology.py 2008-11-01 20:56:33 UTC (rev 4903) @@ -499,7 +499,7 @@ This function calculates the distance transform of the input, by replacing each background element (zero values), with its shortest distance to the foreground (any element non-zero). Three - types of distance metric are supported: 'euclidean', 'city_block' + types of distance metric are supported: 'euclidean', 'taxicab' and 'chessboard'. In addition to the distance transform, the feature transform can @@ -517,7 +517,7 @@ case of the euclidean distance transform. This function employs a slow brute force algorithm, see also the - function distance_transform_cdt for more efficient city_block and + function distance_transform_cdt for more efficient taxicab and chessboard algorithms. the distances and indices arguments can be used to give optional @@ -536,7 +536,7 @@ metric = metric.lower() if metric == 'euclidean': metric = 1 - elif metric == 'cityblock': + elif metric in ['taxicab', 'cityblock', 'manhattan']: metric = 2 elif metric == 'chessboard': metric = 3 @@ -598,18 +598,18 @@ else: return None -def distance_transform_cdt(input, structure = 'chessboard', +def distance_transform_cdt(input, metric = 'chessboard', return_distances = True, return_indices = False, distances = None, indices = None): """Distance transform for chamfer type of transforms. - The structure determines the type of chamfering that is done. If - the structure is equal to 'cityblock' a structure is generated + The metric determines the type of chamfering that is done. If + the metric is equal to 'taxicab' a structure is generated using generate_binary_structure with a squared distance equal to - 1. If the structure is equal to 'chessboard', a structure is + 1. If the metric is equal to 'chessboard', a metric is generated using generate_binary_structure with a squared distance equal to the rank of the array. These choices correspond to the - common interpretations of the cityblock and the chessboard + common interpretations of the taxicab and the chessboard distance metrics in two dimensions. In addition to the distance transform, the feature transform can @@ -629,22 +629,22 @@ ft_inplace = isinstance(indices, numpy.ndarray) dt_inplace = isinstance(distances, numpy.ndarray) input = numpy.asarray(input) - if structure == 'cityblock': + if metric in ['taxicab', 'cityblock', 'manhattan']: rank = input.ndim - structure = generate_binary_structure(rank, 1) - elif structure == 'chessboard': + metric = generate_binary_structure(rank, 1) + elif metric == 'chessboard': rank = input.ndim - structure = generate_binary_structure(rank, rank) + metric = generate_binary_structure(rank, rank) else: try: - structure = numpy.asarray(structure) + metric = numpy.asarray(metric) except: - raise RuntimeError, 'invalid structure provided' - for s in structure.shape: + raise RuntimeError, 'invalid metric provided' + for s in metric.shape: if s != 3: - raise RuntimeError, 'structure sizes must be equal to 3' - if not structure.flags.contiguous: - structure = structure.copy() + raise RuntimeError, 'metric sizes must be equal to 3' + if not metric.flags.contiguous: + metric = metric.copy() if dt_inplace: if distances.dtype.type != numpy.int32: raise RuntimeError, 'distances must be of int32 type' @@ -661,11 +661,11 @@ ft.shape = dt.shape else: ft = None - _nd_image.distance_transform_op(structure, dt, ft) + _nd_image.distance_transform_op(metric, dt, ft) dt = dt[tuple([slice(None, None, -1)] * rank)] if return_indices: ft = ft[tuple([slice(None, None, -1)] * rank)] - _nd_image.distance_transform_op(structure, dt, ft) + _nd_image.distance_transform_op(metric, dt, ft) dt = dt[tuple([slice(None, None, -1)] * rank)] if return_indices: ft = ft[tuple([slice(None, None, -1)] * rank)] From scipy-svn at scipy.org Sat Nov 1 17:16:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 16:16:43 -0500 (CDT) Subject: [Scipy-svn] r4904 - in trunk/scipy/ndimage: . tests Message-ID: <20081101211643.E545639C088@scipy.org> Author: stefan Date: 2008-11-01 16:16:31 -0500 (Sat, 01 Nov 2008) New Revision: 4904 Modified: trunk/scipy/ndimage/interpolation.py trunk/scipy/ndimage/tests/test_regression.py Log: Correctly assert output shape in `zoom` [patch by Pieter Holtzhausen]. Modified: trunk/scipy/ndimage/interpolation.py =================================================================== --- trunk/scipy/ndimage/interpolation.py 2008-11-01 20:56:33 UTC (rev 4903) +++ trunk/scipy/ndimage/interpolation.py 2008-11-01 21:16:31 UTC (rev 4904) @@ -321,7 +321,7 @@ else: filtered = input zoom = _ni_support._normalize_sequence(zoom, input.ndim) - output_shape = [int(ii * jj) for ii, jj in zip(input.shape, zoom)] + output_shape = tuple([int(ii * jj) for ii, jj in zip(input.shape, zoom)]) zoom = (numpy.array(input.shape)-1)/(numpy.array(output_shape,float)-1) output, return_value = _ni_support._get_output(output, input, output_type, shape = output_shape) Modified: trunk/scipy/ndimage/tests/test_regression.py =================================================================== --- trunk/scipy/ndimage/tests/test_regression.py 2008-11-01 20:56:33 UTC (rev 4903) +++ trunk/scipy/ndimage/tests/test_regression.py 2008-11-01 21:16:31 UTC (rev 4904) @@ -11,5 +11,10 @@ t = ndimage.filters.median_filter(b, (3, 3)) assert_array_almost_equal(ref, t) +def test_zoom_output_shape(): + """Ticket #643""" + x = np.arange(12).reshape((3,4)) + ndimage.zoom(x, 2, output=np.zeros((6,8))) + if __name__ == "__main__": NumpyTest().run() From scipy-svn at scipy.org Sat Nov 1 18:31:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 17:31:02 -0500 (CDT) Subject: [Scipy-svn] r4905 - scipy-docs/trunk/frontpage Message-ID: <20081101223102.02DA339C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 17:30:46 -0500 (Sat, 01 Nov 2008) New Revision: 4905 Modified: scipy-docs/trunk/frontpage/Makefile Log: scipy-docs/frontpage: add upload target in Makefile Modified: scipy-docs/trunk/frontpage/Makefile =================================================================== --- scipy-docs/trunk/frontpage/Makefile 2008-11-01 21:16:31 UTC (rev 4904) +++ scipy-docs/trunk/frontpage/Makefile 2008-11-01 22:30:46 UTC (rev 4905) @@ -9,7 +9,7 @@ # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html web pickle htmlhelp latex changes linkcheck @@ -22,63 +22,72 @@ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview over all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" + @echo " upload USER=... to upload results to docs.scipy.org" clean: - -rm -rf _build/* + -rm -rf build/* dist: html - rm -rf _build/doc - cp -r _build/html _build/doc - rm _build/doc/objects.inv - rm _build/doc/contents.html - rm _build/doc/search.html - rm _build/doc/searchindex.js - cd _build/doc && tar czf ../frontpage.tar.gz * + rm -rf build/dist + cp -r build/html build/dist + rm build/dist/objects.inv + rm build/dist/contents.html + rm build/dist/search.html + rm build/dist/searchindex.js + cd build/dist && tar czf ../dist.tar.gz * + chmod ug=rwX,o=rX -R build/dist + find build/dist -type d -print0 | xargs -0r chmod g+s +upload: + @test -e build/dist || { echo "make dist is required first"; exit 1; } + @test output-is-fine -nt build/dist || { \ + echo "Review the output in build/dist, and do 'touch output-is-fine' before uploading."; exit 1; } + rsync -r -p build/dist/ $(USER)@docs.scipy.org:/home/docserver/www-root/doc/ + html: - mkdir -p _build/html _build/doctrees - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html + mkdir -p build/html build/doctrees + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html @echo - @echo "Build finished. The HTML pages are in _build/html." + @echo "Build finished. The HTML pages are in build/html." pickle: - mkdir -p _build/pickle _build/doctrees - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle + mkdir -p build/pickle build/doctrees + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) build/pickle @echo @echo "Build finished; now you can process the pickle files." web: pickle json: - mkdir -p _build/json _build/doctrees - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json + mkdir -p build/json build/doctrees + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) build/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: - mkdir -p _build/htmlhelp _build/doctrees - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp + mkdir -p build/htmlhelp build/doctrees + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in _build/htmlhelp." + ".hhp project file in build/htmlhelp." latex: - mkdir -p _build/latex _build/doctrees - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex + mkdir -p build/latex build/doctrees + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex @echo - @echo "Build finished; the LaTeX files are in _build/latex." + @echo "Build finished; the LaTeX files are in build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: - mkdir -p _build/changes _build/doctrees - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes + mkdir -p build/changes build/doctrees + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) build/changes @echo - @echo "The overview file is in _build/changes." + @echo "The overview file is in build/changes." linkcheck: - mkdir -p _build/linkcheck _build/doctrees - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck + mkdir -p build/linkcheck build/doctrees + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ - "or in _build/linkcheck/output.txt." + "or in build/linkcheck/output.txt." From scipy-svn at scipy.org Sat Nov 1 18:32:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 1 Nov 2008 17:32:32 -0500 (CDT) Subject: [Scipy-svn] r4906 - in scipy-docs/trunk/frontpage: . _static _templates Message-ID: <20081101223232.D93BE39C05F@scipy.org> Author: ptvirtan Date: 2008-11-01 17:32:06 -0500 (Sat, 01 Nov 2008) New Revision: 4906 Added: scipy-docs/trunk/frontpage/_static/scipy_thumb.png Removed: scipy-docs/trunk/frontpage/_templates/download.html Modified: scipy-docs/trunk/frontpage/ scipy-docs/trunk/frontpage/_static/scipy.css scipy-docs/trunk/frontpage/_templates/indexcontent.html scipy-docs/trunk/frontpage/_templates/indexsidebar.html scipy-docs/trunk/frontpage/_templates/layout.html scipy-docs/trunk/frontpage/conf.py Log: scipy-docs/frontpage: update docs.scipy.org frontpage as per Joe's suggestions Property changes on: scipy-docs/trunk/frontpage ___________________________________________________________________ Name: svn:ignore + build Modified: scipy-docs/trunk/frontpage/_static/scipy.css =================================================================== --- scipy-docs/trunk/frontpage/_static/scipy.css 2008-11-01 22:30:46 UTC (rev 4905) +++ scipy-docs/trunk/frontpage/_static/scipy.css 2008-11-01 22:32:06 UTC (rev 4906) @@ -80,11 +80,14 @@ background-color: rgb(230,230,230); } -div.sphinxsidebar { - background-color: rgb(230,230,230); - overflow: hidden; +div.sphinxsidebar ul span.linkdescr { + color: black; } +div.sphinxsidebar ul li { + margin-bottom: 1em; +} + div.related { background-color: rgb(100,135,220); } @@ -154,3 +157,12 @@ table.footnote td, table.footnote th { border: none; } + +/** + * Logo in the related bar + */ +img.related-logo { + border: 0; + vertical-align: -18%; + margin-right: 0.25em; +} Added: scipy-docs/trunk/frontpage/_static/scipy_thumb.png =================================================================== (Binary files differ) Property changes on: scipy-docs/trunk/frontpage/_static/scipy_thumb.png ___________________________________________________________________ Name: svn:mime-type + image/png Deleted: scipy-docs/trunk/frontpage/_templates/download.html =================================================================== --- scipy-docs/trunk/frontpage/_templates/download.html 2008-11-01 22:30:46 UTC (rev 4905) +++ scipy-docs/trunk/frontpage/_templates/download.html 2008-11-01 22:32:06 UTC (rev 4906) @@ -1,52 +0,0 @@ -{% extends "layout.html" %} -{% set title = 'Download' %} -{% block body %} - -

Download Scipy and Numpy Documentation

- -

This documentation on this site is available for download in - the following formats:

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
HTML (zip)ca. 3 MBNumpy HTML documentation, packaged.
PDF (Numpy reference)ca. 2 MBNumpy reference guide, as PDF.
PDF (Numpy user guide)ca. 0.5 MBNumpy's User Guide (work-in-progress) part, as PDF.
HTML (zip)ca. 3 MBScipy HTML documentation, packaged.
PDF (Scipy reference)ca. 2 MBScipy reference guide (work-in-progress), as PDF.
- -

Additionally, you may be interested in

- - - - - - - - - - -
Guide to NumpyThe original Numpy reference book, by Travis Oliphant.
Scipy.org websiteAdditional community-contributed documentation, tutorials, - examples, etc.
- -{% endblock %} Modified: scipy-docs/trunk/frontpage/_templates/indexcontent.html =================================================================== --- scipy-docs/trunk/frontpage/_templates/indexcontent.html 2008-11-01 22:30:46 UTC (rev 4905) +++ scipy-docs/trunk/frontpage/_templates/indexcontent.html 2008-11-01 22:32:06 UTC (rev 4906) @@ -1,42 +1,37 @@ {% extends "defindex.html" %} {% block tables %} -

Parts of the documentation:

+

Documentation editor:

- - - - +
- -

Work in progress:

+

Mature documentation:

- - - +
- -

Participate:

+

Snapshots of work in progress:

- - - - + + +
- {% endblock %} {% block sidebarsearch %} Modified: scipy-docs/trunk/frontpage/_templates/indexsidebar.html =================================================================== --- scipy-docs/trunk/frontpage/_templates/indexsidebar.html 2008-11-01 22:30:46 UTC (rev 4905) +++ scipy-docs/trunk/frontpage/_templates/indexsidebar.html 2008-11-01 22:32:06 UTC (rev 4906) @@ -1,12 +1,13 @@ -

Download

- - -

Resources

- +

See also:

+
    +
  • SciPy.org
    + all things NumPy/SciPy (bug reports, downloads, conferences, etc.) +
  • +
  • Additional documentation
    + documentation not yet integrated with this site +
  • +
  • Cookbook
    + user-contributed examples and recipes for common tasks +
  • +
+ Modified: scipy-docs/trunk/frontpage/_templates/layout.html =================================================================== --- scipy-docs/trunk/frontpage/_templates/layout.html 2008-11-01 22:30:46 UTC (rev 4905) +++ scipy-docs/trunk/frontpage/_templates/layout.html 2008-11-01 22:32:06 UTC (rev 4906) @@ -1,4 +1,14 @@ {% extends "!layout.html" %} + {% block rootrellink %} +
  • SciPy.org{{ reldelim1 }}
  • {{ shorttitle }}{{ reldelim1 }}
  • {% endblock %} + +{%- block sidebarlogo %} +{%- if logo %} + +{%- endif %} +{%- endblock %} Modified: scipy-docs/trunk/frontpage/conf.py =================================================================== --- scipy-docs/trunk/frontpage/conf.py 2008-11-01 22:30:46 UTC (rev 4905) +++ scipy-docs/trunk/frontpage/conf.py 2008-11-01 22:32:06 UTC (rev 4906) @@ -65,7 +65,7 @@ # List of directories, relative to source directory, that shouldn't be searched # for source files. -exclude_trees = ['_build'] +exclude_trees = ['build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None @@ -131,7 +131,6 @@ # template names. html_additional_pages = { 'index': 'indexcontent.html', - 'download': 'download.html', } # If false, no module index is generated. From scipy-svn at scipy.org Sun Nov 2 03:53:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 02:53:00 -0600 (CST) Subject: [Scipy-svn] r4907 - trunk/scipy/fftpack/tests Message-ID: <20081102085300.CE93339C088@scipy.org> Author: cdavid Date: 2008-11-02 02:52:52 -0600 (Sun, 02 Nov 2008) New Revision: 4907 Modified: trunk/scipy/fftpack/tests/test_basic.py Log: Add failing test for #244: fftn does not work when both shape and axes args are used. Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-11-01 22:32:06 UTC (rev 4906) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:52:52 UTC (rev 4907) @@ -359,6 +359,15 @@ assert_array_almost_equal (y,swapaxes(\ fftn(swapaxes(large_x1,-1,-2)),-1,-2)) + def test_shape_axes_argument2(self): + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-1,), shape=(8,)) + assert_array_almost_equal(y, fft(x, axis=-1, n=8)) + + x = numpy.random.random((10, 5, 3, 7)) + y = fftn(x, axes=(-2,), shape=(4,)) + assert_array_almost_equal(y, fft(x, axis=-2, n=8)) + def test_shape_argument_more(self): # Test that fftn raise a value error exception when s.shape is longer # than x.shape @@ -370,7 +379,6 @@ except ValueError: pass - class TestIfftn(TestCase): def test_definition(self): From scipy-svn at scipy.org Sun Nov 2 03:53:19 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 02:53:19 -0600 (CST) Subject: [Scipy-svn] r4908 - trunk/scipy/fftpack/tests Message-ID: <20081102085319.3F21339C088@scipy.org> Author: cdavid Date: 2008-11-02 02:53:10 -0600 (Sun, 02 Nov 2008) New Revision: 4908 Modified: trunk/scipy/fftpack/tests/test_basic.py Log: Fix fftn test: shape argument in reference and tested call was different. Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:52:52 UTC (rev 4907) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:53:10 UTC (rev 4908) @@ -365,7 +365,7 @@ assert_array_almost_equal(y, fft(x, axis=-1, n=8)) x = numpy.random.random((10, 5, 3, 7)) - y = fftn(x, axes=(-2,), shape=(4,)) + y = fftn(x, axes=(-2,), shape=(8,)) assert_array_almost_equal(y, fft(x, axis=-2, n=8)) def test_shape_argument_more(self): From scipy-svn at scipy.org Sun Nov 2 03:53:37 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 02:53:37 -0600 (CST) Subject: [Scipy-svn] r4909 - trunk/scipy/fftpack/tests Message-ID: <20081102085337.D002339C088@scipy.org> Author: cdavid Date: 2008-11-02 02:53:30 -0600 (Sun, 02 Nov 2008) New Revision: 4909 Modified: trunk/scipy/fftpack/tests/test_basic.py Log: Add a regression test for a bug similar #244, but with fftn instead of fft2. Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:53:10 UTC (rev 4908) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:53:30 UTC (rev 4909) @@ -360,14 +360,21 @@ fftn(swapaxes(large_x1,-1,-2)),-1,-2)) def test_shape_axes_argument2(self): + # Change shape of the last axis x = numpy.random.random((10, 5, 3, 7)) y = fftn(x, axes=(-1,), shape=(8,)) assert_array_almost_equal(y, fft(x, axis=-1, n=8)) + # Change shape of an arbitrary axis which is not the last one x = numpy.random.random((10, 5, 3, 7)) y = fftn(x, axes=(-2,), shape=(8,)) assert_array_almost_equal(y, fft(x, axis=-2, n=8)) + # Change shape of axes: cf #244, where shape and axes were mixed up + x = numpy.random.random((4,4,2)) + y = fftn(x, axes=(-3,-2), shape=(8,8)) + assert_array_almost_equal(y, numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8))) + def test_shape_argument_more(self): # Test that fftn raise a value error exception when s.shape is longer # than x.shape From scipy-svn at scipy.org Sun Nov 2 03:53:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 02:53:53 -0600 (CST) Subject: [Scipy-svn] r4910 - trunk/scipy/fftpack Message-ID: <20081102085353.2F33939C088@scipy.org> Author: cdavid Date: 2008-11-02 02:53:46 -0600 (Sun, 02 Nov 2008) New Revision: 4910 Modified: trunk/scipy/fftpack/basic.py Log: BUG: Refactor fftn axes/shape handling, fix problem similar to #244 which affected fftn as well. Modified: trunk/scipy/fftpack/basic.py =================================================================== --- trunk/scipy/fftpack/basic.py 2008-11-02 08:53:30 UTC (rev 4909) +++ trunk/scipy/fftpack/basic.py 2008-11-02 08:53:46 UTC (rev 4910) @@ -226,41 +226,57 @@ def _raw_fftnd(x, s, axes, direction, overwrite_x, work_function): """ Internal auxiliary function for fftnd, ifftnd.""" if s is None: - s = x.shape - else: - s = tuple(s) if axes is None: - axes = range(len(s)) - elif not len(axes) == len(s): - raise ValueError("when given, axes and shape arguments "\ - "have to be of the same length") + s = x.shape + else: + s = numpy.take(x.shape, axes) - if len(s) > len(x.shape): - raise ValueError("shape cannot be longer than x shape.") - for i in range(-len(s),0): - if x.shape[i]!=s[i]: - x = _fix_shape(x,s[i],i) + s = tuple(s) + if axes is None: + noaxes = True + axes = range(-x.ndim, 0) + else: + noaxes = False + if len(axes) != len(s): + raise ValueError("when given, axes and shape arguments "\ + "have to be of the same length") - if axes is None: + # No need to swap axes, array is in C order + if noaxes: + for i in axes: + x = _fix_shape(x, s[i], i) + #print x.shape, s return work_function(x,s,direction,overwrite_x=overwrite_x) - #XXX: should we allow/check for repeated indices in axes? - # If allowed then using it has an effect of reducing the shape - # implicitly. - s = [x.shape[i] for i in axes] - s = [1]*(len(x.shape)-len(s)) + s - swaps = [] - state = range(-len(s),0) - for i in range(-1,-len(axes)-1,-1): - j = state[axes[i]] - if i==j: continue - state[i],state[j]=state[j],state[i] - swaps.append((j,i)) - x = swapaxes(x, j,i) - r = work_function(x,s,direction,overwrite_x=overwrite_x) - swaps.reverse() - for i,j in swaps: - r = swapaxes(r,i,j) + # We ordered axes, because the code below to push axes at the end of the + # array assumes axes argument is in ascending order. + id = numpy.argsort(axes) + axes = [axes[i] for i in id] + s = [s[i] for i in id] + + # Swap the request axes, last first (i.e. First swap the axis which ends up + # at -1, then at -2, etc...), such as the request axes on which the + # operation is carried become the last ones + for i in range(1, len(axes)+1): + x = numpy.swapaxes(x, axes[-i], -i) + + # We can now operate on the axes waxes, the p last axes (p = len(axes)), by + # fixing the shape of the input array to 1 for any axis the fft is not + # carried upon. + waxes = range(x.ndim - len(axes), x.ndim) + shape = numpy.ones(x.ndim) + shape[waxes] = s + + for i in range(len(waxes)): + x = _fix_shape(x, s[i], waxes[i]) + + r = work_function(x, shape, direction, overwrite_x=overwrite_x) + + # reswap in the reverse order (first axis first, etc...) to get original + # order + for i in range(len(axes), 0, -1): + r = numpy.swapaxes(r, -i, axes[-i]) + return r From scipy-svn at scipy.org Sun Nov 2 03:54:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 02:54:10 -0600 (CST) Subject: [Scipy-svn] r4911 - trunk/scipy/fftpack/tests Message-ID: <20081102085410.AF35F39C088@scipy.org> Author: cdavid Date: 2008-11-02 02:54:02 -0600 (Sun, 02 Nov 2008) New Revision: 4911 Modified: trunk/scipy/fftpack/tests/test_basic.py Log: BUG: Add regression test for #244 proper. Modified: trunk/scipy/fftpack/tests/test_basic.py =================================================================== --- trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:53:46 UTC (rev 4910) +++ trunk/scipy/fftpack/tests/test_basic.py 2008-11-02 08:54:02 UTC (rev 4911) @@ -12,7 +12,7 @@ """ from numpy.testing import * -from scipy.fftpack import ifft,fft,fftn,ifftn,rfft,irfft +from scipy.fftpack import ifft,fft,fftn,ifftn,rfft,irfft, fft2 from scipy.fftpack import _fftpack as fftpack from numpy import arange, add, array, asarray, zeros, dot, exp, pi,\ @@ -230,6 +230,15 @@ assert_array_almost_equal (irfft(rfft(x)),x) assert_array_almost_equal (rfft(irfft(x)),x) +class Testfft2(TestCase): + def test_regression_244(self): + """fft returns wrong result with axes parameter.""" + # fftn (and hence fft2) used to break when both axes and shape were + # used + x = numpy.ones((4,4,2)) + y = fft2(x, shape=(8,8), axes=(-3,-2)) + y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2)) + assert_array_almost_equal(y, y_r) class TestFftn(TestCase): From scipy-svn at scipy.org Sun Nov 2 04:33:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 03:33:23 -0600 (CST) Subject: [Scipy-svn] r4912 - trunk/scipy/stats Message-ID: <20081102093323.02B8E39C089@scipy.org> Author: cdavid Date: 2008-11-02 03:33:17 -0600 (Sun, 02 Nov 2008) New Revision: 4912 Modified: trunk/scipy/stats/SConscript Log: BUG: vonmises cython implementation not added to numscons build. Modified: trunk/scipy/stats/SConscript =================================================================== --- trunk/scipy/stats/SConscript 2008-11-02 08:54:02 UTC (rev 4911) +++ trunk/scipy/stats/SConscript 2008-11-02 09:33:17 UTC (rev 4912) @@ -1,4 +1,4 @@ -# Last Change: Thu Jun 12 07:00 PM 2008 J +# Last Change: Sun Nov 02 06:00 PM 2008 J # vim:syntax=python from os.path import join as pjoin @@ -30,3 +30,6 @@ # mvn extension env.NumpyPythonExtension('mvn', source = ['mvn.pyf', 'mvndst.f']) + +# vonmisses_cython extension +env.NumpyPythonExtension('vonmises_cython', source = ['vonmises_cython.c']) From scipy-svn at scipy.org Sun Nov 2 04:53:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 03:53:00 -0600 (CST) Subject: [Scipy-svn] r4913 - trunk/scipy/stats/tests Message-ID: <20081102095300.36FB339C089@scipy.org> Author: cdavid Date: 2008-11-02 03:52:52 -0600 (Sun, 02 Nov 2008) New Revision: 4913 Modified: trunk/scipy/stats/tests/test_stats.py Log: Add basic regression test for Student's t-test. Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-02 09:33:17 UTC (rev 4912) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-02 09:52:52 UTC (rev 4913) @@ -866,5 +866,24 @@ assert_array_equal(stats.threshold(a,2,4,0), [0,2,3,4,0,0,0]) +# Hypothesis test tests +class TestStudentTest(TestCase): + X1 = np.array([-1, 0, 1]) + X2 = np.array([0, 1, 2]) + T1 = 0 + P1 = 1 + T2 = 1.732051 + P2 = 0.2254033 + def test_onesample(self): + t, p = stats.ttest_1samp(self.X1, 0) + + assert_array_almost_equal(t, self.T1) + assert_array_almost_equal(p, self.P1) + + t, p = stats.ttest_1samp(self.X2, 0) + + assert_array_almost_equal(t, self.T2) + assert_array_almost_equal(p, self.P2) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Sun Nov 2 04:53:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 03:53:18 -0600 (CST) Subject: [Scipy-svn] r4914 - trunk/scipy/stats/tests Message-ID: <20081102095318.A823939C089@scipy.org> Author: cdavid Date: 2008-11-02 03:53:10 -0600 (Sun, 02 Nov 2008) New Revision: 4914 Modified: trunk/scipy/stats/tests/test_stats.py Log: More tests for Student t-test. Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-02 09:52:52 UTC (rev 4913) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-02 09:53:10 UTC (rev 4914) @@ -870,20 +870,34 @@ class TestStudentTest(TestCase): X1 = np.array([-1, 0, 1]) X2 = np.array([0, 1, 2]) - T1 = 0 - P1 = 1 - T2 = 1.732051 - P2 = 0.2254033 + T1_0 = 0 + P1_0 = 1 + T1_1 = -1.732051 + P1_1 = 0.2254033 + T1_2 = -3.464102 + P1_2 = 0.0741799 + T2_0 = 1.732051 + P2_0 = 0.2254033 def test_onesample(self): t, p = stats.ttest_1samp(self.X1, 0) - assert_array_almost_equal(t, self.T1) - assert_array_almost_equal(p, self.P1) + assert_array_almost_equal(t, self.T1_0) + assert_array_almost_equal(p, self.P1_0) t, p = stats.ttest_1samp(self.X2, 0) - assert_array_almost_equal(t, self.T2) - assert_array_almost_equal(p, self.P2) + assert_array_almost_equal(t, self.T2_0) + assert_array_almost_equal(p, self.P2_0) + t, p = stats.ttest_1samp(self.X1, 1) + + assert_array_almost_equal(t, self.T1_1) + assert_array_almost_equal(p, self.P1_1) + + t, p = stats.ttest_1samp(self.X1, 2) + + assert_array_almost_equal(t, self.T1_2) + assert_array_almost_equal(p, self.P1_2) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Sun Nov 2 04:53:35 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 03:53:35 -0600 (CST) Subject: [Scipy-svn] r4915 - trunk/scipy/stats Message-ID: <20081102095335.4F37439C089@scipy.org> Author: cdavid Date: 2008-11-02 03:53:28 -0600 (Sun, 02 Nov 2008) New Revision: 4915 Modified: trunk/scipy/stats/stats.py Log: Use numpy means/var in Student's t-test. Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-02 09:53:10 UTC (rev 4914) +++ trunk/scipy/stats/stats.py 2008-11-02 09:53:28 UTC (rev 4915) @@ -1720,8 +1720,8 @@ Returns: t-value, two-tailed prob """ a = asarray(a) - x = mean(a,None) - v = var(a,None) + x = np.mean(a) + v = np.var(a, ddof=1) n = len(a) df = n-1 svar = ((n-1)*v) / float(df) From scipy-svn at scipy.org Sun Nov 2 05:11:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 04:11:40 -0600 (CST) Subject: [Scipy-svn] r4916 - in trunk/scipy/stats: . tests Message-ID: <20081102101140.AABB939C088@scipy.org> Author: stefan Date: 2008-11-02 04:11:28 -0600 (Sun, 02 Nov 2008) New Revision: 4916 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_stats.py Log: Skew and kurtosis should return the same type for 1-D array input. Closes Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-02 09:53:28 UTC (rev 4915) +++ trunk/scipy/stats/stats.py 2008-11-02 10:11:28 UTC (rev 4916) @@ -806,6 +806,10 @@ m4 = np.extract(can_correct, m4) nval = 1.0/(n-2)/(n-3)*((n*n-1.0)*m4/m2**2.0-3*(n-1)**2.0) np.place(vals, can_correct, nval+3.0) + + if vals.ndim == 0: + vals = vals.item() # array scalar + if fisher: return vals - 3 else: Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-02 09:53:28 UTC (rev 4915) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-02 10:11:28 UTC (rev 4916) @@ -855,6 +855,9 @@ y = stats.kurtosis(self.testcase,0,0) assert_approx_equal(y,1.64) + def test_kurtosis_array_scalar(self): + assert_equal(type(stats.kurtosis([1,2,3])), float) + class TestThreshold(TestCase): def test_basic(self): a = [-1,2,3,4,5,-1,-2] From scipy-svn at scipy.org Sun Nov 2 06:32:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 05:32:28 -0600 (CST) Subject: [Scipy-svn] r4917 - trunk/scipy/signal Message-ID: <20081102113228.CEB5E39C088@scipy.org> Author: stefan Date: 2008-11-02 05:32:19 -0600 (Sun, 02 Nov 2008) New Revision: 4917 Modified: trunk/scipy/signal/signaltools.py Log: Wrap long lines. Modified: trunk/scipy/signal/signaltools.py =================================================================== --- trunk/scipy/signal/signaltools.py 2008-11-02 10:11:28 UTC (rev 4916) +++ trunk/scipy/signal/signaltools.py 2008-11-02 11:32:19 UTC (rev 4917) @@ -17,14 +17,17 @@ from scipy.misc import factorial _modedict = {'valid':0, 'same':1, 'full':2} -_boundarydict = {'fill':0, 'pad':0, 'wrap':2, 'circular':2, 'symm':1, 'symmetric':1, 'reflect':4} +_boundarydict = {'fill':0, 'pad':0, 'wrap':2, 'circular':2, 'symm':1, + 'symmetric':1, 'reflect':4} + def _valfrommode(mode): try: val = _modedict[mode] except KeyError: if mode not in [0,1,2]: - raise ValueError, "Acceptable mode flags are 'valid' (0), 'same' (1), or 'full' (2)." + raise ValueError, "Acceptable mode flags are 'valid' (0)," \ + "'same' (1), or 'full' (2)." val = mode return val @@ -33,7 +36,8 @@ val = _boundarydict[boundary] << 2 except KeyError: if val not in [0,1,2] : - raise ValueError, "Acceptable boundary flags are 'fill', 'wrap' (or 'circular'), \n and 'symm' (or 'symmetric')." + raise ValueError, "Acceptable boundary flags are 'fill', 'wrap'" \ + " (or 'circular'), \n and 'symm' (or 'symmetric')." val = boundary << 2 return val @@ -185,7 +189,8 @@ size = domain.shape for k in range(len(size)): if (size[k] % 2) != 1: - raise ValueError, "Each dimension of domain argument should have an odd number of elements." + raise ValueError, "Each dimension of domain argument " \ + "should have an odd number of elements." return sigtools._order_filterND(a, domain, rank) @@ -692,7 +697,8 @@ a = [0.2156, 0.4160, 0.2781, 0.0836, 0.0069] n = arange(0,M) fac = n*2*pi/(M-1.0) - w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) + a[4]*cos(4*fac) + w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) + \ + a[4]*cos(4*fac) if not sym and not odd: w = w[:-1] return w @@ -1339,17 +1345,19 @@ """Resample to num samples using Fourier method along the given axis. The resampled signal starts at the same value of x but is sampled - with a spacing of len(x) / num * (spacing of x). Because a Fourier method - is used, the signal is assumed periodic. + with a spacing of len(x) / num * (spacing of x). Because a + Fourier method is used, the signal is assumed periodic. - Window controls a Fourier-domain window that tapers the Fourier spectrum - before zero-padding to aleviate ringing in the resampled values for - sampled signals you didn't intend to be interpreted as band-limited. + Window controls a Fourier-domain window that tapers the Fourier + spectrum before zero-padding to aleviate ringing in the resampled + values for sampled signals you didn't intend to be interpreted as + band-limited. - If window is a string then use the named window. If window is a float, then - it represents a value of beta for a kaiser window. If window is a tuple, - then the first component is a string representing the window, and the next - arguments are parameters for that window. + If window is a string then use the named window. If window is a + float, then it represents a value of beta for a kaiser window. If + window is a tuple, then the first component is a string + representing the window, and the next arguments are parameters for + that window. Possible windows are: 'blackman' ('black', 'blk') @@ -1361,12 +1369,14 @@ 'general gauss' ('general', 'ggs') # requires two parameters (power, width) - The first sample of the returned vector is the same as the first sample of the - input vector, the spacing between samples is changed from dx to + The first sample of the returned vector is the same as the first + sample of the input vector, the spacing between samples is changed + from dx to + dx * len(x) / num If t is not None, then it represents the old sample positions, and the new - sample positions will be returned as well as the new samples. + sample positions will be returned as well as the new samples. """ x = asarray(x) X = fft(x,axis=axis) @@ -1420,14 +1430,16 @@ N = dshape[axis] bp = sort(unique(r_[0,bp,N])) if any(bp > N): - raise ValueError, "Breakpoints must be less than length of data along given axis." + raise ValueError, "Breakpoints must be less than length " \ + "of data along given axis." Nreg = len(bp) - 1 # Restructure data so that axis is along first dimension and # all other dimensions are collapsed into second dimension rnk = len(dshape) if axis < 0: axis = axis + rnk newdims = r_[axis,0:axis,axis+1:rnk] - newdata = reshape(transpose(data,tuple(newdims)),(N,prod(dshape,axis=0)/N)) + newdata = reshape(transpose(data, tuple(newdims)), + (N, prod(dshape, axis=0)/N)) newdata = newdata.copy() # make sure we have a copy if newdata.dtype.char not in 'dfDF': newdata = newdata.astype(dtype) @@ -1457,7 +1469,8 @@ #x must be bigger than edge if x.size < edge: - raise ValueError, "Input vector needs to be bigger than 3 * max(len(a),len(b)." + raise ValueError, "Input vector needs to be bigger than " \ + "3 * max(len(a),len(b)." if len(a) < ntaps: a=r_[a,zeros(len(b)-len(a))] From scipy-svn at scipy.org Sun Nov 2 06:32:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 05:32:56 -0600 (CST) Subject: [Scipy-svn] r4918 - trunk/scipy/signal Message-ID: <20081102113256.9361839C088@scipy.org> Author: stefan Date: 2008-11-02 05:32:47 -0600 (Sun, 02 Nov 2008) New Revision: 4918 Modified: trunk/scipy/signal/signaltools.py Log: Update docs. Fix scaling of residue. Modified: trunk/scipy/signal/signaltools.py =================================================================== --- trunk/scipy/signal/signaltools.py 2008-11-02 11:32:19 UTC (rev 4917) +++ trunk/scipy/signal/signaltools.py 2008-11-02 11:32:47 UTC (rev 4918) @@ -1058,7 +1058,10 @@ -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n - See also: residue, poly, polyval, unique_roots + See Also + -------- + residue, poly, polyval, unique_roots + """ extra = k p, indx = cmplx_sort(p) @@ -1108,10 +1111,23 @@ -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n - See also: invres, poly, polyval, unique_roots + Returns + ------- + r : ndarray + Residues + p : ndarray + Poles + k : ndarray + Coefficients of the direct polynomial term. + + See Also + -------- + invres, poly, polyval, unique_roots + """ b,a = map(asarray,(b,a)) + rscale = a[0] k,b = polydiv(b,a) p = roots(a) r = p*0.0 @@ -1142,7 +1158,7 @@ r[indx+m-1] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += sig - return r, p, k + return r/rscale, p, k def residuez(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(z) / a(z). From scipy-svn at scipy.org Sun Nov 2 17:37:41 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 16:37:41 -0600 (CST) Subject: [Scipy-svn] r4919 - in trunk/scipy/stats: . tests Message-ID: <20081102223741.389A239C088@scipy.org> Author: stefan Date: 2008-11-02 16:37:22 -0600 (Sun, 02 Nov 2008) New Revision: 4919 Modified: trunk/scipy/stats/distributions.py trunk/scipy/stats/tests/test_distributions.py Log: Start refactoring rv_continuous and rv_discrete. Fix output of distributions to be more like NumPy (i.e. return scalar for single value). Closes #539. Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-02 11:32:47 UTC (rev 4918) +++ trunk/scipy/stats/distributions.py 2008-11-02 22:37:22 UTC (rev 4919) @@ -240,7 +240,81 @@ newargs[k] = extract(cond,newarr*expand_arr) return newargs -class rv_continuous(object): +class rv_generic(object): + """Class which encapsulates common functionality between rv_discrete + and rv_continuous. + + """ + def _fix_loc_scale(self, args, loc, scale=1): + N = len(args) + if N > self.numargs: + if N == self.numargs + 1 and loc is None: + # loc is given without keyword + loc = args[-1] + if N == self.numargs + 2 and scale is None: + # loc and scale given without keyword + loc, scale = args[-2:] + args = args[:self.numargs] + if scale is None: + scale = 1.0 + if loc is None: + loc = 0.0 + return args, loc, scale + + def _fix_loc(self, args, loc): + args, loc, scale = self._fix_loc_scale(args, loc) + return args, loc + + # These are actually called, and should not be overwritten if you + # want to keep error checking. + def rvs(self,*args,**kwds): + """Random variates of given type. + + *args + ===== + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + + **kwds + ====== + size - number of random variates (default=1) + loc - location parameter (default=0) + scale - scale parameter (default=1) + """ + kwd_names = ['loc', 'scale', 'size', 'discrete'] + loc, scale, size, discrete = map(kwds.get, kwd_names, + [None]*len(kwd_names)) + + args, loc, scale = self._fix_loc_scale(args, loc, scale) + cond = logical_and(self._argcheck(*args),(scale >= 0)) + if not all(cond): + raise ValueError, "Domain error in arguments." + + # self._size is total size of all output values + self._size = product(size, axis=0) + if self._size > 1: + size = numpy.array(size, ndmin=1) + + if scale == 0: + return loc*ones(size, 'd') + + vals = self._rvs(*args) + if self._size is not None: + vals = reshape(vals, size) + + vals = vals * scale + loc + + # Cast to int if discrete + if discrete: + if numpy.isscalar(vals): + vals = int(vals) + else: + vals = vals.astype(int) + + return vals + + +class rv_continuous(rv_generic): """A Generic continuous random variable. Continuous random variables are defined from a standard form chosen @@ -284,7 +358,12 @@ - frozen RV object with the same methods but holding the given shape, location, and scale fixed """ - def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): + def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, + xtol=1e-14, badvalue=None, name=None, longname=None, + shapes=None, extradoc=None): + + rv_generic.__init__(self) + if badvalue is None: badvalue = nan self.badvalue = badvalue @@ -400,59 +479,6 @@ def _munp(self,n,*args): return self.generic_moment(n,*args) - def __fix_loc_scale(self, args, loc, scale): - N = len(args) - if N > self.numargs: - if N == self.numargs + 1 and loc is None: - # loc is given without keyword - loc = args[-1] - if N == self.numargs + 2 and scale is None: - # loc and scale given without keyword - loc, scale = args[-2:] - args = args[:self.numargs] - if scale is None: - scale = 1.0 - if loc is None: - loc = 0.0 - return args, loc, scale - - # These are actually called, but should not - # be overwritten if you want to keep - # the error checking. - def rvs(self,*args,**kwds): - """Random variates of given type. - - *args - ===== - The shape parameter(s) for the distribution (see docstring of the - instance object for more information) - - **kwds - ====== - size - number of random variates (default=1) - loc - location parameter (default=0) - scale - scale parameter (default=1) - """ - loc,scale,size=map(kwds.get,['loc','scale','size']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) - cond = logical_and(self._argcheck(*args),(scale >= 0)) - if not all(cond): - raise ValueError, "Domain error in arguments." - - if size is None: - size = 1 - else: - self._size = product(size,axis=0) - if numpy.isscalar(size): - self._size = size - size = (size,) - - vals = reshape(self._rvs(*args),size) - if scale == 0: - return loc*ones(size,'d') - else: - return vals * scale + loc - def pdf(self,x,*args,**kwds): """Probability density function at x of the given RV. @@ -467,7 +493,7 @@ scale - scale parameter (default=1) """ loc,scale=map(kwds.get,['loc','scale']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) + args, loc, scale = self._fix_loc_scale(args, loc, scale) x,loc,scale = map(arr,(x,loc,scale)) args = tuple(map(arr,args)) x = arr((x-loc)*1.0/scale) @@ -497,7 +523,7 @@ scale - scale parameter (default=1) """ loc,scale=map(kwds.get,['loc','scale']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) + args, loc, scale = self._fix_loc_scale(args, loc, scale) x,loc,scale = map(arr,(x,loc,scale)) args = tuple(map(arr,args)) x = (x-loc)*1.0/scale @@ -528,7 +554,7 @@ scale - scale parameter (default=1) """ loc,scale=map(kwds.get,['loc','scale']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) + args, loc, scale = self._fix_loc_scale(args, loc, scale) x,loc,scale = map(arr,(x,loc,scale)) args = tuple(map(arr,args)) x = (x-loc)*1.0/scale @@ -559,7 +585,7 @@ scale - scale parameter (default=1) """ loc,scale=map(kwds.get,['loc','scale']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) + args, loc, scale = self._fix_loc_scale(args, loc, scale) q,loc,scale = map(arr,(q,loc,scale)) args = tuple(map(arr,args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc==loc) @@ -590,7 +616,7 @@ scale - scale parameter (default=1) """ loc,scale=map(kwds.get,['loc','scale']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) + args, loc, scale = self._fix_loc_scale(args, loc, scale) q,loc,scale = map(arr,(q,loc,scale)) args = tuple(map(arr,args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc==loc) @@ -800,7 +826,7 @@ def entropy(self, *args, **kwds): loc,scale=map(kwds.get,['loc','scale']) - args, loc, scale = self.__fix_loc_scale(args, loc, scale) + args, loc, scale = self._fix_loc_scale(args, loc, scale) args = map(arr,args) cond0 = self._argcheck(*args) & (scale > 0) & (loc==loc) output = zeros(shape(cond0),'d') @@ -3301,7 +3327,7 @@ # Must over-ride one of _pmf or _cdf or pass in # x_k, p(x_k) lists in initialization -class rv_discrete: +class rv_discrete(rv_generic): """A generic discrete random variable. Discrete random variables are defined from a standard form. @@ -3350,6 +3376,9 @@ def __init__(self, a=0, b=inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): + + rv_generic.__init__(self) + if badvalue is None: badvalue = nan self.badvalue = badvalue @@ -3424,16 +3453,6 @@ def _rvs(self, *args): return self._ppf(mtrand.random_sample(self._size),*args) - def __fix_loc(self, args, loc): - N = len(args) - if N > self.numargs: - if N == self.numargs + 1 and loc is None: # loc is given without keyword - loc = args[-1] - args = args[:self.numargs] - if loc is None: - loc = 0 - return args, loc - def _nonzero(self, k, *args): return floor(k)==k @@ -3470,28 +3489,10 @@ return self.generic_moment(n) - def rvs(self, *args, **kwds): - loc,size=map(kwds.get,['loc','size']) - args, loc = self.__fix_loc(args, loc) - cond = self._argcheck(*args) - if not all(cond): - raise ValueError, "Domain error in arguments." + def rvs(self, *args, **kwargs): + kwargs['discrete'] = True + return rv_generic.rvs(self, *args, **kwargs) - if size is None: - size = 1 - else: - self._size = product(size,axis=0) - if numpy.isscalar(size): - self._size = size - size = (size,) - - vals = reshape(self._rvs(*args),size) - if self.return_integers: - vals = arr(vals) - if vals.dtype.char not in numpy.typecodes['AllInteger']: - vals = vals.astype(int) - return vals + loc - def pmf(self, k,*args, **kwds): """Probability mass function at k of the given RV. @@ -3505,7 +3506,7 @@ loc - location parameter (default=0) """ loc = kwds.get('loc') - args, loc = self.__fix_loc(args, loc) + args, loc = self._fix_loc(args, loc) k,loc = map(arr,(k,loc)) args = tuple(map(arr,args)) k = arr((k-loc)) @@ -3533,7 +3534,7 @@ loc - location parameter (default=0) """ loc = kwds.get('loc') - args, loc = self.__fix_loc(args, loc) + args, loc = self._fix_loc(args, loc) k,loc = map(arr,(k,loc)) args = tuple(map(arr,args)) k = arr((k-loc)) @@ -3563,7 +3564,7 @@ loc - location parameter (default=0) """ loc= kwds.get('loc') - args, loc = self.__fix_loc(args, loc) + args, loc = self._fix_loc(args, loc) k,loc = map(arr,(k,loc)) args = tuple(map(arr,args)) k = arr(k-loc) @@ -3593,7 +3594,7 @@ loc - location parameter (default=0) """ loc = kwds.get('loc') - args, loc = self.__fix_loc(args, loc) + args, loc = self._fix_loc(args, loc) q,loc = map(arr,(q,loc)) args = tuple(map(arr,args)) cond0 = self._argcheck(*args) & (loc == loc) @@ -3624,7 +3625,7 @@ """ loc = kwds.get('loc') - args, loc = self.__fix_loc(args, loc) + args, loc = self._fix_loc(args, loc) q,loc = map(arr,(q,loc)) args = tuple(map(arr,args)) cond0 = self._argcheck(*args) & (loc == loc) @@ -3795,7 +3796,7 @@ def entropy(self, *args, **kwds): loc= kwds.get('loc') - args, loc = self.__fix_loc(args, loc) + args, loc = self._fix_loc(args, loc) loc = arr(loc) args = map(arr,args) cond0 = self._argcheck(*args) & (loc==loc) @@ -4180,15 +4181,13 @@ g1 = 0.0 g2 = -6.0/5.0*(d*d+1.0)/(d-1.0)*(d+1.0) return mu, var, g1, g2 - def rvs(self, min, max=None, size=None): + def _rvs(self, min, max=None): """An array of *size* random integers >= min and < max. If max is None, then range is >=0 and < min """ + return mtrand.randint(min, max, self._size) - # Return an array scalar if needed. - return arr(mtrand.randint(min, max, size))[()] - def _entropy(self, min, max): return log(max-min) randint = randint_gen(name='randint',longname='A discrete uniform '\ Modified: trunk/scipy/stats/tests/test_distributions.py =================================================================== --- trunk/scipy/stats/tests/test_distributions.py 2008-11-02 11:32:47 UTC (rev 4918) +++ trunk/scipy/stats/tests/test_distributions.py 2008-11-02 22:37:22 UTC (rev 4919) @@ -83,6 +83,7 @@ val = stats.randint.rvs(15,46) assert((val >= 15) & (val < 46)) assert isinstance(val, numpy.ScalarType),`type(val)` + val = stats.randint(15,46).rvs(3) assert(val.dtype.char in typecodes['AllInteger']) def test_pdf(self): @@ -105,6 +106,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.binom.rvs(10, 0.75) + assert(isinstance(val, int)) + val = stats.binom(10, 0.75).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -116,6 +119,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.bernoulli.rvs(0.75) + assert(isinstance(val, int)) + val = stats.bernoulli(0.75).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -126,6 +131,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.nbinom.rvs(10, 0.75) + assert(isinstance(val, int)) + val = stats.nbinom(10, 0.75).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -136,6 +143,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.geom.rvs(0.75) + assert(isinstance(val, int)) + val = stats.geom(0.75).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -159,6 +168,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.hypergeom.rvs(20, 3, 10) + assert(isinstance(val, int)) + val = stats.hypergeom(20, 3, 10).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -169,6 +180,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.logser.rvs(0.75) + assert(isinstance(val, int)) + val = stats.logser(0.75).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -179,6 +192,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.poisson.rvs(0.5) + assert(isinstance(val, int)) + val = stats.poisson(0.5).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -189,6 +204,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.zipf.rvs(1.5) + assert(isinstance(val, int)) + val = stats.zipf(1.5).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -198,6 +215,8 @@ assert(numpy.shape(vals) == (2, 50)) assert(vals.dtype.char in typecodes['AllInteger']) val = stats.dlaplace.rvs(1.5) + assert(isinstance(val, int)) + val = stats.dlaplace(1.5).rvs(3) assert(isinstance(val, numpy.ndarray)) assert(val.dtype.char in typecodes['AllInteger']) @@ -208,10 +227,14 @@ samples = 1000 r = stats.rv_discrete(name='sample',values=(states,probability)) x = r.rvs(size=samples) + assert(isinstance(x, numpy.ndarray)) for s,p in zip(states,probability): assert abs(sum(x == s)/float(samples) - p) < 0.05 + x = r.rvs() + assert(isinstance(x, int)) + class TestExpon(TestCase): def test_zero(self): assert_equal(stats.expon.pdf(0),1) From scipy-svn at scipy.org Sun Nov 2 18:45:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 17:45:27 -0600 (CST) Subject: [Scipy-svn] r4920 - trunk/scipy/special Message-ID: <20081102234527.B82C739C088@scipy.org> Author: ptvirtan Date: 2008-11-02 17:45:17 -0600 (Sun, 02 Nov 2008) New Revision: 4920 Modified: trunk/scipy/special/info.py Log: special.info: remove references to non-existing functions. Closes #580 Modified: trunk/scipy/special/info.py =================================================================== --- trunk/scipy/special/info.py 2008-11-02 22:37:22 UTC (rev 4919) +++ trunk/scipy/special/info.py 2008-11-02 23:45:17 UTC (rev 4920) @@ -123,7 +123,9 @@ * fdtri -- Inverse of fdtrc * gdtr -- Integral from 0 to x of gamma pdf. * gdtrc -- Integral from x to infinity under gamma pdf. -* gdtri -- Quantiles of gamma distribution +* gdtria -- +* gdtrib -- +* gdtrix -- * nbdtr -- Sum of terms 0 through k of the negative binomial pdf. * nbdtrc -- Sum of terms k+1 to infinity under negative binomial pdf. * nbdtri -- Inverse of nbdtr @@ -131,7 +133,8 @@ * pdtrc -- Sum of terms k+1 to infinity of the Poisson pdf. * pdtri -- Inverse of pdtr * stdtr -- Integral from -infinity to t of the Student-t pdf. -* stdtri -- Inverse of stdtr (quantiles) +* stdtridf -- +* stdtrit -- * chdtr -- Integral from 0 to x of the Chi-square pdf. * chdtrc -- Integral from x to infnity of Chi-square pdf. * chdtri -- Inverse of chdtrc. @@ -156,8 +159,6 @@ * betaln -- Log of the absolute value of the beta function. * betainc -- Incomplete beta integral. * betaincinv -- Inverse of betainc. -* betaincinva -- Inverse (in first argument, a) of betainc -* betaincinvb -- Inverse (in first argument, b) of betainc * psi(digamma) -- Logarithmic derivative of the gamma function. * rgamma -- One divided by the gamma function. * polygamma -- Nth derivative of psi function. From scipy-svn at scipy.org Sun Nov 2 18:55:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 17:55:57 -0600 (CST) Subject: [Scipy-svn] r4921 - in trunk/scipy: fftpack interpolate sparse sparse/tests special Message-ID: <20081102235557.E8EF439C088@scipy.org> Author: jarrod.millman Date: 2008-11-02 17:55:52 -0600 (Sun, 02 Nov 2008) New Revision: 4921 Modified: trunk/scipy/fftpack/basic.py trunk/scipy/interpolate/rbf.py trunk/scipy/sparse/bsr.py trunk/scipy/sparse/compressed.py trunk/scipy/sparse/dok.py trunk/scipy/sparse/extract.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/special/info.py Log: ran reindent Modified: trunk/scipy/fftpack/basic.py =================================================================== --- trunk/scipy/fftpack/basic.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/fftpack/basic.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -241,7 +241,7 @@ raise ValueError("when given, axes and shape arguments "\ "have to be of the same length") - # No need to swap axes, array is in C order + # No need to swap axes, array is in C order if noaxes: for i in axes: x = _fix_shape(x, s[i], i) Modified: trunk/scipy/interpolate/rbf.py =================================================================== --- trunk/scipy/interpolate/rbf.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/interpolate/rbf.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -49,7 +49,7 @@ class Rbf(object): """ Rbf(*args) - + A class for radial basis function approximation/interpolation of n-dimensional scattered data. Modified: trunk/scipy/sparse/bsr.py =================================================================== --- trunk/scipy/sparse/bsr.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/sparse/bsr.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -167,7 +167,7 @@ raise ValueError('need to infer shape') else: self.shape = shape - + if dtype is not None: self.data = self.data.astype(dtype) Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/sparse/compressed.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -83,7 +83,7 @@ raise ValueError,'unable to infer matrix dimensions' else: self.shape = self._swap((major_dim,minor_dim)) - + if dtype is not None: self.data = self.data.astype(dtype) Modified: trunk/scipy/sparse/dok.py =================================================================== --- trunk/scipy/sparse/dok.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/sparse/dok.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -59,7 +59,7 @@ arg1 = arg1.copy() else: arg1 = arg1.todok() - + if dtype is not None: arg1 = arg1.astype(dtype) @@ -379,7 +379,7 @@ for (i,j),v in self.iteritems(): result[i] += v * other[j] return result - + def _mul_multivector(self, other): #matrix * multivector M,N = self.shape @@ -493,7 +493,7 @@ newkey = (key[0]-num, key[1]) base[newkey] = self[key] return base, ext - + def tocoo(self): """ Return a copy of this matrix in COOrdinate format""" from coo import coo_matrix Modified: trunk/scipy/sparse/extract.py =================================================================== --- trunk/scipy/sparse/extract.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/sparse/extract.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -29,7 +29,7 @@ >>> A = csr_matrix([[7.0, 8.0, 0],[0, 0, 9.0]]) >>> find(A) (array([0, 0, 1], dtype=int32), array([0, 1, 2], dtype=int32), array([ 7., 8., 9.])) - + """ A = coo_matrix(A).tocsr() #sums duplicates Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/sparse/tests/test_base.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -151,7 +151,7 @@ def test_from_array(self): A = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) assert_array_equal(self.spmatrix(A).toarray(), A) - + A = array([[1.0 + 3j, 0, 0], [ 0, 2.0 + 5, 0], [ 0, 0, 0]]) @@ -161,7 +161,7 @@ def test_from_matrix(self): A = matrix([[1,0,0],[2,3,4],[0,5,0],[0,0,0]]) assert_array_equal(self.spmatrix(A).todense(), A) - + A = matrix([[1.0 + 3j, 0, 0], [ 0, 2.0 + 5, 0], [ 0, 0, 0]]) @@ -171,7 +171,7 @@ def test_from_list(self): A = [[1,0,0],[2,3,4],[0,5,0],[0,0,0]] assert_array_equal(self.spmatrix(A).todense(), A) - + A = [[1.0 + 3j, 0, 0], [ 0, 2.0 + 5, 0], [ 0, 0, 0]] @@ -224,7 +224,7 @@ dense_dot_dense = dot(dat, b) check2 = dot(self.datsp.toarray(), b) assert_array_equal(dense_dot_dense, check2) - + def test_astype(self): D = array([[1.0 + 3j, 0, 0], [ 0, 2.0 + 5, 0], Modified: trunk/scipy/special/info.py =================================================================== --- trunk/scipy/special/info.py 2008-11-02 23:45:17 UTC (rev 4920) +++ trunk/scipy/special/info.py 2008-11-02 23:55:52 UTC (rev 4921) @@ -123,9 +123,9 @@ * fdtri -- Inverse of fdtrc * gdtr -- Integral from 0 to x of gamma pdf. * gdtrc -- Integral from x to infinity under gamma pdf. -* gdtria -- -* gdtrib -- -* gdtrix -- +* gdtria -- +* gdtrib -- +* gdtrix -- * nbdtr -- Sum of terms 0 through k of the negative binomial pdf. * nbdtrc -- Sum of terms k+1 to infinity under negative binomial pdf. * nbdtri -- Inverse of nbdtr From scipy-svn at scipy.org Sun Nov 2 19:08:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 18:08:38 -0600 (CST) Subject: [Scipy-svn] r4922 - trunk/scipy/cluster Message-ID: <20081103000838.E642E39C088@scipy.org> Author: jarrod.millman Date: 2008-11-02 18:08:36 -0600 (Sun, 02 Nov 2008) New Revision: 4922 Modified: trunk/scipy/cluster/hierarchy.py Log: use in for testing dictionary membership Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-02 23:55:52 UTC (rev 4921) +++ trunk/scipy/cluster/hierarchy.py 2008-11-03 00:08:36 UTC (rev 4922) @@ -1600,7 +1600,7 @@ axis.add_collection(colors_to_collections[color]) # If there is a blue grouping (i.e., links above the color threshold), # it should go last. - if colors_to_collections.has_key('b'): + if 'b' in colors_to_collections: axis.add_collection(colors_to_collections['b']) if contraction_marks is not None: From scipy-svn at scipy.org Sun Nov 2 19:42:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 18:42:32 -0600 (CST) Subject: [Scipy-svn] r4924 - in trunk/scipy: io/tests special/tests Message-ID: <20081103004232.B7AB539C088@scipy.org> Author: jarrod.millman Date: 2008-11-02 18:42:22 -0600 (Sun, 02 Nov 2008) New Revision: 4924 Modified: trunk/scipy/io/tests/test_recaster.py trunk/scipy/special/tests/test_basic.py Log: remove python 2.3 stuff Modified: trunk/scipy/io/tests/test_recaster.py =================================================================== --- trunk/scipy/io/tests/test_recaster.py 2008-11-03 00:26:14 UTC (rev 4923) +++ trunk/scipy/io/tests/test_recaster.py 2008-11-03 00:42:22 UTC (rev 4924) @@ -3,11 +3,6 @@ from scipy.io.recaster import sctype_attributes, Recaster, RecastError -try: # Python 2.3 support - from sets import Set as set -except: - pass - class TestRecaster(TestCase): def test_init(self): Modified: trunk/scipy/special/tests/test_basic.py =================================================================== --- trunk/scipy/special/tests/test_basic.py 2008-11-03 00:26:14 UTC (rev 4923) +++ trunk/scipy/special/tests/test_basic.py 2008-11-03 00:42:22 UTC (rev 4924) @@ -21,17 +21,6 @@ # test_sph_jn # test_sph_kn -#With Py2.3: -#! test_sh_chebyt -#! test_pbdv_seq -#F test_sph_kn -#F test_sph_jn -#F test_sph_in -#F test_sph_jn -#8 test_sh_chebyu -#8 test_sh_jacobi -#8 test_sh_legendre - from numpy import array from numpy.testing import * From scipy-svn at scipy.org Sun Nov 2 19:44:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 18:44:11 -0600 (CST) Subject: [Scipy-svn] r4925 - trunk Message-ID: <20081103004411.E228C39C088@scipy.org> Author: jarrod.millman Date: 2008-11-02 18:44:10 -0600 (Sun, 02 Nov 2008) New Revision: 4925 Modified: trunk/INSTALL.txt Log: update dependencies Modified: trunk/INSTALL.txt =================================================================== --- trunk/INSTALL.txt 2008-11-03 00:42:22 UTC (rev 4924) +++ trunk/INSTALL.txt 2008-11-03 00:44:10 UTC (rev 4925) @@ -32,7 +32,7 @@ __ http://www.python.org -2) NumPy__ 1.1.0 or newer +2) NumPy__ 1.2.0 or newer Debian package: python-numpy From scipy-svn at scipy.org Sun Nov 2 20:23:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:23:52 -0600 (CST) Subject: [Scipy-svn] r4926 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081103012352.B9C8939C088@scipy.org> Author: cdavid Date: 2008-11-02 19:23:35 -0600 (Sun, 02 Nov 2008) New Revision: 4926 Modified: trunk/scipy/sparse/linalg/eigen/arpack/SConscript Log: Do not add LAPACK files for accelerate/veclib. Modified: trunk/scipy/sparse/linalg/eigen/arpack/SConscript =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/SConscript 2008-11-03 00:44:10 UTC (rev 4925) +++ trunk/scipy/sparse/linalg/eigen/arpack/SConscript 2008-11-03 01:23:35 UTC (rev 4926) @@ -2,7 +2,7 @@ from numscons import GetNumpyEnvironment from numscons import CheckF77LAPACK, CheckF77Clib -from numscons import write_info +from numscons import write_info, IsAccelerate, IsVeclib env = GetNumpyEnvironment(ARGUMENTS) @@ -21,6 +21,7 @@ if not st: raise RuntimeError("no lapack found, necessary for arpack module") +use_c_calling = IsAccelerate(env, "lapack") or IsVeclib(env, "lapack) config.Finish() write_info(env) @@ -42,8 +43,9 @@ "dmout.f", "dvout.f", "icnteq.f", "icopy.f", "iset.f", "iswap.f", "ivout.f", "second.f", "smout.f", "svout.f", "zmout.f", "zvout.f"]] -arpack_src += [pjoin('ARPACK', 'LAPACK', s) for s in [ "clahqr.f", "dlahqr.f", -"slahqr.f", "zlahqr.f"]] +if not use_c_calling: + arpack_src += [pjoin('ARPACK', 'LAPACK', s) for s in [ "clahqr.f", "dlahqr.f", + "slahqr.f", "zlahqr.f"]] src = [str(s) for s in arpack_src] From scipy-svn at scipy.org Sun Nov 2 20:24:34 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:24:34 -0600 (CST) Subject: [Scipy-svn] r4927 - in trunk/scipy/sparse/linalg/eigen/arpack/ARPACK: . FWRAPPERS Message-ID: <20081103012434.B9DF739C088@scipy.org> Author: cdavid Date: 2008-11-02 19:24:17 -0600 (Sun, 02 Nov 2008) New Revision: 4927 Added: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_c.c trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_f.f Log: Add wrapper to deal with C/Fortran idiosyncraties Those wrappers deal with two problems: 1: BLAS functions returning complex values (cdot* and zdot*). With Accelerate/veclib frameworks, those functions use the so-called g77 ABI, that return the *address* of the returned value. http://developer.apple.com/hardwaredrivers/ve/errata.html#fortran_conventions To deal with it, we replace every call to this function by a call to a wrapped function (e.g. wcdotu), which itself calls a C wrapper around the cblas_ functions. Effectively, we replace cdotu call -> BLAS cdotu By wcdotu -> F77 wrapper -> C wrapper -> cblas_cdotu We could call the cblas_ function in the F77 wrapper, but I have not found a way to do that. 2: cladiv and zladiv: those LAPACK functions also return a complex value. In this case, the problem is a bit different: Apple, in their infinite wisdom, decided to keep the LAPACK name cladiv/zladiv for the CLAPACK function. So instead of calling: program main complex X, Y, Z complex cladiv X = (1, 0) Y = (0, 1) Z = cladiv(X, Y) print *, Z end you need to do program main complex X, Y, Z X = (1, 0) Y = (0, 1) call cladiv(Z, X, Y) end We again deal with this by replacing the calls to cladiv/zladiv by our wrapper functions wcladiv/wzladiv. Those F77 wrappers directly call fortran, so there is no C wrapper. Added: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_c.c =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_c.c 2008-11-03 01:23:35 UTC (rev 4926) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_c.c 2008-11-03 01:24:17 UTC (rev 4927) @@ -0,0 +1,25 @@ +#include + +#define WRAP_F77(a) a##_ +void WRAP_F77(veclib_cdotc)(const int *N, const complex float *X, const int *incX, +const complex float *Y, const int *incY, complex float *dotc) +{ + cblas_cdotc_sub(*N, X, *incX, Y, *incY, dotc); +} + +void WRAP_F77(veclib_cdotu)(const int *N, const complex float *X, const int *incX, +const complex float *Y, const int *incY, complex float* dotu) +{ + cblas_cdotu_sub(*N, X, *incX, Y, *incY, dotu); +} + +void WRAP_F77(veclib_zdotc)(const int *N, const double complex *X, const int +*incX, const double complex *Y, const int *incY, double complex *dotu) +{ + cblas_zdotc_sub(*N, X, *incX, Y, *incY, dotu); +} +void WRAP_F77(veclib_zdotu)(const int *N, const double complex *X, const int +*incX, const double complex *Y, const int *incY, double complex *dotu) +{ + cblas_zdotu_sub(*N, X, *incX, Y, *incY, dotu); +} Added: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_f.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_f.f 2008-11-03 01:23:35 UTC (rev 4926) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/veclib_cabi_f.f 2008-11-03 01:24:17 UTC (rev 4927) @@ -0,0 +1,55 @@ + double complex function wzdotc(n, zx, incx, zy, incy) + double complex zx(*), zy(*), z + integer n, incx, incy + + call veclib_zdotc(n, zx, incx, zy, incy, z) + + wzdotc = z + return + end + + double complex function wzdotu(n, zx, incx, zy, incy) + double complex zx(*), zy(*), z + integer n, incx, incy + + call veclib_zdotu(n, zx, incx, zy, incy, z) + + wzdotu = z + return + end + + complex function wcdotc(n, cx, incx, cy, incy) + complex cx(*), cy(*), c + integer n, incx, incy + + call veclib_cdotc(n, cx, incx, cy, incy, c) + + wcdotc = c + return + end + + complex function wcdotu(n, cx, incx, cy, incy) + complex cx(*), cy(*), c + integer n, incx, incy + + call veclib_cdotu(n, cx, incx, cy, incy, c) + + wcdotu = c + return + end + + complex function wcladiv(x, y) + complex x, y, z + + call cladiv(z, x, y) + wcladiv = z + return + end + + double complex function wzladiv(x, y) + double complex x, y, z + + call zladiv(z, x, y) + wzladiv = z + return + end From scipy-svn at scipy.org Sun Nov 2 20:25:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:25:26 -0600 (CST) Subject: [Scipy-svn] r4928 - trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS Message-ID: <20081103012526.13F7139C088@scipy.org> Author: cdavid Date: 2008-11-02 19:25:00 -0600 (Sun, 02 Nov 2008) New Revision: 4928 Added: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f Log: Add dummy wrapper for dot and cladiv/zladiv functions. Added: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f 2008-11-03 01:24:17 UTC (rev 4927) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f 2008-11-03 01:25:00 UTC (rev 4928) @@ -0,0 +1,56 @@ + double complex function wzdotc(n, zx, incx, zy, incy) + double complex zx(*), zy(*), z, zdotc + integer n, incx, incy + + zdotc(n, zx, incx, zy, incy, z) + wzdotc = zdotc + + end + + double complex function wzdotu(n, zx, incx, zy, incy) + double complex zx(*), zy(*), z, zdotu + integer n, incx, incy + + zdotu(n, zx, incx, zy, incy, z) + wzdotu = zdotu + + return + end + + complex function wcdotc(n, cx, incx, cy, incy) + complex cx(*), cy(*), c, cdotc + integer n, incx, incy + + cdotc(n, cx, incx, cy, incy, c) + wzdotc = zdotc + + return + end + + complex function wcdotu(n, cx, incx, cy, incy) + complex cx(*), cy(*), c, cdotu + integer n, incx, incy + + cdotu(n, cx, incx, cy, incy, c) + wzdotu = zdotu + + return + end + + complex function wcladiv(x, y) + complex x, y, z + complex cladiv + + z = cladiv(x, y) + wcladiv = z + return + end + + double complex function wzladiv(x, y) + double complex x, y, z + double complex zladiv + + z = zladiv(x, y) + wzladiv = z + return + end From scipy-svn at scipy.org Sun Nov 2 20:26:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:26:26 -0600 (CST) Subject: [Scipy-svn] r4929 - trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK Message-ID: <20081103012626.0D51C39C088@scipy.org> Author: cdavid Date: 2008-11-02 19:25:53 -0600 (Sun, 02 Nov 2008) New Revision: 4929 Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/clahqr.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/zlahqr.f Log: Use wrapped wcladiv/wzladiv instead of direct LAPACK calls. Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/clahqr.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/clahqr.f 2008-11-03 01:25:00 UTC (rev 4928) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/clahqr.f 2008-11-03 01:25:53 UTC (rev 4929) @@ -104,8 +104,8 @@ * .. * .. External Functions .. REAL CLANHS, SLAMCH - COMPLEX CLADIV - EXTERNAL CLANHS, SLAMCH, CLADIV + COMPLEX WCLADIV + EXTERNAL CLANHS, SLAMCH, WCLADIV * .. * .. External Subroutines .. EXTERNAL CCOPY, CLARFG, CSCAL @@ -221,7 +221,7 @@ Y = SQRT( X*X+U ) IF( REAL( X )*REAL( Y )+AIMAG( X )*AIMAG( Y ).LT.RZERO ) $ Y = -Y - T = T - CLADIV( U, ( X+Y ) ) + T = T - WCLADIV( U, ( X+Y ) ) END IF END IF * Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/zlahqr.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/zlahqr.f 2008-11-03 01:25:00 UTC (rev 4928) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/LAPACK/zlahqr.f 2008-11-03 01:25:53 UTC (rev 4929) @@ -104,8 +104,8 @@ * .. * .. External Functions .. DOUBLE PRECISION ZLANHS, DLAMCH - COMPLEX*16 ZLADIV - EXTERNAL ZLANHS, DLAMCH, ZLADIV + COMPLEX*16 WZLADIV + EXTERNAL ZLANHS, DLAMCH, WZLADIV * .. * .. External Subroutines .. EXTERNAL ZCOPY, ZLARFG, ZSCAL @@ -221,7 +221,7 @@ Y = SQRT( X*X+U ) IF( DBLE( X )*DBLE( Y )+DIMAG( X )*DIMAG( Y ).LT.RZERO ) $ Y = -Y - T = T - ZLADIV( U, ( X+Y ) ) + T = T - WZLADIV( U, ( X+Y ) ) END IF END IF * From scipy-svn at scipy.org Sun Nov 2 20:28:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:28:03 -0600 (CST) Subject: [Scipy-svn] r4930 - trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC Message-ID: <20081103012803.3C47239C088@scipy.org> Author: cdavid Date: 2008-11-02 19:26:58 -0600 (Sun, 02 Nov 2008) New Revision: 4930 Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cgetv0.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaitr.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaup2.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cneupd.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zgetv0.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaitr.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaup2.f trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zneupd.f Log: Use wrapped dot functions instead of direct BLAS calls. Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cgetv0.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cgetv0.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cgetv0.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -94,7 +94,7 @@ c clarnv LAPACK routine for generating a random vector. c cgemv Level 2 BLAS routine for matrix vector multiplication. c ccopy Level 1 BLAS that copies one vector to another. -c cdotc Level 1 BLAS that computes the scalar product of two vectors. +c wcdotc Level 1 BLAS that computes the scalar product of two vectors. c scnrm2 Level 1 BLAS that computes the norm of a vector. c c\Author @@ -177,8 +177,8 @@ Real & scnrm2, slapy2 Complex - & cdotc - external cdotc, scnrm2, slapy2 + & wcdotc + external wcdotc, scnrm2, slapy2 c c %-----------------% c | Data Statements | @@ -291,7 +291,7 @@ c first = .FALSE. if (bmat .eq. 'G') then - cnorm = cdotc (n, resid, 1, workd, 1) + cnorm = wcdotc (n, resid, 1, workd, 1) rnorm0 = sqrt(slapy2(real(cnorm),aimag(cnorm))) else if (bmat .eq. 'I') then rnorm0 = scnrm2(n, resid, 1) @@ -348,7 +348,7 @@ end if c if (bmat .eq. 'G') then - cnorm = cdotc (n, resid, 1, workd, 1) + cnorm = wcdotc (n, resid, 1, workd, 1) rnorm = sqrt(slapy2(real(cnorm),aimag(cnorm))) else if (bmat .eq. 'I') then rnorm = scnrm2(n, resid, 1) Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaitr.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaitr.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaitr.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -143,7 +143,7 @@ c cgemv Level 2 BLAS routine for matrix vector multiplication. c caxpy Level 1 BLAS that computes a vector triad. c ccopy Level 1 BLAS that copies one vector to another . -c cdotc Level 1 BLAS that computes the scalar product of two vectors. +c wcdotc Level 1 BLAS that computes the scalar product of two vectors. c cscal Level 1 BLAS that scales a vector. c csscal Level 1 BLAS that scales a complex vector by a real number. c scnrm2 Level 1 BLAS that computes the norm of a vector. @@ -280,10 +280,10 @@ c %--------------------% c Complex - & cdotc + & wcdotc Real & slamch, scnrm2, clanhs, slapy2 - external cdotc, scnrm2, clanhs, slamch, slapy2 + external wcdotc, scnrm2, clanhs, slamch, slapy2 c c %---------------------% c | Intrinsic Functions | @@ -550,7 +550,7 @@ c %-------------------------------------% c if (bmat .eq. 'G') then - cnorm = cdotc (n, resid, 1, workd(ipj), 1) + cnorm = wcdotc (n, resid, 1, workd(ipj), 1) wnorm = sqrt( slapy2(real(cnorm),aimag(cnorm)) ) else if (bmat .eq. 'I') then wnorm = scnrm2(n, resid, 1) @@ -622,7 +622,7 @@ c %------------------------------% c if (bmat .eq. 'G') then - cnorm = cdotc (n, resid, 1, workd(ipj), 1) + cnorm = wcdotc (n, resid, 1, workd(ipj), 1) rnorm = sqrt( slapy2(real(cnorm),aimag(cnorm)) ) else if (bmat .eq. 'I') then rnorm = scnrm2(n, resid, 1) @@ -722,7 +722,7 @@ c %-----------------------------------------------------% c if (bmat .eq. 'G') then - cnorm = cdotc (n, resid, 1, workd(ipj), 1) + cnorm = wcdotc (n, resid, 1, workd(ipj), 1) rnorm1 = sqrt( slapy2(real(cnorm),aimag(cnorm)) ) else if (bmat .eq. 'I') then rnorm1 = scnrm2(n, resid, 1) Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaup2.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaup2.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cnaup2.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -142,7 +142,7 @@ c slamch LAPACK routine that determines machine constants. c slapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c ccopy Level 1 BLAS that copies one vector to another . -c cdotc Level 1 BLAS that computes the scalar product of two vectors. +c wcdotc Level 1 BLAS that computes the scalar product of two vectors. c cswap Level 1 BLAS that swaps two vectors. c scnrm2 Level 1 BLAS that computes the norm of a vector. c @@ -247,10 +247,10 @@ c %--------------------% c Complex - & cdotc + & wcdotc Real & scnrm2, slamch, slapy2 - external cdotc, scnrm2, slamch, slapy2 + external wcdotc, scnrm2, slamch, slapy2 c c %---------------------% c | Intrinsic Functions | @@ -754,7 +754,7 @@ end if c if (bmat .eq. 'G') then - cmpnorm = cdotc (n, resid, 1, workd, 1) + cmpnorm = wcdotc (n, resid, 1, workd, 1) rnorm = sqrt(slapy2(real (cmpnorm),aimag(cmpnorm))) else if (bmat .eq. 'I') then rnorm = scnrm2(n, resid, 1) Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cneupd.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cneupd.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/cneupd.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -325,8 +325,8 @@ external scnrm2, slamch, slapy2 c Complex - & cdotc - external cdotc + & wcdotc + external wcdotc c c %-----------------------% c | Executable Statements | @@ -727,7 +727,7 @@ c | inner product can be set to j. | c %------------------------------------------% c - workev(j) = cdotc(j, workl(ihbds), 1, + workev(j) = wcdotc(j, workl(ihbds), 1, & workl(invsub+(j-1)*ldq), 1) 40 continue c Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zgetv0.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zgetv0.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zgetv0.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -94,7 +94,7 @@ c zlarnv LAPACK routine for generating a random vector. c zgemv Level 2 BLAS routine for matrix vector multiplication. c zcopy Level 1 BLAS that copies one vector to another. -c zdotc Level 1 BLAS that computes the scalar product of two vectors. +c wzdotc Level 1 BLAS that computes the scalar product of two vectors. c dznrm2 Level 1 BLAS that computes the norm of a vector. c c\Author @@ -177,8 +177,8 @@ Double precision & dznrm2, dlapy2 Complex*16 - & zdotc - external zdotc, dznrm2, dlapy2 + & wzdotc + external wzdotc, dznrm2, dlapy2 c c %-----------------% c | Data Statements | @@ -291,7 +291,7 @@ c first = .FALSE. if (bmat .eq. 'G') then - cnorm = zdotc (n, resid, 1, workd, 1) + cnorm = wzdotc (n, resid, 1, workd, 1) rnorm0 = sqrt(dlapy2(dble(cnorm),dimag(cnorm))) else if (bmat .eq. 'I') then rnorm0 = dznrm2(n, resid, 1) @@ -348,7 +348,7 @@ end if c if (bmat .eq. 'G') then - cnorm = zdotc (n, resid, 1, workd, 1) + cnorm = wzdotc (n, resid, 1, workd, 1) rnorm = sqrt(dlapy2(dble(cnorm),dimag(cnorm))) else if (bmat .eq. 'I') then rnorm = dznrm2(n, resid, 1) Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaitr.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaitr.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaitr.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -143,7 +143,7 @@ c zgemv Level 2 BLAS routine for matrix vector multiplication. c zaxpy Level 1 BLAS that computes a vector triad. c zcopy Level 1 BLAS that copies one vector to another . -c zdotc Level 1 BLAS that computes the scalar product of two vectors. +c wzdotc Level 1 BLAS that computes the scalar product of two vectors. c zscal Level 1 BLAS that scales a vector. c zdscal Level 1 BLAS that scales a complex vector by a real number. c dznrm2 Level 1 BLAS that computes the norm of a vector. @@ -280,10 +280,10 @@ c %--------------------% c Complex*16 - & zdotc + & wzdotc Double precision & dlamch, dznrm2, zlanhs, dlapy2 - external zdotc, dznrm2, zlanhs, dlamch, dlapy2 + external wzdotc, dznrm2, zlanhs, dlamch, dlapy2 c c %---------------------% c | Intrinsic Functions | @@ -550,7 +550,7 @@ c %-------------------------------------% c if (bmat .eq. 'G') then - cnorm = zdotc (n, resid, 1, workd(ipj), 1) + cnorm = wzdotc (n, resid, 1, workd(ipj), 1) wnorm = sqrt( dlapy2(dble(cnorm),dimag(cnorm)) ) else if (bmat .eq. 'I') then wnorm = dznrm2(n, resid, 1) @@ -622,7 +622,7 @@ c %------------------------------% c if (bmat .eq. 'G') then - cnorm = zdotc (n, resid, 1, workd(ipj), 1) + cnorm = wzdotc (n, resid, 1, workd(ipj), 1) rnorm = sqrt( dlapy2(dble(cnorm),dimag(cnorm)) ) else if (bmat .eq. 'I') then rnorm = dznrm2(n, resid, 1) @@ -722,7 +722,7 @@ c %-----------------------------------------------------% c if (bmat .eq. 'G') then - cnorm = zdotc (n, resid, 1, workd(ipj), 1) + cnorm = wzdotc (n, resid, 1, workd(ipj), 1) rnorm1 = sqrt( dlapy2(dble(cnorm),dimag(cnorm)) ) else if (bmat .eq. 'I') then rnorm1 = dznrm2(n, resid, 1) Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaup2.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaup2.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/znaup2.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -142,7 +142,7 @@ c dlamch LAPACK routine that determines machine constants. c dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c zcopy Level 1 BLAS that copies one vector to another . -c zdotc Level 1 BLAS that computes the scalar product of two vectors. +c wzdotc Level 1 BLAS that computes the scalar product of two vectors. c zswap Level 1 BLAS that swaps two vectors. c dznrm2 Level 1 BLAS that computes the norm of a vector. c @@ -247,10 +247,10 @@ c %--------------------% c Complex*16 - & zdotc + & wzdotc Double precision & dznrm2 , dlamch , dlapy2 - external zdotc , dznrm2 , dlamch , dlapy2 + external wzdotc , dznrm2 , dlamch , dlapy2 c c %---------------------% c | Intrinsic Functions | @@ -754,7 +754,7 @@ end if c if (bmat .eq. 'G') then - cmpnorm = zdotc (n, resid, 1, workd, 1) + cmpnorm = wzdotc (n, resid, 1, workd, 1) rnorm = sqrt(dlapy2 (dble (cmpnorm),dimag (cmpnorm))) else if (bmat .eq. 'I') then rnorm = dznrm2 (n, resid, 1) Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zneupd.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zneupd.f 2008-11-03 01:25:53 UTC (rev 4929) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/zneupd.f 2008-11-03 01:26:58 UTC (rev 4930) @@ -325,8 +325,8 @@ external dznrm2, dlamch, dlapy2 c Complex*16 - & zdotc - external zdotc + & wzdotc + external wzdotc c c %-----------------------% c | Executable Statements | @@ -727,7 +727,7 @@ c | inner product can be set to j. | c %------------------------------------------% c - workev(j) = zdotc(j, workl(ihbds), 1, + workev(j) = wzdotc(j, workl(ihbds), 1, & workl(invsub+(j-1)*ldq), 1) 40 continue c From scipy-svn at scipy.org Sun Nov 2 20:28:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:28:36 -0600 (CST) Subject: [Scipy-svn] r4931 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081103012836.87B8639C088@scipy.org> Author: cdavid Date: 2008-11-02 19:28:19 -0600 (Sun, 02 Nov 2008) New Revision: 4931 Modified: trunk/scipy/sparse/linalg/eigen/arpack/SConscript Log: Use custom wrappers for dot and cladiv/zladiv funcs with Accelerate, dummy wrappers eveywhere else. Modified: trunk/scipy/sparse/linalg/eigen/arpack/SConscript =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/SConscript 2008-11-03 01:26:58 UTC (rev 4930) +++ trunk/scipy/sparse/linalg/eigen/arpack/SConscript 2008-11-03 01:28:19 UTC (rev 4931) @@ -21,7 +21,7 @@ if not st: raise RuntimeError("no lapack found, necessary for arpack module") -use_c_calling = IsAccelerate(env, "lapack") or IsVeclib(env, "lapack) +use_c_calling = IsAccelerate(env, "lapack") or IsVeclib(env, "lapack") config.Finish() write_info(env) @@ -43,9 +43,13 @@ "dmout.f", "dvout.f", "icnteq.f", "icopy.f", "iset.f", "iswap.f", "ivout.f", "second.f", "smout.f", "svout.f", "zmout.f", "zvout.f"]] -if not use_c_calling: - arpack_src += [pjoin('ARPACK', 'LAPACK', s) for s in [ "clahqr.f", "dlahqr.f", - "slahqr.f", "zlahqr.f"]] +if use_c_calling: + arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'), + pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')] +else: + arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'dummy.f')] +arpack_src += [pjoin('ARPACK', 'LAPACK', s) for s in [ "clahqr.f", "dlahqr.f", +"slahqr.f", "zlahqr.f"]] src = [str(s) for s in arpack_src] From scipy-svn at scipy.org Sun Nov 2 20:29:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:29:18 -0600 (CST) Subject: [Scipy-svn] r4932 - trunk/scipy/sparse/linalg/eigen/arpack/tests Message-ID: <20081103012918.435DC39C088@scipy.org> Author: cdavid Date: 2008-11-02 19:28:54 -0600 (Sun, 02 Nov 2008) New Revision: 4932 Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py Log: Re-enable complex, nonsymmetric arpack tests. Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 01:28:19 UTC (rev 4931) +++ trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 01:28:54 UTC (rev 4932) @@ -148,11 +148,11 @@ decimal=_ndigits[typ]) -# def test_complex_symmetric_modes(self): -# k=2 -# for typ in 'FD': -# for which in ['LM','SM','LR','SR']: -# self.eval_evec(self.symmetric[0],typ,k,which) + def test_complex_symmetric_modes(self): + k=2 + for typ in 'FD': + for which in ['LM','SM','LR','SR']: + self.eval_evec(self.symmetric[0],typ,k,which) @@ -259,12 +259,12 @@ decimal=_ndigits[typ]) -# def test_complex_nonsymmetric_modes(self): -# k=2 -# for typ in 'FD': -# for which in ['LI','LR','LM','SI','SR','SM']: -# for m in self.nonsymmetric: -# self.eval_evec(m,typ,k,which) + def test_complex_nonsymmetric_modes(self): + k=2 + for typ in 'FD': + for which in ['LI','LR','LM','SI','SR','SM']: + for m in self.nonsymmetric: + self.eval_evec(m,typ,k,which) From scipy-svn at scipy.org Sun Nov 2 20:32:54 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:32:54 -0600 (CST) Subject: [Scipy-svn] r4933 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081103013254.8FBF139C088@scipy.org> Author: cdavid Date: 2008-11-02 19:32:36 -0600 (Sun, 02 Nov 2008) New Revision: 4933 Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py Log: Adapt distutils build to deal with C/F ABI wrappers for arpack. Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-03 01:28:54 UTC (rev 4932) +++ trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-03 01:32:36 UTC (rev 4933) @@ -1,7 +1,23 @@ #!/usr/bin/env python - +import re from os.path import join +def needs_veclib_wrapper(info): + """Returns true if needs special veclib wrapper.""" + import re + r_accel = re.compile("Accelerate") + r_vec = re.compile("vecLib") + res = False + try: + tmpstr = info['extra_link_args'] + for i in tmpstr: + if r_accel.search(i) or r_vec.search(i): + res = True + except KeyError: + pass + + return res + def configuration(parent_package='',top_path=None): from numpy.distutils.system_info import get_info, NotFoundError from numpy.distutils.misc_util import Configuration @@ -19,6 +35,12 @@ arpack_sources.extend([join('ARPACK','UTIL', '*.f')]) arpack_sources.extend([join('ARPACK','LAPACK', '*.f')]) + if needs_veclib_wrapper(lapack_opt): + arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'), + pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')] + else: + arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'dummy.f')] + config.add_library('arpack', sources=arpack_sources, include_dirs=[join('ARPACK', 'SRC')]) From scipy-svn at scipy.org Sun Nov 2 20:34:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:34:20 -0600 (CST) Subject: [Scipy-svn] r4934 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081103013420.D7E4439C088@scipy.org> Author: cdavid Date: 2008-11-02 19:34:03 -0600 (Sun, 02 Nov 2008) New Revision: 4934 Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py Log: Typo. Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-03 01:32:36 UTC (rev 4933) +++ trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-03 01:34:03 UTC (rev 4934) @@ -36,10 +36,10 @@ arpack_sources.extend([join('ARPACK','LAPACK', '*.f')]) if needs_veclib_wrapper(lapack_opt): - arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'), - pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')] + arpack_sources += [pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'), + pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')] else: - arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'dummy.f')] + arpack_sources += [pjoin('ARPACK', 'FWRAPPERS', 'dummy.f')] config.add_library('arpack', sources=arpack_sources, include_dirs=[join('ARPACK', 'SRC')]) From scipy-svn at scipy.org Sun Nov 2 20:35:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:35:32 -0600 (CST) Subject: [Scipy-svn] r4935 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081103013532.7AF2139C088@scipy.org> Author: cdavid Date: 2008-11-02 19:35:16 -0600 (Sun, 02 Nov 2008) New Revision: 4935 Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py Log: Another typo. Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-03 01:34:03 UTC (rev 4934) +++ trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-03 01:35:16 UTC (rev 4935) @@ -36,10 +36,10 @@ arpack_sources.extend([join('ARPACK','LAPACK', '*.f')]) if needs_veclib_wrapper(lapack_opt): - arpack_sources += [pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'), - pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')] + arpack_sources += [join('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'), + join('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')] else: - arpack_sources += [pjoin('ARPACK', 'FWRAPPERS', 'dummy.f')] + arpack_sources += [join('ARPACK', 'FWRAPPERS', 'dummy.f')] config.add_library('arpack', sources=arpack_sources, include_dirs=[join('ARPACK', 'SRC')]) From scipy-svn at scipy.org Sun Nov 2 20:41:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:41:40 -0600 (CST) Subject: [Scipy-svn] r4936 - in trunk/scipy: cluster spatial Message-ID: <20081103014140.2B08639C088@scipy.org> Author: damian.eads Date: 2008-11-02 19:41:34 -0600 (Sun, 02 Nov 2008) New Revision: 4936 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/spatial/distance.py Log: Working on docs. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-03 01:35:16 UTC (rev 4935) +++ trunk/scipy/cluster/hierarchy.py 2008-11-03 01:41:34 UTC (rev 4936) @@ -147,6 +147,11 @@ .. [Fis36] Fisher, RA "The use of multiple measurements in taxonomic problems." Annals of Eugenics, 7(2): 179-188. 1936 +Copyright Notice +---------------- + +Copyright (C) Damian Eads, 2007-2008. New BSD License. + """ _copyingtxt=""" Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-03 01:35:16 UTC (rev 4935) +++ trunk/scipy/spatial/distance.py 2008-11-03 01:41:34 UTC (rev 4936) @@ -1517,26 +1517,26 @@ valid = False return valid -def numobs_dm(D): +def numobs_dm(d): """ Returns the number of original observations that correspond to a - square, redudant distance matrix D. + square, redudant distance matrix ``D``. :Parameters: - D : ndarray + d : ndarray The target distance matrix. :Returns: The number of observations in the redundant distance matrix. """ - D = np.asarray(D, order='c') - is_valid_dm(D, tol=np.inf, throw=True, name='D') - return D.shape[0] + d = np.asarray(d, order='c') + is_valid_dm(d, tol=np.inf, throw=True, name='d') + return d.shape[0] def numobs_y(Y): """ Returns the number of original observations that correspond to a - condensed distance matrix Y. + condensed distance matrix ``Y``. :Parameters: Y : ndarray @@ -1565,16 +1565,16 @@ A rectangular distance matrix Y is returned. For each :math:`$i$` and :math:`$j$`, the metric ``dist(u=XA[i], v=XB[j])`` is computed - and stored in the :math:`ij`th entry. + and stored in the :math:`$ij$`th entry. :Parameters: XA : ndarray An :math:`$m_A$` by :math:`$n$` array of :math:`$m_A$` - original observations in an n-dimensional space. + original observations in an :math:`$n$`-dimensional space. XB : ndarray An :math:`$m_B$` by :math:`$n$` array of :math:`$m_B$` - original observations in an n-dimensional space. + original observations in an :math:`$n$`-dimensional space. metric : string or function The distance metric to use. The distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', @@ -1609,7 +1609,7 @@ 2. ``Y = cdist(X, 'minkowski', p)`` Computes the distances using the Minkowski distance - :math:`$||u-v||_p$` (p-norm) where :math:`$p \geq 1$`. + :math:`$||u-v||_p$` (:math:`$p$`-norm) where :math:`$p \geq 1$`. 3. ``Y = cdist(X, 'cityblock')`` From scipy-svn at scipy.org Sun Nov 2 20:42:14 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:42:14 -0600 (CST) Subject: [Scipy-svn] r4937 - trunk/scipy/interpolate Message-ID: <20081103014214.207E939C088@scipy.org> Author: ptvirtan Date: 2008-11-02 19:42:04 -0600 (Sun, 02 Nov 2008) New Revision: 4937 Modified: trunk/scipy/interpolate/interpolate.py Log: scipy.interpolate: move interp2d.__init__ docstring to the class docstring Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-03 01:41:34 UTC (rev 4936) +++ trunk/scipy/interpolate/interpolate.py 2008-11-03 01:42:04 UTC (rev 4937) @@ -44,56 +44,57 @@ # !! found, get rid of it! class interp2d(object): - """ Interpolate over a 2D grid. - - See Also - -------- - bisplrep, bisplev - spline interpolation based on FITPACK - BivariateSpline - a more recent wrapper of the FITPACK routines """ + interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, + fill_value=nan) + + Interpolate over a 2D grid. - def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, - fill_value=np.nan): - """ Initialize a 2D interpolator. + Parameters + ---------- + x : 1D array + y : 1D array + Arrays defining the coordinates of a 2D grid. If the + points lie on a regular grid, x and y can simply specify + the rows and colums, i.e. - Parameters - ---------- - x : 1D array - y : 1D array - Arrays defining the coordinates of a 2D grid. If the - points lie on a regular grid, x and y can simply specify - the rows and colums, i.e. + x = [0,1,2] y = [0,1,2] - x = [0,1,2] y = [0,1,2] + otherwise x and y must specify the full coordinates, i.e. - otherwise x and y must specify the full coordinates, i.e. + x = [0,1,2,0,1.5,2,0,1,2] y = [0,1,2,0,1,2,0,1,2] - x = [0,1,2,0,1.5,2,0,1,2] y = [0,1,2,0,1,2,0,1,2] + If x and y are 2-dimensional, they are flattened (allowing + the use of meshgrid, for example). - If x and y are 2-dimensional, they are flattened (allowing - the use of meshgrid, for example). + z : 1D array + The values of the interpolated function on the grid + points. If z is a 2-dimensional array, it is flattened. - z : 1D array - The values of the interpolated function on the grid - points. If z is a 2-dimensional array, it is flattened. + kind : 'linear', 'cubic', 'quintic' + The kind of interpolation to use. + copy : bool + If True, then data is copied, otherwise only a reference is held. + bounds_error : bool + If True, when interoplated values are requested outside of the + domain of the input data, an error is raised. + If False, then fill_value is used. + fill_value : number + If provided, the value to use for points outside of the + interpolation domain. Defaults to NaN. - kind : 'linear', 'cubic', 'quintic' - The kind of interpolation to use. - copy : bool - If True, then data is copied, otherwise only a reference is held. - bounds_error : bool - If True, when interoplated values are requested outside of the - domain of the input data, an error is raised. - If False, then fill_value is used. - fill_value : number - If provided, the value to use for points outside of the - interpolation domain. Defaults to NaN. + Raises + ------ + ValueError when inputs are invalid. - Raises - ------ - ValueError when inputs are invalid. + See Also + -------- + bisplrep, bisplev - spline interpolation based on FITPACK + BivariateSpline - a more recent wrapper of the FITPACK routines + """ - """ + def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, + fill_value=np.nan): self.x, self.y, self.z = map(ravel, map(array, [x, y, z])) if not map(rank, [self.x, self.y, self.z]) == [1,1,1]: raise ValueError("One of the input arrays is not 1-d.") From scipy-svn at scipy.org Sun Nov 2 20:42:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:42:39 -0600 (CST) Subject: [Scipy-svn] r4938 - in trunk/scipy/interpolate: . tests Message-ID: <20081103014239.4E85839C088@scipy.org> Author: ptvirtan Date: 2008-11-02 19:42:26 -0600 (Sun, 02 Nov 2008) New Revision: 4938 Modified: trunk/scipy/interpolate/interpolate.py trunk/scipy/interpolate/tests/test_interpolate.py Log: scipy.interpolate: clarify interp2d docstrings, and fix broken logic in __init__ concerning meshgrid-like input. Addresses #703. Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-03 01:42:04 UTC (rev 4937) +++ trunk/scipy/interpolate/interpolate.py 2008-11-03 01:42:26 UTC (rev 4938) @@ -8,7 +8,7 @@ from numpy import shape, sometrue, rank, array, transpose, searchsorted, \ ones, logical_or, atleast_1d, atleast_2d, meshgrid, ravel, \ - dot, poly1d + dot, poly1d, asarray import numpy as np import scipy.special as spec import math @@ -47,38 +47,35 @@ """ interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=nan) - + Interpolate over a 2D grid. Parameters ---------- - x : 1D array - y : 1D array + x, y : 1D arrays Arrays defining the coordinates of a 2D grid. If the - points lie on a regular grid, x and y can simply specify - the rows and colums, i.e. + points lie on a regular grid, `x` can specify the column coordinates + and `y` the row coordinates, e.g.:: - x = [0,1,2] y = [0,1,2] + x = [0,1,2]; y = [0,3,7] - otherwise x and y must specify the full coordinates, i.e. + otherwise x and y must specify the full coordinates, i.e.:: - x = [0,1,2,0,1.5,2,0,1,2] y = [0,1,2,0,1,2,0,1,2] + x = [0,1,2,0,1,2,0,1,2]; y = [0,0,0,3,3,3,7,7,7] - If x and y are 2-dimensional, they are flattened (allowing - the use of meshgrid, for example). + If `x` and `y` are multi-dimensional, they are flattened before use. z : 1D array - The values of the interpolated function on the grid - points. If z is a 2-dimensional array, it is flattened. - - kind : 'linear', 'cubic', 'quintic' + The values of the interpolated function on the grid points. If + z is a multi-dimensional array, it is flattened before use. + kind : {'linear', 'cubic', 'quintic'} The kind of interpolation to use. copy : bool If True, then data is copied, otherwise only a reference is held. bounds_error : bool - If True, when interoplated values are requested outside of the + If True, when interpolated values are requested outside of the domain of the input data, an error is raised. - If False, then fill_value is used. + If False, then `fill_value` is used. fill_value : number If provided, the value to use for points outside of the interpolation domain. Defaults to NaN. @@ -89,20 +86,20 @@ See Also -------- - bisplrep, bisplev - spline interpolation based on FITPACK - BivariateSpline - a more recent wrapper of the FITPACK routines + bisplrep, bisplev : spline interpolation based on FITPACK + BivariateSpline : a more recent wrapper of the FITPACK routines + """ def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, - fill_value=np.nan): - self.x, self.y, self.z = map(ravel, map(array, [x, y, z])) - if not map(rank, [self.x, self.y, self.z]) == [1,1,1]: - raise ValueError("One of the input arrays is not 1-d.") - if len(self.x) != len(self.y): - raise ValueError("x and y must have equal lengths") + fill_value=np.nan): + self.x, self.y, self.z = map(ravel, map(asarray, [x, y, z])) + if len(self.z) == len(self.x) * len(self.y): self.x, self.y = meshgrid(x,y) self.x, self.y = map(ravel, [self.x, self.y]) + if len(self.x) != len(self.y): + raise ValueError("x and y must have equal lengths") if len(self.z) != len(self.x): raise ValueError("Invalid length for input z") @@ -116,21 +113,24 @@ self.tck = fitpack.bisplrep(self.x, self.y, self.z, kx=kx, ky=ky, s=0.) def __call__(self,x,y,dx=0,dy=0): - """ Interpolate the function. + """Interpolate the function. Parameters ---------- x : 1D array + x-coordinates of the mesh on which to interpolate. y : 1D array - The points to interpolate. + y-coordinates of the mesh on which to interpolate. dx : int >= 0, < kx + Order of partial derivatives in x. dy : int >= 0, < ky - The order of partial derivatives in x and y, respectively. + Order of partial derivatives in y. Returns ------- z : 2D array with shape (len(y), len(x)) The interpolated values. + """ x = atleast_1d(x) Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-03 01:42:04 UTC (rev 4937) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-03 01:42:26 UTC (rev 4938) @@ -1,5 +1,5 @@ from numpy.testing import * -from numpy import mgrid, pi, sin, ogrid, poly1d +from numpy import mgrid, pi, sin, ogrid, poly1d, linspace import numpy as np from scipy.interpolate import interp1d, interp2d, lagrange @@ -7,15 +7,22 @@ class TestInterp2D(TestCase): def test_interp2d(self): - y, x = mgrid[0:pi:20j, 0:pi:21j] - z = sin(x+y) + y, x = mgrid[0:2:20j, 0:pi:21j] + z = sin(x+0.5*y) I = interp2d(x, y, z) - assert_almost_equal(I(1.0, 1.0), sin(2.0), decimal=2) + assert_almost_equal(I(1.0, 2.0), sin(2.0), decimal=2) - v,u = ogrid[0:pi:24j, 0:pi:25j] - assert_almost_equal(I(u.ravel(), v.ravel()), sin(v+u), decimal=2) + v,u = ogrid[0:2:24j, 0:pi:25j] + assert_almost_equal(I(u.ravel(), v.ravel()), sin(u+0.5*v), decimal=2) + + def test_interp2d_meshgrid_input(self): + # Ticket #703 + x = linspace(0, 2, 16) + y = linspace(0, pi, 21) + z = sin(x[None,:] + y[:,None]/2.) + I = interp2d(x, y, z) + assert_almost_equal(I(1.0, 2.0), sin(2.0), decimal=2) - class TestInterp1D(TestCase): def setUp(self): From scipy-svn at scipy.org Sun Nov 2 20:43:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 19:43:00 -0600 (CST) Subject: [Scipy-svn] r4939 - trunk/scipy/interpolate Message-ID: <20081103014300.7C49439C088@scipy.org> Author: ptvirtan Date: 2008-11-02 19:42:49 -0600 (Sun, 02 Nov 2008) New Revision: 4939 Modified: trunk/scipy/interpolate/fitpack.py Log: scipy.interpolate: more friendly error message from bisplrep when there are too many data points Modified: trunk/scipy/interpolate/fitpack.py =================================================================== --- trunk/scipy/interpolate/fitpack.py 2008-11-03 01:42:26 UTC (rev 4938) +++ trunk/scipy/interpolate/fitpack.py 2008-11-03 01:42:49 UTC (rev 4939) @@ -754,8 +754,11 @@ bx,by=kx*v+ky+1,ky*u+kx+1 b1,b2=bx,bx+v-ky if bx>by: b1,b2=by,by+u-kx - lwrk1=u*v*(2+b1+b2)+2*(u+v+km*(m+ne)+ne-kx-ky)+b2+1 - lwrk2=u*v*(b2+1)+b2 + try: + lwrk1=int32(u*v*(2+b1+b2)+2*(u+v+km*(m+ne)+ne-kx-ky)+b2+1) + lwrk2=int32(u*v*(b2+1)+b2) + except OverflowError: + raise OverflowError("Too many data points to interpolate") tx,ty,c,o = _fitpack._surfit(x,y,z,w,xb,xe,yb,ye,kx,ky,task,s,eps, tx,ty,nxest,nyest,wrk,lwrk1,lwrk2) _curfit_cache['tx']=tx From scipy-svn at scipy.org Sun Nov 2 21:00:22 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 20:00:22 -0600 (CST) Subject: [Scipy-svn] r4940 - trunk/scipy/interpolate Message-ID: <20081103020022.0E38539C088@scipy.org> Author: paul.ivanov Date: 2008-11-02 20:00:11 -0600 (Sun, 02 Nov 2008) New Revision: 4940 Modified: trunk/scipy/interpolate/interpolate_wrapper.py Log: removes DOS ^M, also checking svn privs Modified: trunk/scipy/interpolate/interpolate_wrapper.py =================================================================== --- trunk/scipy/interpolate/interpolate_wrapper.py 2008-11-03 01:42:49 UTC (rev 4939) +++ trunk/scipy/interpolate/interpolate_wrapper.py 2008-11-03 02:00:11 UTC (rev 4940) @@ -1,138 +1,138 @@ -""" helper_funcs.py. - scavenged from enthought,interpolate -""" - -import numpy as np -import sys -import _interpolate # C extension. Does all the real work. - -def atleast_1d_and_contiguous(ary, dtype = np.float64): - return np.atleast_1d( np.ascontiguousarray(ary, dtype) ) - -def nearest(x, y, new_x): - """ Rounds each new_x[i] to the closest value in x - and returns corresponding y. - """ - shifted_x = np.concatenate(( np.array([x[0]-1]) , x[0:-1] )) - - midpoints_of_x = atleast_1d_and_contiguous( .5*(x + shifted_x) ) - new_x = atleast_1d_and_contiguous(new_x) - - TINY = 1e-10 - indices = np.searchsorted(midpoints_of_x, new_x+TINY)-1 - indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int)) - new_y = np.take(y, indices, axis=-1) - - return new_y - - - -def linear(x, y, new_x): - """ Linearly interpolates values in new_x based on the values in x and y - - Parameters - ---------- - x - 1-D array - y - 1-D or 2-D array - new_x - 1-D array - """ - x = atleast_1d_and_contiguous(x, np.float64) - y = atleast_1d_and_contiguous(y, np.float64) - new_x = atleast_1d_and_contiguous(new_x, np.float64) - - assert len(y.shape) < 3, "function only works with 1D or 2D arrays" - if len(y.shape) == 2: - new_y = np.zeros((y.shape[0], len(new_x)), np.float64) - for i in range(len(new_y)): # for each row - _interpolate.linear_dddd(x, y[i], new_x, new_y[i]) - else: - new_y = np.zeros(len(new_x), np.float64) - _interpolate.linear_dddd(x, y, new_x, new_y) - - return new_y - -def logarithmic(x, y, new_x): - """ Linearly interpolates values in new_x based in the log space of y. - - Parameters - ---------- - x - 1-D array - y - 1-D or 2-D array - new_x - 1-D array - """ - x = atleast_1d_and_contiguous(x, np.float64) - y = atleast_1d_and_contiguous(y, np.float64) - new_x = atleast_1d_and_contiguous(new_x, np.float64) - - assert len(y.shape) < 3, "function only works with 1D or 2D arrays" - if len(y.shape) == 2: - new_y = np.zeros((y.shape[0], len(new_x)), np.float64) - for i in range(len(new_y)): - _interpolate.loginterp_dddd(x, y[i], new_x, new_y[i]) - else: - new_y = np.zeros(len(new_x), np.float64) - _interpolate.loginterp_dddd(x, y, new_x, new_y) - - return new_y - -def block_average_above(x, y, new_x): - """ Linearly interpolates values in new_x based on the values in x and y - - Parameters - ---------- - x - 1-D array - y - 1-D or 2-D array - new_x - 1-D array - """ - bad_index = None - x = atleast_1d_and_contiguous(x, np.float64) - y = atleast_1d_and_contiguous(y, np.float64) - new_x = atleast_1d_and_contiguous(new_x, np.float64) - - assert len(y.shape) < 3, "function only works with 1D or 2D arrays" - if len(y.shape) == 2: - new_y = np.zeros((y.shape[0], len(new_x)), np.float64) - for i in range(len(new_y)): - bad_index = _interpolate.block_averave_above_dddd(x, y[i], - new_x, new_y[i]) - if bad_index is not None: - break - else: - new_y = np.zeros(len(new_x), np.float64) - bad_index = _interpolate.block_average_above_dddd(x, y, new_x, new_y) - - if bad_index is not None: - msg = "block_average_above cannot extrapolate and new_x[%d]=%f "\ - "is out of the x range (%f, %f)" % \ - (bad_index, new_x[bad_index], x[0], x[-1]) - raise ValueError, msg - - return new_y - -def block(x, y, new_x): - """ Essentially a step function. - - For each new_x[i], finds largest j such that - x[j] < new_x[j], and returns y[j]. - """ - # find index of values in x that preceed values in x - # This code is a little strange -- we really want a routine that - # returns the index of values where x[j] < x[index] - TINY = 1e-10 - indices = np.searchsorted(x, new_x+TINY)-1 - - # If the value is at the front of the list, it'll have -1. - # In this case, we will use the first (0), element in the array. - # take requires the index array to be an Int - indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int)) - new_y = np.take(y, indices, axis=-1) +""" helper_funcs.py. + scavenged from enthought,interpolate +""" + +import numpy as np +import sys +import _interpolate # C extension. Does all the real work. + +def atleast_1d_and_contiguous(ary, dtype = np.float64): + return np.atleast_1d( np.ascontiguousarray(ary, dtype) ) + +def nearest(x, y, new_x): + """ Rounds each new_x[i] to the closest value in x + and returns corresponding y. + """ + shifted_x = np.concatenate(( np.array([x[0]-1]) , x[0:-1] )) + + midpoints_of_x = atleast_1d_and_contiguous( .5*(x + shifted_x) ) + new_x = atleast_1d_and_contiguous(new_x) + + TINY = 1e-10 + indices = np.searchsorted(midpoints_of_x, new_x+TINY)-1 + indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int)) + new_y = np.take(y, indices, axis=-1) + return new_y + + + +def linear(x, y, new_x): + """ Linearly interpolates values in new_x based on the values in x and y + + Parameters + ---------- + x + 1-D array + y + 1-D or 2-D array + new_x + 1-D array + """ + x = atleast_1d_and_contiguous(x, np.float64) + y = atleast_1d_and_contiguous(y, np.float64) + new_x = atleast_1d_and_contiguous(new_x, np.float64) + + assert len(y.shape) < 3, "function only works with 1D or 2D arrays" + if len(y.shape) == 2: + new_y = np.zeros((y.shape[0], len(new_x)), np.float64) + for i in range(len(new_y)): # for each row + _interpolate.linear_dddd(x, y[i], new_x, new_y[i]) + else: + new_y = np.zeros(len(new_x), np.float64) + _interpolate.linear_dddd(x, y, new_x, new_y) + + return new_y + +def logarithmic(x, y, new_x): + """ Linearly interpolates values in new_x based in the log space of y. + + Parameters + ---------- + x + 1-D array + y + 1-D or 2-D array + new_x + 1-D array + """ + x = atleast_1d_and_contiguous(x, np.float64) + y = atleast_1d_and_contiguous(y, np.float64) + new_x = atleast_1d_and_contiguous(new_x, np.float64) + + assert len(y.shape) < 3, "function only works with 1D or 2D arrays" + if len(y.shape) == 2: + new_y = np.zeros((y.shape[0], len(new_x)), np.float64) + for i in range(len(new_y)): + _interpolate.loginterp_dddd(x, y[i], new_x, new_y[i]) + else: + new_y = np.zeros(len(new_x), np.float64) + _interpolate.loginterp_dddd(x, y, new_x, new_y) + + return new_y + +def block_average_above(x, y, new_x): + """ Linearly interpolates values in new_x based on the values in x and y + + Parameters + ---------- + x + 1-D array + y + 1-D or 2-D array + new_x + 1-D array + """ + bad_index = None + x = atleast_1d_and_contiguous(x, np.float64) + y = atleast_1d_and_contiguous(y, np.float64) + new_x = atleast_1d_and_contiguous(new_x, np.float64) + + assert len(y.shape) < 3, "function only works with 1D or 2D arrays" + if len(y.shape) == 2: + new_y = np.zeros((y.shape[0], len(new_x)), np.float64) + for i in range(len(new_y)): + bad_index = _interpolate.block_averave_above_dddd(x, y[i], + new_x, new_y[i]) + if bad_index is not None: + break + else: + new_y = np.zeros(len(new_x), np.float64) + bad_index = _interpolate.block_average_above_dddd(x, y, new_x, new_y) + + if bad_index is not None: + msg = "block_average_above cannot extrapolate and new_x[%d]=%f "\ + "is out of the x range (%f, %f)" % \ + (bad_index, new_x[bad_index], x[0], x[-1]) + raise ValueError, msg + + return new_y + +def block(x, y, new_x): + """ Essentially a step function. + + For each new_x[i], finds largest j such that + x[j] < new_x[j], and returns y[j]. + """ + # find index of values in x that preceed values in x + # This code is a little strange -- we really want a routine that + # returns the index of values where x[j] < x[index] + TINY = 1e-10 + indices = np.searchsorted(x, new_x+TINY)-1 + + # If the value is at the front of the list, it'll have -1. + # In this case, we will use the first (0), element in the array. + # take requires the index array to be an Int + indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int)) + new_y = np.take(y, indices, axis=-1) + return new_y From scipy-svn at scipy.org Sun Nov 2 21:15:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 20:15:47 -0600 (CST) Subject: [Scipy-svn] r4941 - trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS Message-ID: <20081103021547.9309039C088@scipy.org> Author: cdavid Date: 2008-11-02 20:15:39 -0600 (Sun, 02 Nov 2008) New Revision: 4941 Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f Log: Fix various syntax problems in dummy fortran wrapper for arpack. Modified: trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f 2008-11-03 02:00:11 UTC (rev 4940) +++ trunk/scipy/sparse/linalg/eigen/arpack/ARPACK/FWRAPPERS/dummy.f 2008-11-03 02:15:39 UTC (rev 4941) @@ -1,9 +1,10 @@ double complex function wzdotc(n, zx, incx, zy, incy) - double complex zx(*), zy(*), z, zdotc + double complex zx(*), zy(*), z + double complex zdotc integer n, incx, incy - zdotc(n, zx, incx, zy, incy, z) - wzdotc = zdotc + z = zdotc(n, zx, incx, zy, incy) + wzdotc = z end @@ -11,8 +12,8 @@ double complex zx(*), zy(*), z, zdotu integer n, incx, incy - zdotu(n, zx, incx, zy, incy, z) - wzdotu = zdotu + z = zdotu(n, zx, incx, zy, incy) + wzdotu = z return end @@ -21,8 +22,8 @@ complex cx(*), cy(*), c, cdotc integer n, incx, incy - cdotc(n, cx, incx, cy, incy, c) - wzdotc = zdotc + c = cdotc(n, cx, incx, cy, incy) + wcdotc = c return end @@ -31,8 +32,8 @@ complex cx(*), cy(*), c, cdotu integer n, incx, incy - cdotu(n, cx, incx, cy, incy, c) - wzdotu = zdotu + c = cdotu(n, cx, incx, cy, incy) + wcdotu = c return end From scipy-svn at scipy.org Sun Nov 2 22:12:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 21:12:49 -0600 (CST) Subject: [Scipy-svn] r4942 - scipy-docs/trunk/source Message-ID: <20081103031249.7DCB239C088@scipy.org> Author: ptvirtan Date: 2008-11-02 21:12:39 -0600 (Sun, 02 Nov 2008) New Revision: 4942 Modified: scipy-docs/trunk/source/conf.py Log: Fix intersphinx link to Numpy documentation Modified: scipy-docs/trunk/source/conf.py =================================================================== --- scipy-docs/trunk/source/conf.py 2008-11-03 02:15:39 UTC (rev 4941) +++ scipy-docs/trunk/source/conf.py 2008-11-03 03:12:39 UTC (rev 4942) @@ -200,7 +200,7 @@ # ----------------------------------------------------------------------------- intersphinx_mapping = { 'http://docs.python.org/dev': None, - 'http://www.elisanet.fi/ptvirtan/tmp/numpy-refguide': None, + 'http://docs.scipy.org/doc/numpy': None, } From scipy-svn at scipy.org Sun Nov 2 22:54:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 21:54:29 -0600 (CST) Subject: [Scipy-svn] r4943 - trunk/scipy/sparse/linalg/eigen/arpack/tests Message-ID: <20081103035429.5320439C089@scipy.org> Author: chris.burns Date: 2008-11-02 21:54:26 -0600 (Sun, 02 Nov 2008) New Revision: 4943 Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py Log: Skip complex arpack tests that cause Bus Error on OSX. Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 03:12:39 UTC (rev 4942) +++ trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 03:54:26 UTC (rev 4943) @@ -10,6 +10,11 @@ from numpy import array, finfo, argsort, dot, round, conj, random from scipy.sparse.linalg.eigen.arpack import eigen_symmetric, eigen +# Include platform only for skipping test of complex arpack routines +# in OSX Accelerate Framework. Once these tests are fixed, this +# import should be removed. +from sys import platform +darwin_skip_msg='Complex number bug with Accelerate Framework, see ticket #725.' def assert_almost_equal_cc(actual,desired,decimal=7,err_msg='',verbose=True): # almost equal or complex conjugates almost equal @@ -147,7 +152,7 @@ eval[i]*evec[:,i], decimal=_ndigits[typ]) - + @dec.skipif(platform=='darwin', darwin_skip_msg) def test_complex_symmetric_modes(self): k=2 for typ in 'FD': @@ -259,6 +264,7 @@ decimal=_ndigits[typ]) + @dec.skipif(platform=='darwin', darwin_skip_msg) def test_complex_nonsymmetric_modes(self): k=2 for typ in 'FD': From scipy-svn at scipy.org Sun Nov 2 23:53:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 22:53:39 -0600 (CST) Subject: [Scipy-svn] r4944 - in trunk/scipy: optimize spatial Message-ID: <20081103045339.1514339C088@scipy.org> Author: damian.eads Date: 2008-11-02 22:53:36 -0600 (Sun, 02 Nov 2008) New Revision: 4944 Modified: trunk/scipy/optimize/optimize.py trunk/scipy/spatial/distance.py trunk/scipy/spatial/info.py Log: Working on doc fixes. Modified: trunk/scipy/optimize/optimize.py =================================================================== --- trunk/scipy/optimize/optimize.py 2008-11-03 03:54:26 UTC (rev 4943) +++ trunk/scipy/optimize/optimize.py 2008-11-03 04:53:36 UTC (rev 4944) @@ -101,7 +101,7 @@ full_output=0, disp=1, retall=0, callback=None): """Minimize a function using the downhill simplex algorithm. - *Parameters*: + :Parameters: func : callable func(x,*args) The objective function to be minimized. @@ -113,7 +113,7 @@ Called after each iteration, as callback(xk), where xk is the current parameter vector. - *Returns*: (xopt, {fopt, iter, funcalls, warnflag}) + :Returns: (xopt, {fopt, iter, funcalls, warnflag}) xopt : ndarray Parameter that minimizes function. @@ -146,7 +146,7 @@ retall : bool Set to True to return list of solutions at each iteration. - *Notes* + :Notes: Uses a Nelder-Mead simplex algorithm to find the minimum of function of one or more variables. @@ -406,7 +406,7 @@ args=(), c1=1e-4, c2=0.9, amax=50): """Find alpha that satisfies strong Wolfe conditions. - *Parameters*: + :Parameters: f : callable f(x,*args) Objective function. @@ -426,7 +426,7 @@ c2 : float Parameter for curvature condition rule. - *Returns*: + :Returns: alpha0 : float Alpha for which ``x_new = x0 + alpha * pk``. @@ -435,7 +435,7 @@ gc : int Number of gradient evaluations made. - *Notes* + :Notes: Uses the line search algorithm to enforce strong Wolfe conditions. See Wright and Nocedal, 'Numerical Optimization', @@ -550,7 +550,7 @@ Uses the interpolation algorithm (Armiijo backtracking) as suggested by Wright and Nocedal in 'Numerical Optimization', 1999, pg. 56-57 - *Returns*: (alpha, fc, gc) + :Returns: (alpha, fc, gc) """ @@ -627,7 +627,7 @@ retall=0, callback=None): """Minimize a function using the BFGS algorithm. - *Parameters*: + :Parameters: f : callable f(x,*args) Objective function to be minimized. @@ -648,7 +648,7 @@ iteration. Called as callback(xk), where xk is the current parameter vector. - *Returns*: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, ) + :Returns: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, ) xopt : ndarray Parameters which minimize f, i.e. f(xopt) == fopt. @@ -679,7 +679,7 @@ retall : bool Return a list of results at each iteration if True. - *Notes* + :Notes: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, @@ -801,7 +801,7 @@ maxiter=None, full_output=0, disp=1, retall=0, callback=None): """Minimize a function using a nonlinear conjugate gradient algorithm. - *Parameters*: + :Parameters: f : callable f(x,*args) Objective function to be minimized. x0 : ndarray @@ -822,7 +822,7 @@ iteration. Called as callback(xk), where xk is the current parameter vector. - *Returns*: (xopt, {fopt, func_calls, grad_calls, warnflag}, {allvecs}) + :Returns: (xopt, {fopt, func_calls, grad_calls, warnflag}, {allvecs}) xopt : ndarray Parameters which minimize f, i.e. f(xopt) == fopt. @@ -850,7 +850,7 @@ retall : bool return a list of results at each iteration if True. - *Notes* + :Notes: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak and @@ -955,7 +955,7 @@ callback=None): """Minimize a function using the Newton-CG method. - *Parameters*: + :Parameters: f : callable f(x,*args) Objective function to be minimized. @@ -979,7 +979,7 @@ each iteration. Called as callback(xk), where xk is the current parameter vector. - *Returns*: (xopt, {fopt, fcalls, gcalls, hcalls, warnflag},{allvecs}) + :Returns: (xopt, {fopt, fcalls, gcalls, hcalls, warnflag},{allvecs}) xopt : ndarray Parameters which minimizer f, i.e. ``f(xopt) == fopt``. @@ -1011,7 +1011,7 @@ retall : bool If True, return a list of results at each iteration. - *Notes* + :Notes: 1. scikits.openopt offers a unified syntax to call this and other solvers. 2. Only one of `fhess_p` or `fhess` need to be given. If `fhess` is provided, then `fhess_p` will be ignored. If neither `fhess` @@ -1132,7 +1132,7 @@ full_output=0, disp=1): """Bounded minimization for scalar functions. - *Parameters*: + :Parameters: func : callable f(x,*args) Objective function to be minimized (must accept and return scalars). @@ -1154,7 +1154,7 @@ 3 : print iteration results. - *Returns*: (xopt, {fval, ierr, numfunc}) + :Returns: (xopt, {fval, ierr, numfunc}) xopt : ndarray Parameters (over given interval) which minimize the @@ -1168,7 +1168,7 @@ The number of function calls made. - *Notes* + :Notes: Finds a local minimizer of the scalar function `func` in the interval x1 < xopt < x2 using Brent's method. (See `brent` @@ -1429,7 +1429,7 @@ return the minimum of the function isolated to a fractional precision of tol. - *Parameters*: + :Parameters: func : callable f(x,*args) Objective function. @@ -1445,7 +1445,7 @@ If True, return all output args (xmin, fval, iter, funcalls). - *Returns*: + :Returns: xmin : ndarray Optimum point. @@ -1477,7 +1477,7 @@ return the minimum of the function isolated to a fractional precision of tol. - *Parameters*: + :Parameters: func : callable func(x,*args) Objective function to minimize. @@ -1494,7 +1494,7 @@ full_output : bool If True, return optional outputs. - *Notes* + :Notes: Uses analog of bisection method to decrease the bracketed interval. @@ -1557,7 +1557,7 @@ f(xa) > f(xb) < f(xc). It doesn't always mean that obtained solution will satisfy xa<=x<=xb - *Parameters*: + :Parameters: func : callable f(x,*args) Objective function to minimize. @@ -1570,7 +1570,7 @@ maxiter : int Maximum number of iterations to perform. - *Returns*: xa, xb, xc, fa, fb, fc, funcalls + :Returns: xa, xb, xc, fa, fb, fc, funcalls xa, xb, xc : float Bracket. @@ -1655,7 +1655,7 @@ direc=None): """Minimize a function using modified Powell's method. - *Parameters*: + :Parameters: func : callable f(x,*args) Objective function to be minimized. @@ -1670,7 +1670,7 @@ direc : ndarray Initial direction set. - *Returns*: (xopt, {fopt, xi, direc, iter, funcalls, warnflag}, {allvecs}) + :Returns: (xopt, {fopt, xi, direc, iter, funcalls, warnflag}, {allvecs}) xopt : ndarray Parameter which minimizes `func`. @@ -1708,7 +1708,7 @@ If True, return a list of the solution at each iteration. - *Notes* + :Notes: Uses a modification of Powell's method to find the minimum of a function of N variables. @@ -1825,9 +1825,9 @@ def brute(func, ranges, args=(), Ns=20, full_output=0, finish=fmin): """Minimize a function over a given range by brute force. - *Parameters*: + :Parameters: - func : callable f(x,*args) + func : callable ``f(x,*args)`` Objective function to be minimized. ranges : tuple Each element is a tuple of parameters or a slice object to @@ -1839,7 +1839,7 @@ full_output : bool If True, return the evaluation grid. - *Returns*: (x0, fval, {grid, Jout}) + :Returns: (x0, fval, {grid, Jout}) x0 : ndarray Value of arguments to `func`, giving minimum over the grid. @@ -1851,7 +1851,7 @@ Jout : ndarray Function values over grid: ``Jout = func(*grid)``. - *Notes* + :Notes: Find the minimum of a function evaluated on a grid given by the tuple ranges. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-03 03:54:26 UTC (rev 4943) +++ trunk/scipy/spatial/distance.py 2008-11-03 04:53:36 UTC (rev 4944) @@ -1563,48 +1563,19 @@ thrown if ``XA`` and ``XB`` do not have the same number of columns. - A rectangular distance matrix Y is returned. For each :math:`$i$` + A rectangular distance matrix ``Y`` is returned. For each :math:`$i$` and :math:`$j$`, the metric ``dist(u=XA[i], v=XB[j])`` is computed and stored in the :math:`$ij$`th entry. - - :Parameters: - XA : ndarray - An :math:`$m_A$` by :math:`$n$` array of :math:`$m_A$` - original observations in an :math:`$n$`-dimensional space. - XB : ndarray - An :math:`$m_B$` by :math:`$n$` array of :math:`$m_B$` - original observations in an :math:`$n$`-dimensional space. - metric : string or function - The distance metric to use. The distance function can - be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', - 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', - 'jaccard', 'kulsinski', 'mahalanobis', 'matching', - 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', - 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', - 'yule'. - w : ndarray - The weight vector (for weighted Minkowski). - p : double - The p-norm to apply (for Minkowski, weighted and unweighted) - V : ndarray - The variance vector (for standardized Euclidean). - VI : ndarray - The inverse of the covariance matrix (for Mahalanobis). - - - :Returns: - Y : ndarray - A :math:`$m_A$` by :math:`$m_B$` distance matrix. - Calling Conventions ------------------- 1. ``Y = cdist(X, 'euclidean')`` - Computes the distance between m points using Euclidean distance - (2-norm) as the distance metric between the points. The points - are arranged as m n-dimensional row vectors in the matrix X. + Computes the distance between :math:`$m$` points using + Euclidean distance (2-norm) as the distance metric between the + points. The points are arranged as :math:`$m$` + :math:`$n$`-dimensional row vectors in the matrix X. 2. ``Y = cdist(X, 'minkowski', p)`` @@ -1781,6 +1752,34 @@ dm = cdist(X, 'sokalsneath') + :Parameters: + XA : ndarray + An :math:`$m_A$` by :math:`$n$` array of :math:`$m_A$` + original observations in an :math:`$n$`-dimensional space. + XB : ndarray + An :math:`$m_B$` by :math:`$n$` array of :math:`$m_B$` + original observations in an :math:`$n$`-dimensional space. + metric : string or function + The distance metric to use. The distance function can + be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', + 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', + 'jaccard', 'kulsinski', 'mahalanobis', 'matching', + 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', + 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', + 'yule'. + w : ndarray + The weight vector (for weighted Minkowski). + p : double + The p-norm to apply (for Minkowski, weighted and unweighted) + V : ndarray + The variance vector (for standardized Euclidean). + VI : ndarray + The inverse of the covariance matrix (for Mahalanobis). + + + :Returns: + Y : ndarray + A :math:`$m_A$` by :math:`$m_B$` distance matrix. """ Modified: trunk/scipy/spatial/info.py =================================================================== --- trunk/scipy/spatial/info.py 2008-11-03 03:54:26 UTC (rev 4943) +++ trunk/scipy/spatial/info.py 2008-11-03 04:53:36 UTC (rev 4944) @@ -1,21 +1,4 @@ """ -Vector Quantization / Kmeans -============================ - - Clustering algorithms are useful in information theory, target detection, - communications, compression, and other areas. The vq module only - supports vector quantization and the k-means algorithms. Development - of self-organizing maps (SOM) and other approaches is underway. - -Hierarchical Clustering -======================= - - The hierarchy module provides functions for hierarchical and agglomerative - clustering. Its features include generating hierarchical clusters from - distance matrices, computing distance matrices from observation vectors, - calculating statistics on clusters, cutting linkages to generate flat - clusters, and visualizing clusters with dendrograms. - Distance Computation ==================== From scipy-svn at scipy.org Sun Nov 2 23:55:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 22:55:51 -0600 (CST) Subject: [Scipy-svn] r4945 - trunk/scipy/spatial Message-ID: <20081103045551.7D1A939C088@scipy.org> Author: damian.eads Date: 2008-11-02 22:55:49 -0600 (Sun, 02 Nov 2008) New Revision: 4945 Modified: trunk/scipy/spatial/distance.py Log: Working on doc fixes. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-03 04:53:36 UTC (rev 4944) +++ trunk/scipy/spatial/distance.py 2008-11-03 04:55:49 UTC (rev 4945) @@ -28,9 +28,9 @@ +------------------+-------------------------------------------------+ |is_valid_dm | checks for a valid distance matrix. | +------------------+-------------------------------------------------+ -|is_valid_y | checks for a valid condensed distance matrix. +|is_valid_y | checks for a valid condensed distance matrix. | +------------------+-------------------------------------------------+ -|numobs_dm # of observations in a distance matrix. +|numobs_dm | # of observations in a distance matrix. | +------------------+-------------------------------------------------+ Distance functions between two vectors ``u`` and ``v``. Computing From scipy-svn at scipy.org Mon Nov 3 00:10:13 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 23:10:13 -0600 (CST) Subject: [Scipy-svn] r4946 - in trunk/scipy/stats: . tests Message-ID: <20081103051013.6008639C1EC@scipy.org> Author: ariel.rokem Date: 2008-11-02 23:09:51 -0600 (Sun, 02 Nov 2008) New Revision: 4946 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_stats.py Log: Fix #714 + tests Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-03 04:55:49 UTC (rev 4945) +++ trunk/scipy/stats/stats.py 2008-11-03 05:09:51 UTC (rev 4946) @@ -1005,7 +1005,7 @@ # behaviour at, for example, discontinuities. values = np.sort(a,axis=0) if limit: - values = values[(limit[0] < a) & (a < limit[1])] + values = values[(limit[0] <= values) & (values <= limit[1])] idx = per /100. * (values.shape[0] - 1) if (idx % 1 == 0): Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-03 04:55:49 UTC (rev 4945) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-03 05:09:51 UTC (rev 4946) @@ -902,5 +902,12 @@ assert_array_almost_equal(t, self.T1_2) assert_array_almost_equal(p, self.P1_2) +def test_scoreatpercentile(): + assert_equal(stats.scoreatpercentile(range(10),50),4.5) + assert_equal(stats.scoreatpercentile(range(10),50,(2,7)),4.5) + assert_equal(stats.scoreatpercentile(range(100),50,(1,8)),4.5) + assert_equal(stats.scoreatpercentile(np.array([1, 10 ,100]),50,(10,100)), 55) + assert_equal(stats.scoreatpercentile(np.array([1, 10 ,100]),50,(1,10)), 5.5) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Mon Nov 3 00:10:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 23:10:58 -0600 (CST) Subject: [Scipy-svn] r4947 - scipy-docs/trunk/source Message-ID: <20081103051058.C425939C088@scipy.org> Author: damian.eads Date: 2008-11-02 23:10:54 -0600 (Sun, 02 Nov 2008) New Revision: 4947 Added: scipy-docs/trunk/source/spatial.distance.rst Removed: scipy-docs/trunk/source/cluster.distance.rst Modified: scipy-docs/trunk/source/cluster.rst scipy-docs/trunk/source/index.rst Log: Added index keys for scipy.spatial. Deleted: scipy-docs/trunk/source/cluster.distance.rst =================================================================== --- scipy-docs/trunk/source/cluster.distance.rst 2008-11-03 05:09:51 UTC (rev 4946) +++ scipy-docs/trunk/source/cluster.distance.rst 2008-11-03 05:10:54 UTC (rev 4947) @@ -1,6 +0,0 @@ -===================================================== -Distance computations (:mod:`scipy.cluster.distance`) -===================================================== - -.. automodule:: scipy.cluster.distance - :members: Modified: scipy-docs/trunk/source/cluster.rst =================================================================== --- scipy-docs/trunk/source/cluster.rst 2008-11-03 05:09:51 UTC (rev 4946) +++ scipy-docs/trunk/source/cluster.rst 2008-11-03 05:10:54 UTC (rev 4947) @@ -4,7 +4,6 @@ .. toctree:: - cluster.distance cluster.hierarchy cluster.vq Modified: scipy-docs/trunk/source/index.rst =================================================================== --- scipy-docs/trunk/source/index.rst 2008-11-03 05:09:51 UTC (rev 4946) +++ scipy-docs/trunk/source/index.rst 2008-11-03 05:10:54 UTC (rev 4947) @@ -23,6 +23,7 @@ signal sparse sparse.linalg + spatial special stats weave Copied: scipy-docs/trunk/source/spatial.distance.rst (from rev 4925, scipy-docs/trunk/source/cluster.distance.rst) =================================================================== --- scipy-docs/trunk/source/cluster.distance.rst 2008-11-03 00:44:10 UTC (rev 4925) +++ scipy-docs/trunk/source/spatial.distance.rst 2008-11-03 05:10:54 UTC (rev 4947) @@ -0,0 +1,6 @@ +===================================================== +Distance computations (:mod:`scipy.spatial.distance`) +===================================================== + +.. automodule:: scipy.spatial.distance + :members: From scipy-svn at scipy.org Mon Nov 3 00:21:04 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 23:21:04 -0600 (CST) Subject: [Scipy-svn] r4948 - trunk/scipy/sparse/linalg/eigen/arpack/tests Message-ID: <20081103052104.453E239C088@scipy.org> Author: cdavid Date: 2008-11-02 23:20:56 -0600 (Sun, 02 Nov 2008) New Revision: 4948 Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py Log: Re-enable the arpack tests: they do pass with Accelerate if scipy is correctly built/installed. Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 05:10:54 UTC (rev 4947) +++ trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 05:20:56 UTC (rev 4948) @@ -152,7 +152,7 @@ eval[i]*evec[:,i], decimal=_ndigits[typ]) - @dec.skipif(platform=='darwin', darwin_skip_msg) + #@dec.skipif(platform=='darwin', darwin_skip_msg) def test_complex_symmetric_modes(self): k=2 for typ in 'FD': @@ -264,7 +264,7 @@ decimal=_ndigits[typ]) - @dec.skipif(platform=='darwin', darwin_skip_msg) + #@dec.skipif(platform=='darwin', darwin_skip_msg) def test_complex_nonsymmetric_modes(self): k=2 for typ in 'FD': From scipy-svn at scipy.org Mon Nov 3 00:46:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 2 Nov 2008 23:46:02 -0600 (CST) Subject: [Scipy-svn] r4949 - in trunk/scipy/weave/blitz/blitz: . array generate meta Message-ID: <20081103054602.9E5DD39C088@scipy.org> Author: jarrod.millman Date: 2008-11-02 23:45:13 -0600 (Sun, 02 Nov 2008) New Revision: 4949 Modified: trunk/scipy/weave/blitz/blitz/applics.h trunk/scipy/weave/blitz/blitz/array-impl.h trunk/scipy/weave/blitz/blitz/array-old.h trunk/scipy/weave/blitz/blitz/array.h trunk/scipy/weave/blitz/blitz/array/asexpr.h trunk/scipy/weave/blitz/blitz/array/bops.cc trunk/scipy/weave/blitz/blitz/array/cartesian.h trunk/scipy/weave/blitz/blitz/array/cgsolve.h trunk/scipy/weave/blitz/blitz/array/complex.cc trunk/scipy/weave/blitz/blitz/array/convolve.cc trunk/scipy/weave/blitz/blitz/array/convolve.h trunk/scipy/weave/blitz/blitz/array/cycle.cc trunk/scipy/weave/blitz/blitz/array/domain.h trunk/scipy/weave/blitz/blitz/array/et.h trunk/scipy/weave/blitz/blitz/array/expr.h trunk/scipy/weave/blitz/blitz/array/fastiter.h trunk/scipy/weave/blitz/blitz/array/funcs.h trunk/scipy/weave/blitz/blitz/array/functorExpr.h trunk/scipy/weave/blitz/blitz/array/geometry.h trunk/scipy/weave/blitz/blitz/array/indirect.h trunk/scipy/weave/blitz/blitz/array/interlace.cc trunk/scipy/weave/blitz/blitz/array/io.cc trunk/scipy/weave/blitz/blitz/array/iter.h trunk/scipy/weave/blitz/blitz/array/map.h trunk/scipy/weave/blitz/blitz/array/misc.cc trunk/scipy/weave/blitz/blitz/array/multi.h trunk/scipy/weave/blitz/blitz/array/newbops.cc trunk/scipy/weave/blitz/blitz/array/newet-macros.h trunk/scipy/weave/blitz/blitz/array/newet.h trunk/scipy/weave/blitz/blitz/array/ops.cc trunk/scipy/weave/blitz/blitz/array/ops.h trunk/scipy/weave/blitz/blitz/array/reduce.cc trunk/scipy/weave/blitz/blitz/array/reduce.h trunk/scipy/weave/blitz/blitz/array/resize.cc trunk/scipy/weave/blitz/blitz/array/shape.h trunk/scipy/weave/blitz/blitz/array/slice.h trunk/scipy/weave/blitz/blitz/array/slicing.cc trunk/scipy/weave/blitz/blitz/array/stencil-et.h trunk/scipy/weave/blitz/blitz/array/stencilops.h trunk/scipy/weave/blitz/blitz/array/stencils.cc trunk/scipy/weave/blitz/blitz/array/stencils.h trunk/scipy/weave/blitz/blitz/array/storage.h trunk/scipy/weave/blitz/blitz/array/uops.cc trunk/scipy/weave/blitz/blitz/array/where.h trunk/scipy/weave/blitz/blitz/array/zip.h trunk/scipy/weave/blitz/blitz/bench.h trunk/scipy/weave/blitz/blitz/benchext.h trunk/scipy/weave/blitz/blitz/blitz.h trunk/scipy/weave/blitz/blitz/bzdebug.h trunk/scipy/weave/blitz/blitz/compiler.h trunk/scipy/weave/blitz/blitz/etbase.h trunk/scipy/weave/blitz/blitz/extremum.h trunk/scipy/weave/blitz/blitz/funcs.h trunk/scipy/weave/blitz/blitz/generate/bzfstream.h trunk/scipy/weave/blitz/blitz/indexexpr.h trunk/scipy/weave/blitz/blitz/listinit.h trunk/scipy/weave/blitz/blitz/matdiag.h trunk/scipy/weave/blitz/blitz/matexpr.h trunk/scipy/weave/blitz/blitz/matgen.h trunk/scipy/weave/blitz/blitz/mathf2.h trunk/scipy/weave/blitz/blitz/matltri.h trunk/scipy/weave/blitz/blitz/matref.h trunk/scipy/weave/blitz/blitz/matrix.h trunk/scipy/weave/blitz/blitz/matsymm.h trunk/scipy/weave/blitz/blitz/mattoep.h trunk/scipy/weave/blitz/blitz/matutri.h trunk/scipy/weave/blitz/blitz/memblock.h trunk/scipy/weave/blitz/blitz/meta/dot.h trunk/scipy/weave/blitz/blitz/meta/matassign.h trunk/scipy/weave/blitz/blitz/meta/matmat.h trunk/scipy/weave/blitz/blitz/meta/matvec.h trunk/scipy/weave/blitz/blitz/meta/metaprog.h trunk/scipy/weave/blitz/blitz/meta/product.h trunk/scipy/weave/blitz/blitz/meta/sum.h trunk/scipy/weave/blitz/blitz/meta/vecassign.h trunk/scipy/weave/blitz/blitz/minmax.h trunk/scipy/weave/blitz/blitz/mstruct.h trunk/scipy/weave/blitz/blitz/numinquire.h trunk/scipy/weave/blitz/blitz/numtrait.h trunk/scipy/weave/blitz/blitz/ops.h trunk/scipy/weave/blitz/blitz/prettyprint.h trunk/scipy/weave/blitz/blitz/promote-old.h trunk/scipy/weave/blitz/blitz/promote.h trunk/scipy/weave/blitz/blitz/rand-dunif.h trunk/scipy/weave/blitz/blitz/rand-normal.h trunk/scipy/weave/blitz/blitz/rand-uniform.h trunk/scipy/weave/blitz/blitz/random.h trunk/scipy/weave/blitz/blitz/randref.h trunk/scipy/weave/blitz/blitz/range.h trunk/scipy/weave/blitz/blitz/reduce.h trunk/scipy/weave/blitz/blitz/shapecheck.h trunk/scipy/weave/blitz/blitz/tau.h trunk/scipy/weave/blitz/blitz/timer.h trunk/scipy/weave/blitz/blitz/tiny.h trunk/scipy/weave/blitz/blitz/tinymat.h trunk/scipy/weave/blitz/blitz/tinymatexpr.h trunk/scipy/weave/blitz/blitz/tinyvec-et.h trunk/scipy/weave/blitz/blitz/tinyvec.cc trunk/scipy/weave/blitz/blitz/tinyvec.h trunk/scipy/weave/blitz/blitz/tinyveciter.h trunk/scipy/weave/blitz/blitz/traversal.cc trunk/scipy/weave/blitz/blitz/traversal.h trunk/scipy/weave/blitz/blitz/tuning.h trunk/scipy/weave/blitz/blitz/tvcross.h trunk/scipy/weave/blitz/blitz/tvecglobs.h trunk/scipy/weave/blitz/blitz/update.h trunk/scipy/weave/blitz/blitz/vecbfn.cc trunk/scipy/weave/blitz/blitz/vecbops.cc trunk/scipy/weave/blitz/blitz/vecexpr.h trunk/scipy/weave/blitz/blitz/vecexprwrap.h trunk/scipy/weave/blitz/blitz/vecglobs.h trunk/scipy/weave/blitz/blitz/veciter.h trunk/scipy/weave/blitz/blitz/vecpick.h trunk/scipy/weave/blitz/blitz/vecpickiter.h trunk/scipy/weave/blitz/blitz/vector-et.h trunk/scipy/weave/blitz/blitz/vector.h trunk/scipy/weave/blitz/blitz/vecuops.cc trunk/scipy/weave/blitz/blitz/vecwhere.cc trunk/scipy/weave/blitz/blitz/vecwhere.h trunk/scipy/weave/blitz/blitz/zero.h Log: updating license with permission from the author (see ##649) Modified: trunk/scipy/weave/blitz/blitz/applics.h =================================================================== --- trunk/scipy/weave/blitz/blitz/applics.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/applics.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/asexpr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/asexpr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/asexpr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/bops.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/bops.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/bops.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -1,15 +1,9 @@ /*************************************************************************** * blitz/../array/bops.cc Array expression templates (2 operands) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-suggest at cybervision.com * Bugs: blitz-bugs at cybervision.com Modified: trunk/scipy/weave/blitz/blitz/array/cartesian.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/cartesian.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/cartesian.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/cgsolve.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/cgsolve.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/cgsolve.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/complex.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/complex.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/complex.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/convolve.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/convolve.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/convolve.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/convolve.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/convolve.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/convolve.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/cycle.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/cycle.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/cycle.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/domain.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/domain.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/domain.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/et.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/et.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/et.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/expr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/expr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/expr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/fastiter.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/fastiter.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/fastiter.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/funcs.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/funcs.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/funcs.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/functorExpr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/functorExpr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/functorExpr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/geometry.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/geometry.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/geometry.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/indirect.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/indirect.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/indirect.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/interlace.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/interlace.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/interlace.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/io.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/io.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/io.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/iter.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/iter.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/iter.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/map.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/map.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/map.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/misc.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/misc.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/misc.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/multi.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/multi.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/multi.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/newbops.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/newbops.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/newbops.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/newet-macros.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/newet-macros.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/newet-macros.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/newet.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/newet.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/newet.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/ops.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/ops.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/ops.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/ops.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/ops.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/ops.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/reduce.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/reduce.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/reduce.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/reduce.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/reduce.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/reduce.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/resize.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/resize.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/resize.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/shape.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/shape.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/shape.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/slice.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/slice.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/slice.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/slicing.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/slicing.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/slicing.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/stencil-et.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/stencil-et.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/stencil-et.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/stencilops.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/stencilops.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/stencilops.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/stencils.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/stencils.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/stencils.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/stencils.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/stencils.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/stencils.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/storage.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/storage.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/storage.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/uops.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/array/uops.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/uops.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -1,15 +1,9 @@ /*************************************************************************** * blitz/../array/uops.cc Expression templates for arrays, unary functions * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-suggest at cybervision.com * Bugs: blitz-bugs at cybervision.com Modified: trunk/scipy/weave/blitz/blitz/array/where.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/where.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/where.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array/zip.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array/zip.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array/zip.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array-impl.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array-impl.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array-impl.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array-old.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array-old.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array-old.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/array.h =================================================================== --- trunk/scipy/weave/blitz/blitz/array.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/array.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2000 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/bench.h =================================================================== --- trunk/scipy/weave/blitz/blitz/bench.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/bench.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/benchext.h =================================================================== --- trunk/scipy/weave/blitz/blitz/benchext.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/benchext.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/blitz.h =================================================================== --- trunk/scipy/weave/blitz/blitz/blitz.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/blitz.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/bzdebug.h =================================================================== --- trunk/scipy/weave/blitz/blitz/bzdebug.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/bzdebug.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/compiler.h =================================================================== --- trunk/scipy/weave/blitz/blitz/compiler.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/compiler.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/etbase.h =================================================================== --- trunk/scipy/weave/blitz/blitz/etbase.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/etbase.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/extremum.h =================================================================== --- trunk/scipy/weave/blitz/blitz/extremum.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/extremum.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/funcs.h =================================================================== --- trunk/scipy/weave/blitz/blitz/funcs.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/funcs.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/generate/bzfstream.h =================================================================== --- trunk/scipy/weave/blitz/blitz/generate/bzfstream.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/generate/bzfstream.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org @@ -39,15 +33,9 @@ "/***************************************************************************\n" " * blitz/" << filename << "\t" << description << std::endl << " *\n" -" * This program is free software; you can redistribute it and/or\n" -" * modify it under the terms of the GNU General Public License\n" -" * as published by the Free Software Foundation; either version 2\n" -" * of the License, or (at your option) any later version.\n" +" * This code was relicensed under the modified BSD license for use in SciPy\n" +" * by Todd Veldhuizen (see LICENSE.txt in the weave directory).\n" " *\n" -" * This program is distributed in the hope that it will be useful,\n" -" * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" -" * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" -" * GNU General Public License for more details.\n" " *\n" " * Suggestions: blitz-suggest at cybervision.com\n" " * Bugs: blitz-bugs at cybervision.com\n" Modified: trunk/scipy/weave/blitz/blitz/indexexpr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/indexexpr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/indexexpr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/listinit.h =================================================================== --- trunk/scipy/weave/blitz/blitz/listinit.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/listinit.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matdiag.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matdiag.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matdiag.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matexpr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matexpr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matexpr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matgen.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matgen.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matgen.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/mathf2.h =================================================================== --- trunk/scipy/weave/blitz/blitz/mathf2.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/mathf2.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matltri.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matltri.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matltri.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matref.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matref.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matref.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matrix.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matrix.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matrix.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matsymm.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matsymm.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matsymm.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/mattoep.h =================================================================== --- trunk/scipy/weave/blitz/blitz/mattoep.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/mattoep.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/matutri.h =================================================================== --- trunk/scipy/weave/blitz/blitz/matutri.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/matutri.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/memblock.h =================================================================== --- trunk/scipy/weave/blitz/blitz/memblock.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/memblock.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-1999 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/dot.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/dot.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/dot.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/matassign.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/matassign.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/matassign.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/matmat.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/matmat.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/matmat.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/matvec.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/matvec.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/matvec.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/metaprog.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/metaprog.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/metaprog.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/product.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/product.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/product.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/sum.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/sum.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/sum.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/meta/vecassign.h =================================================================== --- trunk/scipy/weave/blitz/blitz/meta/vecassign.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/meta/vecassign.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/minmax.h =================================================================== --- trunk/scipy/weave/blitz/blitz/minmax.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/minmax.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/mstruct.h =================================================================== --- trunk/scipy/weave/blitz/blitz/mstruct.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/mstruct.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * * Suggestions: blitz-dev at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/numinquire.h =================================================================== --- trunk/scipy/weave/blitz/blitz/numinquire.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/numinquire.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/numtrait.h =================================================================== --- trunk/scipy/weave/blitz/blitz/numtrait.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/numtrait.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/ops.h =================================================================== --- trunk/scipy/weave/blitz/blitz/ops.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/ops.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/prettyprint.h =================================================================== --- trunk/scipy/weave/blitz/blitz/prettyprint.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/prettyprint.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -7,15 +7,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/promote-old.h =================================================================== --- trunk/scipy/weave/blitz/blitz/promote-old.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/promote-old.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -4,15 +4,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/promote.h =================================================================== --- trunk/scipy/weave/blitz/blitz/promote.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/promote.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/rand-dunif.h =================================================================== --- trunk/scipy/weave/blitz/blitz/rand-dunif.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/rand-dunif.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/rand-normal.h =================================================================== --- trunk/scipy/weave/blitz/blitz/rand-normal.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/rand-normal.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/rand-uniform.h =================================================================== --- trunk/scipy/weave/blitz/blitz/rand-uniform.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/rand-uniform.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/random.h =================================================================== --- trunk/scipy/weave/blitz/blitz/random.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/random.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/randref.h =================================================================== --- trunk/scipy/weave/blitz/blitz/randref.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/randref.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/range.h =================================================================== --- trunk/scipy/weave/blitz/blitz/range.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/range.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/reduce.h =================================================================== --- trunk/scipy/weave/blitz/blitz/reduce.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/reduce.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -7,15 +7,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/shapecheck.h =================================================================== --- trunk/scipy/weave/blitz/blitz/shapecheck.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/shapecheck.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tau.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tau.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tau.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/timer.h =================================================================== --- trunk/scipy/weave/blitz/blitz/timer.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/timer.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tiny.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tiny.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tiny.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tinymat.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tinymat.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tinymat.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tinymatexpr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tinymatexpr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tinymatexpr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tinyvec-et.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tinyvec-et.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tinyvec-et.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2000 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tinyvec.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/tinyvec.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tinyvec.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tinyvec.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tinyvec.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tinyvec.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tinyveciter.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tinyveciter.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tinyveciter.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/traversal.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/traversal.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/traversal.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/traversal.h =================================================================== --- trunk/scipy/weave/blitz/blitz/traversal.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/traversal.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tuning.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tuning.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tuning.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tvcross.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tvcross.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tvcross.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/tvecglobs.h =================================================================== --- trunk/scipy/weave/blitz/blitz/tvecglobs.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/tvecglobs.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -3,15 +3,9 @@ * * $Id: tvecglobs.h 1414 2005-11-01 22:04:59Z cookedm $ * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/update.h =================================================================== --- trunk/scipy/weave/blitz/blitz/update.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/update.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vecbfn.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/vecbfn.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecbfn.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -1,15 +1,9 @@ /*************************************************************************** * blitz/../vecbfn.cc Vector expression binary functions (2 operands) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-suggest at cybervision.com * Bugs: blitz-bugs at cybervision.com Modified: trunk/scipy/weave/blitz/blitz/vecbops.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/vecbops.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecbops.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -1,15 +1,9 @@ /*************************************************************************** * blitz/../vecbops.cc Vector expression templates (2 operands) * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-suggest at cybervision.com * Bugs: blitz-bugs at cybervision.com Modified: trunk/scipy/weave/blitz/blitz/vecexpr.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vecexpr.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecexpr.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vecexprwrap.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vecexprwrap.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecexprwrap.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vecglobs.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vecglobs.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecglobs.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/veciter.h =================================================================== --- trunk/scipy/weave/blitz/blitz/veciter.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/veciter.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vecpick.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vecpick.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecpick.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vecpickiter.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vecpickiter.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecpickiter.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -7,15 +7,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vector-et.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vector-et.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vector-et.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vector.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vector.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vector.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/vecuops.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/vecuops.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecuops.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -1,15 +1,9 @@ /*************************************************************************** * blitz/../vecuops.cc Expression templates for vectors, unary functions * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-suggest at cybervision.com * Bugs: blitz-bugs at cybervision.com Modified: trunk/scipy/weave/blitz/blitz/vecwhere.cc =================================================================== --- trunk/scipy/weave/blitz/blitz/vecwhere.cc 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecwhere.cc 2008-11-03 05:45:13 UTC (rev 4949) @@ -1,15 +1,9 @@ /*************************************************************************** * blitz/../vecwhere.cc where(X,Y,Z) function for vectors * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-suggest at cybervision.com * Bugs: blitz-bugs at cybervision.com Modified: trunk/scipy/weave/blitz/blitz/vecwhere.h =================================================================== --- trunk/scipy/weave/blitz/blitz/vecwhere.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/vecwhere.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -6,15 +6,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org Modified: trunk/scipy/weave/blitz/blitz/zero.h =================================================================== --- trunk/scipy/weave/blitz/blitz/zero.h 2008-11-03 05:20:56 UTC (rev 4948) +++ trunk/scipy/weave/blitz/blitz/zero.h 2008-11-03 05:45:13 UTC (rev 4949) @@ -5,15 +5,9 @@ * * Copyright (C) 1997-2001 Todd Veldhuizen * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. + * This code was relicensed under the modified BSD license for use in SciPy + * by Todd Veldhuizen (see LICENSE.txt in the weave directory). * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. * * Suggestions: blitz-dev at oonumerics.org * Bugs: blitz-bugs at oonumerics.org From scipy-svn at scipy.org Mon Nov 3 01:10:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 00:10:51 -0600 (CST) Subject: [Scipy-svn] r4950 - trunk/scipy/weave/blitz/blitz/generate Message-ID: <20081103061051.A543139C088@scipy.org> Author: jarrod.millman Date: 2008-11-03 00:10:48 -0600 (Mon, 03 Nov 2008) New Revision: 4950 Modified: trunk/scipy/weave/blitz/blitz/generate/genpromote.cpp Log: one more (see #649) Modified: trunk/scipy/weave/blitz/blitz/generate/genpromote.cpp =================================================================== --- trunk/scipy/weave/blitz/blitz/generate/genpromote.cpp 2008-11-03 05:45:13 UTC (rev 4949) +++ trunk/scipy/weave/blitz/blitz/generate/genpromote.cpp 2008-11-03 06:10:48 UTC (rev 4950) @@ -41,15 +41,9 @@ " *\n" " * Copyright (C) 1997-2001 Todd Veldhuizen \n" " *\n" -" * This program is free software; you can redistribute it and/or\n" -" * modify it under the terms of the GNU General Public License\n" -" * as published by the Free Software Foundation; either version 2\n" -" * of the License, or (at your option) any later version.\n" +" * This code was relicensed under the modified BSD license for use in SciPy\n" +" * by Todd Veldhuizen (see LICENSE.txt in the weave directory).\n" " *\n" -" * This program is distributed in the hope that it will be useful,\n" -" * but WITHOUT ANY WARRANTY; without even the implied warranty of\n" -" * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" -" * GNU General Public License for more details.\n" " *\n" " * Suggestions: blitz-dev at oonumerics.org\n" " * Bugs: blitz-bugs at oonumerics.org\n" From scipy-svn at scipy.org Mon Nov 3 01:34:37 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 00:34:37 -0600 (CST) Subject: [Scipy-svn] r4951 - trunk/scipy/sparse/linalg/eigen/arpack/tests Message-ID: <20081103063437.CDB3A39C088@scipy.org> Author: chris.burns Date: 2008-11-03 00:34:34 -0600 (Mon, 03 Nov 2008) New Revision: 4951 Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py Log: Remove the OSX skipping of arpack tests. David Cournapeau fixed the tests Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 06:10:48 UTC (rev 4950) +++ trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-03 06:34:34 UTC (rev 4951) @@ -10,12 +10,6 @@ from numpy import array, finfo, argsort, dot, round, conj, random from scipy.sparse.linalg.eigen.arpack import eigen_symmetric, eigen -# Include platform only for skipping test of complex arpack routines -# in OSX Accelerate Framework. Once these tests are fixed, this -# import should be removed. -from sys import platform -darwin_skip_msg='Complex number bug with Accelerate Framework, see ticket #725.' - def assert_almost_equal_cc(actual,desired,decimal=7,err_msg='',verbose=True): # almost equal or complex conjugates almost equal try: @@ -152,7 +146,6 @@ eval[i]*evec[:,i], decimal=_ndigits[typ]) - #@dec.skipif(platform=='darwin', darwin_skip_msg) def test_complex_symmetric_modes(self): k=2 for typ in 'FD': @@ -263,8 +256,6 @@ eval[i]*evec[:,i], decimal=_ndigits[typ]) - - #@dec.skipif(platform=='darwin', darwin_skip_msg) def test_complex_nonsymmetric_modes(self): k=2 for typ in 'FD': @@ -272,8 +263,5 @@ for m in self.nonsymmetric: self.eval_evec(m,typ,k,which) - - - if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Mon Nov 3 02:02:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 01:02:17 -0600 (CST) Subject: [Scipy-svn] r4952 - trunk/scipy/spatial Message-ID: <20081103070217.6CBAE39C089@scipy.org> Author: damian.eads Date: 2008-11-03 01:02:14 -0600 (Mon, 03 Nov 2008) New Revision: 4952 Modified: trunk/scipy/spatial/distance.py Log: Working on doc fixes. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-03 06:34:34 UTC (rev 4951) +++ trunk/scipy/spatial/distance.py 2008-11-03 07:02:14 UTC (rev 4952) @@ -183,9 +183,9 @@ :Parameters: u : ndarray - An :math:`n`-dimensional vector. + An n-dimensional vector. v : ndarray - An :math:`n`-dimensional vector. + An n-dimensional vector. p : ndarray The norm of the difference :math:`${||u-v||}_p$`. @@ -1565,10 +1565,9 @@ A rectangular distance matrix ``Y`` is returned. For each :math:`$i$` and :math:`$j$`, the metric ``dist(u=XA[i], v=XB[j])`` is computed - and stored in the :math:`$ij$`th entry. + and stored in the :math:`$ij$` th entry. - Calling Conventions - ------------------- + The following are common calling conventions: 1. ``Y = cdist(X, 'euclidean')`` From scipy-svn at scipy.org Mon Nov 3 02:23:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 01:23:08 -0600 (CST) Subject: [Scipy-svn] r4953 - trunk/scipy/integrate Message-ID: <20081103072308.AB75C39C088@scipy.org> Author: chris.burns Date: 2008-11-03 01:22:35 -0600 (Mon, 03 Nov 2008) New Revision: 4953 Modified: trunk/scipy/integrate/__odepack.h trunk/scipy/integrate/__quadpack.h trunk/scipy/integrate/multipack.h trunk/scipy/integrate/setup.py Log: Update deprecated numpy array creation functions. Changed PyArray_FromDims to PyArray_SimpleNew. Change params to use npy_intp for 64bit platforms. Update dependencies in setup.py. Most of the work was done by paul.ivanov. Modified: trunk/scipy/integrate/__odepack.h =================================================================== --- trunk/scipy/integrate/__odepack.h 2008-11-03 07:02:14 UTC (rev 4952) +++ trunk/scipy/integrate/__odepack.h 2008-11-03 07:22:35 UTC (rev 4953) @@ -120,11 +120,11 @@ { int itol = 0; double tol=1.49012e-8; - int one = 1; + npy_intp one = 1; /* Setup tolerances */ if (o_rtol == NULL) { - *ap_rtol = (PyArrayObject *)PyArray_FromDims(1,&one,PyArray_DOUBLE); + *ap_rtol = (PyArrayObject *)PyArray_SimpleNew(1, &one, PyArray_DOUBLE); if (*ap_rtol == NULL) PYERR2(odepack_error,"Error constructing relative tolerance."); *(double *)(*ap_rtol)->data = tol; /* Default */ } @@ -139,7 +139,7 @@ } if (o_atol == NULL) { - *ap_atol = (PyArrayObject *)PyArray_FromDims(1,&one,PyArray_DOUBLE); + *ap_atol = (PyArrayObject *)PyArray_SimpleNew(1,&one,PyArray_DOUBLE); if (*ap_atol == NULL) PYERR2(odepack_error,"Error constructing absolute tolerance"); *(double *)(*ap_atol)->data = tol; } @@ -211,8 +211,9 @@ PyArrayObject *ap_hu=NULL, *ap_tcur=NULL, *ap_tolsf=NULL, *ap_tsw=NULL; PyArrayObject *ap_nst=NULL, *ap_nfe=NULL, *ap_nje=NULL, *ap_nqu=NULL; PyArrayObject *ap_mused=NULL; - int imxer=0, lenrw=0, leniw=0, out_sz=0, col_deriv = 0; - int k, dims[2], ntimes, crit_ind=0; + int imxer=0, lenrw=0, leniw=0, col_deriv = 0; + npy_intp out_sz=0,dims[2]; + int k, ntimes, crit_ind=0; int allocated = 0, full_output = 0, numcrit=0; double *yout, *yout_ptr, *tout_ptr, *tcrit; double *wa; @@ -258,7 +259,7 @@ t = tout[0]; /* Setup array to hold the output evaluations*/ - ap_yout= (PyArrayObject *)PyArray_FromDims(2,dims,PyArray_DOUBLE); + ap_yout= (PyArrayObject *)PyArray_SimpleNew(2,dims,PyArray_DOUBLE); if (ap_yout== NULL) goto fail; yout = (double *) ap_yout->data; /* Copy initial vector into first row of output */ @@ -296,15 +297,15 @@ /* If full output make some useful output arrays */ if (full_output) { out_sz = ntimes-1; - ap_hu = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_DOUBLE); - ap_tcur = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_DOUBLE); - ap_tolsf = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_DOUBLE); - ap_tsw = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_DOUBLE); - ap_nst = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_INT); - ap_nfe = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_INT); - ap_nje = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_INT); - ap_nqu = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_INT); - ap_mused = (PyArrayObject *)PyArray_FromDims(1,&out_sz,PyArray_INT); + ap_hu = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_DOUBLE); + ap_tcur = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_DOUBLE); + ap_tolsf = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_DOUBLE); + ap_tsw = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_DOUBLE); + ap_nst = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_INT); + ap_nfe = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_INT); + ap_nje = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_INT); + ap_nqu = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_INT); + ap_mused = (PyArrayObject *)PyArray_SimpleNew(1,&out_sz,PyArray_INT); if (ap_hu == NULL || ap_tcur == NULL || ap_tolsf == NULL || ap_tsw == NULL || ap_nst == NULL || ap_nfe == NULL || ap_nje == NULL || ap_nqu == NULL || ap_mused == NULL) goto fail; } Modified: trunk/scipy/integrate/__quadpack.h =================================================================== --- trunk/scipy/integrate/__quadpack.h 2008-11-03 07:02:14 UTC (rev 4952) +++ trunk/scipy/integrate/__quadpack.h 2008-11-03 07:22:35 UTC (rev 4953) @@ -105,7 +105,8 @@ PyObject *extra_args = NULL; PyObject *fcn; - int limit=50, full_output = 0; + npy_intp limit=50; + int full_output = 0; double a, b, epsabs=1.49e-8, epsrel=1.49e-8; int neval=0, ier=6, last=0, *iord; double result=0.0, abserr=0.0; @@ -122,11 +123,11 @@ QUAD_INIT_FUNC(fcn,extra_args) /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); if (ap_iord == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL) goto fail; iord = (int *)ap_iord->data; alist = (double *)ap_alist->data; @@ -183,7 +184,8 @@ PyObject *extra_args = NULL; PyObject *fcn; - int limit=50, full_output = 0; + npy_intp limit=50; + int full_output = 0; double bound, epsabs=1.49e-8, epsrel=1.49e-8; int inf, neval=0, ier=6, last=0, *iord; double result=0.0, abserr=0.0; @@ -200,11 +202,11 @@ QUAD_INIT_FUNC(fcn,extra_args); /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); if (ap_iord == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL) goto fail; iord = (int *)ap_iord->data; alist = (double *)ap_alist->data; @@ -265,7 +267,8 @@ PyObject *extra_args = NULL; PyObject *fcn, *o_points; - int limit=50, full_output = 0, npts2; + npy_intp limit=50, npts2; + int full_output = 0; double a, b, epsabs=1.49e-8, epsrel=1.49e-8; int neval=0, ier=6, last=0, *iord; int *level, *ndin; @@ -289,14 +292,14 @@ points = (double *)ap_points->data; /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_pts = (PyArrayObject *)PyArray_FromDims(1,&npts2,PyArray_DOUBLE); - ap_level = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_ndin = (PyArrayObject *)PyArray_FromDims(1,&npts2,PyArray_DOUBLE); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_pts = (PyArrayObject *)PyArray_SimpleNew(1,&npts2,PyArray_DOUBLE); + ap_level = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_ndin = (PyArrayObject *)PyArray_SimpleNew(1,&npts2,PyArray_DOUBLE); if (ap_iord == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL || ap_pts == NULL || ap_level == NULL || ap_ndin == NULL) goto fail; iord = (int *)ap_iord->data; alist = (double *)ap_alist->data; @@ -366,10 +369,11 @@ PyObject *extra_args = NULL, *o_chebmo = NULL; PyObject *fcn; - int limit=50, full_output = 0, maxp1=50, icall=1; + npy_intp limit=50, sz[2]; + int full_output = 0, maxp1=50, icall=1; double a, b, epsabs=1.49e-8, epsrel=1.49e-8; int neval=0, ier=6, integr=1, last=0, momcom=0, *iord; - int sz[2], *nnlog; + int *nnlog; double result=0.0, abserr=0.0, omega=0.0; double *chebmo; double *alist, *blist, *rlist, *elist; @@ -393,18 +397,18 @@ else { sz[0] = 25; sz[1] = maxp1; - ap_chebmo = (PyArrayObject *)PyArray_FromDims(2,sz,PyArray_DOUBLE); + ap_chebmo = (PyArrayObject *)PyArray_SimpleNew(2,sz,PyArray_DOUBLE); if (ap_chebmo == NULL) goto fail; } chebmo = (double *) ap_chebmo->data; /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_nnlog = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_nnlog = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); if (ap_iord == NULL || ap_nnlog == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL) goto fail; iord = (int *)ap_iord->data; nnlog = (int *)ap_nnlog->data; @@ -469,10 +473,11 @@ PyObject *extra_args = NULL; PyObject *fcn; - int limlst = 50, limit=50, full_output = 0, maxp1=50; + npy_intp limlst = 50, limit=50, sz[2]; + int full_output = 0, maxp1=50; double a, epsabs=1.49e-8; int neval=0, ier=6, integr=1, *iord; - int sz[2], lst, *nnlog, *ierlst; + int lst, *nnlog, *ierlst; double *chebmo, *rslst, *erlst; double result=0.0, abserr=0.0, omega=0.0; double *alist, *blist, *rlist, *elist; @@ -489,20 +494,20 @@ sz[0] = 25; sz[1] = maxp1; - ap_chebmo = (PyArrayObject *)PyArray_FromDims(2,sz,PyArray_DOUBLE); + ap_chebmo = (PyArrayObject *)PyArray_SimpleNew(2,sz,PyArray_DOUBLE); if (ap_chebmo == NULL) goto fail; chebmo = (double *) ap_chebmo->data; /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_nnlog = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rslst = (PyArrayObject *)PyArray_FromDims(1,&limlst,PyArray_DOUBLE); - ap_erlst = (PyArrayObject *)PyArray_FromDims(1,&limlst,PyArray_DOUBLE); - ap_ierlst = (PyArrayObject *)PyArray_FromDims(1,&limlst,PyArray_INT); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_nnlog = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rslst = (PyArrayObject *)PyArray_SimpleNew(1,&limlst,PyArray_DOUBLE); + ap_erlst = (PyArrayObject *)PyArray_SimpleNew(1,&limlst,PyArray_DOUBLE); + ap_ierlst = (PyArrayObject *)PyArray_SimpleNew(1,&limlst,PyArray_INT); if (ap_iord == NULL || ap_nnlog == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL || ap_rslst == NULL || ap_erlst == NULL || ap_ierlst == NULL) goto fail; iord = (int *)ap_iord->data; nnlog = (int *)ap_nnlog->data; @@ -574,7 +579,8 @@ PyObject *extra_args = NULL; PyObject *fcn; - int limit=50, full_output = 0; + npy_intp limit=50; + int full_output = 0; double a, b, c, epsabs=1.49e-8, epsrel=1.49e-8; int neval=0, ier=6, last=0, *iord; double result=0.0, abserr=0.0; @@ -591,11 +597,11 @@ QUAD_INIT_FUNC(fcn,extra_args) /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); if (ap_iord == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL) goto fail; iord = (int *)ap_iord->data; alist = (double *)ap_alist->data; @@ -653,7 +659,8 @@ PyObject *extra_args = NULL; PyObject *fcn; - int limit=50, full_output = 0, integr; + int full_output = 0, integr; + npy_intp limit=50; double a, b, epsabs=1.49e-8, epsrel=1.49e-8; double alfa, beta; int neval=0, ier=6, last=0, *iord; @@ -671,11 +678,11 @@ QUAD_INIT_FUNC(fcn,extra_args) /* Setup iwork and work arrays */ - ap_iord = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_INT); - ap_alist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_blist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_rlist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); - ap_elist = (PyArrayObject *)PyArray_FromDims(1,&limit,PyArray_DOUBLE); + ap_iord = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_INT); + ap_alist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_blist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_rlist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); + ap_elist = (PyArrayObject *)PyArray_SimpleNew(1,&limit,PyArray_DOUBLE); if (ap_iord == NULL || ap_alist == NULL || ap_blist == NULL || ap_rlist == NULL || ap_elist == NULL) goto fail; iord = (int *)ap_iord->data; alist = (double *)ap_alist->data; Modified: trunk/scipy/integrate/multipack.h =================================================================== --- trunk/scipy/integrate/multipack.h 2008-11-03 07:02:14 UTC (rev 4952) +++ trunk/scipy/integrate/multipack.h 2008-11-03 07:22:35 UTC (rev 4953) @@ -83,7 +83,7 @@ #define SET_DIAG(ap_diag,o_diag,mode) { /* Set the diag vector from input */ \ if (o_diag == NULL || o_diag == Py_None) { \ - ap_diag = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); \ + ap_diag = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); \ if (ap_diag == NULL) goto fail; \ diag = (double *)ap_diag -> data; \ mode = 1; \ @@ -130,7 +130,7 @@ return new_array; } -static PyObject *call_python_function(PyObject *func, int n, double *x, PyObject *args, int dim, PyObject *error_obj) +static PyObject *call_python_function(PyObject *func, npy_intp n, double *x, PyObject *args, int dim, PyObject *error_obj) { /* This is a generic function to call a python function that takes a 1-D @@ -152,7 +152,7 @@ PyArrayObject *result_array = NULL; /* Build sequence argument from inputs */ - sequence = (PyArrayObject *)PyArray_FromDimsAndData(1, &n, PyArray_DOUBLE, (char *)x); + sequence = (PyArrayObject *)PyArray_SimpleNewFromData(1, &n, PyArray_DOUBLE, (char *)x); if (sequence == NULL) PYERR2(error_obj,"Internal failure to make an array of doubles out of first\n argument to function call."); /* Build argument list */ Modified: trunk/scipy/integrate/setup.py =================================================================== --- trunk/scipy/integrate/setup.py 2008-11-03 07:02:14 UTC (rev 4952) +++ trunk/scipy/integrate/setup.py 2008-11-03 07:22:35 UTC (rev 4953) @@ -29,7 +29,8 @@ config.add_extension('_quadpack', sources=['_quadpackmodule.c'], - libraries=['quadpack', 'linpack_lite', 'mach']) + libraries=['quadpack', 'linpack_lite', 'mach'], + depends=['quadpack.h','__quadpack.h']) # odepack libs = ['odepack','linpack_lite','mach'] @@ -44,6 +45,7 @@ config.add_extension('_odepack', sources=['_odepackmodule.c'], libraries=libs, + depends=['__odepack.h','multipack.h'], **newblas) # vode From scipy-svn at scipy.org Mon Nov 3 02:28:01 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 01:28:01 -0600 (CST) Subject: [Scipy-svn] r4954 - trunk/scipy/odr Message-ID: <20081103072801.3776339C088@scipy.org> Author: chris.burns Date: 2008-11-03 01:27:58 -0600 (Mon, 03 Nov 2008) New Revision: 4954 Modified: trunk/scipy/odr/__odrpack.c trunk/scipy/odr/setup.py Log: Update deprecated numpy array creation functions. Changed PyArray_FromDims to PyArray_SimpleNew, and use npy_intp. Update dependencies in setup.py. Most of the work done by paul.ivanov. Modified: trunk/scipy/odr/__odrpack.c =================================================================== --- trunk/scipy/odr/__odrpack.c 2008-11-03 07:22:35 UTC (rev 4953) +++ trunk/scipy/odr/__odrpack.c 2008-11-03 07:27:58 UTC (rev 4954) @@ -52,17 +52,17 @@ if (*m != 1) { - int dim2[2]; + npy_intp dim2[2]; dim2[0] = *m; dim2[1] = *n; - pyXplusD = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + pyXplusD = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); memcpy(pyXplusD->data, (void *)xplusd, (*m) * (*n) * sizeof(double)); } else { - int dim1[1]; + npy_intp dim1[1]; dim1[0] = *n; - pyXplusD = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + pyXplusD = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); memcpy(pyXplusD->data, (void *)xplusd, (*n) * sizeof(double)); } @@ -337,7 +337,7 @@ PyObject *retobj; - int dim1[1], dim2[2]; + npy_intp dim1[1], dim2[2]; if (info == 50005) { /* fatal error in fcn call; return NULL to propogate the exception */ @@ -407,10 +407,10 @@ wrk7--; dim1[0] = beta->dimensions[0]; - sd_beta = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + sd_beta = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); dim2[0] = beta->dimensions[0]; dim2[1] = beta->dimensions[0]; - cov_beta = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + cov_beta = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); memcpy(sd_beta->data, (void *)((double *)(work->data) + sd), np * sizeof(double)); @@ -453,32 +453,32 @@ { dim1[0] = n; deltaA = - (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); xplusA = - (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); } else { dim2[0] = m; dim2[1] = n; deltaA = - (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); xplusA = - (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); } if (nq == 1) { dim1[0] = n; - epsA = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); - fnA = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + epsA = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); + fnA = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); } else { dim2[0] = nq; dim2[1] = n; - epsA = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); - fnA = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + epsA = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); + fnA = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); } memcpy(deltaA->data, (void *)((double *)(work->data) + delta), @@ -545,7 +545,7 @@ }; int isodr = 1; PyObject *result; - int dim1[1], dim2[2], dim3[3]; + npy_intp dim1[1], dim2[2], dim3[3]; int implicit; /* flag for implicit model */ @@ -697,7 +697,7 @@ dim1[0] = 1; /* initialize y to a dummy array; never referenced */ - y = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + y = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); if ((x = (PyArrayObject *) PyArray_CopyFromObject(px, PyArray_DOUBLE, 1, @@ -733,7 +733,7 @@ { ldwe = ld2we = 1; dim1[0] = n; - we = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + we = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); ((double *)(we->data))[0] = -1.0; } else if (PyNumber_Check(pwe) && !PyArray_Check(pwe)) @@ -751,7 +751,7 @@ dim3[0] = nq; dim3[1] = 1; dim3[2] = 1; - we = (PyArrayObject *) PyArray_FromDims(3, dim3, PyArray_DOUBLE); + we = (PyArrayObject *) PyArray_SimpleNew(3, dim3, PyArray_DOUBLE); if (implicit) { ((double *)(we->data))[0] = val; @@ -830,7 +830,7 @@ ldwd = ld2wd = 1; dim1[0] = m; - wd = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + wd = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); ((double *)(wd->data))[0] = -1.0; } else if (PyNumber_Check(pwd) && !PyArray_Check(pwd)) @@ -848,7 +848,7 @@ dim3[0] = 1; dim3[1] = 1; dim3[2] = m; - wd = (PyArrayObject *) PyArray_FromDims(3, dim3, PyArray_DOUBLE); + wd = (PyArrayObject *) PyArray_SimpleNew(3, dim3, PyArray_DOUBLE); ((double *)(wd->data))[0] = -val; ldwd = ld2wd = 1; } @@ -920,7 +920,7 @@ if (pifixb == NULL) { dim1[0] = np; - ifixb = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_INT); + ifixb = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_INT); *(int *)(ifixb->data) = -1; /* set first element negative */ } else @@ -946,7 +946,7 @@ { dim2[0] = m; dim2[1] = 1; - ifixx = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_INT); + ifixx = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_INT); *(int *)(ifixx->data) = -1; /* set first element negative */ ldifx = 1; } @@ -999,7 +999,7 @@ if (pstpb == NULL) { dim1[0] = np; - stpb = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + stpb = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); *(double *)(stpb->data) = 0.0; } else /* pstpb is a sequence */ @@ -1018,7 +1018,7 @@ { dim2[0] = 1; dim2[1] = m; - stpd = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + stpd = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); *(double *)(stpd->data) = 0.0; ldstpd = 1; } @@ -1050,7 +1050,7 @@ if (psclb == NULL) { dim1[0] = np; - sclb = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + sclb = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); *(double *)(sclb->data) = 0.0; } else /* psclb is a sequence */ @@ -1069,7 +1069,7 @@ { dim2[0] = 1; dim2[1] = n; - scld = (PyArrayObject *) PyArray_FromDims(2, dim2, PyArray_DOUBLE); + scld = (PyArrayObject *) PyArray_SimpleNew(2, dim2, PyArray_DOUBLE); *(double *)(scld->data) = 0.0; ldscld = 1; } @@ -1163,7 +1163,7 @@ { /* initialize our own work array */ dim1[0] = lwork; - work = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_DOUBLE); + work = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); } /* work */ if (piwork != NULL) @@ -1185,7 +1185,7 @@ { /* initialize our own iwork array */ dim1[0] = liwork; - iwork = (PyArrayObject *) PyArray_FromDims(1, dim1, PyArray_INT); + iwork = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_INT); } /* iwork */ /* check if what JOB requests can be done with what the user has Modified: trunk/scipy/odr/setup.py =================================================================== --- trunk/scipy/odr/setup.py 2008-11-03 07:22:35 UTC (rev 4953) +++ trunk/scipy/odr/setup.py 2008-11-03 07:27:58 UTC (rev 4954) @@ -28,6 +28,7 @@ sources=sources, libraries=libraries, include_dirs=include_dirs, + depends=['odrpack.h'], **blas_info ) From scipy-svn at scipy.org Mon Nov 3 02:29:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 01:29:53 -0600 (CST) Subject: [Scipy-svn] r4955 - in trunk/scipy/interpolate: . src Message-ID: <20081103072953.14C5439C088@scipy.org> Author: chris.burns Date: 2008-11-03 01:29:50 -0600 (Mon, 03 Nov 2008) New Revision: 4955 Modified: trunk/scipy/interpolate/setup.py trunk/scipy/interpolate/src/__fitpack.h trunk/scipy/interpolate/src/multipack.h Log: Update deprecated numpy array creation functions. Changed PyArray_FromDims to PyArray_SimpleNew and use npy_intp for params. Update dependencies in setup.py. Again... paul.ivanov did much of the leg-work. Modified: trunk/scipy/interpolate/setup.py =================================================================== --- trunk/scipy/interpolate/setup.py 2008-11-03 07:27:58 UTC (rev 4954) +++ trunk/scipy/interpolate/setup.py 2008-11-03 07:29:50 UTC (rev 4955) @@ -14,6 +14,7 @@ config.add_extension('_fitpack', sources=['src/_fitpackmodule.c'], libraries=['fitpack'], + depends = ['src/__fitpack.h','src/multipack.h'] ) config.add_extension('dfitpack', Modified: trunk/scipy/interpolate/src/__fitpack.h =================================================================== --- trunk/scipy/interpolate/src/__fitpack.h 2008-11-03 07:27:58 UTC (rev 4954) +++ trunk/scipy/interpolate/src/__fitpack.h 2008-11-03 07:29:50 UTC (rev 4955) @@ -71,7 +71,8 @@ static char doc_bispev[] = " [z,ier] = _bispev(tx,ty,c,kx,ky,x,y,nux,nuy)"; static PyObject *fitpack_bispev(PyObject *dummy, PyObject *args) { - int nx,ny,kx,ky,mx,my,lwrk,*iwrk,kwrk,ier,lwa,mxy,nux,nuy; + int nx,ny,kx,ky,mx,my,lwrk,*iwrk,kwrk,ier,lwa,nux,nuy; + npy_intp mxy; double *tx,*ty,*c,*x,*y,*z,*wrk,*wa = NULL; PyArrayObject *ap_x = NULL,*ap_y = NULL,*ap_z = NULL,*ap_tx = NULL,\ *ap_ty = NULL,*ap_c = NULL; @@ -96,7 +97,7 @@ mx = ap_x->dimensions[0]; my = ap_y->dimensions[0]; mxy = mx*my; - ap_z = (PyArrayObject *)PyArray_FromDims(1,&mxy,PyArray_DOUBLE); + ap_z = (PyArrayObject *)PyArray_SimpleNew(1,&mxy,PyArray_DOUBLE); z = (double *) ap_z->data; if (nux || nuy) lwrk = mx*(kx+1-nux)+my*(ky+1-nuy)+(nx-kx-1)*(ny-ky-1); @@ -135,8 +136,9 @@ static char doc_surfit[] = " [tx,ty,c,o] = _surfit(x,y,z,w,xb,xe,yb,ye,kx,ky,iopt,s,eps,tx,ty,nxest,nyest,wrk,lwrk1,lwrk2)"; static PyObject *fitpack_surfit(PyObject *dummy, PyObject *args) { - int iopt,m,kx,ky,nxest,nyest,nx,ny,lwrk1,lwrk2,*iwrk,kwrk,ier,lwa,nxo,nyo,\ - i,lc,lcest,nmax; + int iopt,m,kx,ky,nxest,nyest,lwrk1,lwrk2,*iwrk,kwrk,ier,lwa,nxo,nyo,\ + i,lcest,nmax; + npy_intp nx, ny, lc; double *x,*y,*z,*w,xb,xe,yb,ye,s,*tx,*ty,*c,fp,*wrk1,*wrk2,*wa = NULL,eps; PyArrayObject *ap_x = NULL,*ap_y = NULL,*ap_z,*ap_w = NULL,\ *ap_tx = NULL,*ap_ty = NULL,*ap_c = NULL; @@ -209,19 +211,19 @@ lc = (nx-kx-1)*(ny-ky-1); Py_XDECREF(ap_tx); Py_XDECREF(ap_ty); - ap_tx = (PyArrayObject *)PyArray_FromDims(1,&nx,PyArray_DOUBLE); - ap_ty = (PyArrayObject *)PyArray_FromDims(1,&ny,PyArray_DOUBLE); - ap_c = (PyArrayObject *)PyArray_FromDims(1,&lc,PyArray_DOUBLE); + ap_tx = (PyArrayObject *)PyArray_SimpleNew(1,&nx,PyArray_DOUBLE); + ap_ty = (PyArrayObject *)PyArray_SimpleNew(1,&ny,PyArray_DOUBLE); + ap_c = (PyArrayObject *)PyArray_SimpleNew(1,&lc,PyArray_DOUBLE); if (ap_tx == NULL || ap_ty == NULL || ap_c == NULL) goto fail; if ((iopt==0)||(nx>nxo)||(ny>nyo)) { Py_XDECREF(ap_wrk); - ap_wrk = (PyArrayObject *)PyArray_FromDims(1,&lc,PyArray_DOUBLE); + ap_wrk = (PyArrayObject *)PyArray_SimpleNew(1,&lc,PyArray_DOUBLE); if (ap_wrk == NULL) goto fail; - /*ap_iwrk = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_INT);*/ + /*ap_iwrk = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_INT);*/ } if(ap_wrk->dimensions[0]data,tx,nx*sizeof(double)); @@ -257,7 +259,8 @@ static char doc_parcur[] = " [t,c,o] = _parcur(x,w,u,ub,ue,k,iopt,ipar,s,t,nest,wrk,iwrk,per)"; static PyObject *fitpack_parcur(PyObject *dummy, PyObject *args) { - int k,iopt,ipar,nest,*iwrk,idim,m,mx,n=0,no=0,nc,ier,lc,lwa,lwrk,i,per; + int k,iopt,ipar,nest,*iwrk,idim,m,mx,no=0,nc,ier,lwa,lwrk,i,per; + npy_intp n=0, lc; double *x,*w,*u,*c,*t,*wrk,*wa=NULL,ub,ue,fp,s; PyObject *x_py = NULL,*u_py = NULL,*w_py = NULL,*t_py = NULL; PyObject *wrk_py=NULL,*iwrk_py=NULL; @@ -310,12 +313,12 @@ if (ier==10) goto fail; if (ier>0 && n==0) n=1; lc = (n-k-1)*idim; - ap_t = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_c = (PyArrayObject *)PyArray_FromDims(1,&lc,PyArray_DOUBLE); + ap_t = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_c = (PyArrayObject *)PyArray_SimpleNew(1,&lc,PyArray_DOUBLE); if (ap_t == NULL || ap_c == NULL) goto fail; if ((iopt==0)||(n>no)) { - ap_wrk = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_iwrk = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_INT); + ap_wrk = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_iwrk = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_INT); if (ap_wrk == NULL || ap_iwrk == NULL) goto fail; } memcpy(ap_t->data,t,n*sizeof(double)); @@ -340,7 +343,8 @@ static char doc_curfit[] = " [t,c,o] = _curfit(x,y,w,xb,xe,k,iopt,s,t,nest,wrk,iwrk,per)"; static PyObject *fitpack_curfit(PyObject *dummy, PyObject *args) { - int iopt,m,k,nest,n,lwrk,*iwrk,ier,lwa,lc,no=0,per; + int iopt,m,k,nest,lwrk,*iwrk,ier,lwa,no=0,per; + npy_intp n, lc; double *x,*y,*w,xb,xe,s,*t,*c,fp,*wrk,*wa = NULL; PyArrayObject *ap_x = NULL,*ap_y = NULL,*ap_w = NULL,*ap_t = NULL,*ap_c = NULL; PyArrayObject *ap_wrk = NULL,*ap_iwrk = NULL; @@ -389,16 +393,16 @@ } lc = n-k-1; if (!iopt) { - ap_t = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); + ap_t = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); if (ap_t == NULL) goto fail; } - ap_c = (PyArrayObject *)PyArray_FromDims(1,&lc,PyArray_DOUBLE); + ap_c = (PyArrayObject *)PyArray_SimpleNew(1,&lc,PyArray_DOUBLE); if (ap_c == NULL) goto fail; if ((iopt==0)||(n>no)) { Py_XDECREF(ap_wrk); Py_XDECREF(ap_iwrk); - ap_wrk = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_iwrk = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_INT); + ap_wrk = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_iwrk = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_INT); if (ap_wrk == NULL || ap_iwrk == NULL) goto fail; } memcpy(ap_t->data,t,n*sizeof(double)); @@ -423,7 +427,8 @@ static char doc_spl_[] = " [y,ier] = _spl_(x,nu,t,c,k )"; static PyObject *fitpack_spl_(PyObject *dummy, PyObject *args) { - int n,nu,m,ier,k; + int n,nu,ier,k; + npy_intp m; double *x,*y,*t,*c,*wrk = NULL; PyArrayObject *ap_x = NULL,*ap_y = NULL,*ap_t = NULL,*ap_c = NULL; PyObject *x_py = NULL,*t_py = NULL,*c_py = NULL; @@ -437,7 +442,7 @@ t = (double *) ap_t->data; c = (double *) ap_c->data; n = ap_t->dimensions[0]; - ap_y = (PyArrayObject *)PyArray_FromDims(1,&m,PyArray_DOUBLE); + ap_y = (PyArrayObject *)PyArray_SimpleNew(1,&m,PyArray_DOUBLE); if (ap_y == NULL) goto fail; y = (double *) ap_y->data; if ((wrk = (double *)malloc(n*sizeof(double)))==NULL) { @@ -463,7 +468,8 @@ static char doc_splint[] = " [aint,wrk] = _splint(t,c,k,a,b)"; static PyObject *fitpack_splint(PyObject *dummy, PyObject *args) { - int n,k; + int k; + npy_intp n; double *t,*c,*wrk = NULL,a,b,aint; PyArrayObject *ap_t = NULL,*ap_c = NULL; PyArrayObject *ap_wrk = NULL; @@ -475,7 +481,7 @@ t = (double *) ap_t->data; c = (double *) ap_c->data; n = ap_t->dimensions[0]; - ap_wrk = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); + ap_wrk = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); if (ap_wrk == NULL) goto fail; wrk = (double *) ap_wrk->data; aint = SPLINT(t,&n,c,&k,&a,&b,wrk); @@ -490,7 +496,8 @@ static char doc_sproot[] = " [z,ier] = _sproot(t,c,k,mest)"; static PyObject *fitpack_sproot(PyObject *dummy, PyObject *args) { - int n,k,mest,ier,m; + int n,k,mest,ier; + npy_intp m; double *t,*c,*z=NULL; PyArrayObject *ap_t = NULL,*ap_c = NULL; PyArrayObject *ap_z = NULL; @@ -508,7 +515,7 @@ } SPROOT(t,&n,c,z,&mest,&m,&ier); if (ier==10) m=0; - ap_z = (PyArrayObject *)PyArray_FromDims(1,&m,PyArray_DOUBLE); + ap_z = (PyArrayObject *)PyArray_SimpleNew(1,&m,PyArray_DOUBLE); if (ap_z == NULL) goto fail; memcpy(ap_z->data,z,m*sizeof(double)); if (z) free(z); @@ -524,7 +531,8 @@ static char doc_spalde[] = " [d,ier] = _spalde(t,c,k,x)"; static PyObject *fitpack_spalde(PyObject *dummy, PyObject *args) { - int n,k,k1,ier; + int n,k,ier; + npy_intp k1; double *t,*c,*d=NULL,x; PyArrayObject *ap_t = NULL,*ap_c = NULL,*ap_d = NULL; PyObject *t_py = NULL,*c_py = NULL; @@ -536,7 +544,7 @@ c = (double *) ap_c->data; n = ap_t->dimensions[0]; k1=k+1; - ap_d = (PyArrayObject *)PyArray_FromDims(1,&k1,PyArray_DOUBLE); + ap_d = (PyArrayObject *)PyArray_SimpleNew(1,&k1,PyArray_DOUBLE); if (ap_d == NULL) goto fail; d = (double *) ap_d->data; SPALDE(t,&n,c,&k1,&x,d,&ier); @@ -551,7 +559,8 @@ static char doc_insert[] = " [tt,cc,ier] = _insert(iopt,t,c,k,x,m)"; static PyObject *fitpack_insert(PyObject *dummy, PyObject*args) { - int iopt, n, nn, k, nest, ier, m; + int iopt, n, nn, k, ier, m; + npy_intp nest; double x; double *t, *c, *tt, *cc; PyArrayObject *ap_t = NULL, *ap_c = NULL, *ap_tt = NULL, *ap_cc = NULL; @@ -565,8 +574,8 @@ c = (double *) ap_c->data; n = ap_t->dimensions[0]; nest = n + m; - ap_tt = (PyArrayObject *)PyArray_FromDims(1,&nest,PyArray_DOUBLE); - ap_cc = (PyArrayObject *)PyArray_FromDims(1,&nest,PyArray_DOUBLE); + ap_tt = (PyArrayObject *)PyArray_SimpleNew(1,&nest,PyArray_DOUBLE); + ap_cc = (PyArrayObject *)PyArray_SimpleNew(1,&nest,PyArray_DOUBLE); if (ap_tt == NULL || ap_cc == NULL) goto fail; tt = (double *) ap_tt->data; cc = (double *) ap_cc->data; @@ -660,6 +669,8 @@ The approximation interval is from xk[0] to xk[-1] Any xx outside that interval is set automatically to 0.0 */ + + static char doc_bspleval[] = "y = _bspleval(xx,xk,coef,k,{deriv (0)})\n" "\n" "The spline is defined by the approximation interval xk[0] to xk[-1],\n" Modified: trunk/scipy/interpolate/src/multipack.h =================================================================== --- trunk/scipy/interpolate/src/multipack.h 2008-11-03 07:27:58 UTC (rev 4954) +++ trunk/scipy/interpolate/src/multipack.h 2008-11-03 07:29:50 UTC (rev 4955) @@ -83,7 +83,7 @@ #define SET_DIAG(ap_diag,o_diag,mode) { /* Set the diag vector from input */ \ if (o_diag == NULL || o_diag == Py_None) { \ - ap_diag = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); \ + ap_diag = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); \ if (ap_diag == NULL) goto fail; \ diag = (double *)ap_diag -> data; \ mode = 1; \ @@ -130,7 +130,7 @@ return new_array; } -static PyObject *call_python_function(PyObject *func, int n, double *x, PyObject *args, int dim, PyObject *error_obj) +static PyObject *call_python_function(PyObject *func, npy_intp n, double *x, PyObject *args, int dim, PyObject *error_obj) { /* This is a generic function to call a python function that takes a 1-D @@ -152,7 +152,7 @@ PyArrayObject *result_array = NULL; /* Build sequence argument from inputs */ - sequence = (PyArrayObject *)PyArray_FromDimsAndData(1, &n, PyArray_DOUBLE, (char *)x); + sequence = (PyArrayObject *)PyArray_SimpleNewFromData(1, &n, PyArray_DOUBLE, (char *)x); if (sequence == NULL) PYERR2(error_obj,"Internal failure to make an array of doubles out of first\n argument to function call."); /* Build argument list */ From scipy-svn at scipy.org Mon Nov 3 02:30:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 01:30:47 -0600 (CST) Subject: [Scipy-svn] r4956 - trunk/scipy/io Message-ID: <20081103073047.D40AC39C088@scipy.org> Author: chris.burns Date: 2008-11-03 01:30:45 -0600 (Mon, 03 Nov 2008) New Revision: 4956 Modified: trunk/scipy/io/numpyiomodule.c Log: Changed FromDims to SimpleNew, author paul.ivanov. Modified: trunk/scipy/io/numpyiomodule.c =================================================================== --- trunk/scipy/io/numpyiomodule.c 2008-11-03 07:29:50 UTC (rev 4955) +++ trunk/scipy/io/numpyiomodule.c 2008-11-03 07:30:45 UTC (rev 4956) @@ -101,7 +101,7 @@ } /* Make a 1-D NumPy array of type read_type with n elements */ - if ((arr = (PyArrayObject *)PyArray_FromDims(1,(int*)&n,out_type)) == NULL) + if ((arr = (PyArrayObject *)PyArray_SimpleNew(1,(npy_intp*)&n,out_type)) == NULL) return NULL; if (arr->descr->elsize == 0) { @@ -423,7 +423,7 @@ out_size = (PyArray_SIZE(arr)/els_per_slice)*ceil ( (float) els_per_slice / 8); - if ((out = (PyArrayObject *)PyArray_FromDims(1,&out_size,PyArray_UBYTE))==NULL) { + if ((out = (PyArrayObject *)PyArray_SimpleNew(1,&out_size,PyArray_UBYTE))==NULL) { goto fail; } @@ -469,7 +469,7 @@ out_size = els_per_slice * arrsize / ceil( (float) els_per_slice / 8); - if ((out = (PyArrayObject *)PyArray_FromDims(1,&out_size,out_type))==NULL) + if ((out = (PyArrayObject *)PyArray_SimpleNew(1,&out_size,out_type))==NULL) goto fail; if (out->descr->type_num > PyArray_LONG) { From scipy-svn at scipy.org Mon Nov 3 04:06:59 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 03:06:59 -0600 (CST) Subject: [Scipy-svn] r4957 - in trunk/scipy/spatial: . tests Message-ID: <20081103090659.A978539C088@scipy.org> Author: peridot Date: 2008-11-03 03:06:52 -0600 (Mon, 03 Nov 2008) New Revision: 4957 Added: trunk/scipy/spatial/ckdtree.c trunk/scipy/spatial/ckdtree.pyx trunk/scipy/spatial/info.py trunk/scipy/spatial/kdtree.py trunk/scipy/spatial/tests/test_kdtree.py Removed: trunk/scipy/spatial/info.py Modified: trunk/scipy/spatial/__init__.py trunk/scipy/spatial/setup.py Log: Merged kdtree code. I think scons support is broken. Modified: trunk/scipy/spatial/__init__.py =================================================================== --- trunk/scipy/spatial/__init__.py 2008-11-03 07:30:45 UTC (rev 4956) +++ trunk/scipy/spatial/__init__.py 2008-11-03 09:06:52 UTC (rev 4957) @@ -3,8 +3,11 @@ # from info import __doc__ +from kdtree import * +from ckdtree import * -__all__ = ['distance'] +__all__ = filter(lambda s:not s.startswith('_'),dir()) +__all__ += ['distance'] import distance from numpy.testing import Tester Copied: trunk/scipy/spatial/ckdtree.c (from rev 4956, branches/spatial/scipy/spatial/ckdtree.c) Property changes on: trunk/scipy/spatial/ckdtree.c ___________________________________________________________________ Name: svn:mergeinfo + Copied: trunk/scipy/spatial/ckdtree.pyx (from rev 4956, branches/spatial/scipy/spatial/ckdtree.pyx) Deleted: trunk/scipy/spatial/info.py =================================================================== --- trunk/scipy/spatial/info.py 2008-11-03 07:30:45 UTC (rev 4956) +++ trunk/scipy/spatial/info.py 2008-11-03 09:06:52 UTC (rev 4957) @@ -1,8 +0,0 @@ -""" -Distance Computation -==================== - - The distance module provides functions for computing distances between - pairs of vectors from a set of observation vectors. - -""" Copied: trunk/scipy/spatial/info.py (from rev 4956, branches/spatial/scipy/spatial/info.py) =================================================================== --- branches/spatial/scipy/spatial/info.py 2008-11-03 07:30:45 UTC (rev 4956) +++ trunk/scipy/spatial/info.py 2008-11-03 09:06:52 UTC (rev 4957) @@ -0,0 +1,12 @@ +""" +Spatial data structures and algorithms +====================================== + +Nearest-neighbor queries: + + KDTree -- class for efficient nearest-neighbor queries + distance -- module containing many different distance measures + +""" + +postpone_import = 1 Property changes on: trunk/scipy/spatial/info.py ___________________________________________________________________ Name: svn:mergeinfo + Copied: trunk/scipy/spatial/kdtree.py (from rev 4956, branches/spatial/scipy/spatial/kdtree.py) =================================================================== --- branches/spatial/scipy/spatial/kdtree.py 2008-11-03 07:30:45 UTC (rev 4956) +++ trunk/scipy/spatial/kdtree.py 2008-11-03 09:06:52 UTC (rev 4957) @@ -0,0 +1,675 @@ +# Copyright Anne M. Archibald 2008 +# Released under the scipy license +import numpy as np +from heapq import heappush, heappop +import scipy.sparse + +def minkowski_distance_p(x,y,p=2): + """Compute the pth power of the L**p distance between x and y + + For efficiency, this function computes the L**p distance but does + not extract the pth root. If p is 1 or infinity, this is equal to + the actual L**p distance. + """ + x = np.asarray(x) + y = np.asarray(y) + if p==np.inf: + return np.amax(np.abs(y-x),axis=-1) + elif p==1: + return np.sum(np.abs(y-x),axis=-1) + else: + return np.sum(np.abs(y-x)**p,axis=-1) +def minkowski_distance(x,y,p=2): + """Compute the L**p distance between x and y""" + x = np.asarray(x) + y = np.asarray(y) + if p==np.inf or p==1: + return minkowski_distance_p(x,y,p) + else: + return minkowski_distance_p(x,y,p)**(1./p) + +class Rectangle(object): + """Hyperrectangle class. + + Represents a Cartesian product of intervals. + """ + def __init__(self, maxes, mins): + """Construct a hyperrectangle.""" + self.maxes = np.maximum(maxes,mins).astype(np.float) + self.mins = np.minimum(maxes,mins).astype(np.float) + self.m, = self.maxes.shape + + def __repr__(self): + return "" % zip(self.mins, self.maxes) + + def volume(self): + """Total volume.""" + return np.prod(self.maxes-self.mins) + + def split(self, d, split): + """Produce two hyperrectangles by splitting along axis d. + + In general, if you need to compute maximum and minimum + distances to the children, it can be done more efficiently + by updating the maximum and minimum distances to the parent. + """ # FIXME: do this + mid = np.copy(self.maxes) + mid[d] = split + less = Rectangle(self.mins, mid) + mid = np.copy(self.mins) + mid[d] = split + greater = Rectangle(mid, self.maxes) + return less, greater + + def min_distance_point(self, x, p=2.): + """Compute the minimum distance between x and a point in the hyperrectangle.""" + return minkowski_distance(0, np.maximum(0,np.maximum(self.mins-x,x-self.maxes)),p) + + def max_distance_point(self, x, p=2.): + """Compute the maximum distance between x and a point in the hyperrectangle.""" + return minkowski_distance(0, np.maximum(self.maxes-x,x-self.mins),p) + + def min_distance_rectangle(self, other, p=2.): + """Compute the minimum distance between points in the two hyperrectangles.""" + return minkowski_distance(0, np.maximum(0,np.maximum(self.mins-other.maxes,other.mins-self.maxes)),p) + + def max_distance_rectangle(self, other, p=2.): + """Compute the maximum distance between points in the two hyperrectangles.""" + return minkowski_distance(0, np.maximum(self.maxes-other.mins,other.maxes-self.mins),p) + + +class KDTree(object): + """kd-tree for quick nearest-neighbor lookup + + This class provides an index into a set of k-dimensional points + which can be used to rapidly look up the nearest neighbors of any + point. + + The algorithm used is described in Maneewongvatana and Mount 1999. + The general idea is that the kd-tree is a binary trie, each of whose + nodes represents an axis-aligned hyperrectangle. Each node specifies + an axis and splits the set of points based on whether their coordinate + along that axis is greater than or less than a particular value. + + During construction, the axis and splitting point are chosen by the + "sliding midpoint" rule, which ensures that the cells do not all + become long and thin. + + The tree can be queried for the r closest neighbors of any given point + (optionally returning only those within some maximum distance of the + point). It can also be queried, with a substantial gain in efficiency, + for the r approximate closest neighbors. + + For large dimensions (20 is already large) do not expect this to run + significantly faster than brute force. High-dimensional nearest-neighbor + queries are a substantial open problem in computer science. + + The tree also supports all-neighbors queries, both with arrays of points + and with other kd-trees. These do use a reasonably efficient algorithm, + but the kd-tree is not necessarily the best data structure for this + sort of calculation. + """ + + def __init__(self, data, leafsize=10): + """Construct a kd-tree. + + Parameters: + =========== + + data : array-like, shape (n,k) + The data points to be indexed. This array is not copied, and + so modifying this data will result in bogus results. + leafsize : positive integer + The number of points at which the algorithm switches over to + brute-force. + """ + self.data = np.asarray(data) + self.n, self.m = np.shape(self.data) + self.leafsize = int(leafsize) + if self.leafsize<1: + raise ValueError("leafsize must be at least 1") + self.maxes = np.amax(self.data,axis=0) + self.mins = np.amin(self.data,axis=0) + + self.tree = self.__build(np.arange(self.n), self.maxes, self.mins) + + class node(object): + pass + class leafnode(node): + def __init__(self, idx): + self.idx = idx + self.children = len(idx) + class innernode(node): + def __init__(self, split_dim, split, less, greater): + self.split_dim = split_dim + self.split = split + self.less = less + self.greater = greater + self.children = less.children+greater.children + + def __build(self, idx, maxes, mins): + if len(idx)<=self.leafsize: + return KDTree.leafnode(idx) + else: + data = self.data[idx] + #maxes = np.amax(data,axis=0) + #mins = np.amin(data,axis=0) + d = np.argmax(maxes-mins) + maxval = maxes[d] + minval = mins[d] + if maxval==minval: + # all points are identical; warn user? + return KDTree.leafnode(idx) + data = data[:,d] + + # sliding midpoint rule; see Maneewongvatana and Mount 1999 + # for arguments that this is a good idea. + split = (maxval+minval)/2 + less_idx = np.nonzero(data<=split)[0] + greater_idx = np.nonzero(data>split)[0] + if len(less_idx)==0: + split = np.amin(data) + less_idx = np.nonzero(data<=split)[0] + greater_idx = np.nonzero(data>split)[0] + if len(greater_idx)==0: + split = np.amax(data) + less_idx = np.nonzero(data=split)[0] + if len(less_idx)==0: + # _still_ zero? all must have the same value + assert np.all(data==data[0]), "Troublesome data array: %s" % data + split = data[0] + less_idx = np.arange(len(data)-1) + greater_idx = np.array([len(data)-1]) + + lessmaxes = np.copy(maxes) + lessmaxes[d] = split + greatermins = np.copy(mins) + greatermins[d] = split + return KDTree.innernode(d, split, + self.__build(idx[less_idx],lessmaxes,mins), + self.__build(idx[greater_idx],maxes,greatermins)) + + def __query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf): + + side_distances = np.maximum(0,np.maximum(x-self.maxes,self.mins-x)) + if p!=np.inf: + side_distances**=p + min_distance = np.sum(side_distances) + else: + min_distance = np.amax(side_distances) + + # priority queue for chasing nodes + # entries are: + # minimum distance between the cell and the target + # distances between the nearest side of the cell and the target + # the head node of the cell + q = [(min_distance, + tuple(side_distances), + self.tree)] + # priority queue for the nearest neighbors + # furthest known neighbor first + # entries are (-distance**p, i) + neighbors = [] + + if eps==0: + epsfac=1 + elif p==np.inf: + epsfac = 1/(1+eps) + else: + epsfac = 1/(1+eps)**p + + if p!=np.inf and distance_upper_bound!=np.inf: + distance_upper_bound = distance_upper_bound**p + + while q: + min_distance, side_distances, node = heappop(q) + if isinstance(node, KDTree.leafnode): + # brute-force + data = self.data[node.idx] + ds = minkowski_distance_p(data,x[np.newaxis,:],p) + for i in range(len(ds)): + if ds[i]distance_upper_bound*epsfac: + # since this is the nearest cell, we're done, bail out + break + # compute minimum distances to the children and push them on + if x[node.split_dim]1: + dd = np.empty(retshape+(k,),dtype=np.float) + dd.fill(np.inf) + ii = np.empty(retshape+(k,),dtype=np.int) + ii.fill(self.n) + elif k==1: + dd = np.empty(retshape,dtype=np.float) + dd.fill(np.inf) + ii = np.empty(retshape,dtype=np.int) + ii.fill(self.n) + elif k is None: + dd = np.empty(retshape,dtype=np.object) + ii = np.empty(retshape,dtype=np.object) + else: + raise ValueError("Requested %s nearest neighbors; acceptable numbers are integers greater than or equal to one, or None") + for c in np.ndindex(retshape): + hits = self.__query(x[c], k=k, p=p, distance_upper_bound=distance_upper_bound) + if k>1: + for j in range(len(hits)): + dd[c+(j,)], ii[c+(j,)] = hits[j] + elif k==1: + if len(hits)>0: + dd[c], ii[c] = hits[0] + else: + dd[c] = np.inf + ii[c] = self.n + elif k is None: + dd[c] = [d for (d,i) in hits] + ii[c] = [i for (d,i) in hits] + return dd, ii + else: + hits = self.__query(x, k=k, p=p, distance_upper_bound=distance_upper_bound) + if k==1: + if len(hits)>0: + return hits[0] + else: + return np.inf, self.n + elif k>1: + dd = np.empty(k,dtype=np.float) + dd.fill(np.inf) + ii = np.empty(k,dtype=np.int) + ii.fill(self.n) + for j in range(len(hits)): + dd[j], ii[j] = hits[j] + return dd, ii + elif k is None: + return [d for (d,i) in hits], [i for (d,i) in hits] + else: + raise ValueError("Requested %s nearest neighbors; acceptable numbers are integers greater than or equal to one, or None") + + + def __query_ball_point(self, x, r, p=2., eps=0): + R = Rectangle(self.maxes, self.mins) + + def traverse_checking(node, rect): + if rect.min_distance_point(x,p)>=r/(1.+eps): + return [] + elif rect.max_distance_point(x,p)r/(1.+eps): + return + elif rect1.max_distance_rectangle(rect2, p)max_r + result[idx[c_greater]] += node1.children*node2.children + idx = idx[(min_r<=r[idx]) & (r[idx]<=max_r)] + if len(idx)==0: + return + + if isinstance(node1,KDTree.leafnode): + if isinstance(node2,KDTree.leafnode): + ds = minkowski_distance(self.data[node1.idx][:,np.newaxis,:], + other.data[node2.idx][np.newaxis,:,:], + p).ravel() + ds.sort() + result[idx] += np.searchsorted(ds,r[idx],side='right') + else: + less, greater = rect2.split(node2.split_dim, node2.split) + traverse(node1, rect1, node2.less, less, idx) + traverse(node1, rect1, node2.greater, greater, idx) + else: + if isinstance(node2,KDTree.leafnode): + less, greater = rect1.split(node1.split_dim, node1.split) + traverse(node1.less, less, node2, rect2, idx) + traverse(node1.greater, greater, node2, rect2, idx) + else: + less1, greater1 = rect1.split(node1.split_dim, node1.split) + less2, greater2 = rect2.split(node2.split_dim, node2.split) + traverse(node1.less,less1,node2.less,less2,idx) + traverse(node1.less,less1,node2.greater,greater2,idx) + traverse(node1.greater,greater1,node2.less,less2,idx) + traverse(node1.greater,greater1,node2.greater,greater2,idx) + R1 = Rectangle(self.maxes, self.mins) + R2 = Rectangle(other.maxes, other.mins) + if np.shape(r) == (): + r = np.array([r]) + result = np.zeros(1,dtype=int) + traverse(self.tree, R1, other.tree, R2, np.arange(1)) + return result[0] + elif len(np.shape(r))==1: + r = np.asarray(r) + n, = r.shape + result = np.zeros(n,dtype=int) + traverse(self.tree, R1, other.tree, R2, np.arange(n)) + return result + else: + raise ValueError("r must be either a single value or a one-dimensional array of values") + + def sparse_distance_matrix(self, other, max_distance, p=2.): + """Compute a sparse distance matrix + + Computes a distance matrix between two KDTrees, leaving as zero + any distance greater than max_distance. + + Parameters + ========== + + other : KDTree + + max_distance : positive float + + Returns + ======= + + result : dok_matrix + Sparse matrix representing the results in "dictionary of keys" format. + """ + result = scipy.sparse.dok_matrix((self.n,other.n)) + + def traverse(node1, rect1, node2, rect2): + if rect1.min_distance_rectangle(rect2, p)>max_distance: + return + elif isinstance(node1, KDTree.leafnode): + if isinstance(node2, KDTree.leafnode): + for i in node1.idx: + for j in node2.idx: + d = minkowski_distance(self.data[i],other.data[j],p) + if d<=max_distance: + result[i,j] = d + else: + less, greater = rect2.split(node2.split_dim, node2.split) + traverse(node1,rect1,node2.less,less) + traverse(node1,rect1,node2.greater,greater) + elif isinstance(node2, KDTree.leafnode): + less, greater = rect1.split(node1.split_dim, node1.split) + traverse(node1.less,less,node2,rect2) + traverse(node1.greater,greater,node2,rect2) + else: + less1, greater1 = rect1.split(node1.split_dim, node1.split) + less2, greater2 = rect2.split(node2.split_dim, node2.split) + traverse(node1.less,less1,node2.less,less2) + traverse(node1.less,less1,node2.greater,greater2) + traverse(node1.greater,greater1,node2.less,less2) + traverse(node1.greater,greater1,node2.greater,greater2) + traverse(self.tree, Rectangle(self.maxes, self.mins), + other.tree, Rectangle(other.maxes, other.mins)) + + return result + + +def distance_matrix(x,y,p=2,threshold=1000000): + """Compute the distance matrix. + + Computes the matrix of all pairwise distances. + + Parameters + ========== + + x : array-like, m by k + y : array-like, n by k + p : float 1<=p<=infinity + Which Minkowski p-norm to use. + threshold : positive integer + If m*n*k>threshold use a python loop instead of creating + a very large temporary. + + Returns + ======= + + result : array-like, m by n + + + """ + + x = np.asarray(x) + m, k = x.shape + y = np.asarray(y) + n, kk = y.shape + + if k != kk: + raise ValueError("x contains %d-dimensional vectors but y contains %d-dimensional vectors" % (k, kk)) + + if m*n*k <= threshold: + return minkowski_distance(x[:,np.newaxis,:],y[np.newaxis,:,:],p) + else: + result = np.empty((m,n),dtype=np.float) #FIXME: figure out the best dtype + if md**2-eps) + + def test_m_nearest(self): + x = self.x + m = self.m + dd, ii = self.kdtree.query(x, m) + d = np.amax(dd) + i = ii[np.argmax(dd)] + assert_almost_equal(d**2,np.sum((x-self.data[i])**2)) + eps = 1e-8 + assert_equal(np.sum(np.sum((self.data-x[np.newaxis,:])**2,axis=1)=self.d/(1.+self.eps)) + +class test_random_ball(ball_consistency): + + def setUp(self): + n = 100 + m = 4 + self.data = np.random.randn(n,m) + self.T = KDTree(self.data,leafsize=2) + self.x = np.random.randn(m) + self.p = 2. + self.eps = 0 + self.d = 0.2 + +class test_random_ball_approx(test_random_ball): + + def setUp(self): + test_random_ball.setUp(self) + self.eps = 0.1 + +class test_random_ball_far(test_random_ball): + + def setUp(self): + test_random_ball.setUp(self) + self.d = 2. + +class test_random_ball_l1(test_random_ball): + + def setUp(self): + test_random_ball.setUp(self) + self.p = 1 + +class test_random_ball_linf(test_random_ball): + + def setUp(self): + test_random_ball.setUp(self) + self.p = np.inf + +def test_random_ball_vectorized(): + + n = 20 + m = 5 + T = KDTree(np.random.randn(n,m)) + + r = T.query_ball_point(np.random.randn(2,3,m),1) + assert_equal(r.shape,(2,3)) + assert isinstance(r[0,0],list) + +class two_trees_consistency: + + def test_all_in_ball(self): + r = self.T1.query_ball_tree(self.T2, self.d, p=self.p, eps=self.eps) + for i, l in enumerate(r): + for j in l: + assert distance(self.data1[i],self.data2[j],self.p)<=self.d*(1.+self.eps) + def test_found_all(self): + r = self.T1.query_ball_tree(self.T2, self.d, p=self.p, eps=self.eps) + for i, l in enumerate(r): + c = np.ones(self.T2.n,dtype=np.bool) + c[l] = False + assert np.all(distance(self.data2[c],self.data1[i],self.p)>=self.d/(1.+self.eps)) + +class test_two_random_trees(two_trees_consistency): + + def setUp(self): + n = 50 + m = 4 + self.data1 = np.random.randn(n,m) + self.T1 = KDTree(self.data1,leafsize=2) + self.data2 = np.random.randn(n,m) + self.T2 = KDTree(self.data2,leafsize=2) + self.p = 2. + self.eps = 0 + self.d = 0.2 + +class test_two_random_trees_far(test_two_random_trees): + + def setUp(self): + test_two_random_trees.setUp(self) + self.d = 2 + +class test_two_random_trees_linf(test_two_random_trees): + + def setUp(self): + test_two_random_trees.setUp(self) + self.p = np.inf + + +class test_rectangle: + + def setUp(self): + self.rect = Rectangle([0,0],[1,1]) + + def test_min_inside(self): + assert_almost_equal(self.rect.min_distance_point([0.5,0.5]),0) + def test_min_one_side(self): + assert_almost_equal(self.rect.min_distance_point([0.5,1.5]),0.5) + def test_min_two_sides(self): + assert_almost_equal(self.rect.min_distance_point([2,2]),np.sqrt(2)) + def test_max_inside(self): + assert_almost_equal(self.rect.max_distance_point([0.5,0.5]),1/np.sqrt(2)) + def test_max_one_side(self): + assert_almost_equal(self.rect.max_distance_point([0.5,1.5]),np.hypot(0.5,1.5)) + def test_max_two_sides(self): + assert_almost_equal(self.rect.max_distance_point([2,2]),2*np.sqrt(2)) + + def test_split(self): + less, greater = self.rect.split(0,0.1) + assert_array_equal(less.maxes,[0.1,1]) + assert_array_equal(less.mins,[0,0]) + assert_array_equal(greater.maxes,[1,1]) + assert_array_equal(greater.mins,[0.1,0]) + + +def test_distance_l2(): + assert_almost_equal(distance([0,0],[1,1],2),np.sqrt(2)) +def test_distance_l1(): + assert_almost_equal(distance([0,0],[1,1],1),2) +def test_distance_linf(): + assert_almost_equal(distance([0,0],[1,1],np.inf),1) +def test_distance_vectorization(): + x = np.random.randn(10,1,3) + y = np.random.randn(1,7,3) + assert_equal(distance(x,y).shape,(10,7)) + +class test_count_neighbors: + + def setUp(self): + n = 50 + m = 2 + self.T1 = KDTree(np.random.randn(n,m),leafsize=2) + self.T2 = KDTree(np.random.randn(n,m),leafsize=2) + + def test_one_radius(self): + r = 0.2 + assert_equal(self.T1.count_neighbors(self.T2, r), + np.sum([len(l) for l in self.T1.query_ball_tree(self.T2,r)])) + + def test_large_radius(self): + r = 1000 + assert_equal(self.T1.count_neighbors(self.T2, r), + np.sum([len(l) for l in self.T1.query_ball_tree(self.T2,r)])) + + def test_multiple_radius(self): + rs = np.exp(np.linspace(np.log(0.01),np.log(10),3)) + results = self.T1.count_neighbors(self.T2, rs) + assert np.all(np.diff(results)>=0) + for r,result in zip(rs, results): + assert_equal(self.T1.count_neighbors(self.T2, r), result) + +class test_sparse_distance_matrix: + def setUp(self): + n = 50 + m = 4 + self.T1 = KDTree(np.random.randn(n,m),leafsize=2) + self.T2 = KDTree(np.random.randn(n,m),leafsize=2) + self.r = 0.3 + + def test_consistency_with_neighbors(self): + M = self.T1.sparse_distance_matrix(self.T2, self.r) + r = self.T1.query_ball_tree(self.T2, self.r) + for i,l in enumerate(r): + for j in l: + assert_equal(M[i,j],distance(self.T1.data[i],self.T2.data[j])) + for ((i,j),d) in M.items(): + assert j in r[i] + +def test_distance_matrix(): + m = 10 + n = 11 + k = 4 + xs = np.random.randn(m,k) + ys = np.random.randn(n,k) + ds = distance_matrix(xs,ys) + assert_equal(ds.shape, (m,n)) + for i in range(m): + for j in range(n): + assert_equal(distance(xs[i],ys[j]),ds[i,j]) +def test_distance_matrix_looping(): + m = 10 + n = 11 + k = 4 + xs = np.random.randn(m,k) + ys = np.random.randn(n,k) + ds = distance_matrix(xs,ys) + dsl = distance_matrix(xs,ys,threshold=1) + assert_equal(ds,dsl) + +if __name__=="__main__": + run_module_suite() Property changes on: trunk/scipy/spatial/tests/test_kdtree.py ___________________________________________________________________ Name: svn:mergeinfo + From scipy-svn at scipy.org Mon Nov 3 04:54:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 03:54:45 -0600 (CST) Subject: [Scipy-svn] r4958 - trunk/scipy/spatial Message-ID: <20081103095445.648F539C088@scipy.org> Author: cdavid Date: 2008-11-03 03:54:38 -0600 (Mon, 03 Nov 2008) New Revision: 4958 Modified: trunk/scipy/spatial/setupscons.py Log: Update setup.py file for numscons build. Modified: trunk/scipy/spatial/setupscons.py =================================================================== --- trunk/scipy/spatial/setupscons.py 2008-11-03 09:06:52 UTC (rev 4957) +++ trunk/scipy/spatial/setupscons.py 2008-11-03 09:54:38 UTC (rev 4958) @@ -4,7 +4,7 @@ def configuration(parent_package = '', top_path = None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs - config = Configuration('cluster', parent_package, top_path) + config = Configuration('spatial', parent_package, top_path) config.add_data_dir('tests') From scipy-svn at scipy.org Mon Nov 3 04:55:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 03:55:00 -0600 (CST) Subject: [Scipy-svn] r4959 - trunk/scipy/spatial Message-ID: <20081103095500.0126C39C089@scipy.org> Author: cdavid Date: 2008-11-03 03:54:54 -0600 (Mon, 03 Nov 2008) New Revision: 4959 Modified: trunk/scipy/spatial/SConscript Log: Update scons script for spatial numscons build. Modified: trunk/scipy/spatial/SConscript =================================================================== --- trunk/scipy/spatial/SConscript 2008-11-03 09:54:38 UTC (rev 4958) +++ trunk/scipy/spatial/SConscript 2008-11-03 09:54:54 UTC (rev 4959) @@ -1,16 +1,12 @@ -# Last Change: Thu Oct 18 09:00 PM 2007 J +# Last Change: Mon Nov 03 06:00 PM 2008 J # vim:syntax=python from os.path import join - from numscons import GetNumpyEnvironment env = GetNumpyEnvironment(ARGUMENTS) -env.NumpyPythonExtension('_vq', source = [join('src', 'vq_module.c'), - join('src', 'vq.c')]) +env.NumpyPythonExtension('ckdtree', source = ['ckdtree.c']) -env.NumpyPythonExtension('_hierarchy_wrap', source = [join('src', 'hierarchy_wrap.c'), - join('src', 'hierarchy.c')]) - -env.NumpyPythonExtension('_distance_wrap', source = [join('src', 'distance_wrap.c'), - join('src', 'distance.c')]) +env.NumpyPythonExtension('_distance_wrap', + source = [join('src', 'distance_wrap.c'), + join('src', 'distance.c')]) From scipy-svn at scipy.org Mon Nov 3 04:55:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 03:55:16 -0600 (CST) Subject: [Scipy-svn] r4960 - trunk/scipy/spatial Message-ID: <20081103095516.88FEA39C089@scipy.org> Author: cdavid Date: 2008-11-03 03:55:09 -0600 (Mon, 03 Nov 2008) New Revision: 4960 Modified: trunk/scipy/spatial/setupscons.py Log: Remove dead code in setupscons script. Modified: trunk/scipy/spatial/setupscons.py =================================================================== --- trunk/scipy/spatial/setupscons.py 2008-11-03 09:54:54 UTC (rev 4959) +++ trunk/scipy/spatial/setupscons.py 2008-11-03 09:55:09 UTC (rev 4960) @@ -7,10 +7,6 @@ config = Configuration('spatial', parent_package, top_path) config.add_data_dir('tests') - - #config.add_extension('_vq', - # sources=[join('src', 'vq_module.c'), join('src', 'vq.c')], - # include_dirs = [get_numpy_include_dirs()]) config.add_sconscript('SConstruct') return config From scipy-svn at scipy.org Mon Nov 3 04:57:42 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 03:57:42 -0600 (CST) Subject: [Scipy-svn] r4961 - trunk/scipy/spatial Message-ID: <20081103095742.43C4B39C088@scipy.org> Author: cdavid Date: 2008-11-03 03:57:32 -0600 (Mon, 03 Nov 2008) New Revision: 4961 Modified: trunk/scipy/spatial/setup.py trunk/scipy/spatial/setupscons.py Log: Update author name for scipy.spatial. Modified: trunk/scipy/spatial/setup.py =================================================================== --- trunk/scipy/spatial/setup.py 2008-11-03 09:55:09 UTC (rev 4960) +++ trunk/scipy/spatial/setup.py 2008-11-03 09:57:32 UTC (rev 4961) @@ -19,7 +19,7 @@ if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "SciPy Developers", - author = "Eric Jones", + author = "Anen Archibald", maintainer_email = "scipy-dev at scipy.org", description = "Spatial algorithms and data structures", url = "http://www.scipy.org", Modified: trunk/scipy/spatial/setupscons.py =================================================================== --- trunk/scipy/spatial/setupscons.py 2008-11-03 09:55:09 UTC (rev 4960) +++ trunk/scipy/spatial/setupscons.py 2008-11-03 09:57:32 UTC (rev 4961) @@ -14,9 +14,9 @@ if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "SciPy Developers", - author = "Eric Jones", + author = "Anen Archibald", maintainer_email = "scipy-dev at scipy.org", - description = "Clustering Algorithms (Information Theory)", + description = "Spatial algorithms and data structures", url = "http://www.scipy.org", license = "SciPy License (BSD Style)", **configuration(top_path='').todict() From scipy-svn at scipy.org Mon Nov 3 05:19:54 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 04:19:54 -0600 (CST) Subject: [Scipy-svn] r4962 - trunk/scipy/cluster/src Message-ID: <20081103101954.E820C39C088@scipy.org> Author: cdavid Date: 2008-11-03 04:19:46 -0600 (Mon, 03 Nov 2008) New Revision: 4962 Modified: trunk/scipy/cluster/src/hierarchy.c Log: Remove unnecessary include of distance.h. Modified: trunk/scipy/cluster/src/hierarchy.c =================================================================== --- trunk/scipy/cluster/src/hierarchy.c 2008-11-03 09:57:32 UTC (rev 4961) +++ trunk/scipy/cluster/src/hierarchy.c 2008-11-03 10:19:46 UTC (rev 4962) @@ -66,7 +66,6 @@ #include #include "hierarchy.h" -#include "../../spatial/src/distance.h" static inline double euclidean_distance(const double *u, const double *v, int n) { int i = 0; From scipy-svn at scipy.org Mon Nov 3 05:20:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 04:20:11 -0600 (CST) Subject: [Scipy-svn] r4963 - trunk/scipy/cluster Message-ID: <20081103102011.3A38039C089@scipy.org> Author: cdavid Date: 2008-11-03 04:20:04 -0600 (Mon, 03 Nov 2008) New Revision: 4963 Modified: trunk/scipy/cluster/SConscript Log: Update scons script for scipy.cluster build. Modified: trunk/scipy/cluster/SConscript =================================================================== --- trunk/scipy/cluster/SConscript 2008-11-03 10:19:46 UTC (rev 4962) +++ trunk/scipy/cluster/SConscript 2008-11-03 10:20:04 UTC (rev 4963) @@ -1,4 +1,4 @@ -# Last Change: Thu Oct 18 09:00 PM 2007 J +# Last Change: Mon Nov 03 07:00 PM 2008 J # vim:syntax=python from os.path import join @@ -6,5 +6,10 @@ env = GetNumpyEnvironment(ARGUMENTS) -env.NumpyPythonExtension('_distance_wrap', source = [join('src', 'distance_wrap.c'), - join('src', 'distance.c')]) +env.NumpyPythonExtension('_hierarchy_wrap', + source = [join('src', 'hierarchy_wrap.c'), + join('src', 'hierarchy.c')]) + +env.NumpyPythonExtension('_vq', + source = [join('src', 'vq_module.c'), + join('src', 'vq.c')]) From scipy-svn at scipy.org Mon Nov 3 05:21:04 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 04:21:04 -0600 (CST) Subject: [Scipy-svn] r4964 - trunk/scipy/spatial Message-ID: <20081103102104.43AE339C088@scipy.org> Author: cdavid Date: 2008-11-03 04:20:55 -0600 (Mon, 03 Nov 2008) New Revision: 4964 Modified: trunk/scipy/spatial/setup.py trunk/scipy/spatial/setupscons.py Log: Fix Anne name in scipy.spatial. Modified: trunk/scipy/spatial/setup.py =================================================================== --- trunk/scipy/spatial/setup.py 2008-11-03 10:20:04 UTC (rev 4963) +++ trunk/scipy/spatial/setup.py 2008-11-03 10:20:55 UTC (rev 4964) @@ -19,7 +19,7 @@ if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "SciPy Developers", - author = "Anen Archibald", + author = "Anne Archibald", maintainer_email = "scipy-dev at scipy.org", description = "Spatial algorithms and data structures", url = "http://www.scipy.org", Modified: trunk/scipy/spatial/setupscons.py =================================================================== --- trunk/scipy/spatial/setupscons.py 2008-11-03 10:20:04 UTC (rev 4963) +++ trunk/scipy/spatial/setupscons.py 2008-11-03 10:20:55 UTC (rev 4964) @@ -14,7 +14,7 @@ if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = "SciPy Developers", - author = "Anen Archibald", + author = "Anne Archibald", maintainer_email = "scipy-dev at scipy.org", description = "Spatial algorithms and data structures", url = "http://www.scipy.org", From scipy-svn at scipy.org Mon Nov 3 05:31:14 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 04:31:14 -0600 (CST) Subject: [Scipy-svn] r4965 - trunk/scipy/special Message-ID: <20081103103114.CACB239C088@scipy.org> Author: cdavid Date: 2008-11-03 04:31:08 -0600 (Mon, 03 Nov 2008) New Revision: 4965 Modified: trunk/scipy/special/setup.py Log: Prefix every internal library with sc_ to avoid name clash with existing libraries. Modified: trunk/scipy/special/setup.py =================================================================== --- trunk/scipy/special/setup.py 2008-11-03 10:20:55 UTC (rev 4964) +++ trunk/scipy/special/setup.py 2008-11-03 10:31:08 UTC (rev 4965) @@ -16,25 +16,25 @@ define_macros.append(('_USE_MATH_DEFINES',None)) # C libraries - config.add_library('c_misc',sources=[join('c_misc','*.c')]) - config.add_library('cephes',sources=[join('cephes','*.c')], + config.add_library('sc_c_misc',sources=[join('c_misc','*.c')]) + config.add_library('sc_cephes',sources=[join('cephes','*.c')], include_dirs=[get_python_inc()], macros=define_macros) # Fortran libraries - config.add_library('mach',sources=[join('mach','*.f')], + config.add_library('sc_mach',sources=[join('mach','*.f')], config_fc={'noopt':(__file__,1)}) - config.add_library('toms',sources=[join('amos','*.f')]) - config.add_library('amos',sources=[join('toms','*.f')]) - config.add_library('cdf',sources=[join('cdflib','*.f')]) - config.add_library('specfun',sources=[join('specfun','*.f')]) + config.add_library('sc_toms',sources=[join('amos','*.f')]) + config.add_library('sc_amos',sources=[join('toms','*.f')]) + config.add_library('sc_cdf',sources=[join('cdflib','*.f')]) + config.add_library('sc_specfun',sources=[join('specfun','*.f')]) # Extension _cephes sources = ['_cephesmodule.c', 'amos_wrappers.c', 'specfun_wrappers.c', 'toms_wrappers.c','cdf_wrappers.c','ufunc_extras.c'] config.add_extension('_cephes', sources=sources, - libraries=['amos','toms','c_misc','cephes','mach', - 'cdf', 'specfun'], + libraries=['sc_amos','sc_toms','sc_c_misc','sc_cephes','sc_mach', + 'sc_cdf', 'sc_specfun'], depends=["ufunc_extras.h", "cephes.h", "amos_wrappers.h", "toms_wrappers.h", "cdf_wrappers.h", "specfun_wrappers.h", @@ -48,7 +48,7 @@ sources=['specfun.pyf'], f2py_options=['--no-wrap-functions'], define_macros=[], - libraries=['specfun']) + libraries=['sc_specfun']) config.add_data_dir('tests') From scipy-svn at scipy.org Mon Nov 3 05:31:41 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 04:31:41 -0600 (CST) Subject: [Scipy-svn] r4966 - trunk/scipy/special Message-ID: <20081103103141.0C94039C088@scipy.org> Author: cdavid Date: 2008-11-03 04:31:23 -0600 (Mon, 03 Nov 2008) New Revision: 4966 Modified: trunk/scipy/special/SConscript Log: Prefix all internal libraries to avoid clashes with system-wide ones. Modified: trunk/scipy/special/SConscript =================================================================== --- trunk/scipy/special/SConscript 2008-11-03 10:31:08 UTC (rev 4965) +++ trunk/scipy/special/SConscript 2008-11-03 10:31:23 UTC (rev 4966) @@ -1,4 +1,4 @@ -# Last Change: Thu Jun 12 07:00 PM 2008 J +# Last Change: Mon Nov 03 07:00 PM 2008 J # vim:syntax=python from os.path import join as pjoin, basename as pbasename import sys @@ -30,16 +30,16 @@ env.DistutilsStaticExtLibrary(libname, source = src) # C libraries -build_lib('c_misc', '.c') -build_lib('cephes', '.c') +build_lib('c_misc', '.c', 'sc_c_misc') +build_lib('cephes', '.c', 'sc_cephes') # F libraries # XXX: handle no opt flags for mach -build_lib('mach', '.f') -build_lib('toms', '.f') -build_lib('amos', '.f') -build_lib('cdflib', '.f', 'cdf') -build_lib('specfun', '.f', 'specfunlib') +build_lib('mach', '.f', 'sc_mach') +build_lib('toms', '.f', 'sc_toms') +build_lib('amos', '.f', 'sc_amos') +build_lib('cdflib', '.f', 'sc_cdf') +build_lib('specfun', '.f', 'sc_specfunlib') env.AppendUnique(LIBPATH = ['.']) @@ -49,10 +49,10 @@ env.NumpyPythonExtension('_cephes', source = src, - LIBS = ['amos', 'toms', 'c_misc', 'cephes', 'mach',\ - 'cdf', 'specfunlib']) + LIBS = ['sc_amos', 'sc_toms', 'sc_c_misc', 'sc_cephes', 'sc_mach',\ + 'sc_cdf', 'sc_specfunlib']) # Specfun extension -env.Prepend(LIBS = ['specfunlib']) +env.Prepend(LIBS = ['sc_specfunlib']) env.NumpyPythonExtension('specfun', source = 'specfun.pyf', F2PYOPTIONS = ["--no-wrap-functions"]) From scipy-svn at scipy.org Mon Nov 3 10:52:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 09:52:43 -0600 (CST) Subject: [Scipy-svn] r4967 - trunk/scipy/optimize Message-ID: <20081103155243.D066539C088@scipy.org> Author: paul.ivanov Date: 2008-11-03 09:52:32 -0600 (Mon, 03 Nov 2008) New Revision: 4967 Modified: trunk/scipy/optimize/__minpack.h trunk/scipy/optimize/minpack.h trunk/scipy/optimize/setup.py Log: more FromDims to SimpleNew, etc. see also r4953 r4954 r4955 r4956. this should get rid of more deprecation warning. Modified: trunk/scipy/optimize/__minpack.h =================================================================== --- trunk/scipy/optimize/__minpack.h 2008-11-03 10:31:23 UTC (rev 4966) +++ trunk/scipy/optimize/__minpack.h 2008-11-03 15:52:32 UTC (rev 4967) @@ -216,14 +216,15 @@ PyObject *fcn, *x0, *extra_args = NULL, *o_diag = NULL; int full_output = 0, maxfev = -10, ml = -10, mu = -10; double xtol = 1.49012e-8, epsfcn = 0.0, factor = 1.0e2; - int n, mode = 2, nprint = 0, info, nfev, ldfjac, lr; + int mode = 2, nprint = 0, info, nfev, ldfjac; + npy_intp n,lr; double *x, *fvec, *diag, *fjac, *r, *qtf; PyArrayObject *ap_x = NULL, *ap_fvec = NULL; PyArrayObject *ap_fjac = NULL, *ap_r = NULL, *ap_qtf = NULL; PyArrayObject *ap_diag = NULL; - int dims[2]; + npy_intp dims[2]; int allocated = 0; double *wa = NULL; @@ -256,9 +257,9 @@ SET_DIAG(ap_diag,o_diag,mode); dims[0] = n; dims[1] = n; - ap_r = (PyArrayObject *)PyArray_FromDims(1,&lr,PyArray_DOUBLE); - ap_qtf = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_fjac = (PyArrayObject *)PyArray_FromDims(2,dims,PyArray_DOUBLE); + ap_r = (PyArrayObject *)PyArray_SimpleNew(1,&lr,PyArray_DOUBLE); + ap_qtf = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_fjac = (PyArrayObject *)PyArray_SimpleNew(2,dims,PyArray_DOUBLE); if (ap_r == NULL || ap_qtf == NULL || ap_fjac ==NULL) goto fail; @@ -316,14 +317,15 @@ PyObject *fcn, *Dfun, *x0, *extra_args = NULL, *o_diag = NULL; int full_output = 0, maxfev = -10, col_deriv = 1; double xtol = 1.49012e-8, factor = 1.0e2; - int n, mode = 2, nprint = 0, info, nfev, njev, ldfjac, lr; + int mode = 2, nprint = 0, info, nfev, njev, ldfjac; + npy_intp n, lr; double *x, *fvec, *diag, *fjac, *r, *qtf; PyArrayObject *ap_x = NULL, *ap_fvec = NULL; PyArrayObject *ap_fjac = NULL, *ap_r = NULL, *ap_qtf = NULL; PyArrayObject *ap_diag = NULL; - int dims[2]; + npy_intp dims[2]; int allocated = 0; double *wa = NULL; @@ -354,9 +356,9 @@ SET_DIAG(ap_diag,o_diag,mode); dims[0] = n; dims[1] = n; - ap_r = (PyArrayObject *)PyArray_FromDims(1,&lr,PyArray_DOUBLE); - ap_qtf = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_fjac = (PyArrayObject *)PyArray_FromDims(2,dims,PyArray_DOUBLE); + ap_r = (PyArrayObject *)PyArray_SimpleNew(1,&lr,PyArray_DOUBLE); + ap_qtf = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_fjac = (PyArrayObject *)PyArray_SimpleNew(2,dims,PyArray_DOUBLE); if (ap_r == NULL || ap_qtf == NULL || ap_fjac ==NULL) goto fail; @@ -417,14 +419,15 @@ int full_output = 0, maxfev = -10; double xtol = 1.49012e-8, ftol = 1.49012e-8; double gtol = 0.0, epsfcn = 0.0, factor = 1.0e2; - int m, n, mode = 2, nprint = 0, info, nfev, ldfjac, *ipvt; + int m, mode = 2, nprint = 0, info, nfev, ldfjac, *ipvt; + npy_intp n; double *x, *fvec, *diag, *fjac, *qtf; PyArrayObject *ap_x = NULL, *ap_fvec = NULL; PyArrayObject *ap_fjac = NULL, *ap_ipvt = NULL, *ap_qtf = NULL; PyArrayObject *ap_diag = NULL; - int dims[2]; + npy_intp dims[2]; int allocated = 0; double *wa = NULL; @@ -452,9 +455,9 @@ m = (ap_fvec->nd > 0 ? ap_fvec->dimensions[0] : 1); dims[0] = n; dims[1] = m; - ap_ipvt = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_INT); - ap_qtf = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_fjac = (PyArrayObject *)PyArray_FromDims(2,dims,PyArray_DOUBLE); + ap_ipvt = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_INT); + ap_qtf = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_fjac = (PyArrayObject *)PyArray_SimpleNew(2,dims,PyArray_DOUBLE); if (ap_ipvt == NULL || ap_qtf == NULL || ap_fjac ==NULL) goto fail; @@ -516,14 +519,15 @@ int full_output = 0, maxfev = -10, col_deriv = 1; double xtol = 1.49012e-8, ftol = 1.49012e-8; double gtol = 0.0, factor = 1.0e2; - int m, n, mode = 2, nprint = 0, info, nfev, njev, ldfjac, *ipvt; + int m, mode = 2, nprint = 0, info, nfev, njev, ldfjac, *ipvt; + npy_intp n; double *x, *fvec, *diag, *fjac, *qtf; PyArrayObject *ap_x = NULL, *ap_fvec = NULL; PyArrayObject *ap_fjac = NULL, *ap_ipvt = NULL, *ap_qtf = NULL; PyArrayObject *ap_diag = NULL; - int dims[2]; + npy_intp dims[2]; int allocated = 0; double *wa = NULL; @@ -551,9 +555,9 @@ m = (ap_fvec->nd > 0 ? ap_fvec->dimensions[0] : 1); dims[0] = n; dims[1] = m; - ap_ipvt = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_INT); - ap_qtf = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); - ap_fjac = (PyArrayObject *)PyArray_FromDims(2,dims,PyArray_DOUBLE); + ap_ipvt = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_INT); + ap_qtf = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); + ap_fjac = (PyArrayObject *)PyArray_SimpleNew(2,dims,PyArray_DOUBLE); if (ap_ipvt == NULL || ap_qtf == NULL || ap_fjac ==NULL) goto fail; Modified: trunk/scipy/optimize/minpack.h =================================================================== --- trunk/scipy/optimize/minpack.h 2008-11-03 10:31:23 UTC (rev 4966) +++ trunk/scipy/optimize/minpack.h 2008-11-03 15:52:32 UTC (rev 4967) @@ -83,7 +83,7 @@ #define SET_DIAG(ap_diag,o_diag,mode) { /* Set the diag vector from input */ \ if (o_diag == NULL || o_diag == Py_None) { \ - ap_diag = (PyArrayObject *)PyArray_FromDims(1,&n,PyArray_DOUBLE); \ + ap_diag = (PyArrayObject *)PyArray_SimpleNew(1,&n,PyArray_DOUBLE); \ if (ap_diag == NULL) goto fail; \ diag = (double *)ap_diag -> data; \ mode = 1; \ @@ -105,7 +105,7 @@ static PyObject *multipack_extra_arguments=NULL; /* a tuple */ static int multipack_jac_transpose=1; -static PyObject *call_python_function(PyObject *func, int n, double *x, PyObject *args, int dim, PyObject *error_obj) +static PyObject *call_python_function(PyObject *func, npy_intp n, double *x, PyObject *args, int dim, PyObject *error_obj) { /* This is a generic function to call a python function that takes a 1-D @@ -127,7 +127,7 @@ PyArrayObject *result_array = NULL; /* Build sequence argument from inputs */ - sequence = (PyArrayObject *)PyArray_FromDimsAndData(1, &n, PyArray_DOUBLE, (char *)x); + sequence = (PyArrayObject *)PyArray_SimpleNewFromData(1, &n, PyArray_DOUBLE, (char *)x); if (sequence == NULL) PYERR2(error_obj,"Internal failure to make an array of doubles out of first\n argument to function call."); /* Build argument list */ Modified: trunk/scipy/optimize/setup.py =================================================================== --- trunk/scipy/optimize/setup.py 2008-11-03 10:31:23 UTC (rev 4966) +++ trunk/scipy/optimize/setup.py 2008-11-03 15:52:32 UTC (rev 4967) @@ -10,7 +10,8 @@ config.add_library('minpack',sources=[join('minpack','*f')]) config.add_extension('_minpack', sources=['_minpackmodule.c'], - libraries=['minpack']) + libraries=['minpack'], + depends=["minpack.h","__minpack.h"]) config.add_library('rootfind', sources=[join('Zeros','*.c')], @@ -28,7 +29,8 @@ sources=['moduleTNC.c','tnc.c'] config.add_extension('moduleTNC', - sources=[join('tnc',x) for x in sources]) + sources=[join('tnc',x) for x in sources], + depends=[join('tnc','tnc.h')]) config.add_extension('_cobyla', sources=[join('cobyla',x) for x in ['cobyla.pyf', From scipy-svn at scipy.org Mon Nov 3 14:15:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 13:15:10 -0600 (CST) Subject: [Scipy-svn] r4968 - trunk/scipy/signal Message-ID: <20081103191510.E1ED139C088@scipy.org> Author: cdavid Date: 2008-11-03 13:14:59 -0600 (Mon, 03 Nov 2008) New Revision: 4968 Added: trunk/scipy/signal/newsig.c Log: Start working on a replacement for linear_filter using array iterator; code is not used yet. Added: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-03 15:52:32 UTC (rev 4967) +++ trunk/scipy/signal/newsig.c 2008-11-03 19:14:59 UTC (rev 4968) @@ -0,0 +1,240 @@ +#include + +static int +RawFilter2(const PyArrayObject *b, const PyArrayObject *a, + const PyArrayObject *x, const PyArrayObject *zi, + const PyArrayObject *zf, PyArrayObject *y, int axis, + BasicFilterFunction *filter_func); + +/* + * XXX: Error checking not done yet + */ +static PyObject * +sigtools_linear_filter2(PyObject * dummy, PyObject * args) +{ + PyObject *b = NULL, *a = NULL, *X = NULL, *Vi = NULL; + PyArrayObject *arY = NULL, *arb = NULL, *ara = NULL, *arX = NULL, + *arVi = NULL, *arVf = NULL; + int axis = -1, typenum, theaxis; + char *ara_ptr, input_flag = 0; + intp na, nb; + BasicFilterFunction *basic_filter; + + if (!PyArg_ParseTuple(args, "OOO|iO", &b, &a, &X, &axis, &Vi)) { + return NULL; + } + + typenum = PyArray_ObjectType(b, 0); + typenum = PyArray_ObjectType(a, typenum); + typenum = PyArray_ObjectType(X, typenum); + if (Vi != NULL) { + typenum = PyArray_ObjectType(Vi, typenum); + } + + arY = NULL; + arVf = NULL; + ara = NULL; + arb = NULL; + arX = NULL; + arVi = NULL; + ara = (PyArrayObject *) PyArray_ContiguousFromObject(a, typenum, 1, 1); + arb = (PyArrayObject *) PyArray_ContiguousFromObject(b, typenum, 1, 1); + arX = (PyArrayObject *) PyArray_FromObject(X, typenum, 0, 0); + if (ara == NULL || arb == NULL || arX == NULL) { + goto fail; + } + + if (axis < -arX->nd || axis > arX->nd - 1) { + PyErr_SetString(PyExc_ValueError, + "selected axis is out of range"); + goto fail; + } + if (axis < 0) { + theaxis = arX->nd + axis; + } else { + theaxis = axis; + } + + if (Vi != NULL) { + arVi = (PyArrayObject *) PyArray_FromObject(Vi, typenum, + arX->nd, arX->nd); + if (arVi == NULL) + goto fail; + input_flag = (PyArray_Size((PyObject *) arVi) > 0); + } + + arY = (PyArrayObject *) PyArray_SimpleNew(arX->nd, + arX->dimensions, typenum); + if (arY == NULL) { + goto fail; + } + + if (input_flag) { + arVf = (PyArrayObject *) PyArray_SimpleNew(arVi->nd, + arVi->dimensions, + typenum); + } + + basic_filter = BasicFilterFunctions[(int) (arX->descr->type_num)]; + if (basic_filter == NULL) { + PyErr_SetString(PyExc_ValueError, + "linear_filter not available for this type"); + goto fail; + } + + /* Skip over leading zeros in vector representing denominator (a) */ + // XXX: TODO +#if 0 + ara_ptr = ara->data; + while (memcmp(ara_ptr, Va.zero, Va.elsize) == 0) { + ara_ptr += Va.elsize; + Va.data = ara_ptr; + Va.numels--; + } +#endif + + na = PyArray_SIZE(ara); + nb = PyArray_SIZE(arb); + if (input_flag) { + if (arVi->dimensions[theaxis] != (na > nb ? na : nb) - 1) { + PyErr_SetString(PyExc_ValueError, + "The number of initial conditions must be max([len(a),len(b)]) - 1"); + goto fail; + } + } + + fprintf(stderr, "%s\n", __func__); + RawFilter2(arb, ara, arX, arVi, arVf, arY, theaxis, basic_filter); + + Py_XDECREF(ara); + Py_XDECREF(arb); + Py_XDECREF(arX); + Py_XDECREF(arVi); + + if (!input_flag) { + return PyArray_Return(arY); + } else { + return Py_BuildValue("(NN)", arY, arVf); + } + + +fail: + Py_XDECREF(ara); + Py_XDECREF(arb); + Py_XDECREF(arX); + Py_XDECREF(arVi); + Py_XDECREF(arVf); + Py_XDECREF(arY); + return NULL; +} + +static int +zfill(const PyArrayObject *x, intp nx, char* xzfilled, intp nxzfilled) +{ + char *xzero; + intp i, nxl; + + nxl = PyArray_ITEMSIZE(x); + + xzero = PyArray_Zero(x); + + if (nx > 0) { + memcpy(xzfilled, x->data, nx * nxl); + } + for(i = nx; i < nxzfilled; ++i) { + memcpy(xzfilled + i * nxl, xzero, nxl); + } + + PyDataMem_FREE(xzero); + + return 0; +} + +/* + * a and b assumed to be contiguous + */ +static int +RawFilter2(const PyArrayObject *b, const PyArrayObject *a, + const PyArrayObject *x, const PyArrayObject *zi, + const PyArrayObject *zf, PyArrayObject *y, int axis, + BasicFilterFunction *filter_func) +{ + PyArrayIterObject *itx, *ity; + intp nitx, i, nxl; + intp na, nb, nal, nbl; + intp nfilt; + char *azfilled, *bzfilled, *zfzfilled; + + itx = (PyArrayIterObject *)PyArray_IterAllButAxis( + (PyObject *)x, &axis); + if (itx == NULL) { + fprintf(stderr, "FAIL\n"); + } + nitx = itx->size; + + ity = (PyArrayIterObject *)PyArray_IterAllButAxis( + (PyObject *)y, &axis); + if (ity == NULL) { + fprintf(stderr, "FAIL\n"); + } + + na = PyArray_SIZE(a); + nal = PyArray_ITEMSIZE(a); + nb = PyArray_SIZE(b); + nbl = PyArray_ITEMSIZE(b); + + nfilt = na > nb ? na : nb; + + azfilled = malloc(nal * nfilt); + bzfilled = malloc(nbl * nfilt); + + nxl = PyArray_ITEMSIZE(x); + zfzfilled = malloc(nxl * (nfilt-1) ); + + zfill(a, na, azfilled, nfilt); + zfill(b, nb, bzfilled, nfilt); + + if (zi != NULL) { + fprintf(stderr, "%s: FAILS\n", __func__); + return -1; + } else { + zfill(x, 0, zfzfilled, nfilt-1); + } + + +#if 0 + fprintf(stderr, "%s: a and b are %f and %f\n", __func__, +((double*)azfilled)[0], ((double*)bzfilled)[0]); + //fprintf(stderr, "%s: itx->size is %d\n", __func__, xsize); +#endif + for(i = 0; i < nitx-1; ++i) { +#if 0 + fprintf(stderr, "item %d is %f, next is %d bytes away, "\ + "filter %d items\n", + i, ((double*)itx->dataptr)[0], itx->strides[axis], + PyArray_DIM(x, axis)); +#endif + filter_func(bzfilled, azfilled, + itx->dataptr, ity->dataptr, zfzfilled, + nfilt, PyArray_DIM(x, axis), itx->strides[axis], + ity->strides[axis]); + PyArray_ITER_NEXT(itx); + PyArray_ITER_NEXT(ity); + + if (zi != NULL) { + fprintf(stderr, "%s: FAIL\n", __func__); + return -1; + } else { + /* XXX: inefficient because of the malloc in there */ + zfill(x, 0, zfzfilled, nfilt-1); + } + + } + //RawFilter(Vb, Va, x, y, vi, vf, basic_filter, theaxis); + /* fprintf(stderr, "Now, Here.\n"); */ + + Py_DECREF(ity); + Py_DECREF(itx); + + return 0; +} From scipy-svn at scipy.org Mon Nov 3 14:39:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 13:39:43 -0600 (CST) Subject: [Scipy-svn] r4969 - trunk/scipy/signal Message-ID: <20081103193943.3574D39C088@scipy.org> Author: cdavid Date: 2008-11-03 13:39:36 -0600 (Mon, 03 Nov 2008) New Revision: 4969 Removed: trunk/scipy/signal/newsig.c Log: Revert 4968: the new code should not have been added to svn. Deleted: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-03 19:14:59 UTC (rev 4968) +++ trunk/scipy/signal/newsig.c 2008-11-03 19:39:36 UTC (rev 4969) @@ -1,240 +0,0 @@ -#include - -static int -RawFilter2(const PyArrayObject *b, const PyArrayObject *a, - const PyArrayObject *x, const PyArrayObject *zi, - const PyArrayObject *zf, PyArrayObject *y, int axis, - BasicFilterFunction *filter_func); - -/* - * XXX: Error checking not done yet - */ -static PyObject * -sigtools_linear_filter2(PyObject * dummy, PyObject * args) -{ - PyObject *b = NULL, *a = NULL, *X = NULL, *Vi = NULL; - PyArrayObject *arY = NULL, *arb = NULL, *ara = NULL, *arX = NULL, - *arVi = NULL, *arVf = NULL; - int axis = -1, typenum, theaxis; - char *ara_ptr, input_flag = 0; - intp na, nb; - BasicFilterFunction *basic_filter; - - if (!PyArg_ParseTuple(args, "OOO|iO", &b, &a, &X, &axis, &Vi)) { - return NULL; - } - - typenum = PyArray_ObjectType(b, 0); - typenum = PyArray_ObjectType(a, typenum); - typenum = PyArray_ObjectType(X, typenum); - if (Vi != NULL) { - typenum = PyArray_ObjectType(Vi, typenum); - } - - arY = NULL; - arVf = NULL; - ara = NULL; - arb = NULL; - arX = NULL; - arVi = NULL; - ara = (PyArrayObject *) PyArray_ContiguousFromObject(a, typenum, 1, 1); - arb = (PyArrayObject *) PyArray_ContiguousFromObject(b, typenum, 1, 1); - arX = (PyArrayObject *) PyArray_FromObject(X, typenum, 0, 0); - if (ara == NULL || arb == NULL || arX == NULL) { - goto fail; - } - - if (axis < -arX->nd || axis > arX->nd - 1) { - PyErr_SetString(PyExc_ValueError, - "selected axis is out of range"); - goto fail; - } - if (axis < 0) { - theaxis = arX->nd + axis; - } else { - theaxis = axis; - } - - if (Vi != NULL) { - arVi = (PyArrayObject *) PyArray_FromObject(Vi, typenum, - arX->nd, arX->nd); - if (arVi == NULL) - goto fail; - input_flag = (PyArray_Size((PyObject *) arVi) > 0); - } - - arY = (PyArrayObject *) PyArray_SimpleNew(arX->nd, - arX->dimensions, typenum); - if (arY == NULL) { - goto fail; - } - - if (input_flag) { - arVf = (PyArrayObject *) PyArray_SimpleNew(arVi->nd, - arVi->dimensions, - typenum); - } - - basic_filter = BasicFilterFunctions[(int) (arX->descr->type_num)]; - if (basic_filter == NULL) { - PyErr_SetString(PyExc_ValueError, - "linear_filter not available for this type"); - goto fail; - } - - /* Skip over leading zeros in vector representing denominator (a) */ - // XXX: TODO -#if 0 - ara_ptr = ara->data; - while (memcmp(ara_ptr, Va.zero, Va.elsize) == 0) { - ara_ptr += Va.elsize; - Va.data = ara_ptr; - Va.numels--; - } -#endif - - na = PyArray_SIZE(ara); - nb = PyArray_SIZE(arb); - if (input_flag) { - if (arVi->dimensions[theaxis] != (na > nb ? na : nb) - 1) { - PyErr_SetString(PyExc_ValueError, - "The number of initial conditions must be max([len(a),len(b)]) - 1"); - goto fail; - } - } - - fprintf(stderr, "%s\n", __func__); - RawFilter2(arb, ara, arX, arVi, arVf, arY, theaxis, basic_filter); - - Py_XDECREF(ara); - Py_XDECREF(arb); - Py_XDECREF(arX); - Py_XDECREF(arVi); - - if (!input_flag) { - return PyArray_Return(arY); - } else { - return Py_BuildValue("(NN)", arY, arVf); - } - - -fail: - Py_XDECREF(ara); - Py_XDECREF(arb); - Py_XDECREF(arX); - Py_XDECREF(arVi); - Py_XDECREF(arVf); - Py_XDECREF(arY); - return NULL; -} - -static int -zfill(const PyArrayObject *x, intp nx, char* xzfilled, intp nxzfilled) -{ - char *xzero; - intp i, nxl; - - nxl = PyArray_ITEMSIZE(x); - - xzero = PyArray_Zero(x); - - if (nx > 0) { - memcpy(xzfilled, x->data, nx * nxl); - } - for(i = nx; i < nxzfilled; ++i) { - memcpy(xzfilled + i * nxl, xzero, nxl); - } - - PyDataMem_FREE(xzero); - - return 0; -} - -/* - * a and b assumed to be contiguous - */ -static int -RawFilter2(const PyArrayObject *b, const PyArrayObject *a, - const PyArrayObject *x, const PyArrayObject *zi, - const PyArrayObject *zf, PyArrayObject *y, int axis, - BasicFilterFunction *filter_func) -{ - PyArrayIterObject *itx, *ity; - intp nitx, i, nxl; - intp na, nb, nal, nbl; - intp nfilt; - char *azfilled, *bzfilled, *zfzfilled; - - itx = (PyArrayIterObject *)PyArray_IterAllButAxis( - (PyObject *)x, &axis); - if (itx == NULL) { - fprintf(stderr, "FAIL\n"); - } - nitx = itx->size; - - ity = (PyArrayIterObject *)PyArray_IterAllButAxis( - (PyObject *)y, &axis); - if (ity == NULL) { - fprintf(stderr, "FAIL\n"); - } - - na = PyArray_SIZE(a); - nal = PyArray_ITEMSIZE(a); - nb = PyArray_SIZE(b); - nbl = PyArray_ITEMSIZE(b); - - nfilt = na > nb ? na : nb; - - azfilled = malloc(nal * nfilt); - bzfilled = malloc(nbl * nfilt); - - nxl = PyArray_ITEMSIZE(x); - zfzfilled = malloc(nxl * (nfilt-1) ); - - zfill(a, na, azfilled, nfilt); - zfill(b, nb, bzfilled, nfilt); - - if (zi != NULL) { - fprintf(stderr, "%s: FAILS\n", __func__); - return -1; - } else { - zfill(x, 0, zfzfilled, nfilt-1); - } - - -#if 0 - fprintf(stderr, "%s: a and b are %f and %f\n", __func__, -((double*)azfilled)[0], ((double*)bzfilled)[0]); - //fprintf(stderr, "%s: itx->size is %d\n", __func__, xsize); -#endif - for(i = 0; i < nitx-1; ++i) { -#if 0 - fprintf(stderr, "item %d is %f, next is %d bytes away, "\ - "filter %d items\n", - i, ((double*)itx->dataptr)[0], itx->strides[axis], - PyArray_DIM(x, axis)); -#endif - filter_func(bzfilled, azfilled, - itx->dataptr, ity->dataptr, zfzfilled, - nfilt, PyArray_DIM(x, axis), itx->strides[axis], - ity->strides[axis]); - PyArray_ITER_NEXT(itx); - PyArray_ITER_NEXT(ity); - - if (zi != NULL) { - fprintf(stderr, "%s: FAIL\n", __func__); - return -1; - } else { - /* XXX: inefficient because of the malloc in there */ - zfill(x, 0, zfzfilled, nfilt-1); - } - - } - //RawFilter(Vb, Va, x, y, vi, vf, basic_filter, theaxis); - /* fprintf(stderr, "Now, Here.\n"); */ - - Py_DECREF(ity); - Py_DECREF(itx); - - return 0; -} From scipy-svn at scipy.org Mon Nov 3 14:50:54 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 13:50:54 -0600 (CST) Subject: [Scipy-svn] r4970 - in trunk/scipy/signal: . tests Message-ID: <20081103195054.49D3239C088@scipy.org> Author: stefan Date: 2008-11-03 13:50:36 -0600 (Mon, 03 Nov 2008) New Revision: 4970 Added: trunk/scipy/signal/tests/test_waveforms.py Modified: trunk/scipy/signal/waveforms.py Log: Fix initial value of logarithmic chirp [patch by Christian Christelis]. Closes #547. Added: trunk/scipy/signal/tests/test_waveforms.py =================================================================== --- trunk/scipy/signal/tests/test_waveforms.py 2008-11-03 19:39:36 UTC (rev 4969) +++ trunk/scipy/signal/tests/test_waveforms.py 2008-11-03 19:50:36 UTC (rev 4970) @@ -0,0 +1,14 @@ +#this program corresponds to special.py + +import numpy as np +from numpy.testing import * + +import scipy.signal as signal + +class TestChirp(TestCase): + def test_log_chirp_at_zero(self): + assert_almost_equal(signal.waveforms.chirp(t=0, method='log'), + 1.0) + +if __name__ == "__main__": + run_module_suite() Modified: trunk/scipy/signal/waveforms.py =================================================================== --- trunk/scipy/signal/waveforms.py 2008-11-03 19:39:36 UTC (rev 4969) +++ trunk/scipy/signal/waveforms.py 2008-11-03 19:50:36 UTC (rev 4970) @@ -177,7 +177,7 @@ "For a logarithmic sweep, f1=%f must be larger than f0=%f." % (f1, f0)) beta = log10(f1-f0)/t1 - phase_angle = 2*pi * (f0*t + pow(10,beta*t)/(beta*log(10))) + phase_angle = 2*pi * (f0*t + (pow(10,beta*t)-1)/(beta*log(10))) else: raise ValueError("method must be 'linear', 'quadratic', or " "'logarithmic' but a value of %r was given." % method) From scipy-svn at scipy.org Mon Nov 3 14:51:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 13:51:46 -0600 (CST) Subject: [Scipy-svn] r4971 - trunk/scipy/signal Message-ID: <20081103195146.BE69339C088@scipy.org> Author: stefan Date: 2008-11-03 13:51:35 -0600 (Mon, 03 Nov 2008) New Revision: 4971 Modified: trunk/scipy/signal/waveforms.py Log: Update chirp docs. Modified: trunk/scipy/signal/waveforms.py =================================================================== --- trunk/scipy/signal/waveforms.py 2008-11-03 19:50:36 UTC (rev 4970) +++ trunk/scipy/signal/waveforms.py 2008-11-03 19:51:35 UTC (rev 4971) @@ -134,21 +134,36 @@ if retquad and retenv: return yI, yQ, yenv -def chirp(t,f0=0,t1=1,f1=100,method='linear',phi=0,qshape=None): +def chirp(t, f0=0, t1=1, f1=100, method='linear', phi=0, qshape=None): """Frequency-swept cosine generator. - Inputs: + Parameters + ---------- + t : ndarray + Times at which to evaluate the waveform. + f0 : float or ndarray, optional + Frequency (in Hz) of the waveform at time 0. If `f0` is an + ndarray, it specifies the frequency change as a polynomial in + `t` (see Notes below). + t1 : float, optional + Time at which `f1` is specified. + f1 : float, optional + Frequency (in Hz) of the waveform at time `t1`. + method : {'linear', 'quadratic', 'logarithmic'}, optional + Kind of frequency sweep. + phi : float + Phase offset, in degrees. + qshape : {'convex', 'concave'} + If method is 'quadratic', `qshape` specifies its shape. - t -- array to evaluate waveform at - f0, f1, t1 -- frequency (in Hz) of waveform is f0 at t=0 and f1 at t=t1 - Alternatively, if f0 is an array, then it forms the coefficients of - a polynomial (c.f. numpy.polval()) in t. The values in f1, t1, - method, and qshape are ignored. - method -- linear, quadratic, or logarithmic frequency sweep - phi -- optional phase in degrees - qshape -- shape parameter for quadratic curve: concave or convex + Notes + ----- + If `f0` is an array, it forms the coefficients of a polynomial in + `t` (see `numpy.polval`). The polynomial determines the waveform + frequency change in time. In this case, the values of `f1`, `t1`, + `method`, and `qshape` are ignored. + """ - # Convert to radians. phi *= pi / 180 if size(f0) > 1: From scipy-svn at scipy.org Mon Nov 3 15:39:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 14:39:00 -0600 (CST) Subject: [Scipy-svn] r4972 - in trunk/scipy/stats: . tests Message-ID: <20081103203900.0F03A39C088@scipy.org> Author: stefan Date: 2008-11-03 14:38:44 -0600 (Mon, 03 Nov 2008) New Revision: 4972 Modified: trunk/scipy/stats/distributions.py trunk/scipy/stats/tests/test_distributions.py Log: Fix generalised bivariate exponential distribution [patch by Konrad Blum]. Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-03 19:51:35 UTC (rev 4971) +++ trunk/scipy/stats/distributions.py 2008-11-03 20:38:44 UTC (rev 4972) @@ -1678,17 +1678,24 @@ class genexpon_gen(rv_continuous): def _pdf(self, x, a, b, c): - return (a+b*(1-exp(-c*x)))*exp((a-b)*x+b*(1-exp(-c*x))/c) + return (a+b*(1-exp(-c*x)))*exp((-a-b)*x+b*(1-exp(-c*x))/c) def _cdf(self, x, a, b, c): - return 1.0-exp((a-b)*x + b*(1-exp(-c*x))/c) + return 1.0-exp((-a-b)*x + b*(1-exp(-c*x))/c) genexpon = genexpon_gen(a=0.0,name='genexpon', longname='A generalized exponential', shapes='a,b,c',extradoc=""" -Generalized exponential distribution +Generalized exponential distribution (Ryu 1993) -genexpon.pdf(x,a,b,c) = (a+b*(1-exp(-c*x))) * exp(a*x-b*x+b/c*(1-exp(-c*x))) +f(x,a,b,c) = (a+b*(1-exp(-c*x))) * exp(-a*x-b*x+b/c*(1-exp(-c*x))) for x >= 0, a,b,c > 0. + +a, b, c are the first, second and third shape parameters. + +References +---------- +"The Exponential Distribution: Theory, Methods and Applications", +N. Balakrishnan, Asit P. Basu """ ) Modified: trunk/scipy/stats/tests/test_distributions.py =================================================================== --- trunk/scipy/stats/tests/test_distributions.py 2008-11-03 19:51:35 UTC (rev 4971) +++ trunk/scipy/stats/tests/test_distributions.py 2008-11-03 20:38:44 UTC (rev 4972) @@ -239,6 +239,19 @@ def test_zero(self): assert_equal(stats.expon.pdf(0),1) +class TestGenExpon(TestCase): + def test_pdf_unity_area(self): + from scipy.integrate import simps + # PDF should integrate to one + assert_almost_equal(simps(stats.genexpon.pdf(numpy.arange(0,10,0.01), + 0.5, 0.5, 2.0), + dx=0.01), 1, 1) + + def test_cdf_bounds(self): + # CDF should always be positive + cdf = stats.genexpon.cdf(numpy.arange(0, 10, 0.01), 0.5, 0.5, 2.0) + assert(numpy.all((0 <= cdf) & (cdf <= 1))) + class TestDocstring(TestCase): def test_docstrings(self): """See ticket #761""" From scipy-svn at scipy.org Mon Nov 3 19:17:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 18:17:11 -0600 (CST) Subject: [Scipy-svn] r4973 - in trunk: . doc doc/seps Message-ID: <20081104001711.37A6439C088@scipy.org> Author: jarrod.millman Date: 2008-11-03 18:17:07 -0600 (Mon, 03 Nov 2008) New Revision: 4973 Added: trunk/doc/ trunk/doc/seps/ trunk/doc/seps/technology-preview.rst Log: adding sep for technology preview proposal Added: trunk/doc/seps/technology-preview.rst =================================================================== --- trunk/doc/seps/technology-preview.rst 2008-11-03 20:38:44 UTC (rev 4972) +++ trunk/doc/seps/technology-preview.rst 2008-11-04 00:17:07 UTC (rev 4973) @@ -0,0 +1,80 @@ +============================= +Technology Previews for SciPy +============================= + +:Author: Jarrod Millman +:Contact: millman at berkeley.edu +:Date: 2008-11-03 + + +Executive summary +================= + +Technology preview code is new code incorporated into the trunk of +SciPy, but may also appear in a future SciPy release at our option. +Such code is considered production grade and well-tested, but which +also has no guarantees of a stable API to enable further improvements +based on community feedback. + +In this document, I propose that we create a new top-level subpackage +in ``scipy`` called ``preview``. The ``scipy.preview`` subpackage +will mirror ``scipy``. This subpackage will be part of the official +releases. Thus all code included in the technology preview will be +available to earlier testers and adopters, but clearly marked as under +very active development with no guareentee of a stable API. + +scipy.preview +============= + +The ``scipy.preview`` subpackage serves to main needs: +#. A place to include code that breaks current APIs of code in ``scipy`` +#. A place to develop new packages, modules, classess, and functions + that have got a stable API yet. + +Consider the following scenarios. + +For example, the new ``scipy.spatial`` subpackage is all new code that +is well-tested and fairly high quality. Since we haven't had the time +to work out the ideal API and there are many possible use cases that we +may not have considered, there is a reluctance to freeze the API at this +time. With the new ``scipy.preview`` subpackage, we can get more input +and reach a wider audience by releasing the current code in the next +release. + +Another example would be if we decided that there is a function signature +that we want to change (e.g., percentileofscore http://codereview.appspot.com/7913). +In this case, we could put a deprecation warning in ``scipy.stats.percentileofscore`` +and place the new function in ``scipy.preview.stats.percentileofscore``. + +Requirements for inclusion +========================== + +Getting code into ``scipy.preview`` would require a high barrier for entry. +We need to work out the details, but new packages, modules, classes, and +functions would need to be started in a branch or in another location. The +authors would need to propose their code for inclusion into scipy.preview. +We would have to have some general agreement (or consensus) that we want +to include this functionality. We would have to agree in general to the name +and would require it to follow our style guide and include a reasonable +amount of tests. + +Requirements for promotion +========================== + +For code in ``scipy.preview`` to be promoted requires .... + +Advantages +========== + + * clear indication to user's what the future of the project holds + * clear path for getting code into ``scipy`` + * lowers the barriers for API changes + * clearly distinquishes what is most in flux + * hopefully increase frequency of releases + * gets new code out faster + +running tests +============= + +``scipy.test('full')`` doesn't run technology preview tests. To run them would +require ``scipy.preview.test('full')``. From scipy-svn at scipy.org Mon Nov 3 19:19:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 18:19:38 -0600 (CST) Subject: [Scipy-svn] r4974 - trunk/doc/seps Message-ID: <20081104001938.990AA39C088@scipy.org> Author: jarrod.millman Date: 2008-11-03 18:19:36 -0600 (Mon, 03 Nov 2008) New Revision: 4974 Modified: trunk/doc/seps/technology-preview.rst Log: clean up Modified: trunk/doc/seps/technology-preview.rst =================================================================== --- trunk/doc/seps/technology-preview.rst 2008-11-04 00:17:07 UTC (rev 4973) +++ trunk/doc/seps/technology-preview.rst 2008-11-04 00:19:36 UTC (rev 4974) @@ -27,6 +27,7 @@ ============= The ``scipy.preview`` subpackage serves to main needs: + #. A place to include code that breaks current APIs of code in ``scipy`` #. A place to develop new packages, modules, classess, and functions that have got a stable API yet. From scipy-svn at scipy.org Mon Nov 3 20:14:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 19:14:40 -0600 (CST) Subject: [Scipy-svn] r4975 - trunk/scipy/sparse Message-ID: <20081104011440.3C77339C088@scipy.org> Author: wnbell Date: 2008-11-03 19:14:35 -0600 (Mon, 03 Nov 2008) New Revision: 4975 Modified: trunk/scipy/sparse/base.py trunk/scipy/sparse/data.py Log: make sparse.conjugate() always copy index arrays Modified: trunk/scipy/sparse/base.py =================================================================== --- trunk/scipy/sparse/base.py 2008-11-04 00:19:36 UTC (rev 4974) +++ trunk/scipy/sparse/base.py 2008-11-04 01:14:35 UTC (rev 4975) @@ -432,7 +432,7 @@ return self.tocsr().conj() def conjugate(self): - return self.tocsr().conj() + return self.conj() # Renamed conjtranspose() -> getH() for compatibility with dense matrices def getH(self): Modified: trunk/scipy/sparse/data.py =================================================================== --- trunk/scipy/sparse/data.py 2008-11-04 00:19:36 UTC (rev 4974) +++ trunk/scipy/sparse/data.py 2008-11-04 01:14:35 UTC (rev 4975) @@ -53,11 +53,11 @@ def astype(self, t): return self._with_data(self.data.astype(t)) - def conj(self, copy=False): - return self._with_data(self.data.conj(),copy=copy) + def conj(self): + return self._with_data(self.data.conj()) def copy(self): - return self._with_data(self.data.copy(),copy=True) + return self._with_data(self.data.copy(), copy=True) ########################### @@ -66,3 +66,5 @@ def _mul_scalar(self, other): return self._with_data(self.data * other) + + From scipy-svn at scipy.org Tue Nov 4 00:24:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 23:24:09 -0600 (CST) Subject: [Scipy-svn] r4976 - trunk/scipy/signal/tests Message-ID: <20081104052409.0036639C088@scipy.org> Author: cdavid Date: 2008-11-03 23:23:58 -0600 (Mon, 03 Nov 2008) New Revision: 4976 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Add simpel FIR/IIR test for lfilter. Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 01:14:35 UTC (rev 4975) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:23:58 UTC (rev 4976) @@ -3,9 +3,11 @@ from numpy.testing import * import scipy.signal as signal +from scipy.signal import lfilter from numpy import array, arange +import numpy as np class TestConvolve(TestCase): def test_basic(self): @@ -98,5 +100,21 @@ cheb_even = signal.chebwin(54, at=-40) assert_array_almost_equal(cheb_even, cheb_even_true, decimal=4) +class TestLinearFilter(TestCase): + def test_rank1(self): + x = np.linspace(0, 5, 6) + b = np.array([1, -1]) + a = np.array([0.5, -0.5]) + + # Test simple IIR + y_r = np.array([0, 2, 4, 6, 8, 10.]) + assert_array_almost_equal(lfilter(b, a, x), y_r) + + # Test simple FIR + b = np.array([1, 1]) + a = np.array([1]) + y_r = np.array([0, 1, 3, 5, 7, 9.]) + assert_array_almost_equal(lfilter(b, a, x), y_r) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Tue Nov 4 00:24:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 23:24:27 -0600 (CST) Subject: [Scipy-svn] r4977 - trunk/scipy/signal/tests Message-ID: <20081104052427.0C04739C088@scipy.org> Author: cdavid Date: 2008-11-03 23:24:19 -0600 (Mon, 03 Nov 2008) New Revision: 4977 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Add basic tests for zi argument. Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:23:58 UTC (rev 4976) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:24:19 UTC (rev 4977) @@ -116,5 +116,24 @@ y_r = np.array([0, 1, 3, 5, 7, 9.]) assert_array_almost_equal(lfilter(b, a, x), y_r) + # Test IIR with initial conditions + b = np.array([1, 1]) + a = np.array([1]) + zi = np.array([1]) + y_r = np.array([1, 1, 3, 5, 7, 9.]) + zf_r = np.array([5]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + + b = np.array([1, 1, 1]) + a = np.array([1]) + zi = np.array([1, 1]) + y_r = np.array([1, 2, 3, 6, 9, 12.]) + zf_r = np.array([9, 5]) + y, zf = lfilter(b, a, x, zi=zi) + assert_array_almost_equal(y, y_r) + assert_array_almost_equal(zf, zf_r) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Tue Nov 4 00:48:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 23:48:26 -0600 (CST) Subject: [Scipy-svn] r4978 - trunk/scipy/signal/tests Message-ID: <20081104054826.A2E5639C088@scipy.org> Author: cdavid Date: 2008-11-03 23:48:17 -0600 (Mon, 03 Nov 2008) New Revision: 4978 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Add basic rank 2 test. Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:24:19 UTC (rev 4977) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:48:17 UTC (rev 4978) @@ -135,5 +135,21 @@ assert_array_almost_equal(y, y_r) assert_array_almost_equal(zf, zf_r) + def test_rank2(self): + shape = (4, 3) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + + b = np.array([1, -1]) + a = np.array([0.5, 0.5]) + + y_r2_a0 = np.array([[0, 2, 4], [6, 4, 2], [0, 2, 4], [6 ,4 ,2]]) + y_r2_a1 = np.array([[0, 2, 0], [6, -4, 6], [12, -10, 12], + [18, -16, 18]]) + + y = lfilter(b, a, x, axis = 0) + assert_array_almost_equal(y_r2_a0, y) + + y = lfilter(b, a, x, axis = 1) + assert_array_almost_equal(y_r2_a1, y) if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Tue Nov 4 00:48:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 3 Nov 2008 23:48:46 -0600 (CST) Subject: [Scipy-svn] r4979 - trunk/scipy/signal/tests Message-ID: <20081104054846.B650339C088@scipy.org> Author: cdavid Date: 2008-11-03 23:48:37 -0600 (Mon, 03 Nov 2008) New Revision: 4979 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Add rank2 tests with initial conditions. Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:48:17 UTC (rev 4978) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:48:37 UTC (rev 4979) @@ -151,5 +151,21 @@ y = lfilter(b, a, x, axis = 1) assert_array_almost_equal(y_r2_a1, y) + + # Test initial condition handling + y_r2_a0_1 = np.array([[1, 1, 1], [7, -5, 7], [13, -11, 13], + [19, -17, 19]]) + zf_r = np.array([-5, -17, -29, -41])[:, np.newaxis] + y, zf = lfilter(b, a, x, axis = 1, zi = np.ones((4, 1))) + assert_array_almost_equal(y_r2_a0_1, y) + assert_array_almost_equal(zf, zf_r) + + # XXX: disabled because it segfaults ATM + #y_r2_a0_0 = np.array([[1, 3, 5], [5, 3, 1], [1, 3, 5], [5 ,3 ,1]]) + #zf_r = np.array([-23, -23, -23]) + #y, zf = lfilter(b, a, x, axis = 0, zi = np.ones((1, 3))) + #assert_array_almost_equal(y_r2_a0_0, y) + #assert_array_almost_equal(zf, zf_r) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Tue Nov 4 01:03:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 00:03:32 -0600 (CST) Subject: [Scipy-svn] r4980 - trunk/scipy/signal/tests Message-ID: <20081104060332.F2C2939C088@scipy.org> Author: cdavid Date: 2008-11-04 00:03:23 -0600 (Tue, 04 Nov 2008) New Revision: 4980 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Add a simple test for lfilter on rank 3 arrays (skipped since it segfaults lfilter). Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 05:48:37 UTC (rev 4979) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 06:03:23 UTC (rev 4980) @@ -167,5 +167,20 @@ #assert_array_almost_equal(y_r2_a0_0, y) #assert_array_almost_equal(zf, zf_r) + # Disabled because it crashes lfilter for now + @dec.skipif(True, "Skipping rank > 2 test for lfilter because its segfaults ATM") + def test_rank3(self): + shape = (4, 3, 2) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + + b = np.array([1, -1]) + a = np.array([0.5, 0.5]) + + # Test last axis + y = lfilter(b, a, x) + for i in range(x.shape[0]): + for j in range(x.shape[1]): + assert_array_almost_equal(y[i, j], lfilter(b, a, x[i, j])) + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Tue Nov 4 01:03:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 00:03:55 -0600 (CST) Subject: [Scipy-svn] r4981 - trunk/scipy/signal/tests Message-ID: <20081104060355.D9E7139C088@scipy.org> Author: cdavid Date: 2008-11-04 00:03:46 -0600 (Tue, 04 Nov 2008) New Revision: 4981 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Use explicit failure instead of comment so that I don't forget to re-enable them once lfilter is fixed. Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 06:03:23 UTC (rev 4980) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 06:03:46 UTC (rev 4981) @@ -152,7 +152,14 @@ y = lfilter(b, a, x, axis = 1) assert_array_almost_equal(y_r2_a1, y) - # Test initial condition handling + def test_rank2_init_cond_a1(self): + # Test initial condition handling along axis 1 + shape = (4, 3) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + + b = np.array([1, -1]) + a = np.array([0.5, 0.5]) + y_r2_a0_1 = np.array([[1, 1, 1], [7, -5, 7], [13, -11, 13], [19, -17, 19]]) zf_r = np.array([-5, -17, -29, -41])[:, np.newaxis] @@ -160,13 +167,23 @@ assert_array_almost_equal(y_r2_a0_1, y) assert_array_almost_equal(zf, zf_r) - # XXX: disabled because it segfaults ATM - #y_r2_a0_0 = np.array([[1, 3, 5], [5, 3, 1], [1, 3, 5], [5 ,3 ,1]]) - #zf_r = np.array([-23, -23, -23]) - #y, zf = lfilter(b, a, x, axis = 0, zi = np.ones((1, 3))) - #assert_array_almost_equal(y_r2_a0_0, y) - #assert_array_almost_equal(zf, zf_r) + # Disabled because it crashes lfilter for now + @dec.skipif(True, "Skipping lfilter test with initial condition along "\ + "axis 0: it segfaults ATM") + def test_rank2_init_cond_a0(self): + # Test initial condition handling along axis 0 + shape = (4, 3) + x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) + b = np.array([1, -1]) + a = np.array([0.5, 0.5]) + + y_r2_a0_0 = np.array([[1, 3, 5], [5, 3, 1], [1, 3, 5], [5 ,3 ,1]]) + zf_r = np.array([-23, -23, -23]) + y, zf = lfilter(b, a, x, axis = 0, zi = np.ones((1, 3))) + assert_array_almost_equal(y_r2_a0_0, y) + assert_array_almost_equal(zf, zf_r) + # Disabled because it crashes lfilter for now @dec.skipif(True, "Skipping rank > 2 test for lfilter because its segfaults ATM") def test_rank3(self): From scipy-svn at scipy.org Tue Nov 4 03:31:35 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:31:35 -0600 (CST) Subject: [Scipy-svn] r4982 - trunk/scipy/signal Message-ID: <20081104083135.EBD4539C088@scipy.org> Author: cdavid Date: 2008-11-04 02:31:29 -0600 (Tue, 04 Nov 2008) New Revision: 4982 Added: trunk/scipy/signal/newsig.c Log: Put new lfilter code back into a git branch. Added: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 06:03:46 UTC (rev 4981) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:31:29 UTC (rev 4982) @@ -0,0 +1,240 @@ +#include + +static int +RawFilter2(const PyArrayObject *b, const PyArrayObject *a, + const PyArrayObject *x, const PyArrayObject *zi, + const PyArrayObject *zf, PyArrayObject *y, int axis, + BasicFilterFunction *filter_func); + +/* + * XXX: Error checking not done yet + */ +static PyObject * +sigtools_linear_filter2(PyObject * dummy, PyObject * args) +{ + PyObject *b = NULL, *a = NULL, *X = NULL, *Vi = NULL; + PyArrayObject *arY = NULL, *arb = NULL, *ara = NULL, *arX = NULL, + *arVi = NULL, *arVf = NULL; + int axis = -1, typenum, theaxis; + char *ara_ptr, input_flag = 0; + intp na, nb; + BasicFilterFunction *basic_filter; + + if (!PyArg_ParseTuple(args, "OOO|iO", &b, &a, &X, &axis, &Vi)) { + return NULL; + } + + typenum = PyArray_ObjectType(b, 0); + typenum = PyArray_ObjectType(a, typenum); + typenum = PyArray_ObjectType(X, typenum); + if (Vi != NULL) { + typenum = PyArray_ObjectType(Vi, typenum); + } + + arY = NULL; + arVf = NULL; + ara = NULL; + arb = NULL; + arX = NULL; + arVi = NULL; + ara = (PyArrayObject *) PyArray_ContiguousFromObject(a, typenum, 1, 1); + arb = (PyArrayObject *) PyArray_ContiguousFromObject(b, typenum, 1, 1); + arX = (PyArrayObject *) PyArray_FromObject(X, typenum, 0, 0); + if (ara == NULL || arb == NULL || arX == NULL) { + goto fail; + } + + if (axis < -arX->nd || axis > arX->nd - 1) { + PyErr_SetString(PyExc_ValueError, + "selected axis is out of range"); + goto fail; + } + if (axis < 0) { + theaxis = arX->nd + axis; + } else { + theaxis = axis; + } + + if (Vi != NULL) { + arVi = (PyArrayObject *) PyArray_FromObject(Vi, typenum, + arX->nd, arX->nd); + if (arVi == NULL) + goto fail; + input_flag = (PyArray_Size((PyObject *) arVi) > 0); + } + + arY = (PyArrayObject *) PyArray_SimpleNew(arX->nd, + arX->dimensions, typenum); + if (arY == NULL) { + goto fail; + } + + if (input_flag) { + arVf = (PyArrayObject *) PyArray_SimpleNew(arVi->nd, + arVi->dimensions, + typenum); + } + + basic_filter = BasicFilterFunctions[(int) (arX->descr->type_num)]; + if (basic_filter == NULL) { + PyErr_SetString(PyExc_ValueError, + "linear_filter not available for this type"); + goto fail; + } + + /* Skip over leading zeros in vector representing denominator (a) */ + // XXX: TODO +#if 0 + ara_ptr = ara->data; + while (memcmp(ara_ptr, Va.zero, Va.elsize) == 0) { + ara_ptr += Va.elsize; + Va.data = ara_ptr; + Va.numels--; + } +#endif + + na = PyArray_SIZE(ara); + nb = PyArray_SIZE(arb); + if (input_flag) { + if (arVi->dimensions[theaxis] != (na > nb ? na : nb) - 1) { + PyErr_SetString(PyExc_ValueError, + "The number of initial conditions must be max([len(a),len(b)]) - 1"); + goto fail; + } + } + + fprintf(stderr, "%s\n", __func__); + RawFilter2(arb, ara, arX, arVi, arVf, arY, theaxis, basic_filter); + + Py_XDECREF(ara); + Py_XDECREF(arb); + Py_XDECREF(arX); + Py_XDECREF(arVi); + + if (!input_flag) { + return PyArray_Return(arY); + } else { + return Py_BuildValue("(NN)", arY, arVf); + } + + +fail: + Py_XDECREF(ara); + Py_XDECREF(arb); + Py_XDECREF(arX); + Py_XDECREF(arVi); + Py_XDECREF(arVf); + Py_XDECREF(arY); + return NULL; +} + +static int +zfill(const PyArrayObject *x, intp nx, char* xzfilled, intp nxzfilled) +{ + char *xzero; + intp i, nxl; + + nxl = PyArray_ITEMSIZE(x); + + xzero = PyArray_Zero(x); + + if (nx > 0) { + memcpy(xzfilled, x->data, nx * nxl); + } + for(i = nx; i < nxzfilled; ++i) { + memcpy(xzfilled + i * nxl, xzero, nxl); + } + + PyDataMem_FREE(xzero); + + return 0; +} + +/* + * a and b assumed to be contiguous + */ +static int +RawFilter2(const PyArrayObject *b, const PyArrayObject *a, + const PyArrayObject *x, const PyArrayObject *zi, + const PyArrayObject *zf, PyArrayObject *y, int axis, + BasicFilterFunction *filter_func) +{ + PyArrayIterObject *itx, *ity; + intp nitx, i, nxl; + intp na, nb, nal, nbl; + intp nfilt; + char *azfilled, *bzfilled, *zfzfilled; + + itx = (PyArrayIterObject *)PyArray_IterAllButAxis( + (PyObject *)x, &axis); + if (itx == NULL) { + fprintf(stderr, "FAIL\n"); + } + nitx = itx->size; + + ity = (PyArrayIterObject *)PyArray_IterAllButAxis( + (PyObject *)y, &axis); + if (ity == NULL) { + fprintf(stderr, "FAIL\n"); + } + + na = PyArray_SIZE(a); + nal = PyArray_ITEMSIZE(a); + nb = PyArray_SIZE(b); + nbl = PyArray_ITEMSIZE(b); + + nfilt = na > nb ? na : nb; + + azfilled = malloc(nal * nfilt); + bzfilled = malloc(nbl * nfilt); + + nxl = PyArray_ITEMSIZE(x); + zfzfilled = malloc(nxl * (nfilt-1) ); + + zfill(a, na, azfilled, nfilt); + zfill(b, nb, bzfilled, nfilt); + + if (zi != NULL) { + fprintf(stderr, "%s: FAILS\n", __func__); + return -1; + } else { + zfill(x, 0, zfzfilled, nfilt-1); + } + + +#if 0 + fprintf(stderr, "%s: a and b are %f and %f\n", __func__, +((double*)azfilled)[0], ((double*)bzfilled)[0]); + //fprintf(stderr, "%s: itx->size is %d\n", __func__, xsize); +#endif + for(i = 0; i < nitx-1; ++i) { +#if 0 + fprintf(stderr, "item %d is %f, next is %d bytes away, "\ + "filter %d items\n", + i, ((double*)itx->dataptr)[0], itx->strides[axis], + PyArray_DIM(x, axis)); +#endif + filter_func(bzfilled, azfilled, + itx->dataptr, ity->dataptr, zfzfilled, + nfilt, PyArray_DIM(x, axis), itx->strides[axis], + ity->strides[axis]); + PyArray_ITER_NEXT(itx); + PyArray_ITER_NEXT(ity); + + if (zi != NULL) { + fprintf(stderr, "%s: FAIL\n", __func__); + return -1; + } else { + /* XXX: inefficient because of the malloc in there */ + zfill(x, 0, zfzfilled, nfilt-1); + } + + } + //RawFilter(Vb, Va, x, y, vi, vf, basic_filter, theaxis); + /* fprintf(stderr, "Now, Here.\n"); */ + + Py_DECREF(ity); + Py_DECREF(itx); + + return 0; +} From scipy-svn at scipy.org Tue Nov 4 03:31:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:31:53 -0600 (CST) Subject: [Scipy-svn] r4983 - trunk/scipy/signal Message-ID: <20081104083153.063B739C088@scipy.org> Author: cdavid Date: 2008-11-04 02:31:47 -0600 (Tue, 04 Nov 2008) New Revision: 4983 Modified: trunk/scipy/signal/newsig.c Log: Trailing whitespace. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:31:29 UTC (rev 4982) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:31:47 UTC (rev 4983) @@ -1,8 +1,8 @@ #include -static int +static int RawFilter2(const PyArrayObject *b, const PyArrayObject *a, - const PyArrayObject *x, const PyArrayObject *zi, + const PyArrayObject *x, const PyArrayObject *zi, const PyArrayObject *zf, PyArrayObject *y, int axis, BasicFilterFunction *filter_func); @@ -63,15 +63,15 @@ input_flag = (PyArray_Size((PyObject *) arVi) > 0); } - arY = (PyArrayObject *) PyArray_SimpleNew(arX->nd, + arY = (PyArrayObject *) PyArray_SimpleNew(arX->nd, arX->dimensions, typenum); if (arY == NULL) { goto fail; } if (input_flag) { - arVf = (PyArrayObject *) PyArray_SimpleNew(arVi->nd, - arVi->dimensions, + arVf = (PyArrayObject *) PyArray_SimpleNew(arVi->nd, + arVi->dimensions, typenum); } @@ -155,7 +155,7 @@ */ static int RawFilter2(const PyArrayObject *b, const PyArrayObject *a, - const PyArrayObject *x, const PyArrayObject *zi, + const PyArrayObject *x, const PyArrayObject *zi, const PyArrayObject *zf, PyArrayObject *y, int axis, BasicFilterFunction *filter_func) { @@ -210,12 +210,12 @@ for(i = 0; i < nitx-1; ++i) { #if 0 fprintf(stderr, "item %d is %f, next is %d bytes away, "\ - "filter %d items\n", + "filter %d items\n", i, ((double*)itx->dataptr)[0], itx->strides[axis], PyArray_DIM(x, axis)); #endif - filter_func(bzfilled, azfilled, - itx->dataptr, ity->dataptr, zfzfilled, + filter_func(bzfilled, azfilled, + itx->dataptr, ity->dataptr, zfzfilled, nfilt, PyArray_DIM(x, axis), itx->strides[axis], ity->strides[axis]); PyArray_ITER_NEXT(itx); From scipy-svn at scipy.org Tue Nov 4 03:32:14 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:32:14 -0600 (CST) Subject: [Scipy-svn] r4984 - trunk/scipy/signal Message-ID: <20081104083214.6279D39C088@scipy.org> Author: cdavid Date: 2008-11-04 02:32:02 -0600 (Tue, 04 Nov 2008) New Revision: 4984 Modified: trunk/scipy/signal/newsig.c Log: Remove redundant NULL. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:31:47 UTC (rev 4983) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:32:02 UTC (rev 4984) @@ -12,11 +12,10 @@ static PyObject * sigtools_linear_filter2(PyObject * dummy, PyObject * args) { - PyObject *b = NULL, *a = NULL, *X = NULL, *Vi = NULL; - PyArrayObject *arY = NULL, *arb = NULL, *ara = NULL, *arX = NULL, - *arVi = NULL, *arVf = NULL; - int axis = -1, typenum, theaxis; - char *ara_ptr, input_flag = 0; + PyObject *b, *a, *X, *Vi; + PyArrayObject *arY, *arb, *ara, *arX, *arVi, *arVf; + int axis = -1, typenum, theaxis; + char *ara_ptr, input_flag = 0; intp na, nb; BasicFilterFunction *basic_filter; @@ -31,12 +30,7 @@ typenum = PyArray_ObjectType(Vi, typenum); } - arY = NULL; - arVf = NULL; - ara = NULL; - arb = NULL; - arX = NULL; - arVi = NULL; + arY = arVf = arVi = NULL; ara = (PyArrayObject *) PyArray_ContiguousFromObject(a, typenum, 1, 1); arb = (PyArrayObject *) PyArray_ContiguousFromObject(b, typenum, 1, 1); arX = (PyArrayObject *) PyArray_FromObject(X, typenum, 0, 0); From scipy-svn at scipy.org Tue Nov 4 03:32:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:32:29 -0600 (CST) Subject: [Scipy-svn] r4985 - trunk/scipy/signal Message-ID: <20081104083229.BD43E39C088@scipy.org> Author: cdavid Date: 2008-11-04 02:32:23 -0600 (Tue, 04 Nov 2008) New Revision: 4985 Modified: trunk/scipy/signal/newsig.c Log: Set default value for optional arguments of lfilter. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:32:02 UTC (rev 4984) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:32:23 UTC (rev 4985) @@ -14,11 +14,13 @@ { PyObject *b, *a, *X, *Vi; PyArrayObject *arY, *arb, *ara, *arX, *arVi, *arVf; - int axis = -1, typenum, theaxis; + int axis, typenum, theaxis; char *ara_ptr, input_flag = 0; intp na, nb; BasicFilterFunction *basic_filter; + axis = -1; + Vi = NULL; if (!PyArg_ParseTuple(args, "OOO|iO", &b, &a, &X, &axis, &Vi)) { return NULL; } From scipy-svn at scipy.org Tue Nov 4 03:32:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:32:46 -0600 (CST) Subject: [Scipy-svn] r4986 - trunk/scipy/signal Message-ID: <20081104083246.C0B1539C088@scipy.org> Author: cdavid Date: 2008-11-04 02:32:38 -0600 (Tue, 04 Nov 2008) New Revision: 4986 Modified: trunk/scipy/signal/newsig.c Log: Add a comment on failure handling not done yet. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:32:23 UTC (rev 4985) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:32:38 UTC (rev 4986) @@ -36,6 +36,7 @@ ara = (PyArrayObject *) PyArray_ContiguousFromObject(a, typenum, 1, 1); arb = (PyArrayObject *) PyArray_ContiguousFromObject(b, typenum, 1, 1); arX = (PyArrayObject *) PyArray_FromObject(X, typenum, 0, 0); + /* XXX: fix failure handling here */ if (ara == NULL || arb == NULL || arX == NULL) { goto fail; } @@ -155,7 +156,7 @@ const PyArrayObject *zf, PyArrayObject *y, int axis, BasicFilterFunction *filter_func) { - PyArrayIterObject *itx, *ity; + PyArrayIterObject *itx, *ity, *itzi, *itzf; intp nitx, i, nxl; intp na, nb, nal, nbl; intp nfilt; From scipy-svn at scipy.org Tue Nov 4 03:33:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:33:02 -0600 (CST) Subject: [Scipy-svn] r4987 - trunk/scipy/signal Message-ID: <20081104083302.AFF4739C088@scipy.org> Author: cdavid Date: 2008-11-04 02:32:56 -0600 (Tue, 04 Nov 2008) New Revision: 4987 Modified: trunk/scipy/signal/newsig.c Log: RawFilter2 now works on the whole lfilter test suite without crashing. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:32:38 UTC (rev 4986) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:32:56 UTC (rev 4987) @@ -100,7 +100,7 @@ } } - fprintf(stderr, "%s\n", __func__); + //fprintf(stderr, "%s\n", __func__); RawFilter2(arb, ara, arX, arVi, arVf, arY, theaxis, basic_filter); Py_XDECREF(ara); @@ -157,7 +157,7 @@ BasicFilterFunction *filter_func) { PyArrayIterObject *itx, *ity, *itzi, *itzf; - intp nitx, i, nxl; + intp nitx, i, nxl, nzfl, j; intp na, nb, nal, nbl; intp nfilt; char *azfilled, *bzfilled, *zfzfilled; @@ -175,6 +175,20 @@ fprintf(stderr, "FAIL\n"); } + if (zi != NULL) { + itzi = (PyArrayIterObject *)PyArray_IterAllButAxis( + (PyObject *)zi, &axis); + if (itzi == NULL) { + fprintf(stderr, "FAIL\n"); + } + + itzf = (PyArrayIterObject *)PyArray_IterAllButAxis( + (PyObject *)zf, &axis); + if (itzf == NULL) { + fprintf(stderr, "FAIL\n"); + } + } + na = PyArray_SIZE(a); nal = PyArray_ITEMSIZE(a); nb = PyArray_SIZE(b); @@ -191,45 +205,74 @@ zfill(a, na, azfilled, nfilt); zfill(b, nb, bzfilled, nfilt); - if (zi != NULL) { - fprintf(stderr, "%s: FAILS\n", __func__); - return -1; - } else { - zfill(x, 0, zfzfilled, nfilt-1); - } - - + /* XXX: Check that zf and zi have same type ? */ + if (zf != NULL) { + nzfl = PyArray_ITEMSIZE(zf); + } else { + nzfl = 0; + } #if 0 - fprintf(stderr, "%s: a and b are %f and %f\n", __func__, + fprintf(stderr, "%s: a and b are %f and %f\n", __func__, ((double*)azfilled)[0], ((double*)bzfilled)[0]); - //fprintf(stderr, "%s: itx->size is %d\n", __func__, xsize); + fprintf(stderr, "%s: itx->size is %d\n", __func__, nitx); #endif - for(i = 0; i < nitx-1; ++i) { + for(i = 0; i < nitx; ++i) { + if (zi != NULL) { + char* yoyo; + yoyo = itzi->dataptr; + /* Copy initial conditions zi in zfzfilled buffer */ + for(j = 0; j < nfilt - 1; ++j) { + memcpy(zfzfilled + j * nzfl, yoyo, nzfl); #if 0 - fprintf(stderr, "item %d is %f, next is %d bytes away, "\ - "filter %d items\n", - i, ((double*)itx->dataptr)[0], itx->strides[axis], - PyArray_DIM(x, axis)); + fprintf(stderr, "%s: Copying %f into zf: is %f\n", + __func__, ((double*)yoyo)[0], + ((double*)zfzfilled)[j]); #endif - filter_func(bzfilled, azfilled, - itx->dataptr, ity->dataptr, zfzfilled, - nfilt, PyArray_DIM(x, axis), itx->strides[axis], - ity->strides[axis]); - PyArray_ITER_NEXT(itx); - PyArray_ITER_NEXT(ity); + yoyo += itzi->strides[axis]; + } + PyArray_ITER_NEXT(itzi); +#if 0 + fprintf(stderr, "%s: FAILS\n", __func__); + return -1; +#endif + } else { + zfill(x, 0, zfzfilled, nfilt-1); + } - if (zi != NULL) { - fprintf(stderr, "%s: FAIL\n", __func__); - return -1; - } else { - /* XXX: inefficient because of the malloc in there */ - zfill(x, 0, zfzfilled, nfilt-1); - } +#if 0 + fprintf(stderr, "item %d is %f, next is %d bytes away, "\ + "filter %d items\n", + i, ((double*)itx->dataptr)[0], itx->strides[axis], + PyArray_DIM(x, axis)); +#endif + filter_func(bzfilled, azfilled, + itx->dataptr, ity->dataptr, zfzfilled, + nfilt, PyArray_DIM(x, axis), itx->strides[axis], + ity->strides[axis]); + PyArray_ITER_NEXT(itx); + PyArray_ITER_NEXT(ity); + /* Copy tmp buffer fo final values back into zf output array */ + if (zi != NULL) { + char *yoyo = itzf->dataptr; + for(j = 0; j < nfilt - 1; ++j) { + memcpy(yoyo, zfzfilled + j * nzfl, nzfl); +#if 0 + fprintf(stderr, "%s: Copying %f into zf output: is %f\n", + __func__, ((double*)zfzfilled)[j], + ((double*)yoyo)[0]); +#endif + yoyo += itzf->strides[axis]; + } + PyArray_ITER_NEXT(itzf); + } } - //RawFilter(Vb, Va, x, y, vi, vf, basic_filter, theaxis); /* fprintf(stderr, "Now, Here.\n"); */ + if (zi != NULL) { + Py_DECREF(itzf); + Py_DECREF(itzi); + } Py_DECREF(ity); Py_DECREF(itx); From scipy-svn at scipy.org Tue Nov 4 03:33:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:33:18 -0600 (CST) Subject: [Scipy-svn] r4988 - trunk/scipy/signal Message-ID: <20081104083318.1ABBC39C088@scipy.org> Author: cdavid Date: 2008-11-04 02:33:11 -0600 (Tue, 04 Nov 2008) New Revision: 4988 Modified: trunk/scipy/signal/newsig.c Log: Remove debug statements + add some comments on RawFilter2. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:32:56 UTC (rev 4987) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:33:11 UTC (rev 4988) @@ -100,7 +100,6 @@ } } - //fprintf(stderr, "%s\n", __func__); RawFilter2(arb, ara, arX, arVi, arVf, arY, theaxis, basic_filter); Py_XDECREF(ara); @@ -149,6 +148,12 @@ /* * a and b assumed to be contiguous + * + * XXX: this code is very conservative, and could be considerably sped up for + * the usual cases (like contiguity). + * + * XXX: the code should be refactored (at least with/without initial + * condition), some code is wasteful here */ static int RawFilter2(const PyArrayObject *b, const PyArrayObject *a, @@ -160,7 +165,7 @@ intp nitx, i, nxl, nzfl, j; intp na, nb, nal, nbl; intp nfilt; - char *azfilled, *bzfilled, *zfzfilled; + char *azfilled, *bzfilled, *zfzfilled, *yoyo; itx = (PyArrayIterObject *)PyArray_IterAllButAxis( (PyObject *)x, &axis); @@ -211,40 +216,21 @@ } else { nzfl = 0; } -#if 0 - fprintf(stderr, "%s: a and b are %f and %f\n", __func__, -((double*)azfilled)[0], ((double*)bzfilled)[0]); - fprintf(stderr, "%s: itx->size is %d\n", __func__, nitx); -#endif + + /* Iterate over the input array */ for(i = 0; i < nitx; ++i) { if (zi != NULL) { - char* yoyo; yoyo = itzi->dataptr; /* Copy initial conditions zi in zfzfilled buffer */ for(j = 0; j < nfilt - 1; ++j) { memcpy(zfzfilled + j * nzfl, yoyo, nzfl); -#if 0 - fprintf(stderr, "%s: Copying %f into zf: is %f\n", - __func__, ((double*)yoyo)[0], - ((double*)zfzfilled)[j]); -#endif yoyo += itzi->strides[axis]; } PyArray_ITER_NEXT(itzi); -#if 0 - fprintf(stderr, "%s: FAILS\n", __func__); - return -1; -#endif } else { zfill(x, 0, zfzfilled, nfilt-1); } -#if 0 - fprintf(stderr, "item %d is %f, next is %d bytes away, "\ - "filter %d items\n", - i, ((double*)itx->dataptr)[0], itx->strides[axis], - PyArray_DIM(x, axis)); -#endif filter_func(bzfilled, azfilled, itx->dataptr, ity->dataptr, zfzfilled, nfilt, PyArray_DIM(x, axis), itx->strides[axis], @@ -254,20 +240,14 @@ /* Copy tmp buffer fo final values back into zf output array */ if (zi != NULL) { - char *yoyo = itzf->dataptr; + yoyo = itzf->dataptr; for(j = 0; j < nfilt - 1; ++j) { memcpy(yoyo, zfzfilled + j * nzfl, nzfl); -#if 0 - fprintf(stderr, "%s: Copying %f into zf output: is %f\n", - __func__, ((double*)zfzfilled)[j], - ((double*)yoyo)[0]); -#endif yoyo += itzf->strides[axis]; } PyArray_ITER_NEXT(itzf); } } - /* fprintf(stderr, "Now, Here.\n"); */ if (zi != NULL) { Py_DECREF(itzf); From scipy-svn at scipy.org Tue Nov 4 03:33:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:33:36 -0600 (CST) Subject: [Scipy-svn] r4989 - trunk/scipy/signal Message-ID: <20081104083336.3173239C088@scipy.org> Author: cdavid Date: 2008-11-04 02:33:27 -0600 (Tue, 04 Nov 2008) New Revision: 4989 Modified: trunk/scipy/signal/sigtoolsmodule.c Log: Use new lfilter implementation instead of old one. Modified: trunk/scipy/signal/sigtoolsmodule.c =================================================================== --- trunk/scipy/signal/sigtoolsmodule.c 2008-11-04 08:33:11 UTC (rev 4988) +++ trunk/scipy/signal/sigtoolsmodule.c 2008-11-04 08:33:27 UTC (rev 4989) @@ -1962,6 +1962,11 @@ /* fprintf(stderr, "Here.\n"); */ + if (Vi != NULL) { + fprintf(stderr, "%s: Vs and Vf has %d and %d dims\n", __func__, + arVi->nd, arVf->nd); + + } RawFilter(Vb, Va, x, y, vi, vf, basic_filter, thedim); /* fprintf(stderr, "Now, Here.\n");*/ @@ -2164,13 +2169,13 @@ } +#include "newsig.c" - static struct PyMethodDef toolbox_module_methods[] = { {"_correlateND", sigtools_correlateND, METH_VARARGS, doc_correlateND}, {"_convolve2d", sigtools_convolve2d, METH_VARARGS, doc_convolve2d}, {"_order_filterND", sigtools_order_filterND, METH_VARARGS, doc_order_filterND}, - {"_linear_filter",sigtools_linear_filter, METH_VARARGS, doc_linear_filter}, + {"_linear_filter",sigtools_linear_filter2, METH_VARARGS, doc_linear_filter}, {"_remez",sigtools_remez, METH_VARARGS, doc_remez}, {"_medfilt2d", sigtools_median2d, METH_VARARGS, doc_median2d}, {NULL, NULL, 0} /* sentinel */ From scipy-svn at scipy.org Tue Nov 4 03:33:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:33:55 -0600 (CST) Subject: [Scipy-svn] r4990 - trunk/scipy/signal/tests Message-ID: <20081104083355.4A22B39C088@scipy.org> Author: cdavid Date: 2008-11-04 02:33:47 -0600 (Tue, 04 Nov 2008) New Revision: 4990 Modified: trunk/scipy/signal/tests/test_signaltools.py Log: Re-enable tests which used to segfault: new lfilter should handle them just fine. Modified: trunk/scipy/signal/tests/test_signaltools.py =================================================================== --- trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 08:33:27 UTC (rev 4989) +++ trunk/scipy/signal/tests/test_signaltools.py 2008-11-04 08:33:47 UTC (rev 4990) @@ -168,8 +168,8 @@ assert_array_almost_equal(zf, zf_r) # Disabled because it crashes lfilter for now - @dec.skipif(True, "Skipping lfilter test with initial condition along "\ - "axis 0: it segfaults ATM") + #@dec.skipif(True, "Skipping lfilter test with initial condition along "\ + # "axis 0: it segfaults ATM") def test_rank2_init_cond_a0(self): # Test initial condition handling along axis 0 shape = (4, 3) @@ -179,13 +179,13 @@ a = np.array([0.5, 0.5]) y_r2_a0_0 = np.array([[1, 3, 5], [5, 3, 1], [1, 3, 5], [5 ,3 ,1]]) - zf_r = np.array([-23, -23, -23]) + zf_r = np.array([[-23, -23, -23]]) y, zf = lfilter(b, a, x, axis = 0, zi = np.ones((1, 3))) assert_array_almost_equal(y_r2_a0_0, y) assert_array_almost_equal(zf, zf_r) # Disabled because it crashes lfilter for now - @dec.skipif(True, "Skipping rank > 2 test for lfilter because its segfaults ATM") + #@dec.skipif(True, "Skipping rank > 2 test for lfilter because its segfaults ATM") def test_rank3(self): shape = (4, 3, 2) x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) From scipy-svn at scipy.org Tue Nov 4 03:34:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 02:34:10 -0600 (CST) Subject: [Scipy-svn] r4991 - trunk/scipy/signal Message-ID: <20081104083410.E577439C088@scipy.org> Author: cdavid Date: 2008-11-04 02:34:04 -0600 (Tue, 04 Nov 2008) New Revision: 4991 Modified: trunk/scipy/signal/newsig.c Log: Raise a python exception if a[0] == 0. Modified: trunk/scipy/signal/newsig.c =================================================================== --- trunk/scipy/signal/newsig.c 2008-11-04 08:33:47 UTC (rev 4990) +++ trunk/scipy/signal/newsig.c 2008-11-04 08:34:04 UTC (rev 4991) @@ -15,8 +15,8 @@ PyObject *b, *a, *X, *Vi; PyArrayObject *arY, *arb, *ara, *arX, *arVi, *arVf; int axis, typenum, theaxis; - char *ara_ptr, input_flag = 0; - intp na, nb; + char *ara_ptr, input_flag = 0, *azero; + intp na, nb, nal; BasicFilterFunction *basic_filter; axis = -1; @@ -80,15 +80,16 @@ } /* Skip over leading zeros in vector representing denominator (a) */ - // XXX: TODO -#if 0 + /* XXX: handle this correctly */ + azero = PyArray_Zero(ara); ara_ptr = ara->data; - while (memcmp(ara_ptr, Va.zero, Va.elsize) == 0) { - ara_ptr += Va.elsize; - Va.data = ara_ptr; - Va.numels--; + nal = PyArray_ITEMSIZE(ara); + if (memcmp(ara_ptr, azero, nal) == 0) { + PyErr_SetString(PyExc_ValueError, + "BUG: filter coefficient a[0] == 0 not supported yet"); + goto fail; } -#endif + PyDataMem_FREE(azero); na = PyArray_SIZE(ara); nb = PyArray_SIZE(arb); From scipy-svn at scipy.org Tue Nov 4 07:08:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 06:08:03 -0600 (CST) Subject: [Scipy-svn] r4992 - trunk/scipy/signal Message-ID: <20081104120803.EDC7139C088@scipy.org> Author: stefan Date: 2008-11-04 06:07:22 -0600 (Tue, 04 Nov 2008) New Revision: 4992 Modified: trunk/scipy/signal/waveforms.py Log: Fix error message in `gausspulse`. Closes #756. Modified: trunk/scipy/signal/waveforms.py =================================================================== --- trunk/scipy/signal/waveforms.py 2008-11-04 08:34:04 UTC (rev 4991) +++ trunk/scipy/signal/waveforms.py 2008-11-04 12:07:22 UTC (rev 4992) @@ -104,7 +104,8 @@ if bw <= 0: raise ValueError, "Fractional bandwidth (bw=%.2f) must be > 0." % bw if bwr >= 0: - raise ValueError, "Reference level for bandwidth must be < 0 dB" % bwr + raise ValueError, "Reference level for bandwidth (bwr=%.2f) must " \ + "be < 0 dB" % bwr # exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f) From scipy-svn at scipy.org Tue Nov 4 11:32:59 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 4 Nov 2008 10:32:59 -0600 (CST) Subject: [Scipy-svn] r4993 - trunk/scipy Message-ID: <20081104163259.479C139C05F@scipy.org> Author: cdavid Date: 2008-11-04 10:32:55 -0600 (Tue, 04 Nov 2008) New Revision: 4993 Modified: trunk/scipy/setupscons.py Log: Add spatial to numscons build. Modified: trunk/scipy/setupscons.py =================================================================== --- trunk/scipy/setupscons.py 2008-11-04 12:07:22 UTC (rev 4992) +++ trunk/scipy/setupscons.py 2008-11-04 16:32:55 UTC (rev 4993) @@ -21,6 +21,7 @@ config.add_subpackage('optimize') config.add_subpackage('signal') config.add_subpackage('sparse') + config.add_subpackage('spatial') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') From scipy-svn at scipy.org Wed Nov 5 06:03:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 5 Nov 2008 05:03:33 -0600 (CST) Subject: [Scipy-svn] r4994 - trunk/scipy/cluster/tests Message-ID: <20081105110333.A617F39C089@scipy.org> Author: cdavid Date: 2008-11-05 05:03:25 -0600 (Wed, 05 Nov 2008) New Revision: 4994 Modified: trunk/scipy/cluster/tests/test_vq.py Log: Do not display warning when running test for kmean cluster error. Modified: trunk/scipy/cluster/tests/test_vq.py =================================================================== --- trunk/scipy/cluster/tests/test_vq.py 2008-11-04 16:32:55 UTC (rev 4993) +++ trunk/scipy/cluster/tests/test_vq.py 2008-11-05 11:03:25 UTC (rev 4994) @@ -1,9 +1,10 @@ #! /usr/bin/env python # David Cournapeau -# Last Change: Tue Jun 24 04:00 PM 2008 J +# Last Change: Wed Nov 05 07:00 PM 2008 J import os.path +import warnings import numpy as np from numpy.testing import * @@ -98,7 +99,12 @@ [-2.31149087,-0.05160469]]) res = kmeans(data, initk) - res = kmeans2(data, initk, missing = 'warn') + warnings.simplefilter('ignore', UserWarning) + try: + res = kmeans2(data, initk, missing = 'warn') + finally: + warnings.simplefilter('default', UserWarning) + try : res = kmeans2(data, initk, missing = 'raise') raise AssertionError("Exception not raised ! Should not happen") From scipy-svn at scipy.org Wed Nov 5 06:05:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 5 Nov 2008 05:05:10 -0600 (CST) Subject: [Scipy-svn] r4995 - trunk/scipy Message-ID: <20081105110510.1A60A39C089@scipy.org> Author: cdavid Date: 2008-11-05 05:05:06 -0600 (Wed, 05 Nov 2008) New Revision: 4995 Modified: trunk/scipy/setupscons.py Log: Include package constants in numscons build. Modified: trunk/scipy/setupscons.py =================================================================== --- trunk/scipy/setupscons.py 2008-11-05 11:03:25 UTC (rev 4994) +++ trunk/scipy/setupscons.py 2008-11-05 11:05:06 UTC (rev 4995) @@ -8,6 +8,7 @@ config = Configuration(pkgname, parent_package, top_path, setup_name = 'setupscons.py') config.add_subpackage('cluster') + config.add_subpackage('constants') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') From scipy-svn at scipy.org Wed Nov 5 06:19:01 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 5 Nov 2008 05:19:01 -0600 (CST) Subject: [Scipy-svn] r4996 - trunk/scipy/interpolate/tests Message-ID: <20081105111901.56F3939C089@scipy.org> Author: cdavid Date: 2008-11-05 05:18:54 -0600 (Wed, 05 Nov 2008) New Revision: 4996 Modified: trunk/scipy/interpolate/tests/test_rbf.py Log: Make sure decimal argument is an integer in assert_array_almost_equal to avoid spurious warnings. Modified: trunk/scipy/interpolate/tests/test_rbf.py =================================================================== --- trunk/scipy/interpolate/tests/test_rbf.py 2008-11-05 11:05:06 UTC (rev 4995) +++ trunk/scipy/interpolate/tests/test_rbf.py 2008-11-05 11:18:54 UTC (rev 4996) @@ -2,6 +2,7 @@ # Created by John Travers, Robert Hetland, 2007 """ Test functions for rbf module """ +import numpy as np from numpy.testing import assert_array_almost_equal, assert_almost_equal from numpy import linspace, sin, random, exp, log10 from scipy.interpolate.rbf import Rbf @@ -58,7 +59,7 @@ #plt.plot(x, y, 'o', xi, sin(xi), ':', xi, yi, '-') #plt.title(function) #plt.show() - assert_array_almost_equal(yi, sin(xi), decimal=-log10(atol), + assert_array_almost_equal(yi, sin(xi), decimal=-np.int(log10(atol)) - 1, err_msg="abs-diff: %f" % abs(yi - sin(xi)).max()) def test_rbf_regularity(): From scipy-svn at scipy.org Thu Nov 6 06:54:30 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 05:54:30 -0600 (CST) Subject: [Scipy-svn] r4997 - trunk/scipy/signal/tests Message-ID: <20081106115430.3B8FE39C089@scipy.org> Author: cdavid Date: 2008-11-06 05:54:13 -0600 (Thu, 06 Nov 2008) New Revision: 4997 Added: trunk/scipy/signal/tests/test_filter_design.py Log: Add a simple test for tf2zpk. Added: trunk/scipy/signal/tests/test_filter_design.py =================================================================== --- trunk/scipy/signal/tests/test_filter_design.py 2008-11-05 11:18:54 UTC (rev 4996) +++ trunk/scipy/signal/tests/test_filter_design.py 2008-11-06 11:54:13 UTC (rev 4997) @@ -0,0 +1,21 @@ +import numpy as np +from numpy.testing import TestCase, assert_array_almost_equal + +from scipy.signal import tf2zpk + +class TestTf2zpk(TestCase): + def test_simple(self): + z_r = np.array([0.5, -0.5]) + p_r = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)]) + # Sort the zeros/poles so that we don't fail the test if the order + # changes + z_r.sort() + p_r.sort() + b = np.poly(z_r) + a = np.poly(p_r) + + z, p, k = tf2zpk(b, a) + z.sort() + p.sort() + assert_array_almost_equal(z, z_r) + assert_array_almost_equal(p, p_r) From scipy-svn at scipy.org Thu Nov 6 06:55:19 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 05:55:19 -0600 (CST) Subject: [Scipy-svn] r4998 - trunk/scipy/signal Message-ID: <20081106115519.EF3C239C089@scipy.org> Author: cdavid Date: 2008-11-06 05:54:41 -0600 (Thu, 06 Nov 2008) New Revision: 4998 Modified: trunk/scipy/signal/filter_design.py Log: Warn about badly conditionned coefficients in normalize. Modified: trunk/scipy/signal/filter_design.py =================================================================== --- trunk/scipy/signal/filter_design.py 2008-11-06 11:54:13 UTC (rev 4997) +++ trunk/scipy/signal/filter_design.py 2008-11-06 11:54:41 UTC (rev 4998) @@ -2,6 +2,7 @@ """ import types +import warnings import numpy from numpy import atleast_1d, poly, polyval, roots, real, asarray, allclose, \ @@ -11,6 +12,8 @@ from scipy import special, optimize from scipy.misc import comb +class BadCoefficients(UserWarning): + pass abs = absolute @@ -170,8 +173,11 @@ b = asarray([b],b.dtype.char) while a[0] == 0.0 and len(a) > 1: a = a[1:] - while allclose(b[:,0], 0, rtol=1e-14) and (b.shape[-1] > 1): - b = b[:,1:] + if allclose(b[:,0], 0, rtol=1e-14): + warnings.warn("Badly conditionned filter coefficients (numerator): the " + "results may be meaningless", BadCoefficients) + while allclose(b[:,0], 0, rtol=1e-14) and (b.shape[-1] > 1): + b = b[:,1:] if b.shape[0] == 1: b = b[0] outb = b * (1.0) / a[0] @@ -1543,3 +1549,5 @@ m = numpy.arange(0,N) h = win*special.sinc(cutoff*(m-alpha)) return h / numpy.sum(h,axis=0) + +warnings.simplefilter("always", BadCoefficients) From scipy-svn at scipy.org Thu Nov 6 06:56:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 05:56:06 -0600 (CST) Subject: [Scipy-svn] r4999 - trunk/scipy/signal/tests Message-ID: <20081106115606.46A9339C2EA@scipy.org> Author: cdavid Date: 2008-11-06 05:55:41 -0600 (Thu, 06 Nov 2008) New Revision: 4999 Modified: trunk/scipy/signal/tests/test_filter_design.py Log: Check the warning works as expected for #651 case. Modified: trunk/scipy/signal/tests/test_filter_design.py =================================================================== --- trunk/scipy/signal/tests/test_filter_design.py 2008-11-06 11:54:41 UTC (rev 4998) +++ trunk/scipy/signal/tests/test_filter_design.py 2008-11-06 11:55:41 UTC (rev 4999) @@ -1,7 +1,9 @@ +import warnings + import numpy as np from numpy.testing import TestCase, assert_array_almost_equal -from scipy.signal import tf2zpk +from scipy.signal import tf2zpk, bessel, BadCoefficients class TestTf2zpk(TestCase): def test_simple(self): @@ -19,3 +21,18 @@ p.sort() assert_array_almost_equal(z, z_r) assert_array_almost_equal(p, p_r) + + def test_bad_filter(self): + """Regression test for #651: better handling of badly conditionned + filter coefficients.""" + b, a = bessel(20, 0.1) + warnings.simplefilter("error", BadCoefficients) + try: + try: + z, p, k = tf2zpk(b, a) + raise AssertionError("tf2zpk did not warn about bad "\ + "coefficients") + except BadCoefficients: + pass + finally: + warnings.simplefilter("always", BadCoefficients) From scipy-svn at scipy.org Thu Nov 6 06:56:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 05:56:47 -0600 (CST) Subject: [Scipy-svn] r5000 - trunk/scipy/signal Message-ID: <20081106115647.4B05139C1AE@scipy.org> Author: cdavid Date: 2008-11-06 05:56:24 -0600 (Thu, 06 Nov 2008) New Revision: 5000 Modified: trunk/scipy/signal/filter_design.py Log: Mention the warning in tf2zpk and zpk2tf. Modified: trunk/scipy/signal/filter_design.py =================================================================== --- trunk/scipy/signal/filter_design.py 2008-11-06 11:55:41 UTC (rev 4999) +++ trunk/scipy/signal/filter_design.py 2008-11-06 11:56:24 UTC (rev 5000) @@ -124,6 +124,9 @@ def tf2zpk(b,a): """Return zero, pole, gain (z,p,k) representation from a numerator, denominator representation of a linear filter. + + If some values of b are too close to 0, they are removed. In that case, a + BadCoefficients warning is emitted. """ b,a = normalize(b,a) b = (b+0.0) / a[0] @@ -146,6 +149,9 @@ Outputs: (b,a) b, a --- numerator and denominator polynomials. + + If some values of b are too close to 0, they are removed. In that case, a + BadCoefficients warning is emitted. """ z = atleast_1d(z) k = atleast_1d(k) @@ -163,6 +169,9 @@ def normalize(b,a): """Normalize polynomial representation of a transfer function. + + If values of b are too close to 0, they are removed. In that case, a + BadCoefficients warning is emitted. """ b,a = map(atleast_1d,(b,a)) if len(a.shape) != 1: From scipy-svn at scipy.org Thu Nov 6 06:57:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 05:57:12 -0600 (CST) Subject: [Scipy-svn] r5001 - trunk/scipy/signal Message-ID: <20081106115712.E384439C1AE@scipy.org> Author: cdavid Date: 2008-11-06 05:57:03 -0600 (Thu, 06 Nov 2008) New Revision: 5001 Modified: trunk/scipy/signal/filter_design.py Log: Make the docstring of filter design more compliant to the numpy format. Modified: trunk/scipy/signal/filter_design.py =================================================================== --- trunk/scipy/signal/filter_design.py 2008-11-06 11:56:24 UTC (rev 5000) +++ trunk/scipy/signal/filter_design.py 2008-11-06 11:57:03 UTC (rev 5001) @@ -36,23 +36,22 @@ def freqs(b,a,worN=None,plot=None): """Compute frequency response of analog filter. - Description: + Given the numerator (b) and denominator (a) of a filter compute its + frequency response. - Given the numerator (b) and denominator (a) of a filter compute its - frequency response. + b[0]*(jw)**(nb-1) + b[1]*(jw)**(nb-2) + ... + b[nb-1] + H(w) = -------------------------------------------------------- + a[0]*(jw)**(na-1) + a[1]*(jw)**(na-2) + ... + a[na-1] - b[0]*(jw)**(nb-1) + b[1]*(jw)**(nb-2) + ... + b[nb-1] - H(w) = -------------------------------------------------------- - a[0]*(jw)**(na-1) + a[1]*(jw)**(na-2) + ... + a[na-1] - - Inputs: - + Parameters + ---------- b, a --- the numerator and denominator of a linear filter. worN --- If None, then compute at 200 frequencies around the interesting parts of the response curve (determined by pole-zero locations). If a single integer, the compute at that many frequencies. Otherwise, compute the response at frequencies given in worN. - Outputs: (w,h) + Returns + ------- w -- The frequencies at which h was computed. h -- The frequency response. @@ -74,19 +73,17 @@ def freqz(b, a=1, worN=None, whole=0, plot=None): """Compute frequency response of a digital filter. - Description: + Given the numerator (b) and denominator (a) of a digital filter compute + its frequency response. - Given the numerator (b) and denominator (a) of a digital filter compute - its frequency response. + jw -jw -jmw + jw B(e) b[0] + b[1]e + .... + b[m]e + H(e) = ---- = ------------------------------------ + jw -jw -jnw + A(e) a[0] + a[2]e + .... + a[n]e - jw -jw -jmw - jw B(e) b[0] + b[1]e + .... + b[m]e - H(e) = ---- = ------------------------------------ - jw -jw -jnw - A(e) a[0] + a[2]e + .... + a[n]e - - Inputs: - + Parameters + ---------- b, a --- the numerator and denominator of a linear filter. worN --- If None, then compute at 512 frequencies around the unit circle. If a single integer, the compute at that many frequencies. @@ -95,8 +92,8 @@ unit-circle. If whole is non-zero compute frequencies from 0 to 2*pi. - Outputs: (w,h) - + Returns + ------- w -- The frequencies at which h was computed. h -- The frequency response. @@ -141,14 +138,16 @@ """Return polynomial transfer function representation from zeros and poles - Inputs: + Parameters + ---------- - z, p --- sequences representing the zeros and poles. - k --- system gain. + z, p --- sequences representing the zeros and poles. + k --- system gain. - Outputs: (b,a) + Returns + ------- - b, a --- numerator and denominator polynomials. + b, a --- numerator and denominator polynomials. If some values of b are too close to 0, they are removed. In that case, a BadCoefficients warning is emitted. @@ -340,34 +339,32 @@ def iirdesign(wp, ws, gpass, gstop, analog=0, ftype='ellip', output='ba'): """Complete IIR digital and analog filter design. - Description: + Given passband and stopband frequencies and gains construct an analog or + digital IIR filter of minimum order for a given basic type. Return the + output in numerator, denominator ('ba') or pole-zero ('zpk') form. - Given passband and stopband frequencies and gains construct an analog or - digital IIR filter of minimum order for a given basic type. Return the - output in numerator, denominator ('ba') or pole-zero ('zpk') form. + Parameters + ---------- + wp, ws -- Passband and stopband edge frequencies, normalized from 0 + to 1 (1 corresponds to pi radians / sample). For example: + Lowpass: wp = 0.2, ws = 0.3 + Highpass: wp = 0.3, ws = 0.2 + Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + gpass -- The maximum loss in the passband (dB). + gstop -- The minimum attenuation in the stopband (dB). + analog -- Non-zero to design an analog filter (in this case wp and + ws are in radians / second). + ftype -- The type of iir filter to design: + elliptic : 'ellip' + Butterworth : 'butter', + Chebyshev I : 'cheby1', + Chebyshev II: 'cheby2', + Bessel : 'bessel' + output -- Type of output: numerator/denominator ('ba') or pole-zero ('zpk') - Inputs: - - wp, ws -- Passband and stopband edge frequencies, normalized from 0 - to 1 (1 corresponds to pi radians / sample). For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] - gpass -- The maximum loss in the passband (dB). - gstop -- The minimum attenuation in the stopband (dB). - analog -- Non-zero to design an analog filter (in this case wp and - ws are in radians / second). - ftype -- The type of iir filter to design: - elliptic : 'ellip' - Butterworth : 'butter', - Chebyshev I : 'cheby1', - Chebyshev II: 'cheby2', - Bessel : 'bessel' - output -- Type of output: numerator/denominator ('ba') or pole-zero ('zpk') - - Outputs: (b,a) or (z,p,k) - + Returns + ------- b,a -- Numerator and denominator of the iir filter. z,p,k -- Zeros, poles, and gain of the iir filter. """ @@ -395,24 +392,22 @@ def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=0, ftype='butter', output='ba'): """IIR digital and analog filter design given order and critical points. - Description: + Design an Nth order lowpass digital or analog filter and return the filter + coefficients in (B,A) (numerator, denominator) or (Z,P,K) form. - Design an Nth order lowpass digital or analog filter and return the filter - coefficients in (B,A) (numerator, denominator) or (Z,P,K) form. + Parameters + ---------- + N -- the order of the filter. + Wn -- a scalar or length-2 sequence giving the critical frequencies. + rp, rs -- For chebyshev and elliptic filters provides the maximum ripple + in the passband and the minimum attenuation in the stop band. + btype -- the type of filter (lowpass, highpass, bandpass, or bandstop). + analog -- non-zero to return an analog filter, otherwise + a digital filter is returned. + ftype -- the type of IIR filter (Butterworth, Cauer (Elliptic), + Bessel, Chebyshev1, Chebyshev2) + output -- 'ba' for (b,a) output, 'zpk' for (z,p,k) output. - Inputs: - - N -- the order of the filter. - Wn -- a scalar or length-2 sequence giving the critical frequencies. - rp, rs -- For chebyshev and elliptic filters provides the maximum ripple - in the passband and the minimum attenuation in the stop band. - btype -- the type of filter (lowpass, highpass, bandpass, or bandstop). - analog -- non-zero to return an analog filter, otherwise - a digital filter is returned. - ftype -- the type of IIR filter (Butterworth, Cauer (Elliptic), - Bessel, Chebyshev1, Chebyshev2) - output -- 'ba' for (b,a) output, 'zpk' for (z,p,k) output. - SEE ALSO butterord, cheb1ord, cheb2ord, ellipord """ @@ -559,19 +554,19 @@ Returns the non-integer order for an analog band stop filter. - Inputs: + Parameters + ---------- + wp -- passb edge + ind -- index specifying which passb edge to vary (0 or 1). + passb -- two element vector of fixed passband edges. + stopb -- two element vector of fixed stopband edges. + gstop -- amount in dB of attenuation in stopband. + gpass -- amount in dB of ripple in the passband. + type -- 'butter', 'cheby', or 'ellip': - wp -- passb edge - ind -- index specifying which passb edge to vary (0 or 1). - passb -- two element vector of fixed passband edges. - stopb -- two element vector of fixed stopband edges. - gstop -- amount in dB of attenuation in stopband. - gpass -- amount in dB of ripple in the passband. - type -- 'butter', 'cheby', or 'ellip': - - Outputs: (n,) - - n -- filter order (possibly non-integer) + Returns + ------- + n -- filter order (possibly non-integer) """ passbC = passb.copy() @@ -602,31 +597,29 @@ def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. - Description: + Return the order of the lowest order digital Butterworth filter that loses + no more than gpass dB in the passband and has at least gstop dB attenuation + in the stopband. - Return the order of the lowest order digital Butterworth filter that - loses no more than gpass dB in the passband and has at least gstop dB - attenuation in the stopband. + Parameters + ---------- + wp, ws -- Passband and stopband edge frequencies, normalized from 0 + to 1 (1 corresponds to pi radians / sample). For example: + Lowpass: wp = 0.2, ws = 0.3 + Highpass: wp = 0.3, ws = 0.2 + Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + gpass -- The maximum loss in the passband (dB). + gstop -- The minimum attenuation in the stopband (dB). + analog -- Non-zero to design an analog filter (in this case wp and + ws are in radians / second). - Inputs: + Returns + ------- + ord -- The lowest order for a Butterworth filter which meets specs. + Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). + Should be used with scipy.signal.butter to give filter results. - wp, ws -- Passband and stopband edge frequencies, normalized from 0 - to 1 (1 corresponds to pi radians / sample). For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] - gpass -- The maximum loss in the passband (dB). - gstop -- The minimum attenuation in the stopband (dB). - analog -- Non-zero to design an analog filter (in this case wp and - ws are in radians / second). - - Outputs: (ord, Wn) - - ord -- The lowest order for a Butterworth filter which meets specs. - Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). - Should be used with scipy.signal.butter to give filter results. - """ wp = atleast_1d(wp) @@ -710,31 +703,29 @@ def cheb1ord(wp, ws, gpass, gstop, analog=0): """Chebyshev type I filter order selection. - Description: + Return the order of the lowest order digital Chebyshev Type I filter that + loses no more than gpass dB in the passband and has at least gstop dB + attenuation in the stopband. - Return the order of the lowest order digital Chebyshev Type I filter - that loses no more than gpass dB in the passband and has at least gstop dB - attenuation in the stopband. + Parameters + ---------- + wp, ws -- Passband and stopband edge frequencies, normalized from 0 + to 1 (1 corresponds to pi radians / sample). For example: + Lowpass: wp = 0.2, ws = 0.3 + Highpass: wp = 0.3, ws = 0.2 + Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + gpass -- The maximum loss in the passband (dB). + gstop -- The minimum attenuation in the stopband (dB). + analog -- Non-zero to design an analog filter (in this case wp and + ws are in radians / second). - Inputs: + Returns + ------- + ord -- The lowest order for a Chebyshev type I filter that meets specs. + Wn -- The Chebyshev natural frequency (the "3dB frequency") for + use with scipy.signal.cheby1 to give filter results. - wp, ws -- Passband and stopband edge frequencies, normalized from 0 - to 1 (1 corresponds to pi radians / sample). For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] - gpass -- The maximum loss in the passband (dB). - gstop -- The minimum attenuation in the stopband (dB). - analog -- Non-zero to design an analog filter (in this case wp and - ws are in radians / second). - - Outputs: (ord, Wn) - - ord -- The lowest order for a Chebyshev type I filter that meets specs. - Wn -- The Chebyshev natural frequency (the "3dB frequency") for - use with scipy.signal.cheby1 to give filter results. - """ wp = atleast_1d(wp) ws = atleast_1d(ws) @@ -793,25 +784,25 @@ that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. - Inputs: + Parameters + ---------- + wp, ws -- Passband and stopband edge frequencies, normalized from 0 + to 1 (1 corresponds to pi radians / sample). For example: + Lowpass: wp = 0.2, ws = 0.3 + Highpass: wp = 0.3, ws = 0.2 + Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + gpass -- The maximum loss in the passband (dB). + gstop -- The minimum attenuation in the stopband (dB). + analog -- Non-zero to design an analog filter (in this case wp and + ws are in radians / second). - wp, ws -- Passband and stopband edge frequencies, normalized from 0 - to 1 (1 corresponds to pi radians / sample). For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] - gpass -- The maximum loss in the passband (dB). - gstop -- The minimum attenuation in the stopband (dB). - analog -- Non-zero to design an analog filter (in this case wp and - ws are in radians / second). + Returns + ------- + ord -- The lowest order for a Chebyshev type II filter that meets specs. + Wn -- The Chebyshev natural frequency for + use with scipy.signal.cheby2 to give the filter. - Outputs: (ord, Wn) - - ord -- The lowest order for a Chebyshev type II filter that meets specs. - Wn -- The Chebyshev natural frequency for - use with scipy.signal.cheby2 to give the filter. - """ wp = atleast_1d(wp) ws = atleast_1d(ws) @@ -888,31 +879,29 @@ def ellipord(wp, ws, gpass, gstop, analog=0): """Elliptic (Cauer) filter order selection. - Description: + Return the order of the lowest order digital elliptic filter that loses no + more than gpass dB in the passband and has at least gstop dB attenuation in + the stopband. - Return the order of the lowest order digital elliptic filter - that loses no more than gpass dB in the passband and has at least - gstop dB attenuation in the stopband. + Parameters + ---------- + wp, ws -- Passband and stopband edge frequencies, normalized from 0 + to 1 (1 corresponds to pi radians / sample). For example: + Lowpass: wp = 0.2, ws = 0.3 + Highpass: wp = 0.3, ws = 0.2 + Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] + Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] + gpass -- The maximum loss in the passband (dB). + gstop -- The minimum attenuation in the stopband (dB). + analog -- Non-zero to design an analog filter (in this case wp and + ws are in radians / second). - Inputs: + Returns + ------- + ord -- The lowest order for an Elliptic (Cauer) filter that meets specs. + Wn -- The natural frequency for use with scipy.signal.ellip + to give the filter. - wp, ws -- Passband and stopband edge frequencies, normalized from 0 - to 1 (1 corresponds to pi radians / sample). For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] - gpass -- The maximum loss in the passband (dB). - gstop -- The minimum attenuation in the stopband (dB). - analog -- Non-zero to design an analog filter (in this case wp and - ws are in radians / second). - - Outputs: (ord, Wn) - - ord -- The lowest order for an Elliptic (Cauer) filter that meets specs. - Wn -- The natural frequency for use with scipy.signal.ellip - to give the filter. - """ wp = atleast_1d(wp) ws = atleast_1d(ws) @@ -1497,21 +1486,21 @@ def kaiserord(ripple, width): """Design a Kaiser window to limit ripple and width of transition region. - Inputs: + Parameters + ---------- + ripple -- positive number specifying maximum ripple in passband (dB) + and minimum ripple in stopband + width -- width of transition region (normalized so that 1 corresponds + to pi radians / sample) - ripple -- positive number specifying maximum ripple in passband (dB) - and minimum ripple in stopband - width -- width of transition region (normalized so that 1 corresponds - to pi radians / sample) + Returns + ------- + N, beta -- the order and beta parameter for the kaiser window. - Outputs: + signal.kaiser(N,beta,sym=0) returns the window as does + signal.get_window(beta,N) + signal.get_window(('kaiser',beta),N) - N, beta -- the order and beta parameter for the kaiser window. - - signal.kaiser(N,beta,sym=0) returns the window as does - signal.get_window(beta,N) - signal.get_window(('kaiser',beta),N) - Uses the empirical equations discovered by Kaiser. Oppenheim, Schafer, "Discrete-Time Signal Processing,", p.475-476. @@ -1529,20 +1518,20 @@ def firwin(N, cutoff, width=None, window='hamming'): """FIR Filter Design using windowed ideal filter method. - Inputs: + Parameters + ---------- + N -- order of filter (number of taps) + cutoff -- cutoff frequency of filter (normalized so that 1 corresponds to + Nyquist or pi radians / sample) - N -- order of filter (number of taps) - cutoff -- cutoff frequency of filter (normalized so that 1 corresponds to - Nyquist or pi radians / sample) + width -- if width is not None, then assume it is the approximate width of + the transition region (normalized so that 1 corresonds to pi) + for use in kaiser FIR filter design. + window -- desired window to use. - width -- if width is not None, then assume it is the approximate width of - the transition region (normalized so that 1 corresonds to pi) - for use in kaiser FIR filter design. - window -- desired window to use. - - Outputs: - - h -- coefficients of length N fir filter. + Returns + ------- + h -- coefficients of length N fir filter. """ from signaltools import get_window From scipy-svn at scipy.org Thu Nov 6 06:57:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 05:57:28 -0600 (CST) Subject: [Scipy-svn] r5002 - trunk/scipy/signal Message-ID: <20081106115728.D440339C1AE@scipy.org> Author: cdavid Date: 2008-11-06 05:57:21 -0600 (Thu, 06 Nov 2008) New Revision: 5002 Modified: trunk/scipy/signal/filter_design.py Log: Make the docstring of freqs, freqz and tf2pzk/zpk2tf numpy format compliant. Modified: trunk/scipy/signal/filter_design.py =================================================================== --- trunk/scipy/signal/filter_design.py 2008-11-06 11:57:03 UTC (rev 5001) +++ trunk/scipy/signal/filter_design.py 2008-11-06 11:57:21 UTC (rev 5002) @@ -45,16 +45,22 @@ Parameters ---------- - b, a --- the numerator and denominator of a linear filter. - worN --- If None, then compute at 200 frequencies around the interesting - parts of the response curve (determined by pole-zero locations). - If a single integer, the compute at that many frequencies. - Otherwise, compute the response at frequencies given in worN. + b : ndarray + numerator of a linear filter + a : ndarray + numerator of a linear filter + worN : {None, int}, optional + If None, then compute at 200 frequencies around the interesting parts + of the response curve (determined by pole-zero locations). If a single + integer, the compute at that many frequencies. Otherwise, compute the + response at frequencies given in worN. + Returns ------- - - w -- The frequencies at which h was computed. - h -- The frequency response. + w : ndarray + The frequencies at which h was computed. + h : ndarray + The frequency response. """ if worN is None: w = findfreqs(b,a,200) @@ -84,19 +90,25 @@ Parameters ---------- - b, a --- the numerator and denominator of a linear filter. - worN --- If None, then compute at 512 frequencies around the unit circle. - If a single integer, the compute at that many frequencies. - Otherwise, compute the response at frequencies given in worN - whole -- Normally, frequencies are computed from 0 to pi (upper-half of - unit-circle. If whole is non-zero compute frequencies from 0 - to 2*pi. + b : ndarray + numerator of a linear filter + a : ndarray + numerator of a linear filter + worN : {None, int}, optional + If None, then compute at 200 frequencies around the interesting parts + of the response curve (determined by pole-zero locations). If a single + integer, the compute at that many frequencies. Otherwise, compute the + response at frequencies given in worN. + whole : {0,1}, optional + Normally, frequencies are computed from 0 to pi (upper-half of + unit-circle. If whole is non-zero compute frequencies from 0 to 2*pi. Returns ------- - w -- The frequencies at which h was computed. - h -- The frequency response. - + w : ndarray + The frequencies at which h was computed. + h : ndarray + The frequency response. """ b, a = map(atleast_1d, (b,a)) if whole: @@ -122,6 +134,22 @@ """Return zero, pole, gain (z,p,k) representation from a numerator, denominator representation of a linear filter. + Parameters + ---------- + b : ndarray + numerator polynomial. + a : ndarray + numerator and denominator polynomials. + + Returns + ------- + z : ndarray + zeros of the transfer function. + p : ndarray + poles of the transfer function. + k : float + system gain. + If some values of b are too close to 0, they are removed. In that case, a BadCoefficients warning is emitted. """ @@ -140,15 +168,22 @@ Parameters ---------- + z : ndarray + zeros of the transfer function. + p : ndarray + poles of the transfer function. + k : float + system gain. - z, p --- sequences representing the zeros and poles. - k --- system gain. - Returns ------- + b : ndarray + numerator polynomial. + a : ndarray + numerator and denominator polynomials. - b, a --- numerator and denominator polynomials. - + Note + ---- If some values of b are too close to 0, they are removed. In that case, a BadCoefficients warning is emitted. """ From scipy-svn at scipy.org Thu Nov 6 08:24:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 6 Nov 2008 07:24:47 -0600 (CST) Subject: [Scipy-svn] r5003 - trunk/scipy/cluster Message-ID: <20081106132447.BA73A39C089@scipy.org> Author: cdavid Date: 2008-11-06 07:24:44 -0600 (Thu, 06 Nov 2008) New Revision: 5003 Modified: trunk/scipy/cluster/hierarchy.py Log: Catch RuntimeError when importing matplotlib.pylab to handle cases where mpl is there but no X server is available. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-06 11:57:21 UTC (rev 5002) +++ trunk/scipy/cluster/hierarchy.py 2008-11-06 13:24:44 UTC (rev 5003) @@ -1440,8 +1440,13 @@ try: import matplotlib - import matplotlib.pylab - import matplotlib.patches + try: + import matplotlib.pylab + import matplotlib.patches + except RuntimeError, e: + # importing matplotlib.pylab can fail with a RuntimeError if installed + # but the graphic engine cannot be initialized (for example without X) + raise ImportError("Could not import matplotib (error was %s)" % str(e)) #import matplotlib.collections _mpl = True From scipy-svn at scipy.org Fri Nov 7 13:46:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 12:46:36 -0600 (CST) Subject: [Scipy-svn] r5004 - trunk/scipy/cluster/tests Message-ID: <20081107184636.8423B39C260@scipy.org> Author: damian.eads Date: 2008-11-07 12:46:34 -0600 (Fri, 07 Nov 2008) New Revision: 5004 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added tests for cophenet function. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-06 13:24:44 UTC (rev 5003) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 18:46:34 UTC (rev 5004) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, numobs_linkage, inconsistent +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, numobs_linkage, inconsistent, cophenet from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -155,9 +155,38 @@ class TestInconsistent(TestCase): def test_single_inconsistent_tdist(self): + "Testing inconsistency matrix calculation on a single linkage." for i in xrange(0, 100): yield help_single_inconsistent_depth, i +class TestCopheneticDistance(TestCase): + + def test_linkage_cophenet_tdist_Z(self): + "Testing cophenet(Z) on tdist data set." + expectedM = np.array([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, 295, 138, 219, 295, 295]); + Z = linkage(_ytdist, 'single') + M = cophenet(Z) + eps = 1e-10 + self.failUnless(within_tol(M, expectedM, eps)) + + def test_linkage_cophenet_tdist_Z_Y(self): + "Testing cophenet(Z, Y) on tdist data set." + Z = linkage(_ytdist, 'single') + c = cophenet(Z, _ytdist) + expectedc = 0.639931296433393415057366837573 + eps = 1e-10 + self.failUnless(np.abs(c - expectedc) <= eps) + + def test_linkage_cophenet_tdist_Z_Y_EL(self): + "Testing cophenet(Z, Y, []) on tdist data set." + Z = linkage(_ytdist, 'single') + (c, M) = cophenet(Z, _ytdist, []) + eps = 1e-10 + expectedM = np.array([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, 295, 138, 219, 295, 295]); + expectedc = 0.639931296433393415057366837573 + self.failUnless(np.abs(c - expectedc) <= eps) + self.failUnless(within_tol(M, expectedM, eps)) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 14:02:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 13:02:48 -0600 (CST) Subject: [Scipy-svn] r5005 - in trunk/scipy/cluster: . tests Message-ID: <20081107190248.F276939C260@scipy.org> Author: damian.eads Date: 2008-11-07 13:02:46 -0600 (Fri, 07 Nov 2008) New Revision: 5005 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Added more tests. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 18:46:34 UTC (rev 5004) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 19:02:46 UTC (rev 5005) @@ -1035,6 +1035,18 @@ """ Z = np.asarray(Z, order='c') Zs = Z.shape + + # If it's empty, return it. + if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): + return Z.copy() + + if len(Zs) != 2: + raise ValueError("The linkage array must be rectangular.") + + # If it contains no rows, return it. + if Zs[0] == 0: + return Z.copy() + Zpart = Z[:,0:2] Zd = Z[:,2].reshape(Zs[0], 1) if Zpart.min() != 1.0 and Zpart.max() != 2 * Zs[0]: Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 18:46:34 UTC (rev 5004) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 19:02:46 UTC (rev 5005) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, numobs_linkage, inconsistent, cophenet +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -187,6 +187,21 @@ self.failUnless(np.abs(c - expectedc) <= eps) self.failUnless(within_tol(M, expectedM, eps)) +class TestFromMLabLinkage(TestCase): + + def test_from_mlab_linkage_empty(self): + "Testing from_mlab_linkage on empty linkage array." + X = np.asarray([]) + R = from_mlab_linkage([]) + self.failUnless((R == X).all()) + + def test_from_mlab_linkage_single_row(self): + "Testing from_mlab_linkage on linkage array with single row." + expectedZP = np.asarray([[ 0., 1., 3., 2.]]) + Z = [[1,2,3]] + ZP = from_mlab_linkage(Z) + return self.failUnless((ZP == expectedZP).all()) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 14:41:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 13:41:46 -0600 (CST) Subject: [Scipy-svn] r5006 - in trunk/scipy/cluster: . src tests Message-ID: <20081107194146.8550539C260@scipy.org> Author: damian.eads Date: 2008-11-07 13:41:42 -0600 (Fri, 07 Nov 2008) New Revision: 5006 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/src/common.h trunk/scipy/cluster/src/hierarchy.c trunk/scipy/cluster/src/hierarchy_wrap.c trunk/scipy/cluster/tests/test_hierarchy.py Log: Added tests for from_mlab_linkage function. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 19:02:46 UTC (rev 5005) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 19:41:42 UTC (rev 5006) @@ -1033,7 +1033,7 @@ - ZS : ndarray A linkage matrix compatible with this library. """ - Z = np.asarray(Z, order='c') + Z = np.asarray(Z, dtype=np.double, order='c') Zs = Z.shape # If it's empty, return it. @@ -1047,16 +1047,13 @@ if Zs[0] == 0: return Z.copy() - Zpart = Z[:,0:2] - Zd = Z[:,2].reshape(Zs[0], 1) - if Zpart.min() != 1.0 and Zpart.max() != 2 * Zs[0]: + Zpart = Z.copy() + if Zpart[:, 0:2].min() != 1.0 and Zpart[:, 0:2].max() != 2 * Zs[0]: raise ValueError('The format of the indices is not 1..N'); - CS = np.zeros((Zs[0], 1), dtype=np.double) - Zpart = Zpart - 1 - _hierarchy_wrap.calculate_cluster_sizes_wrap(np.hstack([Zpart, \ - Zd]).copy(), \ - CS, int(Zs[0]) + 1) - return np.hstack([Zpart, Zd, CS]).copy() + Zpart[:, 0:2] -= 1.0 + CS = np.zeros((Zs[0],), dtype=np.double) + _hierarchy_wrap.calculate_cluster_sizes_wrap(Zpart, CS, int(Zs[0]) + 1) + return np.hstack([Zpart, CS.reshape(Zs[0], 1)]) def to_mlab_linkage(Z): """ Modified: trunk/scipy/cluster/src/common.h =================================================================== --- trunk/scipy/cluster/src/common.h 2008-11-07 19:02:46 UTC (rev 5005) +++ trunk/scipy/cluster/src/common.h 2008-11-07 19:41:42 UTC (rev 5006) @@ -60,7 +60,6 @@ ((double)((x)/(y))) ? ((x)/(y)) : ((x)/(y) + 1)) #endif - #ifdef CPY_DEBUG #define CPY_DEBUG_MSG(...) fprintf(stderr, __VA_ARGS__) #else Modified: trunk/scipy/cluster/src/hierarchy.c =================================================================== --- trunk/scipy/cluster/src/hierarchy.c 2008-11-07 19:02:46 UTC (rev 5005) +++ trunk/scipy/cluster/src/hierarchy.c 2008-11-07 19:41:42 UTC (rev 5006) @@ -1067,7 +1067,7 @@ } void calculate_cluster_sizes(const double *Z, double *CS, int n) { - int i, j, k; + int i, j, k, q; const double *row; for (k = 0; k < n - 1; k++) { row = Z + (k * 3); @@ -1075,21 +1075,23 @@ j = (int)row[CPY_LIN_RIGHT]; /** If the left node is a non-singleton, add its count. */ if (i >= n) { - CS[k] = CS[i - n]; + q = i - n; + CS[k] += CS[q]; } /** Otherwise just add 1 for the leaf. */ else { - CS[k] = 1.0; + CS[k] += 1.0; } /** If the right node is a non-singleton, add its count. */ if (j >= n) { - CS[k] = CS[k] + CS[j - n]; + q = j - n; + CS[k] += CS[q]; } /** Otherwise just add 1 for the leaf. */ else { - CS[k] = CS[k] + 1.0; + CS[k] += 1.0; } - /** CPY_DEBUG_MSG("i=%d, j=%d, CS[%d]=%d\n", i, j, n+k, (int)CS[k]);**/ + CPY_DEBUG_MSG("i=%d, j=%d, CS[%d]=%d\n", i, j, k, (int)CS[k]); } } Modified: trunk/scipy/cluster/src/hierarchy_wrap.c =================================================================== --- trunk/scipy/cluster/src/hierarchy_wrap.c 2008-11-07 19:02:46 UTC (rev 5005) +++ trunk/scipy/cluster/src/hierarchy_wrap.c 2008-11-07 19:41:42 UTC (rev 5006) @@ -122,7 +122,7 @@ return 0; } calculate_cluster_sizes((const double*)Z->data, (double*)CS_->data, n); - return Py_BuildValue("d", 0.0); + return Py_BuildValue(""); } extern PyObject *get_max_dist_for_each_cluster_wrap(PyObject *self, Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 19:02:46 UTC (rev 5005) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 19:41:42 UTC (rev 5006) @@ -202,6 +202,20 @@ ZP = from_mlab_linkage(Z) return self.failUnless((ZP == expectedZP).all()) + def test_from_mlab_linkage_multiple_rows(self): + "Testing from_mlab_linkage on linkage array with multiple rows." + Z = np.asarray([[3, 6, 138], [4, 5, 219], + [1, 8, 255], [2, 9, 268], [7, 10, 295]]) + expectedZS = np.array([[ 2., 5., 138., 2.], + [ 3., 4., 219., 2.], + [ 0., 7., 255., 3.], + [ 1., 8., 268., 4.], + [ 6., 9., 295., 6.]], + dtype=np.double) + ZS = from_mlab_linkage(Z) + print expectedZS, ZS + self.failUnless((expectedZS == ZS).all()) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 14:52:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 13:52:57 -0600 (CST) Subject: [Scipy-svn] r5007 - in trunk/scipy/cluster: . tests Message-ID: <20081107195257.5E77C39C260@scipy.org> Author: damian.eads Date: 2008-11-07 13:52:54 -0600 (Fri, 07 Nov 2008) New Revision: 5007 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Added tests for to_mlab_linkage function. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 19:41:42 UTC (rev 5006) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 19:52:54 UTC (rev 5007) @@ -1071,11 +1071,17 @@ A linkage matrix compatible with MATLAB(TM)'s hierarchical clustering functions. """ - Z = np.asarray(Z, order='c') + Z = np.asarray(Z, order='c', dtype=np.double) + Zs = Z.shape + if len(Zs) == 0 or (len(Zs) == 1 and Zs[0] == 0): + return Z.copy() is_valid_linkage(Z, throw=True, name='Z') - return np.hstack([Z[:,0:2] + 1, Z[:,2]]) + ZP = Z[:, 0:3].copy() + ZP[:,0:2] += 1.0 + return ZP + def is_monotonic(Z): """ Returns ``True`` if the linkage passed is monotonic. The linkage Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 19:41:42 UTC (rev 5006) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 19:52:54 UTC (rev 5007) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -216,6 +216,37 @@ print expectedZS, ZS self.failUnless((expectedZS == ZS).all()) + +class TestToMLabLinkage(TestCase): + + def test_to_mlab_linkage_empty(self): + "Testing to_mlab_linkage on empty linkage array." + X = np.asarray([]) + R = to_mlab_linkage([]) + self.failUnless((R == X).all()) + + def test_to_mlab_linkage_single_row(self): + "Testing to_mlab_linkage on linkage array with single row." + Z = np.asarray([[ 0., 1., 3., 2.]]) + expectedZP = np.asarray([[1,2,3]]) + ZP = to_mlab_linkage(Z) + return self.failUnless((ZP == expectedZP).all()) + + def test_from_mlab_linkage_multiple_rows(self): + "Testing to_mlab_linkage on linkage array with multiple rows." + expectedZM = np.asarray([[3, 6, 138], [4, 5, 219], + [1, 8, 255], [2, 9, 268], [7, 10, 295]]) + Z = np.array([[ 2., 5., 138., 2.], + [ 3., 4., 219., 2.], + [ 0., 7., 255., 3.], + [ 1., 8., 268., 4.], + [ 6., 9., 295., 6.]], + dtype=np.double) + ZM = to_mlab_linkage(Z) + print expectedZM, ZM + self.failUnless((expectedZM == ZM).all()) + + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 14:56:30 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 13:56:30 -0600 (CST) Subject: [Scipy-svn] r5008 - trunk/scipy/cluster Message-ID: <20081107195630.4C80E39C260@scipy.org> Author: damian.eads Date: 2008-11-07 13:56:27 -0600 (Fri, 07 Nov 2008) New Revision: 5008 Modified: trunk/scipy/cluster/hierarchy.py Log: Changed cnode classname to ClusterNode to conform to Python class naming standards. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 19:52:54 UTC (rev 5007) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 19:56:27 UTC (rev 5008) @@ -74,7 +74,7 @@ +------------------+-------------------------------------------------+ |*Function* | *Description* | +------------------+-------------------------------------------------+ -|cnode |represents cluster nodes in a cluster hierarchy. | +|ClusterNode |represents cluster nodes in a cluster hierarchy. | +------------------+-------------------------------------------------+ |lvlist |a left-to-right traversal of the leaves. | +------------------+-------------------------------------------------+ @@ -616,7 +616,7 @@ int(_cpy_euclid_methods[method])) return Z -class cnode: +class ClusterNode: """ A tree node class for representing a cluster. Leaf nodes correspond to original observations, while non-leaf nodes correspond to @@ -684,7 +684,7 @@ is a leaf, None is returned. :Returns: - left : cnode + left : ClusterNode The left child of the target node. """ return self.left @@ -695,7 +695,7 @@ is a leaf, None is returned. :Returns: - right : cnode + right : ClusterNode The left child of the target node. """ return self.right @@ -727,7 +727,7 @@ :Parameters: - func : function - Applied to each leaf cnode object in the pre-order + Applied to each leaf ClusterNode object in the pre-order traversal. Given the i'th leaf node in the pre-order traversal ``n[i]``, the result of func(n[i]) is stored in L[i]. If not provided, the index of the original observation @@ -770,19 +770,19 @@ return preorder -_cnode_bare = cnode(0) -_cnode_type = type(cnode) +_cnode_bare = ClusterNode(0) +_cnode_type = type(ClusterNode) def totree(Z, rd=False): """ Converts a hierarchical clustering encoded in the matrix Z (by linkage) into an easy-to-use tree object. The reference r to the - root cnode object is returned. + root ClusterNode object is returned. - Each cnode object has a left, right, dist, id, and count - attribute. The left and right attributes point to cnode objects + Each ClusterNode object has a left, right, dist, id, and count + attribute. The left and right attributes point to ClusterNode objects that were combined to generate the cluster. If both are None then - the cnode object is a leaf node, its count must be 1, and its + the ClusterNode object is a leaf node, its count must be 1, and its distance is meaningless but set to 0. :Parameters: @@ -792,16 +792,16 @@ function documentation). r : bool - When ``False``, a reference to the root cnode object is + When ``False``, a reference to the root ClusterNode object is returned. Otherwise, a tuple (r,d) is returned. ``r`` is a reference to the root node while ``d`` is a dictionary - mapping cluster ids to cnode references. If a cluster id is + mapping cluster ids to ClusterNode references. If a cluster id is less than n, then it corresponds to a singleton cluster (leaf node). See ``linkage`` for more information on the assignment of cluster ids to clusters. Note: This function is provided for the convenience of the library - user. cnodes are not used as input to any of the functions in this + user. ClusterNodes are not used as input to any of the functions in this library. """ @@ -833,7 +833,7 @@ # Create the nodes corresponding to the n original objects. for i in xrange(0, n): - d[i] = cnode(i) + d[i] = ClusterNode(i) nd = None @@ -844,7 +844,7 @@ raise ValueError('Corrupt matrix Z. Index to derivative cluster is used before it is formed. See row %d, column 0' % fi) if fj > i + n: raise ValueError('Corrupt matrix Z. Index to derivative cluster is used before it is formed. See row %d, column 1' % fj) - nd = cnode(i + n, d[fi], d[fj], Z[i, 2]) + nd = ClusterNode(i + n, d[fi], d[fj], Z[i, 2]) # ^ id ^ left ^ right ^ dist if Z[i,3] != nd.count: raise ValueError('Corrupt matrix Z. The count Z[%d,3] is incorrect.' % i) From scipy-svn at scipy.org Fri Nov 7 15:01:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:01:06 -0600 (CST) Subject: [Scipy-svn] r5009 - trunk/scipy/cluster Message-ID: <20081107200106.5635A39C260@scipy.org> Author: damian.eads Date: 2008-11-07 14:00:57 -0600 (Fri, 07 Nov 2008) New Revision: 5009 Modified: trunk/scipy/cluster/hierarchy.py Log: Changed method names in class ClusterNode to conform to Python method naming standards. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 19:56:27 UTC (rev 5008) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 20:00:57 UTC (rev 5009) @@ -649,7 +649,7 @@ else: self.count = left.count + right.count - def getId(self): + def get_id(self): """ The identifier of the target node. For :math:`$0 leq i < n$`, :math:`$i$` corresponds to original observation @@ -665,7 +665,7 @@ """ return self.id - def getCount(self): + def get_count(self): """ The number of leaf nodes (original observations) belonging to the cluster node nd. If the target node is a leaf, 1 is @@ -678,7 +678,7 @@ """ return self.count - def getLeft(self): + def get_left(self): """ Returns a reference to the left child tree object. If the node is a leaf, None is returned. @@ -689,7 +689,7 @@ """ return self.left - def getRight(self): + def get_right(self): """ Returns a reference to the right child tree object. If the node is a leaf, None is returned. @@ -700,7 +700,7 @@ """ return self.right - def isLeaf(self): + def is_leaf(self): """ Returns True iff the target node is a leaf. @@ -710,7 +710,7 @@ """ return self.left is None - def preOrder(self, func=(lambda x: x.id)): + def pre_order(self, func=(lambda x: x.id)): """ Performs preorder traversal without recursive function calls. When a leaf node is first encountered, ``func`` is called with @@ -719,7 +719,7 @@ For example, the statement: - ids = root.preOrder(lambda x: x.id) + ids = root.pre_order(lambda x: x.id) returns a list of the node ids corresponding to the leaf nodes of the tree as they appear from left to right. @@ -751,7 +751,7 @@ while k >= 0: nd = curNode[k] ndid = nd.id - if nd.isLeaf(): + if nd.is_leaf(): preorder.append(func(nd)) k = k - 1 else: @@ -2393,15 +2393,15 @@ return tr def _leader_identify(tr, T): - if tr.isLeaf(): + if tr.is_leaf(): return T[tr.id] else: - left = tr.getLeft() - right = tr.getRight() + left = tr.get_left() + right = tr.get_right() lfid = _leader_identify(left, T) rfid = _leader_identify(right, T) - print 'ndid: %d lid: %d lfid: %d rid: %d rfid: %d' % (tr.getId(), - left.getId(), lfid, right.getId(), rfid) + print 'ndid: %d lid: %d lfid: %d rid: %d rfid: %d' % (tr.get_id(), + left.get_id(), lfid, right.get_id(), rfid) if lfid != rfid: if lfid != -1: print 'leader: %d with tag %d' % (left.id, lfid) @@ -2412,7 +2412,7 @@ return lfid def _leaders_test_recurs_mark(tr, T): - if tr.isLeaf(): + if tr.is_leaf(): tr.asgn = T[tr.id] else: tr.asgn = -1 From scipy-svn at scipy.org Fri Nov 7 15:03:15 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:03:15 -0600 (CST) Subject: [Scipy-svn] r5010 - trunk/scipy/cluster Message-ID: <20081107200315.8979F39C260@scipy.org> Author: damian.eads Date: 2008-11-07 14:03:12 -0600 (Fri, 07 Nov 2008) New Revision: 5010 Modified: trunk/scipy/cluster/hierarchy.py Log: Changed some function names to conform to standards and to be more explicit. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 20:00:57 UTC (rev 5009) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 20:03:12 UTC (rev 5010) @@ -76,9 +76,9 @@ +------------------+-------------------------------------------------+ |ClusterNode |represents cluster nodes in a cluster hierarchy. | +------------------+-------------------------------------------------+ -|lvlist |a left-to-right traversal of the leaves. | +|leaves_list |a left-to-right traversal of the leaves. | +------------------+-------------------------------------------------+ -|totree |represents a linkage matrix as a tree object. | +|to_tree |represents a linkage matrix as a tree object. | +------------------+-------------------------------------------------+ These are predicates for checking the validity of linkage and @@ -622,12 +622,12 @@ to original observations, while non-leaf nodes correspond to non-singleton clusters. - The totree function converts a matrix returned by the linkage + The to_tree function converts a matrix returned by the linkage function into an easy-to-use tree representation. :SeeAlso: - - totree: for converting a linkage matrix Z into a tree object. + - to_tree: for converting a linkage matrix Z into a tree object. """ def __init__(self, id, left=None, right=None, dist=0, count=1): @@ -773,7 +773,7 @@ _cnode_bare = ClusterNode(0) _cnode_type = type(ClusterNode) -def totree(Z, rd=False): +def to_tree(Z, rd=False): """ Converts a hierarchical clustering encoded in the matrix Z (by linkage) into an easy-to-use tree object. The reference r to the @@ -1436,9 +1436,9 @@ T = fcluster(Z, criterion=criterion, depth=depth, R=R, t=t) return T -def lvlist(Z): +def leaves_list(Z): """ - L = lvlist(Z): + L = leaves_list(Z): Returns a list of leaf node ids as they appear in the tree from left to right. Z is a linkage matrix. @@ -2388,7 +2388,7 @@ # These are test functions to help me test the leaders function. def _leaders_test(Z, T): - tr = totree(Z) + tr = to_tree(Z) _leaders_test_recurs_mark(tr, T) return tr From scipy-svn at scipy.org Fri Nov 7 15:45:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:45:06 -0600 (CST) Subject: [Scipy-svn] r5011 - in trunk/scipy/cluster: . tests Message-ID: <20081107204506.03F6139C260@scipy.org> Author: damian.eads Date: 2008-11-07 14:45:02 -0600 (Fri, 07 Nov 2008) New Revision: 5011 Added: trunk/scipy/cluster/tests/fclusterdata-X.txt trunk/scipy/cluster/tests/fclusterdata-maxclusts-3.txt Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Added data files for new tests. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-07 20:03:12 UTC (rev 5010) +++ trunk/scipy/cluster/hierarchy.py 2008-11-07 20:45:02 UTC (rev 5011) @@ -1374,7 +1374,7 @@ return T def fclusterdata(X, t, criterion='inconsistent', \ - distance='euclid', depth=2, method='single', R=None): + metric='euclidean', depth=2, method='single', R=None): """ T = fclusterdata(X, t) @@ -1390,7 +1390,7 @@ observation i belongs. T = fclusterdata(X, t, criterion='inconsistent', method='single', - distance='euclid', depth=2, R=None) + metric='euclid', depth=2, R=None) Clusters the original observations in the n by m data matrix X using the thresholding criterion, linkage method, and distance metric @@ -1406,7 +1406,7 @@ method: the linkage method to use. See linkage for descriptions. - distance: the distance metric for calculating pairwise + metric: the distance metric for calculating pairwise distances. See distance.pdist for descriptions and linkage to verify compatibility with the linkage method. @@ -1422,12 +1422,12 @@ This function is similar to MATLAB(TM) clusterdata function. """ - X = np.asarray(X, order='c') + X = np.asarray(X, order='c', dtype=np.double) if type(X) != np.ndarray or len(X.shape) != 2: raise TypeError('The observation matrix X must be an n by m numpy array.') - Y = distance.pdist(X, metric=distance) + Y = distance.pdist(X, metric=metric) Z = linkage(Y, method=method) if R is None: R = inconsistent(Z, d=depth) Added: trunk/scipy/cluster/tests/fclusterdata-X.txt =================================================================== --- trunk/scipy/cluster/tests/fclusterdata-X.txt 2008-11-07 20:03:12 UTC (rev 5010) +++ trunk/scipy/cluster/tests/fclusterdata-X.txt 2008-11-07 20:45:02 UTC (rev 5011) @@ -0,0 +1,30 @@ + 5.2656366e-01 3.1416019e-01 8.0065637e-02 + 7.5020518e-01 4.6029983e-01 8.9869646e-01 + 6.6546123e-01 6.9401142e-01 9.1046570e-01 + 9.6404759e-01 1.4308220e-03 7.3987422e-01 + 1.0815906e-01 5.5302879e-01 6.6380478e-02 + 9.3135913e-01 8.2542491e-01 9.5231544e-01 + 6.7808696e-01 3.4190397e-01 5.6148195e-01 + 9.8273094e-01 7.0460521e-01 8.7097863e-02 + 6.1469161e-01 4.6998923e-02 6.0240645e-01 + 5.8016126e-01 9.1735497e-01 5.8816385e-01 + 1.3824631e+00 1.9635816e+00 1.9443788e+00 + 2.1067586e+00 1.6714873e+00 1.3485448e+00 + 1.3988007e+00 1.6614205e+00 1.3222455e+00 + 1.7141046e+00 1.4917638e+00 1.4543217e+00 + 1.5410234e+00 1.8437495e+00 1.6465895e+00 + 2.0851248e+00 1.8452435e+00 2.1734085e+00 + 1.3074874e+00 1.5380165e+00 2.1600774e+00 + 1.4144770e+00 1.9932907e+00 1.9910742e+00 + 1.6194349e+00 1.4770328e+00 1.8978816e+00 + 1.5988060e+00 1.5498898e+00 1.5756335e+00 + 3.3724738e+00 2.6963531e+00 3.3998170e+00 + 3.1370512e+00 3.3652809e+00 3.0608907e+00 + 3.2941325e+00 3.1961950e+00 2.9070017e+00 + 2.6551051e+00 3.0678590e+00 2.9719854e+00 + 3.3094104e+00 2.5928397e+00 2.5771411e+00 + 2.5955722e+00 3.3347737e+00 3.0879319e+00 + 2.5820618e+00 3.4161567e+00 3.2644199e+00 + 2.7112700e+00 2.7703245e+00 2.6346650e+00 + 2.7961785e+00 3.2547372e+00 3.4180156e+00 + 2.6474175e+00 2.5453804e+00 3.2535411e+00 Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-3.txt =================================================================== --- trunk/scipy/cluster/tests/fclusterdata-maxclusts-3.txt 2008-11-07 20:03:12 UTC (rev 5010) +++ trunk/scipy/cluster/tests/fclusterdata-maxclusts-3.txt 2008-11-07 20:45:02 UTC (rev 5011) @@ -0,0 +1,30 @@ + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:03:12 UTC (rev 5010) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:45:02 UTC (rev 5011) @@ -54,6 +54,7 @@ eo = {} _filenames = ["iris.txt", + "mlab-random.txt", "linkage-single-tdist.txt", "linkage-complete-tdist.txt", "linkage-average-tdist.txt", @@ -246,7 +247,12 @@ print expectedZM, ZM self.failUnless((expectedZM == ZM).all()) +class TestFcluster(TestCase): + def test_fcluster(self): + "Tests fclusterdata with 'maxclusts' criterion with maxclusts=3." + + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 15:48:41 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:48:41 -0600 (CST) Subject: [Scipy-svn] r5012 - trunk/scipy/cluster/tests Message-ID: <20081107204841.8F4E039C661@scipy.org> Author: damian.eads Date: 2008-11-07 14:48:38 -0600 (Fri, 07 Nov 2008) New Revision: 5012 Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt Log: Added data files for new tests. Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt =================================================================== (Binary files differ) Property changes on: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt =================================================================== (Binary files differ) Property changes on: trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt ___________________________________________________________________ Name: svn:mime-type + application/octet-stream From scipy-svn at scipy.org Fri Nov 7 15:49:24 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:49:24 -0600 (CST) Subject: [Scipy-svn] r5013 - trunk/scipy/cluster/tests Message-ID: <20081107204924.DCC0F39C663@scipy.org> Author: damian.eads Date: 2008-11-07 14:49:18 -0600 (Fri, 07 Nov 2008) New Revision: 5013 Removed: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt Log: Need to unbinarify them first. Deleted: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt =================================================================== (Binary files differ) Deleted: trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt =================================================================== (Binary files differ) From scipy-svn at scipy.org Fri Nov 7 15:57:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:57:53 -0600 (CST) Subject: [Scipy-svn] r5014 - trunk/scipy/cluster/tests Message-ID: <20081107205753.41330C7C006@scipy.org> Author: damian.eads Date: 2008-11-07 14:57:48 -0600 (Fri, 07 Nov 2008) New Revision: 5014 Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added data files for new tests. Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt =================================================================== --- trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt 2008-11-07 20:49:18 UTC (rev 5013) +++ trunk/scipy/cluster/tests/fclusterdata-maxclusts-2.txt 2008-11-07 20:57:48 UTC (rev 5014) @@ -0,0 +1,30 @@ + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 + 1.0000000e+00 Added: trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt =================================================================== --- trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt 2008-11-07 20:49:18 UTC (rev 5013) +++ trunk/scipy/cluster/tests/fclusterdata-maxclusts-4.txt 2008-11-07 20:57:48 UTC (rev 5014) @@ -0,0 +1,30 @@ + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 3.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 4.0000000e+00 + 1.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 + 2.0000000e+00 Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:49:18 UTC (rev 5013) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:57:48 UTC (rev 5014) @@ -54,7 +54,10 @@ eo = {} _filenames = ["iris.txt", - "mlab-random.txt", + "fclusterdata-X.txt", + "fclusterdata-maxclusts-1.txt", + "fclusterdata-maxclusts-2.txt", + "fclusterdata-maxclusts-3.txt", "linkage-single-tdist.txt", "linkage-complete-tdist.txt", "linkage-average-tdist.txt", @@ -249,10 +252,12 @@ class TestFcluster(TestCase): - def test_fcluster(self): + def test_fclusterdata_maxclusts_3(self): "Tests fclusterdata with 'maxclusts' criterion with maxclusts=3." + expectedT = eo['fclusterdata-maxclusts-3'] + T = hi.fcluster(Z, criterion='maxclust', t=3) + self.failUnless((expectedT == T).all()) - def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 15:59:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 14:59:03 -0600 (CST) Subject: [Scipy-svn] r5015 - trunk/scipy/cluster/tests Message-ID: <20081107205903.AAB8539C343@scipy.org> Author: damian.eads Date: 2008-11-07 14:58:53 -0600 (Fri, 07 Nov 2008) New Revision: 5015 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Tweak on a test. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:57:48 UTC (rev 5014) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:58:53 UTC (rev 5015) @@ -55,9 +55,9 @@ _filenames = ["iris.txt", "fclusterdata-X.txt", - "fclusterdata-maxclusts-1.txt", "fclusterdata-maxclusts-2.txt", "fclusterdata-maxclusts-3.txt", + "fclusterdata-maxclusts-4.txt", "linkage-single-tdist.txt", "linkage-complete-tdist.txt", "linkage-average-tdist.txt", From scipy-svn at scipy.org Fri Nov 7 16:05:05 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 15:05:05 -0600 (CST) Subject: [Scipy-svn] r5016 - trunk/scipy/cluster/tests Message-ID: <20081107210505.1ACF939C343@scipy.org> Author: damian.eads Date: 2008-11-07 15:05:03 -0600 (Fri, 07 Nov 2008) New Revision: 5016 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added more tests for fclusterdata. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 20:58:53 UTC (rev 5015) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:05:03 UTC (rev 5016) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, is_isomorphic from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -252,12 +252,27 @@ class TestFcluster(TestCase): + def test_fclusterdata_maxclusts_2(self): + "Tests fclusterdata with 'maxclusts' criterion with maxclusts=2 with a random data set consisting of three clusters." + expectedT = eo['fclusterdata-maxclusts-2'] + X = eo['fclusterdata-X'] + T = fclusterdata(X, criterion='maxclust', t=2) + self.failUnless(is_isomorphic(T, expectedT)) + def test_fclusterdata_maxclusts_3(self): - "Tests fclusterdata with 'maxclusts' criterion with maxclusts=3." + "Tests fclusterdata with 'maxclusts' criterion with maxclusts=3 with a random data set consisting of three clusters." expectedT = eo['fclusterdata-maxclusts-3'] - T = hi.fcluster(Z, criterion='maxclust', t=3) - self.failUnless((expectedT == T).all()) + X = eo['fclusterdata-X'] + T = fclusterdata(X, criterion='maxclust', t=3) + self.failUnless(is_isomorphic(T, expectedT)) + def test_fclusterdata_maxclusts_4(self): + "Tests fclusterdata with 'maxclusts' criterion with maxclusts=4 with a random data set consisting of three clusters." + expectedT = eo['fclusterdata-maxclusts-4'] + X = eo['fclusterdata-X'] + T = fclusterdata(X, criterion='maxclust', t=4) + self.failUnless(is_isomorphic(T, expectedT)) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 16:26:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 15:26:10 -0600 (CST) Subject: [Scipy-svn] r5017 - trunk/scipy/cluster/tests Message-ID: <20081107212610.223B839C226@scipy.org> Author: damian.eads Date: 2008-11-07 15:26:07 -0600 (Fri, 07 Nov 2008) New Revision: 5017 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added tests for fcluster. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:05:03 UTC (rev 5016) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:26:07 UTC (rev 5017) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, is_isomorphic +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -253,26 +253,53 @@ class TestFcluster(TestCase): def test_fclusterdata_maxclusts_2(self): - "Tests fclusterdata with 'maxclusts' criterion with maxclusts=2 with a random data set consisting of three clusters." + "Tests fclusterdata(X, criterion='maxclust', t=2) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-2'] X = eo['fclusterdata-X'] T = fclusterdata(X, criterion='maxclust', t=2) self.failUnless(is_isomorphic(T, expectedT)) def test_fclusterdata_maxclusts_3(self): - "Tests fclusterdata with 'maxclusts' criterion with maxclusts=3 with a random data set consisting of three clusters." + "Tests fclusterdata(X, criterion='maxclust', t=3) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-3'] X = eo['fclusterdata-X'] T = fclusterdata(X, criterion='maxclust', t=3) self.failUnless(is_isomorphic(T, expectedT)) def test_fclusterdata_maxclusts_4(self): - "Tests fclusterdata with 'maxclusts' criterion with maxclusts=4 with a random data set consisting of three clusters." + "Tests fclusterdata(X, criterion='maxclust', t=4) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-4'] X = eo['fclusterdata-X'] T = fclusterdata(X, criterion='maxclust', t=4) self.failUnless(is_isomorphic(T, expectedT)) + def test_fcluster_maxclusts_2(self): + "Tests fcluster(Z, criterion='maxclust', t=2) on a random 3-cluster data set." + expectedT = eo['fclusterdata-maxclusts-2'] + X = eo['fclusterdata-X'] + Y = pdist(X) + Z = linkage(Y) + T = fcluster(Z, criterion='maxclust', t=2) + self.failUnless(is_isomorphic(T, expectedT)) + + def test_fcluster_maxclusts_3(self): + "Tests fcluster(Z, criterion='maxclust', t=3) on a random 3-cluster data set." + expectedT = eo['fclusterdata-maxclusts-3'] + X = eo['fclusterdata-X'] + Y = pdist(X) + Z = linkage(Y) + T = fcluster(Z, criterion='maxclust', t=3) + self.failUnless(is_isomorphic(T, expectedT)) + + def test_fcluster_maxclusts_4(self): + "Tests fcluster(Z, criterion='maxclust', t=4) on a random 3-cluster data set." + expectedT = eo['fclusterdata-maxclusts-4'] + X = eo['fclusterdata-X'] + Y = pdist(X) + Z = linkage(Y) + T = fcluster(Z, criterion='maxclust', t=4) + self.failUnless(is_isomorphic(T, expectedT)) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 16:49:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 15:49:56 -0600 (CST) Subject: [Scipy-svn] r5018 - trunk/scipy/cluster/tests Message-ID: <20081107214956.26CF039C1AE@scipy.org> Author: damian.eads Date: 2008-11-07 15:48:41 -0600 (Fri, 07 Nov 2008) New Revision: 5018 Added: trunk/scipy/cluster/tests/linkage-Q-average.txt trunk/scipy/cluster/tests/linkage-Q-centroid.txt trunk/scipy/cluster/tests/linkage-Q-complete.txt trunk/scipy/cluster/tests/linkage-Q-median.txt trunk/scipy/cluster/tests/linkage-Q-single.txt trunk/scipy/cluster/tests/linkage-Q-ward.txt trunk/scipy/cluster/tests/linkage-Q-weighted.txt Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added more tests for linkage functions. Added: trunk/scipy/cluster/tests/linkage-Q-average.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-average.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-average.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 2.9000000e+01 3.3000000e+01 3.5174379e-01 + 6.0000000e+00 3.4000000e+01 3.5532162e-01 + 1.3000000e+01 3.2000000e+01 3.6158453e-01 + 1.5000000e+01 3.1000000e+01 3.7715616e-01 + 1.7000000e+01 1.9000000e+01 4.1203984e-01 + 2.4000000e+01 3.7000000e+01 4.2046824e-01 + 4.0000000e+00 3.6000000e+01 4.2863303e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 1.0000000e+01 3.8000000e+01 4.9787637e-01 + 4.0000000e+01 4.1000000e+01 5.2994677e-01 + 1.2000000e+01 3.9000000e+01 5.7421684e-01 + 2.5000000e+01 2.8000000e+01 6.2656347e-01 + 3.5000000e+01 4.2000000e+01 6.4347240e-01 + 4.6000000e+01 4.7000000e+01 6.8297315e-01 + 4.3000000e+01 4.5000000e+01 6.9186391e-01 + 8.0000000e+00 4.4000000e+01 7.4416964e-01 + 2.1000000e+01 3.0000000e+01 7.5491453e-01 + 1.6000000e+01 5.0000000e+01 8.1859847e-01 + 4.9000000e+01 5.3000000e+01 8.5939683e-01 + 5.1000000e+01 5.2000000e+01 8.7992146e-01 + 4.8000000e+01 5.5000000e+01 8.9017230e-01 + 5.4000000e+01 5.6000000e+01 2.0198221e+00 + 5.7000000e+01 5.8000000e+01 3.2920100e+00 Added: trunk/scipy/cluster/tests/linkage-Q-centroid.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-centroid.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-centroid.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 6.0000000e+00 3.4000000e+01 3.3746118e-01 + 2.9000000e+01 3.3000000e+01 3.4067653e-01 + 1.3000000e+01 3.2000000e+01 3.5113828e-01 + 1.5000000e+01 3.9000000e+01 3.3976558e-01 + 2.4000000e+01 3.8000000e+01 3.9064620e-01 + 4.0000000e+00 3.6000000e+01 4.0386341e-01 + 1.7000000e+01 1.9000000e+01 4.1203984e-01 + 1.0000000e+01 3.7000000e+01 4.6647208e-01 + 3.1000000e+01 4.3000000e+01 4.7930518e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 4.0000000e+01 4.5000000e+01 5.2671920e-01 + 3.5000000e+01 4.1000000e+01 5.9378517e-01 + 2.5000000e+01 2.8000000e+01 6.2656347e-01 + 4.2000000e+01 4.4000000e+01 6.2815954e-01 + 8.0000000e+00 4.6000000e+01 7.1857916e-01 + 5.0000000e+01 5.1000000e+01 7.0424537e-01 + 1.2000000e+01 4.7000000e+01 7.2968219e-01 + 1.6000000e+01 5.3000000e+01 7.1788349e-01 + 3.0000000e+01 4.9000000e+01 7.5478395e-01 + 4.8000000e+01 5.5000000e+01 7.0355234e-01 + 2.1000000e+01 5.6000000e+01 7.3561818e-01 + 5.2000000e+01 5.4000000e+01 1.9510405e+00 + 5.7000000e+01 5.8000000e+01 3.2347576e+00 Added: trunk/scipy/cluster/tests/linkage-Q-complete.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-complete.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-complete.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 1.3000000e+01 3.2000000e+01 3.8163338e-01 + 2.9000000e+01 3.3000000e+01 3.9446675e-01 + 1.5000000e+01 3.1000000e+01 3.9629062e-01 + 6.0000000e+00 3.4000000e+01 4.1110592e-01 + 1.7000000e+01 1.9000000e+01 4.1203984e-01 + 2.4000000e+01 2.8000000e+01 4.5328393e-01 + 4.0000000e+00 3.6000000e+01 4.7908167e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 1.0000000e+01 4.0000000e+01 5.7813912e-01 + 3.9000000e+01 4.1000000e+01 6.4162409e-01 + 3.0000000e+01 4.2000000e+01 6.6157735e-01 + 1.2000000e+01 3.7000000e+01 7.0851770e-01 + 2.1000000e+01 3.5000000e+01 7.8597665e-01 + 1.6000000e+01 4.6000000e+01 8.3623329e-01 + 8.0000000e+00 4.5000000e+01 8.8244371e-01 + 3.8000000e+01 4.7000000e+01 9.2493420e-01 + 2.5000000e+01 4.9000000e+01 9.2757043e-01 + 4.3000000e+01 5.1000000e+01 1.0046401e+00 + 4.8000000e+01 5.0000000e+01 1.1468365e+00 + 4.4000000e+01 5.4000000e+01 1.2396527e+00 + 5.2000000e+01 5.3000000e+01 1.2958546e+00 + 5.5000000e+01 5.7000000e+01 3.0467645e+00 + 5.6000000e+01 5.8000000e+01 5.1343343e+00 Added: trunk/scipy/cluster/tests/linkage-Q-median.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-median.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-median.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 6.0000000e+00 3.4000000e+01 3.3746118e-01 + 2.9000000e+01 3.3000000e+01 3.4067653e-01 + 1.3000000e+01 3.2000000e+01 3.5113828e-01 + 1.5000000e+01 3.9000000e+01 3.4054836e-01 + 4.0000000e+00 3.6000000e+01 4.0386341e-01 + 2.4000000e+01 3.8000000e+01 4.1015077e-01 + 1.7000000e+01 1.9000000e+01 4.1203984e-01 + 1.0000000e+01 3.7000000e+01 4.6883527e-01 + 3.1000000e+01 4.3000000e+01 4.7930518e-01 + 4.0000000e+01 4.5000000e+01 4.7776681e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 3.5000000e+01 4.2000000e+01 5.6937028e-01 + 2.5000000e+01 2.8000000e+01 6.2656347e-01 + 8.0000000e+00 4.7000000e+01 7.1857916e-01 + 4.8000000e+01 4.9000000e+01 7.1925426e-01 + 3.0000000e+01 5.1000000e+01 6.7611684e-01 + 2.1000000e+01 5.2000000e+01 6.6632819e-01 + 4.4000000e+01 5.0000000e+01 7.2115997e-01 + 4.1000000e+01 5.4000000e+01 6.5190047e-01 + 1.6000000e+01 4.6000000e+01 7.3662916e-01 + 1.2000000e+01 5.6000000e+01 7.0941723e-01 + 5.5000000e+01 5.7000000e+01 2.1188553e+00 + 5.3000000e+01 5.8000000e+01 3.2138035e+00 Added: trunk/scipy/cluster/tests/linkage-Q-single.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-single.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-single.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 2.4000000e+01 3.3000000e+01 2.9703742e-01 + 6.0000000e+00 3.4000000e+01 2.9953732e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 1.5000000e+01 3.2000000e+01 3.0777762e-01 + 2.9000000e+01 3.6000000e+01 3.0902082e-01 + 1.9000000e+01 3.9000000e+01 3.3102505e-01 + 1.3000000e+01 4.1000000e+01 3.4153568e-01 + 3.1000000e+01 4.2000000e+01 3.5802170e-01 + 3.7000000e+01 3.8000000e+01 3.6459874e-01 + 4.0000000e+00 4.4000000e+01 3.7818440e-01 + 1.0000000e+01 4.5000000e+01 4.0129405e-01 + 1.7000000e+01 4.3000000e+01 4.1203984e-01 + 1.2000000e+01 4.7000000e+01 4.4459698e-01 + 2.8000000e+01 4.0000000e+01 4.5328393e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 4.6000000e+01 5.0000000e+01 5.0546088e-01 + 3.5000000e+01 4.9000000e+01 5.0591731e-01 + 3.0000000e+01 5.2000000e+01 5.9356257e-01 + 8.0000000e+00 5.1000000e+01 6.0048760e-01 + 2.5000000e+01 5.3000000e+01 6.2656347e-01 + 1.6000000e+01 4.8000000e+01 6.5449319e-01 + 2.1000000e+01 5.5000000e+01 7.0629051e-01 + 5.4000000e+01 5.6000000e+01 1.0267612e+00 + 5.7000000e+01 5.8000000e+01 1.2085488e+00 Added: trunk/scipy/cluster/tests/linkage-Q-ward.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-ward.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-ward.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 6.0000000e+00 3.4000000e+01 3.8966661e-01 + 2.9000000e+01 3.3000000e+01 3.9337938e-01 + 1.3000000e+01 1.5000000e+01 3.9833425e-01 + 1.7000000e+01 1.9000000e+01 4.1203984e-01 + 3.2000000e+01 3.9000000e+01 4.2295183e-01 + 2.4000000e+01 2.8000000e+01 4.5328393e-01 + 4.0000000e+00 3.6000000e+01 4.6634129e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 1.0000000e+01 3.7000000e+01 5.7130929e-01 + 3.0000000e+01 4.2000000e+01 6.7688894e-01 + 3.1000000e+01 4.0000000e+01 6.7783989e-01 + 1.2000000e+01 4.1000000e+01 7.1501676e-01 + 8.0000000e+00 4.4000000e+01 8.2974374e-01 + 2.1000000e+01 2.5000000e+01 8.3155740e-01 + 1.6000000e+01 4.7000000e+01 8.6628075e-01 + 3.5000000e+01 5.0000000e+01 9.1696168e-01 + 3.8000000e+01 4.6000000e+01 1.0741259e+00 + 4.3000000e+01 4.5000000e+01 1.1631255e+00 + 4.8000000e+01 5.1000000e+01 1.3123400e+00 + 5.2000000e+01 5.3000000e+01 1.3876562e+00 + 4.9000000e+01 5.4000000e+01 1.4432735e+00 + 5.5000000e+01 5.7000000e+01 6.1697318e+00 + 5.6000000e+01 5.8000000e+01 1.1811665e+01 Added: trunk/scipy/cluster/tests/linkage-Q-weighted.txt =================================================================== --- trunk/scipy/cluster/tests/linkage-Q-weighted.txt 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/linkage-Q-weighted.txt 2008-11-07 21:48:41 UTC (rev 5018) @@ -0,0 +1,29 @@ + 1.1000000e+01 1.8000000e+01 6.3937355e-02 + 1.4000000e+01 2.0000000e+01 1.7716924e-01 + 2.6000000e+01 2.7000000e+01 1.9481726e-01 + 2.0000000e+00 3.0000000e+00 2.4887981e-01 + 2.2000000e+01 2.3000000e+01 2.7739218e-01 + 7.0000000e+00 9.0000000e+00 3.0440560e-01 + 2.9000000e+01 3.3000000e+01 3.5174379e-01 + 6.0000000e+00 3.4000000e+01 3.5532162e-01 + 1.3000000e+01 3.2000000e+01 3.6158453e-01 + 1.5000000e+01 3.1000000e+01 3.7715616e-01 + 1.7000000e+01 1.9000000e+01 4.1203984e-01 + 4.0000000e+00 3.6000000e+01 4.2863303e-01 + 2.4000000e+01 3.7000000e+01 4.4128967e-01 + 1.0000000e+00 5.0000000e+00 4.8198330e-01 + 1.0000000e+01 3.8000000e+01 5.0195626e-01 + 4.0000000e+01 4.1000000e+01 5.3409020e-01 + 3.9000000e+01 4.6000000e+01 6.0088461e-01 + 2.5000000e+01 2.8000000e+01 6.2656347e-01 + 3.5000000e+01 4.3000000e+01 6.2840379e-01 + 8.0000000e+00 4.4000000e+01 7.4416964e-01 + 1.2000000e+01 4.7000000e+01 7.4874549e-01 + 2.1000000e+01 3.0000000e+01 7.5491453e-01 + 4.2000000e+01 4.5000000e+01 7.8567175e-01 + 4.8000000e+01 4.9000000e+01 8.3312410e-01 + 5.2000000e+01 5.4000000e+01 8.4939549e-01 + 1.6000000e+01 5.1000000e+01 8.5308187e-01 + 5.0000000e+01 5.3000000e+01 8.6159523e-01 + 5.5000000e+01 5.6000000e+01 1.9999532e+00 + 5.7000000e+01 5.8000000e+01 3.2929087e+00 Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:26:07 UTC (rev 5017) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:48:41 UTC (rev 5018) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -76,7 +76,15 @@ "inconsistent-weighted-tdist-depth-1.txt", "inconsistent-weighted-tdist-depth-2.txt", "inconsistent-weighted-tdist-depth-3.txt", - "inconsistent-weighted-tdist-depth-4.txt"] + "inconsistent-weighted-tdist-depth-4.txt", + "linkage-Q-average.txt", + "linkage-Q-complete.txt", + "linkage-Q-single.txt", + "linkage-Q-weighted.txt", + "linkage-Q-centroid.txt", + "linkage-Q-median.txt", + "linkage-Q-ward.txt" + ] def load_testing_files(): for fn in _filenames: @@ -156,6 +164,47 @@ #print Z, expectedZ, np.abs(Z - expectedZ).max() self.failUnless(within_tol(Z, expectedZ, eps)) + ################### linkage on Q + def test_linkage_single_q(self): + "Tests linkage(Y, 'single') on the Q data set." + X = eo['fclusterdata-X'] + Z = single(X) + Zmlab = eo['linkage-Q-single'] + eps = 1e-06 + expectedZ = from_mlab_linkage(Zmlab) + print abs(Z-expectedZ).max() + self.failUnless(within_tol(Z, expectedZ, eps)) + + def test_linkage_complete_q(self): + "Tests linkage(Y, 'complete') on the Q data set." + X = eo['fclusterdata-X'] + Z = complete(X) + Zmlab = eo['linkage-Q-complete'] + eps = 1e-07 + expectedZ = from_mlab_linkage(Zmlab) + print abs(Z-expectedZ).max() + self.failUnless(within_tol(Z, expectedZ, eps)) + + def test_linkage_centroid_q(self): + "Tests linkage(Y, 'centroid') on the Q data set." + X = eo['fclusterdata-X'] + Z = centroid(X) + Zmlab = eo['linkage-Q-centroid'] + eps = 1e-07 + expectedZ = from_mlab_linkage(Zmlab) + print abs(Z-expectedZ).max() + self.failUnless(within_tol(Z, expectedZ, eps)) + + def test_linkage_weighted_q(self): + "Tests linkage(Y, 'weighted') on the Q data set." + X = eo['fclusterdata-X'] + Z = weighted(X) + Zmlab = eo['linkage-Q-weighted'] + eps = 1e-07 + expectedZ = from_mlab_linkage(Zmlab) + print abs(Z-expectedZ).max() + self.failUnless(within_tol(Z, expectedZ, eps)) + class TestInconsistent(TestCase): def test_single_inconsistent_tdist(self): From scipy-svn at scipy.org Fri Nov 7 16:52:07 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 15:52:07 -0600 (CST) Subject: [Scipy-svn] r5019 - trunk/scipy/cluster/tests Message-ID: <20081107215207.6E3B539C1AE@scipy.org> Author: damian.eads Date: 2008-11-07 15:52:04 -0600 (Fri, 07 Nov 2008) New Revision: 5019 Added: trunk/scipy/cluster/tests/Q-X.txt Removed: trunk/scipy/cluster/tests/fclusterdata-X.txt Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Renamed test data file because its use is more generic than just testing flat clustering. Copied: trunk/scipy/cluster/tests/Q-X.txt (from rev 5011, trunk/scipy/cluster/tests/fclusterdata-X.txt) Deleted: trunk/scipy/cluster/tests/fclusterdata-X.txt =================================================================== --- trunk/scipy/cluster/tests/fclusterdata-X.txt 2008-11-07 21:48:41 UTC (rev 5018) +++ trunk/scipy/cluster/tests/fclusterdata-X.txt 2008-11-07 21:52:04 UTC (rev 5019) @@ -1,30 +0,0 @@ - 5.2656366e-01 3.1416019e-01 8.0065637e-02 - 7.5020518e-01 4.6029983e-01 8.9869646e-01 - 6.6546123e-01 6.9401142e-01 9.1046570e-01 - 9.6404759e-01 1.4308220e-03 7.3987422e-01 - 1.0815906e-01 5.5302879e-01 6.6380478e-02 - 9.3135913e-01 8.2542491e-01 9.5231544e-01 - 6.7808696e-01 3.4190397e-01 5.6148195e-01 - 9.8273094e-01 7.0460521e-01 8.7097863e-02 - 6.1469161e-01 4.6998923e-02 6.0240645e-01 - 5.8016126e-01 9.1735497e-01 5.8816385e-01 - 1.3824631e+00 1.9635816e+00 1.9443788e+00 - 2.1067586e+00 1.6714873e+00 1.3485448e+00 - 1.3988007e+00 1.6614205e+00 1.3222455e+00 - 1.7141046e+00 1.4917638e+00 1.4543217e+00 - 1.5410234e+00 1.8437495e+00 1.6465895e+00 - 2.0851248e+00 1.8452435e+00 2.1734085e+00 - 1.3074874e+00 1.5380165e+00 2.1600774e+00 - 1.4144770e+00 1.9932907e+00 1.9910742e+00 - 1.6194349e+00 1.4770328e+00 1.8978816e+00 - 1.5988060e+00 1.5498898e+00 1.5756335e+00 - 3.3724738e+00 2.6963531e+00 3.3998170e+00 - 3.1370512e+00 3.3652809e+00 3.0608907e+00 - 3.2941325e+00 3.1961950e+00 2.9070017e+00 - 2.6551051e+00 3.0678590e+00 2.9719854e+00 - 3.3094104e+00 2.5928397e+00 2.5771411e+00 - 2.5955722e+00 3.3347737e+00 3.0879319e+00 - 2.5820618e+00 3.4161567e+00 3.2644199e+00 - 2.7112700e+00 2.7703245e+00 2.6346650e+00 - 2.7961785e+00 3.2547372e+00 3.4180156e+00 - 2.6474175e+00 2.5453804e+00 3.2535411e+00 Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:48:41 UTC (rev 5018) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:52:04 UTC (rev 5019) @@ -54,7 +54,7 @@ eo = {} _filenames = ["iris.txt", - "fclusterdata-X.txt", + "Q-X.txt", "fclusterdata-maxclusts-2.txt", "fclusterdata-maxclusts-3.txt", "fclusterdata-maxclusts-4.txt", @@ -167,7 +167,7 @@ ################### linkage on Q def test_linkage_single_q(self): "Tests linkage(Y, 'single') on the Q data set." - X = eo['fclusterdata-X'] + X = eo['Q-X'] Z = single(X) Zmlab = eo['linkage-Q-single'] eps = 1e-06 @@ -177,7 +177,7 @@ def test_linkage_complete_q(self): "Tests linkage(Y, 'complete') on the Q data set." - X = eo['fclusterdata-X'] + X = eo['Q-X'] Z = complete(X) Zmlab = eo['linkage-Q-complete'] eps = 1e-07 @@ -187,7 +187,7 @@ def test_linkage_centroid_q(self): "Tests linkage(Y, 'centroid') on the Q data set." - X = eo['fclusterdata-X'] + X = eo['Q-X'] Z = centroid(X) Zmlab = eo['linkage-Q-centroid'] eps = 1e-07 @@ -197,7 +197,7 @@ def test_linkage_weighted_q(self): "Tests linkage(Y, 'weighted') on the Q data set." - X = eo['fclusterdata-X'] + X = eo['Q-X'] Z = weighted(X) Zmlab = eo['linkage-Q-weighted'] eps = 1e-07 @@ -304,28 +304,28 @@ def test_fclusterdata_maxclusts_2(self): "Tests fclusterdata(X, criterion='maxclust', t=2) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-2'] - X = eo['fclusterdata-X'] + X = eo['Q-X'] T = fclusterdata(X, criterion='maxclust', t=2) self.failUnless(is_isomorphic(T, expectedT)) def test_fclusterdata_maxclusts_3(self): "Tests fclusterdata(X, criterion='maxclust', t=3) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-3'] - X = eo['fclusterdata-X'] + X = eo['Q-X'] T = fclusterdata(X, criterion='maxclust', t=3) self.failUnless(is_isomorphic(T, expectedT)) def test_fclusterdata_maxclusts_4(self): "Tests fclusterdata(X, criterion='maxclust', t=4) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-4'] - X = eo['fclusterdata-X'] + X = eo['Q-X'] T = fclusterdata(X, criterion='maxclust', t=4) self.failUnless(is_isomorphic(T, expectedT)) def test_fcluster_maxclusts_2(self): "Tests fcluster(Z, criterion='maxclust', t=2) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-2'] - X = eo['fclusterdata-X'] + X = eo['Q-X'] Y = pdist(X) Z = linkage(Y) T = fcluster(Z, criterion='maxclust', t=2) @@ -334,7 +334,7 @@ def test_fcluster_maxclusts_3(self): "Tests fcluster(Z, criterion='maxclust', t=3) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-3'] - X = eo['fclusterdata-X'] + X = eo['Q-X'] Y = pdist(X) Z = linkage(Y) T = fcluster(Z, criterion='maxclust', t=3) @@ -343,7 +343,7 @@ def test_fcluster_maxclusts_4(self): "Tests fcluster(Z, criterion='maxclust', t=4) on a random 3-cluster data set." expectedT = eo['fclusterdata-maxclusts-4'] - X = eo['fclusterdata-X'] + X = eo['Q-X'] Y = pdist(X) Z = linkage(Y) T = fcluster(Z, criterion='maxclust', t=4) From scipy-svn at scipy.org Fri Nov 7 17:14:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 16:14:08 -0600 (CST) Subject: [Scipy-svn] r5020 - trunk/scipy/cluster/tests Message-ID: <20081107221408.39B9039C1AE@scipy.org> Author: damian.eads Date: 2008-11-07 16:14:00 -0600 (Fri, 07 Nov 2008) New Revision: 5020 Added: trunk/scipy/cluster/tests/inconsistent-Q-single-1.txt trunk/scipy/cluster/tests/inconsistent-Q-single-2.txt trunk/scipy/cluster/tests/inconsistent-Q-single-3.txt trunk/scipy/cluster/tests/inconsistent-Q-single-4.txt trunk/scipy/cluster/tests/inconsistent-Q-single-5.txt trunk/scipy/cluster/tests/inconsistent-Q-single-6.txt Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added some more tests to inconsistent. Added: trunk/scipy/cluster/tests/inconsistent-Q-single-1.txt =================================================================== --- trunk/scipy/cluster/tests/inconsistent-Q-single-1.txt 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/inconsistent-Q-single-1.txt 2008-11-07 22:14:00 UTC (rev 5020) @@ -0,0 +1,29 @@ + 6.3937355e-02 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.7716924e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.9481726e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4887981e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.7739218e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.9703742e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.9953732e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.0440560e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.0777762e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.0902082e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.3102505e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.4153568e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.5802170e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.6459874e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.7818440e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.0129405e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.1203984e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.4459698e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.5328393e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.8198330e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 5.0546088e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 5.0591731e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 5.9356257e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 6.0048760e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 6.2656347e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 6.5449319e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 7.0629051e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.0267612e+00 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.2085488e+00 0.0000000e+00 1.0000000e+00 0.0000000e+00 Added: trunk/scipy/cluster/tests/inconsistent-Q-single-2.txt =================================================================== --- trunk/scipy/cluster/tests/inconsistent-Q-single-2.txt 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/inconsistent-Q-single-2.txt 2008-11-07 22:14:00 UTC (rev 5020) @@ -0,0 +1,29 @@ + 6.3937355e-02 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.7716924e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.9481726e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4887981e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.7739218e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4592734e-01 7.2280574e-02 2.0000000e+00 7.0710678e-01 + 2.7420856e-01 3.5820263e-02 2.0000000e+00 7.0710678e-01 + 3.0440560e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4247343e-01 9.2354075e-02 2.0000000e+00 7.0710678e-01 + 3.0302912e-01 8.4735429e-03 2.0000000e+00 7.0710678e-01 + 3.1940134e-01 1.6438416e-02 2.0000000e+00 7.0710678e-01 + 3.3628037e-01 7.4321374e-03 2.0000000e+00 7.0710678e-01 + 2.5449825e-01 1.6523631e-01 3.0000000e+00 6.2651759e-01 + 3.2284722e-01 3.6239721e-02 3.0000000e+00 1.1520929e+00 + 3.7139157e-01 9.6065094e-03 2.0000000e+00 7.0710678e-01 + 3.8973922e-01 1.6340989e-02 2.0000000e+00 7.0710678e-01 + 3.8503077e-01 3.8196594e-02 2.0000000e+00 7.0710678e-01 + 4.2831841e-01 2.3021378e-02 2.0000000e+00 7.0710678e-01 + 3.8115238e-01 1.0200942e-01 2.0000000e+00 7.0710678e-01 + 4.8198330e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.6291274e-01 5.4639241e-02 3.0000000e+00 7.7871022e-01 + 4.1219781e-01 1.1967450e-01 3.0000000e+00 7.8312006e-01 + 5.4973994e-01 6.1974561e-02 2.0000000e+00 7.0710678e-01 + 5.5297424e-01 6.7194042e-02 2.0000000e+00 7.0710678e-01 + 6.1006302e-01 2.3335155e-02 2.0000000e+00 7.0710678e-01 + 5.4954508e-01 1.4841903e-01 2.0000000e+00 7.0710678e-01 + 6.6642699e-01 5.6375531e-02 2.0000000e+00 7.0710678e-01 + 7.6058065e-01 2.3209524e-01 3.0000000e+00 1.1468590e+00 + 9.8053348e-01 2.5430019e-01 3.0000000e+00 8.9663826e-01 Added: trunk/scipy/cluster/tests/inconsistent-Q-single-3.txt =================================================================== --- trunk/scipy/cluster/tests/inconsistent-Q-single-3.txt 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/inconsistent-Q-single-3.txt 2008-11-07 22:14:00 UTC (rev 5020) @@ -0,0 +1,29 @@ + 6.3937355e-02 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.7716924e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.9481726e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4887981e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.7739218e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4592734e-01 7.2280574e-02 2.0000000e+00 7.0710678e-01 + 2.7420856e-01 3.5820263e-02 2.0000000e+00 7.0710678e-01 + 3.0440560e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4247343e-01 9.2354075e-02 2.0000000e+00 7.0710678e-01 + 2.6695850e-01 6.2762807e-02 3.0000000e+00 6.7017912e-01 + 2.7199064e-01 8.2936326e-02 3.0000000e+00 7.1180408e-01 + 3.2677945e-01 1.7274852e-02 3.0000000e+00 8.5420299e-01 + 2.7362995e-01 1.4023592e-01 4.0000000e+00 6.0178414e-01 + 3.0435537e-01 4.7363902e-02 4.0000000e+00 1.2719259e+00 + 3.3668152e-01 4.0510441e-02 4.0000000e+00 1.0244985e+00 + 3.8135906e-01 1.8552498e-02 3.0000000e+00 1.0745175e+00 + 2.9388364e-01 1.5622696e-01 4.0000000e+00 7.5631117e-01 + 4.0488617e-01 4.3728723e-02 3.0000000e+00 9.0811730e-01 + 3.5311406e-01 8.6956328e-02 3.0000000e+00 1.1519561e+00 + 4.8198330e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.4173066e-01 6.1522522e-02 4.0000000e+00 1.0358844e+00 + 3.8640356e-01 1.1049599e-01 4.0000000e+00 1.0816117e+00 + 4.5753900e-01 1.3330898e-01 4.0000000e+00 1.0203631e+00 + 4.9730646e-01 8.1987855e-02 4.0000000e+00 1.2584931e+00 + 5.7534778e-01 6.2351485e-02 3.0000000e+00 8.2140277e-01 + 5.0371000e-01 1.3159281e-01 3.0000000e+00 1.1458315e+00 + 6.4213885e-01 5.7955510e-02 3.0000000e+00 1.1069121e+00 + 6.4635996e-01 2.2772591e-01 5.0000000e+00 1.6704345e+00 + 8.0385745e-01 2.5222314e-01 6.0000000e+00 1.6044971e+00 Added: trunk/scipy/cluster/tests/inconsistent-Q-single-4.txt =================================================================== --- trunk/scipy/cluster/tests/inconsistent-Q-single-4.txt 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/inconsistent-Q-single-4.txt 2008-11-07 22:14:00 UTC (rev 5020) @@ -0,0 +1,29 @@ + 6.3937355e-02 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.7716924e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.9481726e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4887981e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.7739218e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4592734e-01 7.2280574e-02 2.0000000e+00 7.0710678e-01 + 2.7420856e-01 3.5820263e-02 2.0000000e+00 7.0710678e-01 + 3.0440560e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4247343e-01 9.2354075e-02 2.0000000e+00 7.0710678e-01 + 2.6695850e-01 6.2762807e-02 3.0000000e+00 6.7017912e-01 + 2.7199064e-01 8.2936326e-02 3.0000000e+00 7.1180408e-01 + 2.8937690e-01 7.6123263e-02 4.0000000e+00 6.8518849e-01 + 2.8045948e-01 1.2240424e-01 5.0000000e+00 6.3365630e-01 + 3.0435537e-01 4.7363902e-02 4.0000000e+00 1.2719259e+00 + 3.1912118e-01 5.2655955e-02 5.0000000e+00 1.1216818e+00 + 3.4960402e-01 4.5450828e-02 5.0000000e+00 1.1372736e+00 + 3.0131193e-01 1.3631230e-01 5.0000000e+00 8.1231048e-01 + 3.2402631e-01 1.5115571e-01 5.0000000e+00 7.9765872e-01 + 3.1353986e-01 1.0632688e-01 4.0000000e+00 1.3142874e+00 + 4.8198330e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 4.2630427e-01 6.3471504e-02 5.0000000e+00 1.2471203e+00 + 3.6853033e-01 1.0370286e-01 5.0000000e+00 1.3248137e+00 + 4.2783536e-01 1.3319157e-01 5.0000000e+00 1.2442770e+00 + 4.7348205e-01 8.8766656e-02 5.0000000e+00 1.4307800e+00 + 4.9134389e-01 1.3799391e-01 5.0000000e+00 9.7989526e-01 + 4.6728793e-01 1.2981031e-01 4.0000000e+00 1.4421448e+00 + 6.0808346e-01 8.2935544e-02 4.0000000e+00 1.1841370e+00 + 5.6588963e-01 2.0619528e-01 8.0000000e+00 2.2351217e+00 + 7.0741835e-01 2.4917629e-01 9.0000000e+00 2.0111480e+00 Added: trunk/scipy/cluster/tests/inconsistent-Q-single-5.txt =================================================================== --- trunk/scipy/cluster/tests/inconsistent-Q-single-5.txt 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/inconsistent-Q-single-5.txt 2008-11-07 22:14:00 UTC (rev 5020) @@ -0,0 +1,29 @@ + 6.3937355e-02 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.7716924e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.9481726e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4887981e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.7739218e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4592734e-01 7.2280574e-02 2.0000000e+00 7.0710678e-01 + 2.7420856e-01 3.5820263e-02 2.0000000e+00 7.0710678e-01 + 3.0440560e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4247343e-01 9.2354075e-02 2.0000000e+00 7.0710678e-01 + 2.6695850e-01 6.2762807e-02 3.0000000e+00 6.7017912e-01 + 2.7199064e-01 8.2936326e-02 3.0000000e+00 7.1180408e-01 + 2.8937690e-01 7.6123263e-02 4.0000000e+00 6.8518849e-01 + 2.6324444e-01 1.1732171e-01 6.0000000e+00 8.0784074e-01 + 3.0435537e-01 4.7363902e-02 4.0000000e+00 1.2719259e+00 + 3.1912118e-01 5.2655955e-02 5.0000000e+00 1.1216818e+00 + 3.3281665e-01 5.7823149e-02 6.0000000e+00 1.1842557e+00 + 3.0238954e-01 1.2195000e-01 6.0000000e+00 8.9914142e-01 + 3.2519277e-01 1.3522797e-01 6.0000000e+00 8.8298461e-01 + 3.1353986e-01 1.0632688e-01 4.0000000e+00 1.3142874e+00 + 4.8198330e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.9078061e-01 7.9802007e-02 7.0000000e+00 1.4370599e+00 + 3.3957815e-01 1.1675958e-01 6.0000000e+00 1.4246296e+00 + 4.0603571e-01 1.3055016e-01 6.0000000e+00 1.4364353e+00 + 4.5533483e-01 9.0992001e-02 6.0000000e+00 1.5952257e+00 + 4.6095671e-01 1.4413236e-01 6.0000000e+00 1.1489908e+00 + 3.7910412e-01 1.9099694e-01 6.0000000e+00 1.4418506e+00 + 5.2716833e-01 1.5144040e-01 6.0000000e+00 1.1827899e+00 + 5.2633231e-01 2.0011385e-01 1.0000000e+01 2.5007208e+00 + 6.2830766e-01 2.3939755e-01 1.3000000e+01 2.4237553e+00 Added: trunk/scipy/cluster/tests/inconsistent-Q-single-6.txt =================================================================== --- trunk/scipy/cluster/tests/inconsistent-Q-single-6.txt 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/inconsistent-Q-single-6.txt 2008-11-07 22:14:00 UTC (rev 5020) @@ -0,0 +1,29 @@ + 6.3937355e-02 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.7716924e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 1.9481726e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4887981e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.7739218e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4592734e-01 7.2280574e-02 2.0000000e+00 7.0710678e-01 + 2.7420856e-01 3.5820263e-02 2.0000000e+00 7.0710678e-01 + 3.0440560e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 2.4247343e-01 9.2354075e-02 2.0000000e+00 7.0710678e-01 + 2.6695850e-01 6.2762807e-02 3.0000000e+00 6.7017912e-01 + 2.7199064e-01 8.2936326e-02 3.0000000e+00 7.1180408e-01 + 2.8937690e-01 7.6123263e-02 4.0000000e+00 6.8518849e-01 + 2.6324444e-01 1.1732171e-01 6.0000000e+00 8.0784074e-01 + 3.0435537e-01 4.7363902e-02 4.0000000e+00 1.2719259e+00 + 3.1912118e-01 5.2655955e-02 5.0000000e+00 1.1216818e+00 + 3.3281665e-01 5.7823149e-02 6.0000000e+00 1.1842557e+00 + 2.8450093e-01 1.2096771e-01 7.0000000e+00 1.0543220e+00 + 3.2270489e-01 1.2362105e-01 7.0000000e+00 9.8601409e-01 + 3.1353986e-01 1.0632688e-01 4.0000000e+00 1.3142874e+00 + 4.8198330e-01 0.0000000e+00 1.0000000e+00 0.0000000e+00 + 3.7304301e-01 8.9306070e-02 8.0000000e+00 1.4827420e+00 + 3.3957815e-01 1.1675958e-01 6.0000000e+00 1.4246296e+00 + 3.7586164e-01 1.4344374e-01 7.0000000e+00 1.5176747e+00 + 4.1699399e-01 1.0466959e-01 8.0000000e+00 1.7530748e+00 + 4.3753967e-01 1.4543138e-01 7.0000000e+00 1.2997456e+00 + 3.7223569e-01 1.7529999e-01 7.0000000e+00 1.6101398e+00 + 4.9600440e-01 1.6096634e-01 7.0000000e+00 1.3063980e+00 + 4.6410730e-01 2.2064134e-01 1.3000000e+01 2.5500836e+00 + 5.6675775e-01 2.3884131e-01 1.7000000e+01 2.6871022e+00 Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 21:52:04 UTC (rev 5019) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 22:14:00 UTC (rev 5020) @@ -62,6 +62,12 @@ "linkage-complete-tdist.txt", "linkage-average-tdist.txt", "linkage-weighted-tdist.txt", + "inconsistent-Q-single-1.txt", + "inconsistent-Q-single-2.txt", + "inconsistent-Q-single-3.txt", + "inconsistent-Q-single-4.txt", + "inconsistent-Q-single-5.txt", + "inconsistent-Q-single-6.txt", "inconsistent-complete-tdist-depth-1.txt", "inconsistent-complete-tdist-depth-2.txt", "inconsistent-complete-tdist-depth-3.txt", @@ -207,11 +213,130 @@ class TestInconsistent(TestCase): - def test_single_inconsistent_tdist(self): - "Testing inconsistency matrix calculation on a single linkage." - for i in xrange(0, 100): - yield help_single_inconsistent_depth, i + def test_single_inconsistent_tdist_1(self): + "Testing inconsistency matrix calculation (depth=1) on a single linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'single') + R = inconsistent(Z, 1) + Rright = eo['inconsistent-single-tdist-depth-1'] + eps = 1e-15 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + def test_single_inconsistent_tdist_2(self): + "Testing inconsistency matrix calculation (depth=2) on a single linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'single') + R = inconsistent(Z, 2) + Rright = eo['inconsistent-single-tdist-depth-2'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_single_inconsistent_tdist_3(self): + "Testing inconsistency matrix calculation (depth=3) on a single linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'single') + R = inconsistent(Z, 3) + Rright = eo['inconsistent-single-tdist-depth-3'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_single_inconsistent_tdist_4(self): + "Testing inconsistency matrix calculation (depth=4) on a single linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'single') + R = inconsistent(Z, 4) + Rright = eo['inconsistent-single-tdist-depth-4'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + # with complete linkage... + + def test_complete_inconsistent_tdist_1(self): + "Testing inconsistency matrix calculation (depth=1) on a complete linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'complete') + R = inconsistent(Z, 1) + Rright = eo['inconsistent-complete-tdist-depth-1'] + eps = 1e-15 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_complete_inconsistent_tdist_2(self): + "Testing inconsistency matrix calculation (depth=2) on a complete linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'complete') + R = inconsistent(Z, 2) + Rright = eo['inconsistent-complete-tdist-depth-2'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_complete_inconsistent_tdist_3(self): + "Testing inconsistency matrix calculation (depth=3) on a complete linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'complete') + R = inconsistent(Z, 3) + Rright = eo['inconsistent-complete-tdist-depth-3'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_complete_inconsistent_tdist_4(self): + "Testing inconsistency matrix calculation (depth=4) on a complete linkage." + Y = squareform(_tdist) + Z = linkage(Y, 'complete') + R = inconsistent(Z, 4) + Rright = eo['inconsistent-complete-tdist-depth-4'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + # with single linkage and Q data set + + def test_single_inconsistent_tdist_1(self): + "Testing inconsistency matrix calculation (depth=1) on a weighted linkage." + X = eo['Q-X'] + Z = linkage(X, 'single', 'euclidean') + R = inconsistent(Z, 1) + Rright = eo['inconsistent-Q-single-1'] + eps = 1e-06 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_single_inconsistent_tdist_2(self): + "Testing inconsistency matrix calculation (depth=2) on a weighted linkage." + X = eo['Q-X'] + Z = linkage(X, 'single', 'euclidean') + R = inconsistent(Z, 2) + Rright = eo['inconsistent-Q-single-2'] + eps = 1e-06 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_single_inconsistent_tdist_3(self): + "Testing inconsistency matrix calculation (depth=3) on a weighted linkage." + X = eo['Q-X'] + Z = linkage(X, 'single', 'euclidean') + R = inconsistent(Z, 3) + Rright = eo['inconsistent-Q-single-3'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + + def test_single_inconsistent_tdist_4(self): + "Testing inconsistency matrix calculation (depth=4) on a weighted linkage." + X = eo['Q-X'] + Z = linkage(X, 'single', 'euclidean') + R = inconsistent(Z, 4) + Rright = eo['inconsistent-Q-single-4'] + eps = 1e-05 + print np.abs(R - Rright).max() + self.failUnless(within_tol(R, Rright, eps)) + class TestCopheneticDistance(TestCase): def test_linkage_cophenet_tdist_Z(self): From scipy-svn at scipy.org Fri Nov 7 17:46:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 16:46:49 -0600 (CST) Subject: [Scipy-svn] r5021 - trunk/scipy/cluster/tests Message-ID: <20081107224649.9D6F339C1AE@scipy.org> Author: damian.eads Date: 2008-11-07 16:46:45 -0600 (Fri, 07 Nov 2008) New Revision: 5021 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Added test to leaders function. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 22:14:00 UTC (rev 5020) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 22:46:45 UTC (rev 5021) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -298,7 +298,7 @@ # with single linkage and Q data set def test_single_inconsistent_tdist_1(self): - "Testing inconsistency matrix calculation (depth=1) on a weighted linkage." + "Testing inconsistency matrix calculation (depth=1, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 1) @@ -308,7 +308,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_tdist_2(self): - "Testing inconsistency matrix calculation (depth=2) on a weighted linkage." + "Testing inconsistency matrix calculation (depth=2, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 2) @@ -318,7 +318,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_tdist_3(self): - "Testing inconsistency matrix calculation (depth=3) on a weighted linkage." + "Testing inconsistency matrix calculation (depth=3, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 3) @@ -328,7 +328,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_tdist_4(self): - "Testing inconsistency matrix calculation (depth=4) on a weighted linkage." + "Testing inconsistency matrix calculation (depth=4, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 4) @@ -474,6 +474,18 @@ T = fcluster(Z, criterion='maxclust', t=4) self.failUnless(is_isomorphic(T, expectedT)) +class TestLeaders(TestCase): + + def test_leaders_single(self): + "Tests leaders using a flat clustering generated by single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(Y) + T = fcluster(Z, criterion='maxclust', t=3) + Lright = (np.array([53, 55, 56]), np.array([2, 3, 1])) + L = leaders(Z, T) + self.failUnless((L[0] == Lright[0]).all() and (L[1] == Lright[1]).all()) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Fri Nov 7 17:49:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 7 Nov 2008 16:49:09 -0600 (CST) Subject: [Scipy-svn] r5022 - trunk/scipy/cluster/tests Message-ID: <20081107224909.55E6239C1AE@scipy.org> Author: damian.eads Date: 2008-11-07 16:49:07 -0600 (Fri, 07 Nov 2008) New Revision: 5022 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Minor tweak in test function. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 22:46:45 UTC (rev 5021) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-07 22:49:07 UTC (rev 5022) @@ -297,7 +297,7 @@ # with single linkage and Q data set - def test_single_inconsistent_tdist_1(self): + def test_single_inconsistent_Q_1(self): "Testing inconsistency matrix calculation (depth=1, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') @@ -307,7 +307,7 @@ print np.abs(R - Rright).max() self.failUnless(within_tol(R, Rright, eps)) - def test_single_inconsistent_tdist_2(self): + def test_single_inconsistent_Q_2(self): "Testing inconsistency matrix calculation (depth=2, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') @@ -317,7 +317,7 @@ print np.abs(R - Rright).max() self.failUnless(within_tol(R, Rright, eps)) - def test_single_inconsistent_tdist_3(self): + def test_single_inconsistent_Q_3(self): "Testing inconsistency matrix calculation (depth=3, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') @@ -327,7 +327,7 @@ print np.abs(R - Rright).max() self.failUnless(within_tol(R, Rright, eps)) - def test_single_inconsistent_tdist_4(self): + def test_single_inconsistent_Q_4(self): "Testing inconsistency matrix calculation (depth=4, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') From scipy-svn at scipy.org Sat Nov 8 02:59:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 01:59:27 -0600 (CST) Subject: [Scipy-svn] r5023 - trunk/scipy/linalg/tests Message-ID: <20081108075927.C9D7139C226@scipy.org> Author: cdavid Date: 2008-11-08 01:59:17 -0600 (Sat, 08 Nov 2008) New Revision: 5023 Added: trunk/scipy/linalg/tests/test_build.py Log: Add fortran ABI mismatch test for scipy.linalg. Added: trunk/scipy/linalg/tests/test_build.py =================================================================== --- trunk/scipy/linalg/tests/test_build.py 2008-11-07 22:49:07 UTC (rev 5022) +++ trunk/scipy/linalg/tests/test_build.py 2008-11-08 07:59:17 UTC (rev 5023) @@ -0,0 +1,51 @@ +from subprocess import call, PIPE, Popen +import sys +import re + +import numpy as np +from numpy.testing import TestCase, dec + +from scipy.linalg import flapack + +# XXX: this is copied from numpy trunk. Can be removed when we will depend on +# numpy 1.3 +class FindDependenciesLdd: + def __init__(self): + self.cmd = ['ldd'] + + try: + st = call(self.cmd, stdout=PIPE, stderr=PIPE) + except OSError: + raise RuntimeError("command %s cannot be run" % self.cmd) + + def get_dependencies(self, file): + p = Popen(self.cmd + [file], stdout=PIPE, stderr=PIPE) + stdout, stderr = p.communicate() + if not (p.returncode == 0): + raise RuntimeError("Failed to check dependencies for %s" % libfile) + + return stdout + + def grep_dependencies(self, file, deps): + stdout = self.get_dependencies(file) + + rdeps = dict([(dep, re.compile(dep)) for dep in deps]) + founds = [] + for l in stdout.splitlines(): + for k, v in rdeps.items(): + if v.search(l): + founds.append(k) + + return founds + +class TestF77Mismatch(TestCase): + @dec.skipif(not(sys.platform[:5] == 'linux'), + "Skipping fortran compiler mismatch on non Linux platform") + def test_lapack(self): + f = FindDependenciesLdd() + deps = f.grep_dependencies(flapack.__file__, + ['libg2c', 'libgfortran']) + self.failIf(len(deps) > 1, +"""Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to +cause random crashes and wrong results. See numpy INSTALL.txt for more +information.""") From scipy-svn at scipy.org Sat Nov 8 02:59:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 01:59:46 -0600 (CST) Subject: [Scipy-svn] r5024 - trunk/scipy/linalg/tests Message-ID: <20081108075946.BF62639C226@scipy.org> Author: cdavid Date: 2008-11-08 01:59:38 -0600 (Sat, 08 Nov 2008) New Revision: 5024 Modified: trunk/scipy/linalg/tests/test_build.py Log: Fix typo. Modified: trunk/scipy/linalg/tests/test_build.py =================================================================== --- trunk/scipy/linalg/tests/test_build.py 2008-11-08 07:59:17 UTC (rev 5023) +++ trunk/scipy/linalg/tests/test_build.py 2008-11-08 07:59:38 UTC (rev 5024) @@ -46,6 +46,6 @@ deps = f.grep_dependencies(flapack.__file__, ['libg2c', 'libgfortran']) self.failIf(len(deps) > 1, -"""Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to -cause random crashes and wrong results. See numpy INSTALL.txt for more -information.""") +"""Both g77 and gfortran runtimes linked in scipy.linalg.flapack ! This is +likely to cause random crashes and wrong results. See numpy INSTALL.txt for +more information.""") From scipy-svn at scipy.org Sat Nov 8 19:44:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 18:44:50 -0600 (CST) Subject: [Scipy-svn] r5025 - in trunk/scipy/io/matlab: . tests Message-ID: <20081109004450.CAA2D39C249@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-08 18:44:40 -0600 (Sat, 08 Nov 2008) New Revision: 5025 Added: trunk/scipy/io/matlab/tests/gen_mat4files.m trunk/scipy/io/matlab/tests/gen_mat5files.m trunk/scipy/io/matlab/tests/save_matfile.m Removed: trunk/scipy/io/matlab/tests/gen_unittests.m trunk/scipy/io/matlab/tests/gen_unittests4.m trunk/scipy/io/matlab/tests/save_test.m Modified: trunk/scipy/io/matlab/mio.py trunk/scipy/io/matlab/mio4.py trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py trunk/scipy/io/matlab/tests/test_mio.py Log: Re-enabled matlab io tests, partial fixes for errors Modified: trunk/scipy/io/matlab/mio.py =================================================================== --- trunk/scipy/io/matlab/mio.py 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/mio.py 2008-11-09 00:44:40 UTC (rev 5025) @@ -8,17 +8,19 @@ import sys import warnings -from miobase import get_matfile_version +from miobase import get_matfile_version, filldoc from mio4 import MatFile4Reader, MatFile4Writer from mio5 import MatFile5Reader, MatFile5Writer __all__ = ['find_mat_file', 'mat_reader_factory', 'loadmat', 'savemat'] + at filldoc def find_mat_file(file_name, appendmat=True): ''' Try to find .mat file on system path - file_name - file name string - append_mat - If True, and file_name does not end in '.mat', appends it + file_name : string + file name for mat file + %(append_arg)s ''' if appendmat and file_name[-4:] == ".mat": file_name = file_name[:-4] @@ -42,10 +44,15 @@ pass return full_name + at filldoc def mat_reader_factory(file_name, appendmat=True, **kwargs): - """Create reader for matlab (TM) .mat format files + """Create reader for matlab .mat format files - See docstring for loadmat for input options + %(file_arg)s + %(append_arg)s + %(basename_arg)s + %(load_args)s + %(struct_arg)s """ if isinstance(file_name, basestring): full_name = find_mat_file(file_name, appendmat) @@ -58,54 +65,42 @@ except AttributeError: raise IOError, 'Reader needs file name or open file-like object' byte_stream = file_name - + # Deal with deprecations + if kwargs.has_key('basename'): + warnings.warn( + 'basename argument will be removed in future scipy versions', + DeprecationWarning, stacklevel=2) + del kwargs['basename'] mjv, mnv = get_matfile_version(byte_stream) if mjv == 0: return MatFile4Reader(byte_stream, **kwargs) elif mjv == 1: return MatFile5Reader(byte_stream, **kwargs) elif mjv == 2: - raise NotImplementedError('Please use PyTables for matlab v7.3 (HDF) files') + raise NotImplementedError('Please use HDF reader for matlab v7.3 files') else: raise TypeError('Did not recognize version %s' % mv) -def loadmat(file_name, mdict=None, appendmat=True, basename='raw', **kwargs): + at filldoc +def loadmat(file_name, mdict=None, appendmat=True, **kwargs): ''' Load Matlab(tm) file - file_name - Name of the mat file - (do not need .mat extension if appendmat==True) - If name not a full path name, search for the file on - the sys.path list and use the first one found (the - current directory is searched first). - Can also pass open file-like object - m_dict - optional dictionary in which to insert matfile variables - appendmat - True to append the .mat extension to the end of the - given filename, if not already present - base_name - base name for unnamed variables (unused in code) - byte_order - byte order ('native', 'little', 'BIG') - in ('native', '=') - or in ('little', '<') - or in ('BIG', '>') - mat_dtype - return arrays in same dtype as loaded into matlab - (instead of the dtype with which they are saved) - squeeze_me - whether to squeeze matrix dimensions or not - chars_as_strings - whether to convert char arrays to string arrays - mat_dtype - return matrices with datatype that matlab would load as - (rather than in the datatype matlab saves as) - matlab_compatible - returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False, - mat_dtype=True) - struct_as_record - whether to load matlab structs as numpy record arrays, or - as old-style numpy arrays with dtype=object. - (warns if not set, and defaults to False. non-recarrays - cannot be exported via savemat.) + %(file_arg)s + m_dict : dict, optional + dictionary in which to insert matfile variables + %(append_arg)s + %(basename_arg)s + %(load_args)s + %(struct_arg)s + + Notes + ----- + v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported. - v4 (Level 1.0), v6 and v7.1 matfiles are supported. - + You will need an HDF5 python library to read matlab 7.3 format mat + files. Because scipy does not supply one, we do not implement the + HDF5 / 7.3 interface here. ''' - if not kwargs.get('struct_as_record', False): - warnings.warn("loading matlab structures as arrays of dtype=object is deprecated", - DeprecationWarning, stacklevel=2) MR = mat_reader_factory(file_name, appendmat, **kwargs) matfile_dict = MR.get_variables() if mdict is not None: @@ -114,14 +109,22 @@ mdict = matfile_dict return mdict + at filldoc def savemat(file_name, mdict, appendmat=True, format='4'): """Save a dictionary of names and arrays into the MATLAB-style .mat file. This saves the arrayobjects in the given dictionary to a matlab style .mat file. - appendmat - if true, appends '.mat' extension to filename, if not present - format - '4' for matlab 4 mat files, '5' for matlab 5 onwards + file_name : {string, file-like object} + Name of the mat file (do not need .mat extension if + appendmat==True) Can also pass open file-like object + m_dict : dict + dictionary from which to save matfile variables + %(append_arg)s + format : {'4', '5'} string, optional + '4' for matlab 4 mat files, '5' for matlab 5 (up to matlab + 7.2) """ file_is_string = isinstance(file_name, basestring) if file_is_string: Modified: trunk/scipy/io/matlab/mio4.py =================================================================== --- trunk/scipy/io/matlab/mio4.py 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/mio4.py 2008-11-09 00:44:40 UTC (rev 5025) @@ -5,7 +5,7 @@ import numpy as np from miobase import MatFileReader, MatArrayReader, MatMatrixGetter, \ - MatFileWriter, MatStreamWriter, spsparse + MatFileWriter, MatStreamWriter, spsparse, filldoc SYS_LITTLE_ENDIAN = sys.byteorder == 'little' @@ -186,7 +186,13 @@ class MatFile4Reader(MatFileReader): ''' Reader for Mat4 files ''' + @filldoc def __init__(self, mat_stream, *args, **kwargs): + ''' Initialize matlab 4 file reader + + %(matstream_arg)s + %(load_args)s + ''' self._array_reader = Mat4ArrayReader( mat_stream, None, Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/mio5.py 2008-11-09 00:44:40 UTC (rev 5025) @@ -6,13 +6,14 @@ import sys import zlib -from cStringIO import StringIO +from StringIO import StringIO from copy import copy as pycopy +import warnings import numpy as np from miobase import MatFileReader, MatArrayReader, MatMatrixGetter, \ - MatFileWriter, MatStreamWriter, spsparse + MatFileWriter, MatStreamWriter, spsparse, filldoc miINT8 = 1 miUINT8 = 2 @@ -161,6 +162,102 @@ mxUINT64_CLASS, ) + +class mat_struct(object): + ''' Placeholder for holding read data from structs + + We will deprecate this method of holding struct information in a + future version of scipy, in favor of the recarray method (see + loadmat doctstring) + ''' + pass + + +class MatlabObject(object): + ''' Class to contain data read from matlab objects + + Contains classname, and record array for field names and values + + Attribute access fetches and sets record array fields if present + + ''' + def __init__(self, classname, fields): + """ Initialize MatlabObject + + Parameters + ---------- + self : object + classname : string + class name for matlab object + fields : {recarray, string list} + either a recarray or a list of field names + + >>> import numpy as np + >>> arr = np.zeros((1,1),dtype=[('field1','i2'),('field2','i2')]) + >>> obj = MatlabObject('myclass', arr) + >>> obj = MatlabObject('myclass', ['field1', 'field2']) + + """ + # Initialize to make field setting work with __setattr__ + self.__dict__['_fields'] = [] + self.classname = classname + try: # recarray + fdict = fields.dtype.fields + except AttributeError: # something else + fields = tuple(fields) + else: # recarray again + self._fields = fdict.keys() + self.mobj_recarray = fields + return + # something else again + self._fields = fields + dtype = [(field, object) for field in fields] + self.mobj_recarray = np.zeros((1,1), dtype) + + def __getattr__(self, name): + ''' get attributes from object + + Get attribute if present, otherwise field from recarray + + >>> import numpy as np + >>> arr = np.zeros((1,1),dtype=[('field1','i2'),('field2','i2')]) + >>> obj = MatlabObject('myclass', arr) + >>> obj.field1 + array([[0]], dtype=int16) + >>> obj = MatlabObject('myclass', ['field1', 'field2']) + >>> obj.field1 + array([[0]], dtype=object) + >>> obj.classname + 'myclass' + ''' + if name in self.__dict__: + return self.__dict__[name] + mobj_recarray = self.__dict__['mobj_recarray'] + if name in self.__dict__['_fields']: + return mobj_recarray[name] + else: + raise AttributeError( + "no field named %s in MatlabObject" % name) + + def __setattr__(self, name, value): + ''' set attributes in object + + Set field value from recarray, if present, else attribute + + >>> import numpy as np + >>> arr = np.zeros((1,1),dtype=[('field1','i2'),('field2','i2')]) + >>> obj = MatlabObject('myclass', arr) + >>> obj.field1[0,0] = 1 + >>> obj.strangename = 'test' + >>> obj.strangename + 'test' + ''' + if name in self._fields: + self.mobj_recarray[name] = value + else: + self.__dict__[name] = value + + class Mat5ArrayReader(MatArrayReader): ''' Class to get Mat5 arrays @@ -411,10 +508,6 @@ def get_item(self): return self.read_element() -class mat_struct(object): - ''' Placeholder for holding read data from structs ''' - pass - class Mat5StructMatrixGetter(Mat5MatrixGetter): def __init__(self, array_reader, header): super(Mat5StructMatrixGetter, self).__init__(array_reader, header) @@ -445,27 +538,7 @@ return result.reshape(tupdims).T -class MatlabObject(object): - ''' Class to contain read data from matlab objects ''' - def __init__(self, classname, field_names): - self.__dict__['classname'] = classname - self.__dict__['mobj_recarray'] = np.empty((1,1), dtype=[(field_name, object) - for field_name in field_names]) - def __getattr__(self, name): - mobj_recarray = self.__dict__['mobj_recarray'] - if name in mobj_recarray.dtype.fields: - return mobj_recarray[0,0][name] - else: - raise AttributeError, "no field named %s in MatlabObject"%(name) - - def __setattr__(self, name, value): - if name in self.__dict__['mobj_recarray'].dtype.fields: - self.__dict__['mobj_recarray'][0,0][name] = value - else: - self.__dict__[name] = value - - class Mat5ObjectMatrixGetter(Mat5MatrixGetter): def get_array(self): '''Matlab ojects are essentially structs, with an extra field, the classname.''' @@ -499,7 +572,7 @@ uint16_codec - char codec to use for uint16 char arrays (defaults to system default codec) ''' - + @filldoc def __init__(self, mat_stream, byte_order=None, @@ -507,34 +580,24 @@ squeeze_me=False, chars_as_strings=True, matlab_compatible=False, - struct_as_record=False, + struct_as_record=None, # default False, for now uint16_codec=None ): + '''Initializer for matlab 5 file format reader + + %(matstream_arg)s + %(load_args)s + %(struct_arg)s + uint16_codec : {None, string} + Set codec to use for uint16 char arrays (e.g. 'utf-8'). + Use system default codec if None ''' - mat_stream : file-like - object with file API, open for reading - byte_order : {None, string} - specification of byte order, one of: - ('native', '=', 'little', '<', 'BIG', '>') - mat_dtype : {True, False} boolean - If True, return arrays in same dtype as loaded into matlab - otherwise return with dtype with which they were saved - squeeze_me : {False, True} boolean - If True, squeezes dimensions of size 1 from arrays - chars_as_strings : {True, False} boolean - If True, convert char arrays to string arrays - matlab_compatible : {False, True} boolean - If True, returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False - mat_dtype=True, struct_as_record=True) - struct_as_record : {False, True} boolean - If True, return strutures as numpy records, - otherwise, return as custom object (for - compatibility with scipy 0.6) - uint16_codec : {None, string} - Set codec to use for uint16 char arrays - (e.g. 'utf-8'). Use system default codec if None - ''' + # Deal with deprecations + if struct_as_record is None: + warnings.warn("Using struct_as_record default value (False)" + + " This will change to True in future versions", + DeprecationWarning, stacklevel=2) + struct_as_record = False self.codecs = {} # Missing inputs to array reader set later (processor func # below, dtypes, codecs via our own set_dtype function, called Modified: trunk/scipy/io/matlab/miobase.py =================================================================== --- trunk/scipy/io/matlab/miobase.py 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/miobase.py 2008-11-09 00:44:40 UTC (rev 5025) @@ -14,6 +14,60 @@ except ImportError: spsparse = None +def filldoc(func): + ''' Decorator to put recurring doc elements into mio doc strings ''' + doc_dict = \ + {'file_arg': + '''file_name : string + Name of the mat file (do not need .mat extension if + appendmat==True) If name not a full path name, search for the + file on the sys.path list and use the first one found (the + current directory is searched first). Can also pass open + file-like object''', + 'append_arg': + '''appendmat : {True, False} optional + True to append the .mat extension to the end of the given + filename, if not already present''', + 'basename_arg': + '''base_name : string, optional, unused + base name for unnamed variables. The code no longer uses + this. We deprecate for this version of scipy, and will remove + it in future versions''', + 'load_args': + '''byte_order : {None, string}, optional + None by default, implying byte order guessed from mat + file. Otherwise can be one of ('native', '=', 'little', '<', + 'BIG', '>') + mat_dtype : {False, True} optional + If True, return arrays in same dtype as would be loaded into + matlab (instead of the dtype with which they are saved) + squeeze_me : {False, True} optional + whether to squeeze unit matrix dimensions or not + chars_as_strings : {True, False} optional + whether to convert char arrays to string arrays + matlab_compatible : {False, True} + returns matrices as would be loaded by matlab (implies + squeeze_me=False, chars_as_strings=False, mat_dtype=True, + struct_as_record=True)''', + 'struct_arg': + '''struct_as_record : {False, True} optional + Whether to load matlab structs as numpy record arrays, or as + old-style numpy arrays with dtype=object. Setting this flag + to False replicates the behaviour of scipy version 0.6 + (returning numpy object arrays). The preferred setting is + True, because it allows easier round-trip load and save of + matlab files. In a future version of scipy, we will change + the default setting to True, and following versions may remove + this flag entirely. For now, we set the default to False, for + backwards compatibility, but issue a deprecation warning. + Note that non-record arrays cannot be exported via savemat.''', + 'matstream_arg': + '''mat_stream : file-like + object with file API, open for reading'''} + func.__doc__ = func.__doc__ % doc_dict + return func + + def small_product(arr): ''' Faster than product for small arrays ''' res = 1 @@ -84,7 +138,6 @@ scipy.io.matlab.byteordercodes module instead. """)(ByteOrder) - class MatStreamAgent(object): ''' Base object for readers / getters from mat file streams @@ -133,32 +186,21 @@ guess_byte_order - guesses file byte order from file """ + @filldoc def __init__(self, mat_stream, byte_order=None, mat_dtype=False, squeeze_me=False, chars_as_strings=True, matlab_compatible=False, - struct_as_record=False + struct_as_record=None ): ''' + Initializer for mat file reader + mat_stream : file-like - object with file API, open for reading - byte_order : {None, string} - specification of byte order, one of: - ('native', '=', 'little', '<', 'BIG', '>') - mat_dtype : {True, False} boolean - If True, return arrays in same dtype as loaded into matlab - otherwise return with dtype with which they were saved - squeeze_me : {False, True} boolean - If True, squeezes dimensions of size 1 from arrays - chars_as_strings : {True, False} boolean - If True, convert char arrays to string arrays - matlab_compatible : {False, True} boolean - If True, returns matrices as would be loaded by matlab - (implies squeeze_me=False, chars_as_strings=False - mat_dtype=True) - + object with file API, open for reading + %(load_args)s ''' # Initialize stream self.mat_stream = mat_stream Copied: trunk/scipy/io/matlab/tests/gen_mat4files.m (from rev 4827, trunk/scipy/io/matlab/tests/gen_unittests4.m) =================================================================== --- trunk/scipy/io/matlab/tests/gen_unittests4.m 2008-10-22 13:52:41 UTC (rev 4827) +++ trunk/scipy/io/matlab/tests/gen_mat4files.m 2008-11-09 00:44:40 UTC (rev 5025) @@ -0,0 +1,50 @@ +% Generates mat files for loadmat unit tests +% Uses save_matfile.m function +% This is the version for matlab 4 + +% work out matlab version and file suffix for test files +global FILEPREFIX FILESUFFIX +sepchar = '/'; +if strcmp(computer, 'PCWIN'), sepchar = '\'; end +FILEPREFIX = [pwd sepchar 'data' sepchar]; +mlv = version; +FILESUFFIX = ['_' mlv '_' computer '.mat']; + +% basic double array +theta = 0:pi/4:2*pi; +save_matfile('testdouble', theta); + +% string +save_matfile('teststring', '"Do nine men interpret?" "Nine men," I nod.') + +% complex +save_matfile('testcomplex', cos(theta) + 1j*sin(theta)); + +% asymmetric array to check indexing +a = zeros(3, 5); +a(:,1) = [1:3]'; +a(1,:) = 1:5; + +% 2D matrix +save_matfile('testmatrix', a); + +% minus number - tests signed int +save_matfile('testminus', -1); + +% single character +save_matfile('testonechar', 'r'); + +% string array +save_matfile('teststringarray', ['one '; 'two '; 'three']); + +% sparse array +save_matfile('testsparse', sparse(a)); + +% sparse complex array +b = sparse(a); +b(1,1) = b(1,1) + j; +save_matfile('testsparsecomplex', b); + +% Two variables in same file +save([FILEPREFIX 'testmulti' FILESUFFIX], 'a', 'theta') + Copied: trunk/scipy/io/matlab/tests/gen_mat5files.m (from rev 4827, trunk/scipy/io/matlab/tests/gen_unittests.m) =================================================================== --- trunk/scipy/io/matlab/tests/gen_unittests.m 2008-10-22 13:52:41 UTC (rev 4827) +++ trunk/scipy/io/matlab/tests/gen_mat5files.m 2008-11-09 00:44:40 UTC (rev 5025) @@ -0,0 +1,92 @@ +% Generates mat files for loadmat unit tests +% This is the version for matlab 5 and higher +% Uses save_matfile.m function + +% work out matlab version and file suffix for test files +global FILEPREFIX FILESUFFIX +FILEPREFIX = [fullfile(pwd, 'data') filesep]; +temp = ver('MATLAB'); +mlv = temp.Version; +FILESUFFIX = ['_' mlv '_' computer '.mat']; + +% basic double array +theta = 0:pi/4:2*pi; +save_matfile('testdouble', theta); + +% string +save_matfile('teststring', '"Do nine men interpret?" "Nine men," I nod.') + +% complex +save_matfile('testcomplex', cos(theta) + 1j*sin(theta)); + +% asymmetric array to check indexing +a = zeros(3, 5); +a(:,1) = [1:3]'; +a(1,:) = 1:5; + +% 2D matrix +save_matfile('testmatrix', a); + +% minus number - tests signed int +save_matfile('testminus', -1); + +% single character +save_matfile('testonechar', 'r'); + +% string array +save_matfile('teststringarray', ['one '; 'two '; 'three']); + +% sparse array +save_matfile('testsparse', sparse(a)); + +% sparse complex array +b = sparse(a); +b(1,1) = b(1,1) + j; +save_matfile('testsparsecomplex', b); + +% Two variables in same file +save([FILEPREFIX 'testmulti' FILESUFFIX], 'a', 'theta') + + +% struct +save_matfile('teststruct', ... + struct('stringfield','Rats live on no evil star.',... + 'doublefield',[sqrt(2) exp(1) pi],... + 'complexfield',(1+1j)*[sqrt(2) exp(1) pi])); + +% cell +save_matfile('testcell', ... + {['This cell contains this string and 3 arrays of increasing' ... + ' length'], 1., 1.:2., 1.:3.}); + +% Empty cells in two cell matrices +save_matfile('testemptycell', {1, 2, [], [], 3}); + +% 3D matrix +save_matfile('test3dmatrix', reshape(1:24,[2 3 4])) + +% nested cell array +save_matfile('testcellnest', {1, {2, 3, {4, 5}}}); + +% nested struct +save_matfile('teststructnest', struct('one', 1, 'two', ... + struct('three', 'number 3'))); + +% array of struct +save_matfile('teststructarr', [struct('one', 1, 'two', 2) ... + struct('one', 'number 1', 'two', 'number 2')]); + +% matlab object +save_matfile('testobject', inline('x')) + +% array of matlab objects +%save_matfile('testobjarr', [inline('x') inline('y')]) + +% unicode test +if str2num(mlv) > 7 % function added 7.0.1 + fid = fopen([FILEPREFIX 'japanese_utf8.txt']); + from_japan = fread(fid, 'uint8')'; + fclose(fid); + save_matfile('testunicode', native2unicode(from_japan, 'utf-8')); +end + \ No newline at end of file Deleted: trunk/scipy/io/matlab/tests/gen_unittests.m =================================================================== --- trunk/scipy/io/matlab/tests/gen_unittests.m 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/tests/gen_unittests.m 2008-11-09 00:44:40 UTC (rev 5025) @@ -1,92 +0,0 @@ -% Generates mat files for loadmat unit tests -% This is the version for matlab 5 and higher -% Uses save_test.m function - -% work out matlab version and file suffix for test files -global FILEPREFIX FILESUFFIX -FILEPREFIX = [fullfile(pwd, 'data') filesep]; -temp = ver('MATLAB'); -mlv = temp.Version; -FILESUFFIX = ['_' mlv '_' computer '.mat']; - -% basic double array -save_test('testdouble', 0:pi/4:2*pi); - -% string -save_test('teststring', '"Do nine men interpret?" "Nine men," I nod.') - -% complex -theta = 0:pi/4:2*pi; -save_test('testcomplex', cos(theta) + 1j*sin(theta)); - -% asymmetric array to check indexing -a = zeros(3, 5); -a(:,1) = [1:3]'; -a(1,:) = 1:5; - -% 2D matrix -save_test('testmatrix', a); - -% minus number - tests signed int -save_test('testminus', -1); - -% single character -save_test('testonechar', 'r'); - -% string array -save_test('teststringarray', ['one '; 'two '; 'three']); - -% sparse array -save_test('testsparse', sparse(a)); - -% sparse complex array -b = sparse(a); -b(1,1) = b(1,1) + j; -save_test('testsparsecomplex', b); - -% Two variables in same file -save([FILEPREFIX 'testmulti' FILESUFFIX], 'a', 'theta') - - -% struct -save_test('teststruct', ... - struct('stringfield','Rats live on no evil star.',... - 'doublefield',[sqrt(2) exp(1) pi],... - 'complexfield',(1+1j)*[sqrt(2) exp(1) pi])); - -% cell -save_test('testcell', ... - {['This cell contains this string and 3 arrays of increasing' ... - ' length'], 1., 1.:2., 1.:3.}); - -% Empty cells in two cell matrices -save_test('testemptycell', {1, 2, [], [], 3}); - -% 3D matrix -save_test('test3dmatrix', reshape(1:24,[2 3 4])) - -% nested cell array -save_test('testcellnest', {1, {2, 3, {4, 5}}}); - -% nested struct -save_test('teststructnest', struct('one', 1, 'two', ... - struct('three', 'number 3'))); - -% array of struct -save_test('teststructarr', [struct('one', 1, 'two', 2) ... - struct('one', 'number 1', 'two', 'number 2')]); - -% matlab object -save_test('testobject', inline('x')) - -% array of matlab objects -%save_test('testobjarr', [inline('x') inline('y')]) - -% unicode test -if str2num(mlv) > 7 % function added 7.0.1 - fid = fopen([FILEPREFIX 'japanese_utf8.txt']); - from_japan = fread(fid, 'uint8')'; - fclose(fid); - save_test('testunicode', native2unicode(from_japan, 'utf-8')); -end - \ No newline at end of file Deleted: trunk/scipy/io/matlab/tests/gen_unittests4.m =================================================================== --- trunk/scipy/io/matlab/tests/gen_unittests4.m 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/tests/gen_unittests4.m 2008-11-09 00:44:40 UTC (rev 5025) @@ -1,50 +0,0 @@ -% Generates mat files for loadmat unit tests -% Uses save_test.m function -% This is the version for matlab 4 - -% work out matlab version and file suffix for test files -global FILEPREFIX FILESUFFIX -sepchar = '/'; -if strcmp(computer, 'PCWIN'), sepchar = '\'; end -FILEPREFIX = [pwd sepchar 'data' sepchar]; -mlv = version; -FILESUFFIX = ['_' mlv '_' computer '.mat']; - -% basic double array -save_test('testdouble', 0:pi/4:2*pi); - -% string -save_test('teststring', '"Do nine men interpret?" "Nine men," I nod.') - -% complex -theta = 0:pi/4:2*pi; -save_test('testcomplex', cos(theta) + 1j*sin(theta)); - -% asymmetric array to check indexing -a = zeros(3, 5); -a(:,1) = [1:3]'; -a(1,:) = 1:5; - -% 2D matrix -save_test('testmatrix', a); - -% minus number - tests signed int -save_test('testminus', -1); - -% single character -save_test('testonechar', 'r'); - -% string array -save_test('teststringarray', ['one '; 'two '; 'three']); - -% sparse array -save_test('testsparse', sparse(a)); - -% sparse complex array -b = sparse(a); -b(1,1) = b(1,1) + j; -save_test('testsparsecomplex', b); - -% Two variables in same file -save([FILEPREFIX 'testmulti' FILESUFFIX], 'a', 'theta') - Copied: trunk/scipy/io/matlab/tests/save_matfile.m (from rev 4827, trunk/scipy/io/matlab/tests/save_test.m) Deleted: trunk/scipy/io/matlab/tests/save_test.m =================================================================== --- trunk/scipy/io/matlab/tests/save_test.m 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/tests/save_test.m 2008-11-09 00:44:40 UTC (rev 5025) @@ -1,6 +0,0 @@ -function save_test(test_name, v) -% saves variable passed in m with filename from prefix - -global FILEPREFIX FILESUFFIX -eval([test_name ' = v;']); -save([FILEPREFIX test_name FILESUFFIX], test_name, '-V7.3') \ No newline at end of file Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-08 07:59:38 UTC (rev 5024) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 00:44:40 UTC (rev 5025) @@ -1,30 +1,41 @@ #!/usr/bin/env python ''' Nose test generators ''' -import os +from os.path import join, dirname from glob import glob -from cStringIO import StringIO +from StringIO import StringIO from tempfile import mkdtemp -from numpy.testing import * -from numpy import arange, array, pi, cos, exp, sin, sqrt, ndarray, \ - zeros, reshape, transpose, dtype, empty +import warnings +import shutil +import gzip + +from numpy.testing import \ + assert_array_almost_equal, \ + assert_equal, \ + assert_raises + +from nose.tools import assert_true + +import numpy as np +from numpy import array import scipy.sparse as SP from scipy.io.matlab.mio import loadmat, savemat from scipy.io.matlab.mio5 import MatlabObject -import shutil -import gzip +test_data_path = join(dirname(__file__), 'data') -test_data_path = os.path.join(os.path.dirname(__file__), 'data') - def _check_level(label, expected, actual): """ Check one level of a potentially nested object / list """ # object array is returned from cell array in mat file typex = type(expected) typac = type(actual) - if isinstance(expected, ndarray) and expected.dtype.hasobject: + if isinstance(expected, np.ndarray) and expected.dtype.hasobject: assert typex is typac, "Different types at %s" % label - assert len(expected) == len(actual), "Different list lengths at %s" % label + assert len(expected) == len(actual), \ + "Expected list length %d, got %d at %s" % ( + len(expected), + len(actual), + label) for i, ev in enumerate(expected): level_label = "%s, [%d], " % (label, i) _check_level(level_label, ev, actual[i]) @@ -38,7 +49,8 @@ for k in ex_fields: if k.startswith('__') and k.endswith('__'): continue - assert k in ac_fields, "Missing property at %s" % label + assert k in ac_fields, \ + "Missing expected property %s for %s" % (k, label) ev = expected.__dict__[k] v = actual.__dict__[k] level_label = "%s, property %s, " % (label, k) @@ -51,9 +63,14 @@ expected.todense(), err_msg = label, decimal = 5) - elif isinstance(expected, ndarray): + elif isinstance(expected, np.ndarray) and \ + expected.dtype.type not in (np.void, + np.unicode, + np.object, + np.unicode_): if expected.shape: # allow scalar and 0d array comparisons - assert isinstance(actual, ndarray), "Expected ndarray at %s" % label + assert isinstance(actual, np.ndarray), \ + "Expected ndarray at %s" % label assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) else: assert isinstance(expected, typac), \ @@ -78,20 +95,21 @@ _check_case(name, [mat_stream], expected) # Define cases to test -theta = pi/4*arange(9,dtype=float).reshape(9,1) +theta = np.pi/4*np.arange(9,dtype=float).reshape(1,9) case_table4 = [ {'name': 'double', 'expected': {'testdouble': theta} }] case_table4.append( {'name': 'string', - 'expected': {'teststring': u'"Do nine men interpret?" "Nine men," I nod.'}, + 'expected': {'teststring': + array([u'"Do nine men interpret?" "Nine men," I nod.'])}, }) case_table4.append( {'name': 'complex', - 'expected': {'testcomplex': cos(theta) + 1j*sin(theta)} + 'expected': {'testcomplex': np.cos(theta) + 1j*np.sin(theta)} }) -A = zeros((3,5)) +A = np.zeros((3,5)) A[0] = range(1,6) A[:,0] = range(1,4) case_table4.append( @@ -119,34 +137,42 @@ }) case_table4.append( {'name': 'onechar', - 'expected': {'testonechar': u'r'}, + 'expected': {'testonechar': array([u'r'])}, }) case_table5 = [ {'name': 'cell', 'expected': {'testcell': - array([u'This cell contains this string and 3 arrays of '+\ - 'increasing length', - array(1), array([1,2]), array([1,2,3])], - dtype=object)} + array([[ + array([u'This cell contains this string and 3 arrays of increasing length']), + array([[1]]), + array([[1,2]]), + array([[1,2,3]]) + ]], dtype=object)} }] case_table5.append( {'name': 'emptycell', 'expected': {'testemptycell': - array([array(1), array(2), array([]), - array([]), array(3)], dtype=object)} + array([[ + array([[1]]), + array([[2]]), + array([[]]), # This not returning with correct shape + array([[]]), + array([[3]])]], dtype=object)} }) case_table5.append( {'name': 'stringarray', 'expected': {'teststringarray': array( - [u'one ', u'two ', u'three'], dtype=object)}, + [u'one ', u'two ', u'three'])}, }) case_table5.append( {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + 'expected': { + 'test3dmatrix': np.transpose(np.reshape(range(1,25), (4,3,2)))} }) case_table5_rt = [ {'name': '3dmatrix', - 'expected': {'test3dmatrix': transpose(reshape(range(1,25), (4,3,2)))} + 'expected': { + 'test3dmatrix': np.transpose(np.reshape(range(1,25), (4,3,2)))} }, {'name': 'sparsefloat', 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, @@ -155,11 +181,16 @@ 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, }, ] -st = array([(u'Rats live on no evil star.', array([sqrt(2),exp(1),pi]), (1+1j)*array([sqrt(2),exp(1),pi]))], - dtype=[(n, object) for n in ['stringfield', 'doublefield', 'complexfield']]) +sr2 = np.sqrt(2) +dtype = [(n, object) for n in ['stringfield', 'doublefield', 'complexfield']] +st1 = array([ + [(u'Rats live on no evil star.', + array([sr2,np.exp(1), np.pi]), + (1+1j)*array([sr2,np.exp(1), np.pi]))] + ], dtype=dtype) case_table5.append( {'name': 'struct', - 'expected': {'teststruct': st} + 'expected': {'teststruct': st1} }) a = array([array(1), array([array(2), array(3), @@ -171,15 +202,15 @@ {'name': 'cellnest', 'expected': {'testcellnest': a}, }) -st = empty((1,1), dtype=[(n, object) for n in ['one', 'two']]) -st[0,0]['one'] = array(1) -st[0,0]['two'] = empty((1,1), dtype=[('three', object)]) -st[0,0]['two'][0,0]['three'] = u'number 3' +st2 = np.empty((1,1), dtype=[(n, object) for n in ['one', 'two']]) +st2[0,0]['one'] = array(1) +st2[0,0]['two'] = np.empty((1,1), dtype=[('three', object)]) +st2[0,0]['two'][0,0]['three'] = u'number 3' case_table5.append( {'name': 'structnest', - 'expected': {'teststructnest': st} + 'expected': {'teststructnest': st2} }) -a = empty((2,1), dtype=[(n, object) for n in ['one', 'two']]) +a = np.empty((2,1), dtype=[(n, object) for n in ['one', 'two']]) a[0,0]['one'] = array(1) a[0,0]['two'] = array(2) a[1,0]['one'] = u'number 1' @@ -188,7 +219,9 @@ {'name': 'structarr', 'expected': {'teststructarr': a} }) -a = MatlabObject('inline', ['expr', 'args', 'isEmpty', 'numArgs', 'version']) +a = MatlabObject('inline', + ['expr', 'inputExpr', 'args', + 'isEmpty', 'numArgs', 'version']) a.expr = u'x' a.inputExpr = u' x = INLINE_INPUTS_{1};' a.args = u'x' @@ -200,35 +233,33 @@ 'expected': {'testobject': a} }) u_str = file( - os.path.join(test_data_path, 'japanese_utf8.txt'), + join(test_data_path, 'japanese_utf8.txt'), 'rb').read().decode('utf-8') case_table5.append( {'name': 'unicode', - 'expected': {'testunicode': u_str} + 'expected': {'testunicode': array(u_str)} }) # generator for load tests - at dec.knownfailureif(True) def test_load(): for case in case_table4 + case_table5: name = case['name'] expected = case['expected'] - filt = os.path.join(test_data_path, 'test%s_*.mat' % name) + filt = join(test_data_path, 'test%s_*.mat' % name) files = glob(filt) assert files, "No files for test %s using filter %s" % (name, filt) yield _check_case, name, files, expected # generator for round trip tests - at dec.knownfailureif(True) def test_round_trip(): for case in case_table4 + case_table5_rt: name = case['name'] + '_round_trip' expected = case['expected'] format = case in case_table4 and '4' or '5' - #yield _rt_check_case, name, expected, format + yield _rt_check_case, name, expected, format def test_gzip_simple(): - xdense = zeros((20,20)) + xdense = np.zeros((20,20)) xdense[2,3]=2.3 xdense[4,5]=4.5 x = SP.csc_matrix(xdense) @@ -239,7 +270,7 @@ tmpdir = mkdtemp() try: - fname = os.path.join(tmpdir,name) + fname = join(tmpdir,name) mat_stream = gzip.open( fname,mode='wb') savemat(mat_stream, expected, format=format) mat_stream.close() @@ -257,6 +288,28 @@ def test_mat73(): # Check any hdf5 files raise an error filenames = glob( - os.path.join(test_data_path, 'testhdf5*.mat')) + join(test_data_path, 'testhdf5*.mat')) + assert len(filenames) for filename in filenames: assert_raises(NotImplementedError, loadmat, filename, struct_as_record=True) + +def test_warn_struct_record(): + # Use buffer hack to test for deprecation warning + warn_buf = StringIO() + base_show = warnings.showwarning + def showwarn(*args): + base_show(*args, **{'file':warn_buf}) + fname = join(test_data_path, 'testdouble_7.1_GLNX86.mat') + try: + warnings.showwarning = showwarn + # This should not generate a deprecation warning + mres = loadmat(fname, struct_as_record=True) + yield assert_true, warn_buf.tell() == 0 + # This neither + mres = loadmat(fname, struct_as_record=False) + yield assert_true, warn_buf.tell() == 0 + # This should + mres = loadmat(fname) + yield assert_true, warn_buf.tell() > 0 + finally: + warnings.showwarning = base_show From scipy-svn at scipy.org Sat Nov 8 21:32:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 20:32:10 -0600 (CST) Subject: [Scipy-svn] r5026 - trunk/scipy/io/matlab/tests Message-ID: <20081109023210.5009139C0F1@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-08 20:32:07 -0600 (Sat, 08 Nov 2008) New Revision: 5026 Modified: trunk/scipy/io/matlab/tests/test_mio.py Log: Cleaning up, fixing tests - errors remain Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 00:44:40 UTC (rev 5025) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 02:32:07 UTC (rev 5026) @@ -24,26 +24,32 @@ test_data_path = join(dirname(__file__), 'data') +def mlarr(*args, **kwargs): + ''' Return matlab-compatible 2D array''' + arr = np.array(*args, **kwargs) + return np.atleast_2d(arr) + +def _get_fields(obj): + ''' Return field names that we will compare ''' + + def _check_level(label, expected, actual): """ Check one level of a potentially nested object / list """ # object array is returned from cell array in mat file typex = type(expected) typac = type(actual) - if isinstance(expected, np.ndarray) and expected.dtype.hasobject: - assert typex is typac, "Different types at %s" % label - assert len(expected) == len(actual), \ - "Expected list length %d, got %d at %s" % ( - len(expected), - len(actual), - label) - for i, ev in enumerate(expected): - level_label = "%s, [%d], " % (label, i) - _check_level(level_label, ev, actual[i]) + if SP.issparse(expected): # allow different types of sparse matrices + assert SP.issparse(actual) + assert_array_almost_equal(actual.todense(), + expected.todense(), + err_msg = label, + decimal = 5) return - # object, as container for matlab structs and objects - elif isinstance(expected, MatlabObject): - assert isinstance(actual, typex), \ - "Different types %s and %s at %s" % (typex, typac, label) + # Check types are as expected + assert typex is typac, \ + "Expected type %s, got %s at %s" % (typex, typac, label) + # object, as container for matlab objects + if isinstance(expected, MatlabObject): ex_fields = dir(expected) ac_fields = dir(actual) for k in ex_fields: @@ -56,27 +62,26 @@ level_label = "%s, property %s, " % (label, k) _check_level(level_label, ev, v) return - # hoping this is a single value, which might be an array - if SP.issparse(expected): - assert SP.issparse(actual), "Expected sparse at %s" % label - assert_array_almost_equal(actual.todense(), - expected.todense(), - err_msg = label, - decimal = 5) - elif isinstance(expected, np.ndarray) and \ - expected.dtype.type not in (np.void, - np.unicode, - np.object, - np.unicode_): - if expected.shape: # allow scalar and 0d array comparisons - assert isinstance(actual, np.ndarray), \ - "Expected ndarray at %s" % label - assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) - else: - assert isinstance(expected, typac), \ - "Expected %s and actual %s do not match at %s" % \ - (typex, typac, label) + if not isinstance(expected, np.ndarray): + assert_equal(expected, actual) + return + if expected.dtype.hasobject: # array of objects + assert len(expected) == len(actual), \ + "Expected list length %d, got %d at %s" % ( + len(expected), + len(actual), + label) + for i, ev in enumerate(expected): + level_label = "%s, [%d], " % (label, i) + _check_level(level_label, ev, actual[i]) + return + if expected.dtype.type in ( + np.unicode, + np.object, + np.unicode_): assert_equal(actual, expected, err_msg=label) + return + assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) def _check_case(name, files, case): for file_name in files: @@ -118,13 +123,13 @@ }) case_table4.append( {'name': 'sparse', - 'expected': {'testsparse': SP.csc_matrix(A)}, + 'expected': {'testsparse': SP.coo_matrix(A)}, }) B = A.astype(complex) B[0,0] += 1j case_table4.append( {'name': 'sparsecomplex', - 'expected': {'testsparsecomplex': SP.csc_matrix(B)}, + 'expected': {'testsparsecomplex': SP.coo_matrix(B)}, }) case_table4.append( {'name': 'multi', @@ -133,7 +138,7 @@ }) case_table4.append( {'name': 'minus', - 'expected': {'testminus': array(-1)}, + 'expected': {'testminus': mlarr(-1)}, }) case_table4.append( {'name': 'onechar', @@ -142,22 +147,23 @@ case_table5 = [ {'name': 'cell', 'expected': {'testcell': - array([[ - array([u'This cell contains this string and 3 arrays of increasing length']), - array([[1]]), - array([[1,2]]), - array([[1,2,3]]) + mlarr([[ + array( + [u'This cell contains this string and 3 arrays of increasing length']), + mlarr([[1]]), + mlarr([[1,2]]), + mlarr([[1,2,3]]) ]], dtype=object)} }] case_table5.append( {'name': 'emptycell', 'expected': {'testemptycell': - array([[ - array([[1]]), - array([[2]]), - array([[]]), # This not returning with correct shape - array([[]]), - array([[3]])]], dtype=object)} + mlarr([[ + mlarr([[1]]), + mlarr([[2]]), + mlarr([[]]), # This not returning with correct shape + mlarr([[]]), + mlarr([[3]])]], dtype=object)} }) case_table5.append( {'name': 'stringarray', @@ -175,46 +181,49 @@ 'test3dmatrix': np.transpose(np.reshape(range(1,25), (4,3,2)))} }, {'name': 'sparsefloat', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[1,0,2],[0,-3.5,0]]))}, + 'expected': {'testsparsefloat': + SP.coo_matrix(array([[1,0,2],[0,-3.5,0]]))}, }, {'name': 'sparsecomplex', - 'expected': {'testsparsefloat': SP.csc_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, + 'expected': {'testsparsefloat': + SP.coo_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, }, ] -sr2 = np.sqrt(2) +st_sub_arr = array([np.sqrt(2),np.exp(1),np.pi]).reshape(1,3) dtype = [(n, object) for n in ['stringfield', 'doublefield', 'complexfield']] -st1 = array([ - [(u'Rats live on no evil star.', - array([sr2,np.exp(1), np.pi]), - (1+1j)*array([sr2,np.exp(1), np.pi]))] - ], dtype=dtype) +st1 = np.zeros((1,1), dtype) +st1['stringfield'][0,0] = array([u'Rats live on no evil star.']) +st1['doublefield'][0,0] = st_sub_arr +st1['complexfield'][0,0] = st_sub_arr * (1 + 1j) case_table5.append( {'name': 'struct', 'expected': {'teststruct': st1} }) -a = array([array(1), - array([array(2), array(3), - array([array(4), array(5)], - dtype=object)], - dtype=object)], - dtype=object) +CN = np.zeros((1,2), dtype=object) +CN[0,0] = mlarr(1) +CN[0,1] = np.zeros((1,3), dtype=object) +CN[0,1][0,0] = mlarr(2, dtype=np.uint8) +CN[0,1][0,1] = mlarr([[3]], dtype=np.uint8) +CN[0,1][0,2] = np.zeros((1,2), dtype=object) +CN[0,1][0,2][0,0] = mlarr(4, dtype=np.uint8) +CN[0,1][0,2][0,1] = mlarr(5, dtype=np.uint8) case_table5.append( {'name': 'cellnest', - 'expected': {'testcellnest': a}, + 'expected': {'testcellnest': CN}, }) st2 = np.empty((1,1), dtype=[(n, object) for n in ['one', 'two']]) -st2[0,0]['one'] = array(1) +st2[0,0]['one'] = mlarr(1) st2[0,0]['two'] = np.empty((1,1), dtype=[('three', object)]) -st2[0,0]['two'][0,0]['three'] = u'number 3' +st2[0,0]['two'][0,0]['three'] = array(u'number 3') case_table5.append( {'name': 'structnest', 'expected': {'teststructnest': st2} }) -a = np.empty((2,1), dtype=[(n, object) for n in ['one', 'two']]) -a[0,0]['one'] = array(1) -a[0,0]['two'] = array(2) -a[1,0]['one'] = u'number 1' -a[1,0]['two'] = u'number 2' +a = np.empty((1,2), dtype=[(n, object) for n in ['one', 'two']]) +a[0,0]['one'] = mlarr(1) +a[0,0]['two'] = mlarr(2) +a[0,1]['one'] = array(u'number 1') +a[0,1]['two'] = array(u'number 2') case_table5.append( {'name': 'structarr', 'expected': {'teststructarr': a} @@ -225,9 +234,9 @@ a.expr = u'x' a.inputExpr = u' x = INLINE_INPUTS_{1};' a.args = u'x' -a.isEmpty = array(0) -a.numArgs = array(1) -a.version = array(1) +a.isEmpty = mlarr(0) +a.numArgs = mlarr(1) +a.version = mlarr(1) case_table5.append( {'name': 'object', 'expected': {'testobject': a} From scipy-svn at scipy.org Sat Nov 8 22:25:44 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 21:25:44 -0600 (CST) Subject: [Scipy-svn] r5027 - in trunk/scipy/sparse/linalg/isolve: . tests Message-ID: <20081109032544.0173D39C0F1@scipy.org> Author: wnbell Date: 2008-11-08 21:25:42 -0600 (Sat, 08 Nov 2008) New Revision: 5027 Modified: trunk/scipy/sparse/linalg/isolve/iterative.py trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py Log: make sure callback function is called after final iteration Modified: trunk/scipy/sparse/linalg/isolve/iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-09 02:32:07 UTC (rev 5026) +++ trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-09 03:25:42 UTC (rev 5027) @@ -84,6 +84,8 @@ slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): + if callback is not None: + callback(x) break elif (ijob == 1): work[slice2] *= sclr2 @@ -172,6 +174,8 @@ slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): + if callback is not None: + callback(x) break elif (ijob == 1): if matvec is None: @@ -262,6 +266,8 @@ slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): + if callback is not None: + callback(x) break elif (ijob == 1): work[slice2] *= sclr2 @@ -346,6 +352,8 @@ slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): + if callback is not None: + callback(x) break elif (ijob == 1): work[slice2] *= sclr2 @@ -559,6 +567,8 @@ slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): + if callback is not None: + callback(x) break elif (ijob == 1): work[slice2] *= sclr2 @@ -585,3 +595,4 @@ ijob = 2 return postprocess(x), info + Modified: trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py 2008-11-09 02:32:07 UTC (rev 5026) +++ trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py 2008-11-09 03:25:42 UTC (rev 5027) @@ -77,12 +77,9 @@ x, info = solver(A, b, x0=x0, tol=1e-8, maxiter=3, callback=callback) - assert(len(residuals) in [2,3]) + assert_equal(len(residuals), 3) - # TODO enforce this condition instead! - #assert_equal(len(residuals), 2) - def test_convergence(self): """test whether all methods converge""" From scipy-svn at scipy.org Sat Nov 8 23:13:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 22:13:28 -0600 (CST) Subject: [Scipy-svn] r5028 - trunk/scipy/io/matlab/tests Message-ID: <20081109041328.19D1739C0F1@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-08 22:13:26 -0600 (Sat, 08 Nov 2008) New Revision: 5028 Modified: trunk/scipy/io/matlab/tests/test_mio.py Log: Cleaned up load tests, roundtrip test errors remain Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 03:25:42 UTC (rev 5027) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 04:13:26 UTC (rev 5028) @@ -27,17 +27,13 @@ def mlarr(*args, **kwargs): ''' Return matlab-compatible 2D array''' arr = np.array(*args, **kwargs) - return np.atleast_2d(arr) + if arr.size: + return np.atleast_2d(arr) + # empty elements return as shape (0,0) + return arr.reshape((0,0)) -def _get_fields(obj): - ''' Return field names that we will compare ''' - - def _check_level(label, expected, actual): - """ Check one level of a potentially nested object / list """ - # object array is returned from cell array in mat file - typex = type(expected) - typac = type(actual) + """ Check one level of a potentially nested array """ if SP.issparse(expected): # allow different types of sparse matrices assert SP.issparse(actual) assert_array_almost_equal(actual.todense(), @@ -46,6 +42,8 @@ decimal = 5) return # Check types are as expected + typex = type(expected) + typac = type(actual) assert typex is typac, \ "Expected type %s, got %s at %s" % (typex, typac, label) # object, as container for matlab objects @@ -62,25 +60,34 @@ level_label = "%s, property %s, " % (label, k) _check_level(level_label, ev, v) return - if not isinstance(expected, np.ndarray): + # A field in a record array may not be an ndarray + # A scalar from a record array will be type np.void + if not isinstance(expected, (np.void, np.ndarray)): assert_equal(expected, actual) return - if expected.dtype.hasobject: # array of objects - assert len(expected) == len(actual), \ - "Expected list length %d, got %d at %s" % ( - len(expected), - len(actual), - label) + # This is an ndarray + assert_true(expected.shape == actual.shape, + msg='Expected shape %s, got %s at %s' % (expected.shape, + actual.shape, + label) + ) + ex_dtype = expected.dtype + if ex_dtype.hasobject: # array of objects for i, ev in enumerate(expected): level_label = "%s, [%d], " % (label, i) _check_level(level_label, ev, actual[i]) return - if expected.dtype.type in ( - np.unicode, - np.object, - np.unicode_): + if ex_dtype.fields: # probably recarray + for fn in ex_dtype.fields: + level_label = "%s, field %s, " % (label, fn) + _check_level(level_label, + expected[fn], actual[fn]) + return + if ex_dtype.type in (np.unicode, # string + np.unicode_): assert_equal(actual, expected, err_msg=label) return + # Something numeric assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) def _check_case(name, files, case): @@ -144,27 +151,26 @@ {'name': 'onechar', 'expected': {'testonechar': array([u'r'])}, }) +# Cell arrays stored as object arrays +CA = mlarr([ + [], # placeholder, object array constructor wierdness otherwise + mlarr(1), + mlarr([1,2]), + mlarr([1,2,3])], dtype=object).reshape(1,-1) +CA[0,0] = array( + [u'This cell contains this string and 3 arrays of increasing length']) case_table5 = [ {'name': 'cell', - 'expected': {'testcell': - mlarr([[ - array( - [u'This cell contains this string and 3 arrays of increasing length']), - mlarr([[1]]), - mlarr([[1,2]]), - mlarr([[1,2,3]]) - ]], dtype=object)} - }] + 'expected': {'testcell': CA}}] +CAE = mlarr([ + mlarr(1), + mlarr(2), + mlarr([]), + mlarr([]), + mlarr(3)], dtype=object).reshape(1,-1) case_table5.append( {'name': 'emptycell', - 'expected': {'testemptycell': - mlarr([[ - mlarr([[1]]), - mlarr([[2]]), - mlarr([[]]), # This not returning with correct shape - mlarr([[]]), - mlarr([[3]])]], dtype=object)} - }) + 'expected': {'testemptycell': CAE}}) case_table5.append( {'name': 'stringarray', 'expected': {'teststringarray': array( @@ -214,7 +220,7 @@ st2 = np.empty((1,1), dtype=[(n, object) for n in ['one', 'two']]) st2[0,0]['one'] = mlarr(1) st2[0,0]['two'] = np.empty((1,1), dtype=[('three', object)]) -st2[0,0]['two'][0,0]['three'] = array(u'number 3') +st2[0,0]['two'][0,0]['three'] = array([u'number 3']) case_table5.append( {'name': 'structnest', 'expected': {'teststructnest': st2} @@ -222,31 +228,31 @@ a = np.empty((1,2), dtype=[(n, object) for n in ['one', 'two']]) a[0,0]['one'] = mlarr(1) a[0,0]['two'] = mlarr(2) -a[0,1]['one'] = array(u'number 1') -a[0,1]['two'] = array(u'number 2') +a[0,1]['one'] = array([u'number 1']) +a[0,1]['two'] = array([u'number 2']) case_table5.append( {'name': 'structarr', 'expected': {'teststructarr': a} }) -a = MatlabObject('inline', +MO = MatlabObject('inline', ['expr', 'inputExpr', 'args', 'isEmpty', 'numArgs', 'version']) -a.expr = u'x' -a.inputExpr = u' x = INLINE_INPUTS_{1};' -a.args = u'x' -a.isEmpty = mlarr(0) -a.numArgs = mlarr(1) -a.version = mlarr(1) +MO.expr = u'x' +MO.inputExpr = u' x = INLINE_INPUTS_{1};' +MO.args = u'x' +MO.isEmpty = mlarr(0) +MO.numArgs = mlarr(1) +MO.version = mlarr(1) case_table5.append( {'name': 'object', - 'expected': {'testobject': a} + 'expected': {'testobject': MO} }) u_str = file( join(test_data_path, 'japanese_utf8.txt'), 'rb').read().decode('utf-8') case_table5.append( {'name': 'unicode', - 'expected': {'testunicode': array(u_str)} + 'expected': {'testunicode': array([u_str])} }) # generator for load tests From scipy-svn at scipy.org Sun Nov 9 00:32:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 8 Nov 2008 23:32:51 -0600 (CST) Subject: [Scipy-svn] r5029 - in trunk/scipy/io/matlab: . tests Message-ID: <20081109053251.162C639C0F1@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-08 23:32:46 -0600 (Sat, 08 Nov 2008) New Revision: 5029 Modified: trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/tests/gen_mat5files.m trunk/scipy/io/matlab/tests/test_mio.py Log: Added all load checks to roundtrip checks, fixed transpose in save of char data in matlab 5, all 51 tests now pass for me Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-11-09 04:13:26 UTC (rev 5028) +++ trunk/scipy/io/matlab/mio5.py 2008-11-09 05:32:46 UTC (rev 5029) @@ -728,14 +728,22 @@ is_global=False, is_complex=False, is_logical=False, - nzmax=0): + nzmax=0, + shape=None): ''' Write header for given data options mclass - mat5 matrix class is_global - True if matrix is global is_complex - True if matrix is complex is_logical - True if matrix is logical nzmax - max non zero elements for sparse arrays + shape : {None, tuple} optional + directly specify shape if this is not the same as for + self.arr ''' + if shape is None: + shape = self.arr.shape + if len(shape) < 2: + shape = shape + (0,) * (len(shape)-2) self._mat_tag_pos = self.file_stream.tell() self.write_dtype(self.mat_tag) # write array flags (complex, global, logical, class, nzmax) @@ -746,13 +754,7 @@ af['flags_class'] = mclass | flags << 8 af['nzmax'] = nzmax self.write_dtype(af) - # write array shape - if self.arr.ndim < 2: - new_arr = np.atleast_2d(self.arr) - if type(new_arr) != type(self.arr): - raise ValueError("Array should be 2-dimensional.") - self.arr = new_arr - self.write_element(np.array(self.arr.shape, dtype='i4')) + self.write_element(np.array(shape, dtype='i4')) # write name self.write_element(np.array([ord(c) for c in self.name], 'i1')) @@ -786,22 +788,33 @@ self.write_element(self.arr) self.update_matrix_tag() + class Mat5CharWriter(Mat5MatrixWriter): codec='ascii' def write(self): self.arr_to_chars() - self.write_header(mclass=mxCHAR_CLASS) + # We have to write the shape directly, because we are going + # recode the characters, and the resulting stream of chars + # may have a different length + shape = self.arr.shape + self.write_header(mclass=mxCHAR_CLASS,shape=shape) + # We need to do our own transpose (not using the normal + # write routines that do this for us) + arr = self.arr.T.copy() if self.arr.dtype.kind == 'U': # Recode unicode using self.codec - n_chars = np.product(self.arr.shape) + n_chars = np.product(shape) st_arr = np.ndarray(shape=(), dtype=self.arr_dtype_number(n_chars), - buffer=self.arr) + buffer=arr) st = st_arr.item().encode(self.codec) - self.arr = np.ndarray(shape=(len(st)), dtype='u1', buffer=st) - self.write_element(self.arr,mdtype=miUTF8) + arr = np.ndarray(shape=(len(st),), + dtype='u1', + buffer=st) + self.write_element(arr, mdtype=miUTF8) self.update_matrix_tag() + class Mat5UniCharWriter(Mat5CharWriter): codec='UTF8' @@ -976,17 +989,20 @@ continue is_global = name in self.global_vars self.writer_getter.rewind() - self.writer_getter.matrix_writer_factory( + mat_writer = self.writer_getter.matrix_writer_factory( var, name, - is_global, - ).write() + is_global) + mat_writer.write() stream = self.writer_getter.stream + bytes_written = stream.tell() + stream.seek(0) + out_str = stream.read(bytes_written) if self.do_compression: - str = zlib.compress(stream.getvalue(stream.tell())) + out_str = zlib.compress(out_str) tag = np.empty((), mdtypes_template['tag_full']) tag['mdtype'] = miCOMPRESSED tag['byte_count'] = len(str) - self.file_stream.write(tag.tostring() + str) + self.file_stream.write(tag.tostring() + out_str) else: - self.file_stream.write(stream.getvalue(stream.tell())) + self.file_stream.write(out_str) Modified: trunk/scipy/io/matlab/tests/gen_mat5files.m =================================================================== --- trunk/scipy/io/matlab/tests/gen_mat5files.m 2008-11-09 04:13:26 UTC (rev 5028) +++ trunk/scipy/io/matlab/tests/gen_mat5files.m 2008-11-09 05:32:46 UTC (rev 5029) @@ -89,4 +89,8 @@ fclose(fid); save_matfile('testunicode', native2unicode(from_japan, 'utf-8')); end - \ No newline at end of file + +% sparse float + + +% sparse complex Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 04:13:26 UTC (rev 5028) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 05:32:46 UTC (rev 5029) @@ -25,87 +25,16 @@ test_data_path = join(dirname(__file__), 'data') def mlarr(*args, **kwargs): - ''' Return matlab-compatible 2D array''' + ''' Convenience function to return matlab-compatible 2D array + Note that matlab writes empty shape as (0,0) - replicated here + ''' arr = np.array(*args, **kwargs) if arr.size: return np.atleast_2d(arr) # empty elements return as shape (0,0) return arr.reshape((0,0)) -def _check_level(label, expected, actual): - """ Check one level of a potentially nested array """ - if SP.issparse(expected): # allow different types of sparse matrices - assert SP.issparse(actual) - assert_array_almost_equal(actual.todense(), - expected.todense(), - err_msg = label, - decimal = 5) - return - # Check types are as expected - typex = type(expected) - typac = type(actual) - assert typex is typac, \ - "Expected type %s, got %s at %s" % (typex, typac, label) - # object, as container for matlab objects - if isinstance(expected, MatlabObject): - ex_fields = dir(expected) - ac_fields = dir(actual) - for k in ex_fields: - if k.startswith('__') and k.endswith('__'): - continue - assert k in ac_fields, \ - "Missing expected property %s for %s" % (k, label) - ev = expected.__dict__[k] - v = actual.__dict__[k] - level_label = "%s, property %s, " % (label, k) - _check_level(level_label, ev, v) - return - # A field in a record array may not be an ndarray - # A scalar from a record array will be type np.void - if not isinstance(expected, (np.void, np.ndarray)): - assert_equal(expected, actual) - return - # This is an ndarray - assert_true(expected.shape == actual.shape, - msg='Expected shape %s, got %s at %s' % (expected.shape, - actual.shape, - label) - ) - ex_dtype = expected.dtype - if ex_dtype.hasobject: # array of objects - for i, ev in enumerate(expected): - level_label = "%s, [%d], " % (label, i) - _check_level(level_label, ev, actual[i]) - return - if ex_dtype.fields: # probably recarray - for fn in ex_dtype.fields: - level_label = "%s, field %s, " % (label, fn) - _check_level(level_label, - expected[fn], actual[fn]) - return - if ex_dtype.type in (np.unicode, # string - np.unicode_): - assert_equal(actual, expected, err_msg=label) - return - # Something numeric - assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) -def _check_case(name, files, case): - for file_name in files: - matdict = loadmat(file_name, struct_as_record=True) - label = "test %s; file %s" % (name, file_name) - for k, expected in case.items(): - k_label = "%s, variable %s" % (label, k) - assert k in matdict, "Missing key at %s" % k_label - _check_level(k_label, expected, matdict[k]) - -# Round trip tests -def _rt_check_case(name, expected, format): - mat_stream = StringIO() - savemat(mat_stream, expected, format=format) - mat_stream.seek(0) - _check_case(name, [mat_stream], expected) - # Define cases to test theta = np.pi/4*np.arange(9,dtype=float).reshape(1,9) case_table4 = [ @@ -181,20 +110,6 @@ 'expected': { 'test3dmatrix': np.transpose(np.reshape(range(1,25), (4,3,2)))} }) -case_table5_rt = [ - {'name': '3dmatrix', - 'expected': { - 'test3dmatrix': np.transpose(np.reshape(range(1,25), (4,3,2)))} - }, - {'name': 'sparsefloat', - 'expected': {'testsparsefloat': - SP.coo_matrix(array([[1,0,2],[0,-3.5,0]]))}, - }, - {'name': 'sparsecomplex', - 'expected': {'testsparsefloat': - SP.coo_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, - }, - ] st_sub_arr = array([np.sqrt(2),np.exp(1),np.pi]).reshape(1,3) dtype = [(n, object) for n in ['stringfield', 'doublefield', 'complexfield']] st1 = np.zeros((1,1), dtype) @@ -254,7 +169,95 @@ {'name': 'unicode', 'expected': {'testunicode': array([u_str])} }) +# These should also have matlab load equivalents, but I can't get to matlab at the moment +case_table5_rt = case_table5[:] +case_table5_rt.append( + {'name': 'sparsefloat', + 'expected': {'testsparsefloat': + SP.coo_matrix(array([[1,0,2],[0,-3.5,0]]))}, + }) +case_table5_rt.append( + {'name': 'sparsecomplex', + 'expected': {'testsparsecomplex': + SP.coo_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, + }) + +def _check_level(label, expected, actual): + """ Check one level of a potentially nested array """ + if SP.issparse(expected): # allow different types of sparse matrices + assert SP.issparse(actual) + assert_array_almost_equal(actual.todense(), + expected.todense(), + err_msg = label, + decimal = 5) + return + # Check types are as expected + typex = type(expected) + typac = type(actual) + assert typex is typac, \ + "Expected type %s, got %s at %s" % (typex, typac, label) + # object, as container for matlab objects + if isinstance(expected, MatlabObject): + ex_fields = dir(expected) + ac_fields = dir(actual) + for k in ex_fields: + if k.startswith('__') and k.endswith('__'): + continue + assert k in ac_fields, \ + "Missing expected property %s for %s" % (k, label) + ev = expected.__dict__[k] + v = actual.__dict__[k] + level_label = "%s, property %s, " % (label, k) + _check_level(level_label, ev, v) + return + # A field in a record array may not be an ndarray + # A scalar from a record array will be type np.void + if not isinstance(expected, (np.void, np.ndarray)): + assert_equal(expected, actual) + return + # This is an ndarray + assert_true(expected.shape == actual.shape, + msg='Expected shape %s, got %s at %s' % (expected.shape, + actual.shape, + label) + ) + ex_dtype = expected.dtype + if ex_dtype.hasobject: # array of objects + for i, ev in enumerate(expected): + level_label = "%s, [%d], " % (label, i) + _check_level(level_label, ev, actual[i]) + return + if ex_dtype.fields: # probably recarray + for fn in ex_dtype.fields: + level_label = "%s, field %s, " % (label, fn) + _check_level(level_label, + expected[fn], actual[fn]) + return + if ex_dtype.type in (np.unicode, # string + np.unicode_): + assert_equal(actual, expected, err_msg=label) + return + # Something numeric + assert_array_almost_equal(actual, expected, err_msg=label, decimal=5) + +def _load_check_case(name, files, case): + for file_name in files: + matdict = loadmat(file_name, struct_as_record=True) + label = "test %s; file %s" % (name, file_name) + for k, expected in case.items(): + k_label = "%s, variable %s" % (label, k) + assert k in matdict, "Missing key at %s" % k_label + _check_level(k_label, expected, matdict[k]) + +# Round trip tests +def _rt_check_case(name, expected, format): + mat_stream = StringIO() + savemat(mat_stream, expected, format=format) + mat_stream.seek(0) + _load_check_case(name, [mat_stream], expected) + + # generator for load tests def test_load(): for case in case_table4 + case_table5: @@ -263,7 +266,7 @@ filt = join(test_data_path, 'test%s_*.mat' % name) files = glob(filt) assert files, "No files for test %s using filter %s" % (name, filt) - yield _check_case, name, files, expected + yield _load_check_case, name, files, expected # generator for round trip tests def test_round_trip(): From scipy-svn at scipy.org Sun Nov 9 01:39:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 9 Nov 2008 00:39:29 -0600 (CST) Subject: [Scipy-svn] r5030 - in trunk/scipy/io/matlab: . tests Message-ID: <20081109063929.50EFD39C0F1@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-09 00:39:26 -0600 (Sun, 09 Nov 2008) New Revision: 5030 Modified: trunk/scipy/io/matlab/mio.py trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py trunk/scipy/io/matlab/tests/test_mio.py Log: Added extra warnings for future behavior change, pulled out try, finally incompatible with 2.4 Modified: trunk/scipy/io/matlab/mio.py =================================================================== --- trunk/scipy/io/matlab/mio.py 2008-11-09 05:32:46 UTC (rev 5029) +++ trunk/scipy/io/matlab/mio.py 2008-11-09 06:39:26 UTC (rev 5030) @@ -22,6 +22,9 @@ file name for mat file %(append_arg)s ''' + warnings.warn('Searching for mat files on python system path will be ' + + 'removed in future versions of scipy', + FutureWarning, stacklevel=2) if appendmat and file_name[-4:] == ".mat": file_name = file_name[:-4] if os.sep in file_name: @@ -55,10 +58,13 @@ %(struct_arg)s """ if isinstance(file_name, basestring): - full_name = find_mat_file(file_name, appendmat) - if full_name is None: - raise IOError, "%s not found on the path." % file_name - byte_stream = open(full_name, 'rb') + try: + byte_stream = open(file_name, 'rb') + except IOError: + full_name = find_mat_file(file_name, appendmat) + if full_name is None: + raise IOError, "%s not found on the path." % file_name + byte_stream = open(full_name, 'rb') else: try: file_name.read(0) @@ -110,7 +116,7 @@ return mdict @filldoc -def savemat(file_name, mdict, appendmat=True, format='4'): +def savemat(file_name, mdict, appendmat=True, format=None): """Save a dictionary of names and arrays into the MATLAB-style .mat file. This saves the arrayobjects in the given dictionary to a matlab @@ -126,6 +132,11 @@ '4' for matlab 4 mat files, '5' for matlab 5 (up to matlab 7.2) """ + if format is None: + warnings.warn( + "Using default format '4'. Default will change to '5' in future versions of scipy", + FutureWarning, stacklevel=2) + format = '4' file_is_string = isinstance(file_name, basestring) if file_is_string: if appendmat and file_name[-4:] != ".mat": Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-11-09 05:32:46 UTC (rev 5029) +++ trunk/scipy/io/matlab/mio5.py 2008-11-09 06:39:26 UTC (rev 5030) @@ -596,7 +596,7 @@ if struct_as_record is None: warnings.warn("Using struct_as_record default value (False)" + " This will change to True in future versions", - DeprecationWarning, stacklevel=2) + FutureWarning, stacklevel=2) struct_as_record = False self.codecs = {} # Missing inputs to array reader set later (processor func Modified: trunk/scipy/io/matlab/miobase.py =================================================================== --- trunk/scipy/io/matlab/miobase.py 2008-11-09 05:32:46 UTC (rev 5029) +++ trunk/scipy/io/matlab/miobase.py 2008-11-09 06:39:26 UTC (rev 5030) @@ -59,7 +59,7 @@ matlab files. In a future version of scipy, we will change the default setting to True, and following versions may remove this flag entirely. For now, we set the default to False, for - backwards compatibility, but issue a deprecation warning. + backwards compatibility, but issue a warning. Note that non-record arrays cannot be exported via savemat.''', 'matstream_arg': '''mat_stream : file-like Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 05:32:46 UTC (rev 5029) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 06:39:26 UTC (rev 5030) @@ -1,5 +1,7 @@ #!/usr/bin/env python -''' Nose test generators ''' +''' Nose test generators + +''' from os.path import join, dirname from glob import glob from StringIO import StringIO @@ -19,7 +21,7 @@ from numpy import array import scipy.sparse as SP -from scipy.io.matlab.mio import loadmat, savemat +from scipy.io.matlab.mio import loadmat, savemat, find_mat_file from scipy.io.matlab.mio5 import MatlabObject test_data_path = join(dirname(__file__), 'data') @@ -311,23 +313,27 @@ for filename in filenames: assert_raises(NotImplementedError, loadmat, filename, struct_as_record=True) -def test_warn_struct_record(): - # Use buffer hack to test for deprecation warning - warn_buf = StringIO() - base_show = warnings.showwarning - def showwarn(*args): - base_show(*args, **{'file':warn_buf}) + +def test_warnings(): fname = join(test_data_path, 'testdouble_7.1_GLNX86.mat') + warnings.simplefilter('error') + # This should not generate a warning + mres = loadmat(fname, struct_as_record=True) + # This neither + mres = loadmat(fname, struct_as_record=False) + # This should + yield assert_raises, FutureWarning, loadmat, fname + # This too + yield assert_raises, FutureWarning, find_mat_file, fname + # we need kwargs for this one try: - warnings.showwarning = showwarn - # This should not generate a deprecation warning - mres = loadmat(fname, struct_as_record=True) - yield assert_true, warn_buf.tell() == 0 - # This neither - mres = loadmat(fname, struct_as_record=False) - yield assert_true, warn_buf.tell() == 0 - # This should - mres = loadmat(fname) - yield assert_true, warn_buf.tell() > 0 - finally: - warnings.showwarning = base_show + mres = loadmat(fname, struct_as_record=False, basename='raw') + except DeprecationWarning: + pass + else: + assert False, 'Did not raise deprecation warning' + # Test warning for default format change + savemat(StringIO(), {}, False, '4') + savemat(StringIO(), {}, False, '5') + yield assert_raises, FutureWarning, savemat, StringIO(), {} + warnings.resetwarnings() From scipy-svn at scipy.org Sun Nov 9 09:34:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 9 Nov 2008 08:34:16 -0600 (CST) Subject: [Scipy-svn] r5031 - trunk/scipy/io/matlab/tests Message-ID: <20081109143416.B996439C0F1@scipy.org> Author: cdavid Date: 2008-11-09 08:34:11 -0600 (Sun, 09 Nov 2008) New Revision: 5031 Modified: trunk/scipy/io/matlab/tests/test_mio.py Log: Add regression test for 653. Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 06:39:26 UTC (rev 5030) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-09 14:34:11 UTC (rev 5031) @@ -337,3 +337,7 @@ savemat(StringIO(), {}, False, '5') yield assert_raises, FutureWarning, savemat, StringIO(), {} warnings.resetwarnings() + +def test_regression_653(): + """Regression test for #653.""" + savemat(StringIO(), {'d':{1:2}}, format='5') From scipy-svn at scipy.org Sun Nov 9 18:56:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 9 Nov 2008 17:56:23 -0600 (CST) Subject: [Scipy-svn] r5032 - trunk/scipy/interpolate/tests Message-ID: <20081109235623.D717239C088@scipy.org> Author: ptvirtan Date: 2008-11-09 17:56:13 -0600 (Sun, 09 Nov 2008) New Revision: 5032 Modified: trunk/scipy/interpolate/tests/test_rbf.py Log: test_rbf: use allclose instead assert_array_almost_equal to make tests more strict Modified: trunk/scipy/interpolate/tests/test_rbf.py =================================================================== --- trunk/scipy/interpolate/tests/test_rbf.py 2008-11-09 14:34:11 UTC (rev 5031) +++ trunk/scipy/interpolate/tests/test_rbf.py 2008-11-09 23:56:13 UTC (rev 5032) @@ -4,7 +4,7 @@ import numpy as np from numpy.testing import assert_array_almost_equal, assert_almost_equal -from numpy import linspace, sin, random, exp, log10 +from numpy import linspace, sin, random, exp, log10, allclose from scipy.interpolate.rbf import Rbf FUNCTIONS = ('multiquadric', 'inverse multiquadric', 'gaussian', @@ -59,15 +59,15 @@ #plt.plot(x, y, 'o', xi, sin(xi), ':', xi, yi, '-') #plt.title(function) #plt.show() - assert_array_almost_equal(yi, sin(xi), decimal=-np.int(log10(atol)) - 1, - err_msg="abs-diff: %f" % abs(yi - sin(xi)).max()) + msg = "abs-diff: %f" % abs(yi - sin(xi)).max() + assert allclose(yi, sin(xi), atol=atol), msg def test_rbf_regularity(): tolerances = { 'multiquadric': 0.05, - 'inverse multiquadric': 0.01, + 'inverse multiquadric': 0.02, 'gaussian': 0.01, - 'cubic': 0.1, + 'cubic': 0.15, 'quintic': 0.1, 'thin-plate': 0.1, 'linear': 0.2 From scipy-svn at scipy.org Sun Nov 9 20:58:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 9 Nov 2008 19:58:06 -0600 (CST) Subject: [Scipy-svn] r5033 - trunk/scipy/signal Message-ID: <20081110015806.D2EDB39C088@scipy.org> Author: ptvirtan Date: 2008-11-09 19:57:55 -0600 (Sun, 09 Nov 2008) New Revision: 5033 Modified: trunk/scipy/signal/signaltools.py Log: Fix signal.hilber* docstrings Modified: trunk/scipy/signal/signaltools.py =================================================================== --- trunk/scipy/signal/signaltools.py 2008-11-09 23:56:13 UTC (rev 5032) +++ trunk/scipy/signal/signaltools.py 2008-11-10 01:57:55 UTC (rev 5033) @@ -921,7 +921,36 @@ def hilbert(x, N=None): - """Return the hilbert transform of x of length N. + """Compute the analytic signal. + + The transformation is done along the first axis. + + Parameters + ---------- + x : array-like + Signal data + N : int, optional + Number of Fourier components. Default: ``x.shape[0]`` + + Returns + ------- + xa : ndarray, shape (N,) + x.shape[1:] + Analytic signal of `x` + + Notes + ----- + The analytic signal `x_a(t)` of `x(t)` is:: + + x_a = F^{-1}(F(x) 2U) = x + i y + + where ``F`` is the Fourier transform, ``U`` the unit step function, + and ``y`` the Hilbert transform of ``x``. [1] + + References + ---------- + .. [1] Wikipedia, "Analytic signal". + http://en.wikipedia.org/wiki/Analytic_signal + """ x = asarray(x) if N is None: @@ -946,7 +975,12 @@ return x def hilbert2(x,N=None): - """Return the '2-D' hilbert transform of x of length N. + """Compute the '2-D' analytic signal of `x` of length `N`. + + See also + -------- + hilbert + """ x = asarray(x) x = asarray(x) From scipy-svn at scipy.org Sun Nov 9 22:06:01 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 9 Nov 2008 21:06:01 -0600 (CST) Subject: [Scipy-svn] r5034 - in trunk/scipy/sparse/linalg/isolve: . tests Message-ID: <20081110030601.2594B39C0EA@scipy.org> Author: wnbell Date: 2008-11-09 21:05:57 -0600 (Sun, 09 Nov 2008) New Revision: 5034 Modified: trunk/scipy/sparse/linalg/isolve/iterative.py trunk/scipy/sparse/linalg/isolve/minres.py trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py Log: test 'info' output of iterative methods make GMRES use default restart of 10 (as opposed to n) resolves ticket #666 (the mark of the beast!) Modified: trunk/scipy/sparse/linalg/isolve/iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-10 01:57:55 UTC (rev 5033) +++ trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-10 03:05:57 UTC (rev 5034) @@ -1,14 +1,5 @@ -## Automatically adapted for scipy Oct 18, 2005 by +"""Iterative methods for solving linear systems""" - -# Iterative methods using reverse-communication raw material -# These methods solve -# Ax = b for x - -# where A must have A.matvec(x,*args) defined -# or be a numeric array - - __all__ = ['bicg','bicgstab','cg','cgs','gmres','qmr'] import _iterative @@ -106,6 +97,10 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 + + if info > 0 and iter_ == maxiter and resid > tol: + #info isn't set appropriately otherwise + info = iter_ return postprocess(x), info @@ -197,6 +192,10 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 + + if info > 0 and iter_ == maxiter and resid > tol: + #info isn't set appropriately otherwise + info = iter_ return postprocess(x), info @@ -284,6 +283,11 @@ bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 + + if info > 0 and iter_ == maxiter and resid > tol: + #info isn't set appropriately otherwise + info = iter_ + return postprocess(x), info @@ -369,11 +373,15 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 + + if info > 0 and iter_ == maxiter and resid > tol: + #info isn't set appropriately otherwise + info = iter_ return postprocess(x), info -def gmres(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None, M=None, callback=None): +def gmres(A, b, x0=None, tol=1e-5, restrt=20, maxiter=None, xtype=None, M=None, callback=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: @@ -397,7 +405,7 @@ x0 -- (0) default starting guess. tol -- (1e-5) relative tolerance to achieve - restrt -- (n) When to restart (change this to get faster performance -- but + restrt -- (10) When to restart (change this to get faster performance -- but may not converge). maxiter -- (10*n) maximum number of iterations xtype -- The type of the result. If None, then it will be @@ -416,14 +424,14 @@ if maxiter is None: maxiter = n*10 + restrt = min(restrt, n) + matvec = A.matvec psolve = M.matvec ltr = _type_conv[x.dtype.char] revcom = getattr(_iterative, ltr + 'gmresrevcom') stoptest = getattr(_iterative, ltr + 'stoptest2') - if restrt is None: - restrt = n resid = tol ndx1 = 1 ndx2 = -1 @@ -480,6 +488,10 @@ if iter_num > maxiter: break + + if info >= 0 and resid > tol: + #info isn't set appropriately otherwise + info = maxiter return postprocess(x), info @@ -593,6 +605,10 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 + + if info > 0 and iter_ == maxiter and resid > tol: + #info isn't set appropriately otherwise + info = iter_ return postprocess(x), info Modified: trunk/scipy/sparse/linalg/isolve/minres.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/minres.py 2008-11-10 01:57:55 UTC (rev 5033) +++ trunk/scipy/sparse/linalg/isolve/minres.py 2008-11-10 03:05:57 UTC (rev 5034) @@ -67,7 +67,7 @@ istop = 0; itn = 0; Anorm = 0; Acond = 0; rnorm = 0; ynorm = 0; - xtype = A.dtype #TODO update + xtype = x.dtype eps = finfo(xtype).eps @@ -273,9 +273,14 @@ print last + ' Arnorm = %12.4e' % (Arnorm,) print last + msg[istop+1] - return (postprocess(x),0) + if istop == 6: + info = maxiter + else: + info = 0 + return (postprocess(x),info) + if __name__ == '__main__': from scipy import ones, arange from scipy.linalg import norm Modified: trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py 2008-11-10 01:57:55 UTC (rev 5033) +++ trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py 2008-11-10 03:05:57 UTC (rev 5034) @@ -8,6 +8,7 @@ from scipy.linalg import norm from scipy.sparse import spdiags, csr_matrix +from scipy.sparse.linalg.interface import LinearOperator from scipy.sparse.linalg.isolve import cg, cgs, bicg, bicgstab, gmres, qmr, minres #def callback(x): @@ -66,6 +67,7 @@ """test whether maxiter is respected""" A = Poisson1D + tol = 1e-12 for solver,req_sym,req_pos in self.solvers: b = arange(A.shape[0], dtype=float) @@ -75,11 +77,11 @@ def callback(x): residuals.append( norm(b - A*x) ) - x, info = solver(A, b, x0=x0, tol=1e-8, maxiter=3, callback=callback) + x, info = solver(A, b, x0=x0, tol=tol, maxiter=3, callback=callback) assert_equal(len(residuals), 3) + assert_equal(info, 3) - def test_convergence(self): """test whether all methods converge""" @@ -101,33 +103,44 @@ assert( norm(b - A*x) < tol*norm(b) ) def test_precond(self): - """test whether all methods accept a preconditioner""" + """test whether all methods accept a trivial preconditioner""" tol = 1e-8 + + def identity(b,which=None): + """trivial preconditioner""" + return b for solver,req_sym,req_pos in self.solvers: + for A,sym,pos in self.cases: if req_sym and not sym: continue if req_pos and not pos: continue M,N = A.shape - D = spdiags( [abs(1.0/A.diagonal())], [0], M, N) - def precond(b,which=None): - return D*b + D = spdiags( [1.0/A.diagonal()], [0], M, N) - A = A.copy() - A.psolve = precond - A.rpsolve = precond - b = arange(A.shape[0], dtype=float) x0 = 0*b - x, info = solver(A, b, x0=x0, tol=tol) + precond = LinearOperator(A.shape, identity, rmatvec=identity) + if solver == qmr: + x, info = solver(A, b, M1=precond, M2=precond, x0=x0, tol=tol) + else: + x, info = solver(A, b, M=precond, x0=x0, tol=tol) assert_equal(info,0) assert( norm(b - A*x) < tol*norm(b) ) + + A = A.copy() + A.psolve = identity + A.rpsolve = identity + x, info = solver(A, b, x0=x0, tol=tol) + assert_equal(info,0) + assert( norm(b - A*x) < tol*norm(b) ) + class TestQMR(TestCase): def test_leftright_precond(self): """Check that QMR works with left and right preconditioners""" From scipy-svn at scipy.org Mon Nov 10 05:34:30 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 04:34:30 -0600 (CST) Subject: [Scipy-svn] r5035 - trunk/scipy/spatial Message-ID: <20081110103430.392EF39C260@scipy.org> Author: cdavid Date: 2008-11-10 04:34:25 -0600 (Mon, 10 Nov 2008) New Revision: 5035 Modified: trunk/scipy/spatial/ckdtree.pyx Log: Make inner indices 32 bits integers instead of long for 64 bits support. Modified: trunk/scipy/spatial/ckdtree.pyx =================================================================== --- trunk/scipy/spatial/ckdtree.pyx 2008-11-10 03:05:57 UTC (rev 5034) +++ trunk/scipy/spatial/ckdtree.pyx 2008-11-10 10:34:25 UTC (rev 5035) @@ -218,7 +218,7 @@ raise ValueError("leafsize must be at least 1") self.maxes = np.ascontiguousarray(np.amax(self.data,axis=0)) self.mins = np.ascontiguousarray(np.amin(self.data,axis=0)) - self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.int)) + self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.int32)) inner_data = self.data self.raw_data = inner_data.data From scipy-svn at scipy.org Mon Nov 10 07:35:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 06:35:49 -0600 (CST) Subject: [Scipy-svn] r5036 - trunk/scipy/lib/lapack/tests Message-ID: <20081110123549.ED6A339C05F@scipy.org> Author: cdavid Date: 2008-11-10 06:35:41 -0600 (Mon, 10 Nov 2008) New Revision: 5036 Modified: trunk/scipy/lib/lapack/tests/esv_tests.py Log: Make sure reference is 32 bits float when testing for 32 bits syevr. Modified: trunk/scipy/lib/lapack/tests/esv_tests.py =================================================================== --- trunk/scipy/lib/lapack/tests/esv_tests.py 2008-11-10 10:34:25 UTC (rev 5035) +++ trunk/scipy/lib/lapack/tests/esv_tests.py 2008-11-10 12:35:41 UTC (rev 5036) @@ -1,4 +1,4 @@ - +import numpy as np from numpy.testing import * from numpy import dot @@ -34,7 +34,12 @@ def check_syevr(self,sym='sy'): a = [[1,2,3],[2,2,3],[3,3,6]] - exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] + if self.lapack.prefix == 's': + exact_dtype = np.float32 + else: + exact_dtype = np.float + exact_w = np.array([-0.6699243371851365, 0.4876938861533345, + 9.182230451031804], exact_dtype) f = getattr(self.lapack,sym+'evr') w,v,info = f(a) assert not info,`info` @@ -56,7 +61,12 @@ def check_syevr_irange(self,sym='sy',irange=[0,2]): a = [[1,2,3],[2,2,3],[3,3,6]] - exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] + if self.lapack.prefix == 's': + exact_dtype = np.float32 + else: + exact_dtype = np.float + exact_w = np.array([-0.6699243371851365, 0.4876938861533345, + 9.182230451031804], exact_dtype) f = getattr(self.lapack,sym+'evr') w,v,info = f(a,irange=irange) assert not info,`info` From scipy-svn at scipy.org Mon Nov 10 07:36:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 06:36:09 -0600 (CST) Subject: [Scipy-svn] r5037 - trunk/scipy/lib/lapack/tests Message-ID: <20081110123609.DED4739C05F@scipy.org> Author: cdavid Date: 2008-11-10 06:36:01 -0600 (Mon, 10 Nov 2008) New Revision: 5037 Modified: trunk/scipy/lib/lapack/tests/esv_tests.py Log: Add the decimal precision when comparing results for scipy.lib.lapack. Modified: trunk/scipy/lib/lapack/tests/esv_tests.py =================================================================== --- trunk/scipy/lib/lapack/tests/esv_tests.py 2008-11-10 12:35:41 UTC (rev 5036) +++ trunk/scipy/lib/lapack/tests/esv_tests.py 2008-11-10 12:36:01 UTC (rev 5037) @@ -43,9 +43,9 @@ f = getattr(self.lapack,sym+'evr') w,v,info = f(a) assert not info,`info` - assert_array_almost_equal(w,exact_w) + assert_array_almost_equal(w,exact_w, decimal=self.decimal) for i in range(3): - assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i]) + assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i], decimal=self.decimal) ## def check_heevr_complex(self): ## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] @@ -73,9 +73,9 @@ rslice = slice(irange[0],irange[1]+1) m = irange[1] - irange[0] + 1 assert_equal(len(w),m) - assert_array_almost_equal(w,exact_w[rslice]) + assert_array_almost_equal(w,exact_w[rslice], decimal=self.decimal) for i in range(m): - assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i]) + assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i], decimal=self.decimal) def check_syevr_irange_low(self): self.check_syevr_irange(irange=[0,1]) From scipy-svn at scipy.org Mon Nov 10 08:20:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 07:20:57 -0600 (CST) Subject: [Scipy-svn] r5038 - in trunk/scipy: spatial stats Message-ID: <20081110132057.8962539C05F@scipy.org> Author: cdavid Date: 2008-11-10 07:20:36 -0600 (Mon, 10 Nov 2008) New Revision: 5038 Modified: trunk/scipy/spatial/ckdtree.c trunk/scipy/stats/vonmises_cython.c Log: Regenerate cython files with a cython handling sizeof(Py_ssize_t) != sizeof(npy_intp). Modified: trunk/scipy/spatial/ckdtree.c =================================================================== --- trunk/scipy/spatial/ckdtree.c 2008-11-10 12:36:01 UTC (rev 5037) +++ trunk/scipy/spatial/ckdtree.c 2008-11-10 13:20:36 UTC (rev 5038) @@ -1,4 +1,4 @@ -/* Generated by Cython 0.9.8.1.1 on Mon Oct 13 11:57:06 2008 */ +/* Generated by Cython 0.10 on Mon Nov 10 22:15:02 2008 */ #define PY_SSIZE_T_CLEAN #include "Python.h" @@ -31,14 +31,15 @@ typedef struct { void *buf; + PyObject *obj; Py_ssize_t len; + Py_ssize_t itemsize; int readonly; - const char *format; int ndim; + char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; - Py_ssize_t itemsize; void *internal; } Py_buffer; @@ -63,6 +64,9 @@ #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyString_Type PyBytes_Type @@ -104,8 +108,8 @@ #endif #include #define __PYX_HAVE_API__scipy__spatial__ckdtree +#include "stdlib.h" #include "numpy/arrayobject.h" -#include "stdlib.h" #ifdef __GNUC__ @@ -175,48 +179,31 @@ static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char **__pyx_f; -static INLINE void __Pyx_SafeReleaseBuffer(PyObject* obj, Py_buffer* info); + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, PyObject* kw_name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static INLINE void __Pyx_ZeroBuffer(Py_buffer* buf); /*proto*/ static INLINE const char* __Pyx_ConsumeWhitespace(const char* ts); /*proto*/ -static INLINE const char* __Pyx_BufferTypestringCheckEndian(const char* ts); /*proto*/ static void __Pyx_BufferNdimError(Py_buffer* buffer, int expected_ndim); /*proto*/ -static const char* __Pyx_BufferTypestringCheck_item_double(const char* ts); /*proto*/ +static const char* __Pyx_DescribeTokenInFormatString(const char* ts); /*proto*/ +static const char* __Pyx_CheckTypestring_double(const char* ts); /*proto*/ -static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd); /*proto*/ +static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast); /*proto*/ static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ -static const char* __Pyx_BufferTypestringCheck_item_nn___pyx_t_5numpy_int32_t(const char* ts); /*proto*/ +static const char* __Pyx_CheckTypestring_nn___pyx_t_5numpy_int32_t(const char* ts); /*proto*/ -static int __Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t(PyObject* obj, Py_buffer* buf, int flags, int nd); /*proto*/ -static const char* __Pyx_BufferTypestringCheck_item_int(const char* ts); /*proto*/ +static int __Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast); /*proto*/ -static int __Pyx_GetBuffer_int(PyObject* obj, Py_buffer* buf, int flags, int nd); /*proto*/ -static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ -#define __Pyx_BufPtrStrided2d(buf, i0, s0, i1, s1) ((char*)buf + i0 * s0 + i1 * s1) +static INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ -static INLINE void __Pyx_RaiseArgtupleTooLong(Py_ssize_t num_expected, Py_ssize_t num_found); /*proto*/ -#if (PY_MAJOR_VERSION < 3) && !(Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER) -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(PyObject *obj, Py_buffer *view); -#else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyObject_ReleaseBuffer -#endif - -Py_ssize_t __Pyx_zeros[] = {0, 0}; -Py_ssize_t __Pyx_minusones[] = {-1, -1}; - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ - -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ - -static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/ -static int __Pyx_EndUnpack(PyObject *); /*proto*/ - -static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - static INLINE PyObject *__Pyx_GetItemInt(PyObject *o, Py_ssize_t i, int is_unsigned) { PyObject *r; if (PyList_CheckExact(o) && 0 <= i && i < PyList_GET_SIZE(o)) { @@ -238,14 +225,45 @@ } return r; } +static const char* __Pyx_CheckTypestring_int(const char* ts); /*proto*/ +static int __Pyx_GetBuffer_int(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast); /*proto*/ +static void __Pyx_RaiseBufferIndexError(int axis); /*proto*/ +#define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); +static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else +#define __Pyx_GetBuffer PyObject_GetBuffer +#define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + +Py_ssize_t __Pyx_zeros[] = {0, 0}; +Py_ssize_t __Pyx_minusones[] = {-1, -1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ + +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/ +static int __Pyx_EndUnpack(PyObject *); /*proto*/ + +static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + static void __Pyx_WriteUnraisable(const char *name); /*proto*/ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/ -static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size); /*proto*/ -static PyObject *__Pyx_ImportModule(char *name); /*proto*/ +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static void __Pyx_AddTraceback(const char *funcname); /*proto*/ @@ -287,22 +305,60 @@ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; + +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":15 + * + * # priority queue + * cdef union heapcontents: # <<<<<<<<<<<<<< + * int intdata + * char* ptrdata + */ + union __pyx_t_5scipy_7spatial_7ckdtree_heapcontents { int intdata; char *ptrdata; }; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":19 + * char* ptrdata + * + * cdef struct heapitem: # <<<<<<<<<<<<<< + * double priority + * heapcontents contents + */ + struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem { double priority; union __pyx_t_5scipy_7spatial_7ckdtree_heapcontents contents; }; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":23 + * heapcontents contents + * + * cdef struct heap: # <<<<<<<<<<<<<< + * int n + * heapitem* heap + */ + struct __pyx_t_5scipy_7spatial_7ckdtree_heap { int n; struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem *heap; int space; }; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":139 + * + * # Tree structure + * cdef struct innernode: # <<<<<<<<<<<<<< + * int split_dim + * int n_points + */ + struct __pyx_t_5scipy_7spatial_7ckdtree_innernode { int split_dim; int n_points; @@ -311,6 +367,14 @@ struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *greater; }; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":145 + * innernode* less + * innernode* greater + * cdef struct leafnode: # <<<<<<<<<<<<<< + * int split_dim + * int n_points + */ + struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode { int split_dim; int n_points; @@ -318,11 +382,27 @@ int end_idx; }; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":153 + * # this is the standard trick for variable-size arrays: + * # malloc sizeof(nodeinfo)+self.m*sizeof(double) bytes. + * cdef struct nodeinfo: # <<<<<<<<<<<<<< + * innernode* node + * double side_distances[0] + */ + struct __pyx_t_5scipy_7spatial_7ckdtree_nodeinfo { struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *node; double side_distances[0]; }; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":157 + * double side_distances[0] + * + * cdef class cKDTree: # <<<<<<<<<<<<<< + * """kd-tree for quick nearest-neighbor lookup + * + */ + struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree { PyObject_HEAD struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *__pyx_vtab; @@ -347,18 +427,21 @@ void (*__query)(struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *, double *, int *, double *, int, double, double, double); }; static struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *__pyx_vtabptr_5scipy_7spatial_7ckdtree_cKDTree; +/* Module declarations from python_buffer */ + +/* Module declarations from stdlib */ + /* Module declarations from numpy */ /* Module declarations from numpy */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; -/* Module declarations from stdlib */ - /* Module declarations from scipy.spatial.ckdtree */ static PyTypeObject *__pyx_ptype_5scipy_7spatial_7ckdtree_cKDTree = 0; static double __pyx_v_5scipy_7spatial_7ckdtree_infinity; -static double __pyx_k_17; +static double __pyx_k_24; static PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heapcreate(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *, int); /*proto*/ static PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heapdestroy(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *); /*proto*/ static PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heapresize(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *, int); /*proto*/ @@ -379,6 +462,20 @@ static PyObject *__pyx_kp___dealloc__; static char __pyx_k_query[] = "query"; static PyObject *__pyx_kp_query; +static char __pyx_k_data[] = "data"; +static PyObject *__pyx_kp_data; +static char __pyx_k_leafsize[] = "leafsize"; +static PyObject *__pyx_kp_leafsize; +static char __pyx_k_x[] = "x"; +static PyObject *__pyx_kp_x; +static char __pyx_k_k[] = "k"; +static PyObject *__pyx_kp_k; +static char __pyx_k_eps[] = "eps"; +static PyObject *__pyx_kp_eps; +static char __pyx_k_p[] = "p"; +static PyObject *__pyx_kp_p; +static char __pyx_k_23[] = "distance_upper_bound"; +static PyObject *__pyx_kp_23; static char __pyx_k_numpy[] = "numpy"; static PyObject *__pyx_kp_numpy; static char __pyx_k_np[] = "np"; @@ -405,8 +502,8 @@ static PyObject *__pyx_kp_amin; static char __pyx_k_arange[] = "arange"; static PyObject *__pyx_kp_arange; -static char __pyx_k_int[] = "int"; -static PyObject *__pyx_kp_int; +static char __pyx_k_27[] = "int32"; +static PyObject *__pyx_kp_27; static char __pyx_k_asarray[] = "asarray"; static PyObject *__pyx_kp_asarray; static char __pyx_k_astype[] = "astype"; @@ -421,67 +518,164 @@ static PyObject *__pyx_kp_empty; static char __pyx_k_fill[] = "fill"; static PyObject *__pyx_kp_fill; -static char __pyx_k_22[] = "i"; -static PyObject *__pyx_kp_22; +static char __pyx_k_30[] = "i"; +static PyObject *__pyx_kp_30; static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_kp_18; -static char __pyx_k_18[] = "Heap containing %d items cannot be resized to %d"; -static PyObject *__pyx_kp_19; -static char __pyx_k_19[] = "leafsize must be at least 1"; -static PyObject *__pyx_kp_20; -static PyObject *__pyx_kp_21; -static char __pyx_k_20[] = "x must consist of vectors of length %d but has shape %s"; -static char __pyx_k_21[] = "Only p-norms with 1<=p<=infinity permitted"; +static PyObject *__pyx_kp_25; +static char __pyx_k_25[] = "Heap containing %d items cannot be resized to %d"; +static PyObject *__pyx_kp_26; +static char __pyx_k_26[] = "leafsize must be at least 1"; +static PyObject *__pyx_kp_28; +static PyObject *__pyx_kp_29; +static char __pyx_k_28[] = "x must consist of vectors of length %d but has shape %s"; +static char __pyx_k_29[] = "Only p-norms with 1<=p<=infinity permitted"; static char __pyx_k___getbuffer__[] = "__getbuffer__"; static PyObject *__pyx_kp___getbuffer__; +static char __pyx_k___releasebuffer__[] = "__releasebuffer__"; +static PyObject *__pyx_kp___releasebuffer__; +static char __pyx_k_info[] = "info"; +static PyObject *__pyx_kp_info; +static char __pyx_k_flags[] = "flags"; +static PyObject *__pyx_kp_flags; +static char __pyx_k_iteritems[] = "iteritems"; +static PyObject *__pyx_kp_iteritems; +static char __pyx_k_next[] = "next"; +static PyObject *__pyx_kp_next; +static char __pyx_k_StopIteration[] = "StopIteration"; +static PyObject *__pyx_kp_StopIteration; +static char __pyx_k_pop[] = "pop"; +static PyObject *__pyx_kp_pop; static char __pyx_k_RuntimeError[] = "RuntimeError"; static PyObject *__pyx_kp_RuntimeError; static PyObject *__pyx_kp_1; -static PyObject *__pyx_kp_16; +static PyObject *__pyx_kp_2; +static PyObject *__pyx_kp_20; +static PyObject *__pyx_kp_21; +static PyObject *__pyx_kp_22; +static PyObject *__pyx_builtin_StopIteration; static PyObject *__pyx_builtin_RuntimeError; -static char __pyx_k_1[] = "Py_intptr_t and Py_ssize_t differs in size, numpy.pxd does not support this"; -static char __pyx_k_2[] = "b"; -static char __pyx_k_3[] = "B"; -static char __pyx_k_4[] = "h"; -static char __pyx_k_5[] = "H"; -static char __pyx_k_6[] = "i"; -static char __pyx_k_7[] = "I"; -static char __pyx_k_8[] = "l"; -static char __pyx_k_9[] = "L"; -static char __pyx_k_10[] = "q"; -static char __pyx_k_11[] = "Q"; -static char __pyx_k_12[] = "f"; -static char __pyx_k_13[] = "d"; -static char __pyx_k_14[] = "g"; -static char __pyx_k_15[] = "O"; -static char __pyx_k_16[] = "only objects, int and float dtypes supported for ndarray buffer access so far (dtype is %d)"; +static char __pyx_k_1[] = "ndarray is not C contiguous"; +static char __pyx_k_2[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_3[] = "b"; +static char __pyx_k_4[] = "B"; +static char __pyx_k_5[] = "h"; +static char __pyx_k_6[] = "H"; +static char __pyx_k_7[] = "i"; +static char __pyx_k_8[] = "I"; +static char __pyx_k_9[] = "l"; +static char __pyx_k_10[] = "L"; +static char __pyx_k_11[] = "q"; +static char __pyx_k_12[] = "Q"; +static char __pyx_k_13[] = "f"; +static char __pyx_k_14[] = "d"; +static char __pyx_k_15[] = "g"; +static char __pyx_k_16[] = "Zf"; +static char __pyx_k_17[] = "Zd"; +static char __pyx_k_18[] = "Zg"; +static char __pyx_k_19[] = "O"; +static char __pyx_k_20[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_21[] = "Format string allocated too short."; +static char __pyx_k_22[] = "unknown dtype code in numpy.pxd (%d)"; +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":28 + * int space + * + * cdef inline heapcreate(heap* self,int initial_size): # <<<<<<<<<<<<<< + * self.space = initial_size + * self.heap = stdlib.malloc(sizeof(heapitem)*self.space) + */ + static INLINE PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heapcreate(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *__pyx_v_self, int __pyx_v_initial_size) { PyObject *__pyx_r; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":29 + * + * cdef inline heapcreate(heap* self,int initial_size): + * self.space = initial_size # <<<<<<<<<<<<<< + * self.heap = stdlib.malloc(sizeof(heapitem)*self.space) + * self.n=0 + */ __pyx_v_self->space = __pyx_v_initial_size; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":30 + * cdef inline heapcreate(heap* self,int initial_size): + * self.space = initial_size + * self.heap = stdlib.malloc(sizeof(heapitem)*self.space) # <<<<<<<<<<<<<< + * self.n=0 + * + */ __pyx_v_self->heap = ((struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem *)malloc(((sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem)) * __pyx_v_self->space))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":31 + * self.space = initial_size + * self.heap = stdlib.malloc(sizeof(heapitem)*self.space) + * self.n=0 # <<<<<<<<<<<<<< + * + * cdef inline heapdestroy(heap* self): + */ __pyx_v_self->n = 0; __pyx_r = Py_None; Py_INCREF(Py_None); return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":33 + * self.n=0 + * + * cdef inline heapdestroy(heap* self): # <<<<<<<<<<<<<< + * stdlib.free(self.heap) + * + */ + static INLINE PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heapdestroy(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *__pyx_v_self) { PyObject *__pyx_r; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":34 + * + * cdef inline heapdestroy(heap* self): + * stdlib.free(self.heap) # <<<<<<<<<<<<<< + * + * cdef inline heapresize(heap* self, int new_space): + */ free(__pyx_v_self->heap); __pyx_r = Py_None; Py_INCREF(Py_None); return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":36 + * stdlib.free(self.heap) + * + * cdef inline heapresize(heap* self, int new_space): # <<<<<<<<<<<<<< + * if new_spacen); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":38 + * cdef inline heapresize(heap* self, int new_space): + * if new_spacestdlib.realloc(self.heap,new_space*sizeof(heapitem)) + */ __pyx_2 = PyInt_FromLong(__pyx_v_self->n); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = PyInt_FromLong(__pyx_v_new_space); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_4 = PyTuple_New(2); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -489,20 +683,36 @@ PyTuple_SET_ITEM(__pyx_4, 1, __pyx_3); __pyx_2 = 0; __pyx_3 = 0; - __pyx_2 = PyNumber_Remainder(__pyx_kp_18, ((PyObject *)__pyx_4)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(__pyx_kp_25, ((PyObject *)__pyx_4)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_4)); __pyx_4 = 0; - __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_3, 0, __pyx_2); - __pyx_2 = 0; - __pyx_4 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; - __Pyx_Raise(__pyx_4, 0, 0); - Py_DECREF(__pyx_4); __pyx_4 = 0; + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; + __Pyx_Raise(__pyx_3, 0, 0); + Py_DECREF(__pyx_3); __pyx_3 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L3; } __pyx_L3:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":39 + * if new_spacestdlib.realloc(self.heap,new_space*sizeof(heapitem)) + * + */ __pyx_v_self->space = __pyx_v_new_space; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":40 + * raise ValueError("Heap containing %d items cannot be resized to %d" % (self.n, new_space)) + * self.space = new_space + * self.heap = stdlib.realloc(self.heap,new_space*sizeof(heapitem)) # <<<<<<<<<<<<<< + * + * cdef inline heappush(heap* self, heapitem item): + */ __pyx_v_self->heap = ((struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem *)realloc(((void *)__pyx_v_self->heap), (__pyx_v_new_space * (sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem))))); __pyx_r = Py_None; Py_INCREF(Py_None); @@ -517,31 +727,119 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":42 + * self.heap = stdlib.realloc(self.heap,new_space*sizeof(heapitem)) + * + * cdef inline heappush(heap* self, heapitem item): # <<<<<<<<<<<<<< + * cdef int i + * cdef heapitem t + */ + static INLINE PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heappush(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *__pyx_v_self, struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_v_item) { int __pyx_v_i; struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_v_t; PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":46 + * cdef heapitem t + * + * self.n += 1 # <<<<<<<<<<<<<< + * if self.n>self.space: + * heapresize(self,2*self.space+1) + */ __pyx_v_self->n += 1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":47 + * + * self.n += 1 + * if self.n>self.space: # <<<<<<<<<<<<<< + * heapresize(self,2*self.space+1) + * + */ __pyx_1 = (__pyx_v_self->n > __pyx_v_self->space); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":48 + * self.n += 1 + * if self.n>self.space: + * heapresize(self,2*self.space+1) # <<<<<<<<<<<<<< + * + * i = self.n-1 + */ __pyx_2 = __pyx_f_5scipy_7spatial_7ckdtree_heapresize(__pyx_v_self, ((2 * __pyx_v_self->space) + 1)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; goto __pyx_L3; } __pyx_L3:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":50 + * heapresize(self,2*self.space+1) + * + * i = self.n-1 # <<<<<<<<<<<<<< + * self.heap[i] = item + * while i>0 and self.heap[i].priorityn - 1); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":51 + * + * i = self.n-1 + * self.heap[i] = item # <<<<<<<<<<<<<< + * while i>0 and self.heap[i].priorityheap[__pyx_v_i]) = __pyx_v_item; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":52 + * i = self.n-1 + * self.heap[i] = item + * while i>0 and self.heap[i].priority 0); if (__pyx_1) { __pyx_1 = ((__pyx_v_self->heap[__pyx_v_i]).priority < (__pyx_v_self->heap[((__pyx_v_i - 1) / 2)]).priority); } if (!__pyx_1) break; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":53 + * self.heap[i] = item + * while i>0 and self.heap[i].priorityheap[((__pyx_v_i - 1) / 2)]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":54 + * while i>0 and self.heap[i].priorityheap[((__pyx_v_i - 1) / 2)]) = (__pyx_v_self->heap[__pyx_v_i]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":55 + * t = self.heap[(i-1)//2] + * self.heap[(i-1)//2] = self.heap[i] + * self.heap[i] = t # <<<<<<<<<<<<<< + * i = (i-1)//2 + * + */ (__pyx_v_self->heap[__pyx_v_i]) = __pyx_v_t; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":56 + * self.heap[(i-1)//2] = self.heap[i] + * self.heap[i] = t + * i = (i-1)//2 # <<<<<<<<<<<<<< + * + * cdef heapitem heappeek(heap* self): + */ __pyx_v_i = ((__pyx_v_i - 1) / 2); } @@ -555,8 +853,24 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":58 + * i = (i-1)//2 + * + * cdef heapitem heappeek(heap* self): # <<<<<<<<<<<<<< + * return self.heap[0] + * + */ + static struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_f_5scipy_7spatial_7ckdtree_heappeek(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *__pyx_v_self) { struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_r; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":59 + * + * cdef heapitem heappeek(heap* self): + * return self.heap[0] # <<<<<<<<<<<<<< + * + * cdef heapremove(heap* self): + */ __pyx_r = (__pyx_v_self->heap[0]); goto __pyx_L0; @@ -564,6 +878,14 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":61 + * return self.heap[0] + * + * cdef heapremove(heap* self): # <<<<<<<<<<<<<< + * cdef heapitem t + * cdef int i, j, k, l + */ + static PyObject *__pyx_f_5scipy_7spatial_7ckdtree_heapremove(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *__pyx_v_self) { struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_v_t; int __pyx_v_i; @@ -573,50 +895,210 @@ PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":65 + * cdef int i, j, k, l + * + * self.heap[0] = self.heap[self.n-1] # <<<<<<<<<<<<<< + * self.n -= 1 + * if self.n < self.space//4 and self.space>40: #FIXME: magic number + */ (__pyx_v_self->heap[0]) = (__pyx_v_self->heap[(__pyx_v_self->n - 1)]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":66 + * + * self.heap[0] = self.heap[self.n-1] + * self.n -= 1 # <<<<<<<<<<<<<< + * if self.n < self.space//4 and self.space>40: #FIXME: magic number + * heapresize(self,self.space//2+1) + */ __pyx_v_self->n -= 1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":67 + * self.heap[0] = self.heap[self.n-1] + * self.n -= 1 + * if self.n < self.space//4 and self.space>40: #FIXME: magic number # <<<<<<<<<<<<<< + * heapresize(self,self.space//2+1) + * + */ __pyx_1 = (__pyx_v_self->n < (__pyx_v_self->space / 4)); if (__pyx_1) { __pyx_1 = (__pyx_v_self->space > 40); } if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":68 + * self.n -= 1 + * if self.n < self.space//4 and self.space>40: #FIXME: magic number + * heapresize(self,self.space//2+1) # <<<<<<<<<<<<<< + * + * i=0 + */ __pyx_2 = __pyx_f_5scipy_7spatial_7ckdtree_heapresize(__pyx_v_self, ((__pyx_v_self->space / 2) + 1)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 68; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; goto __pyx_L3; } __pyx_L3:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":70 + * heapresize(self,self.space//2+1) + * + * i=0 # <<<<<<<<<<<<<< + * j=1 + * k=2 + */ __pyx_v_i = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":71 + * + * i=0 + * j=1 # <<<<<<<<<<<<<< + * k=2 + * while ((j self.heap[j].priority or + */ __pyx_v_k = 2; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":73 + * j=1 + * k=2 + * while ((j self.heap[j].priority or + * kn); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":74 + * k=2 + * while ((j self.heap[j].priority or # <<<<<<<<<<<<<< + * k self.heap[k].priority)): + */ __pyx_1 = ((__pyx_v_self->heap[__pyx_v_i]).priority > (__pyx_v_self->heap[__pyx_v_j]).priority); } if (!__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":75 + * while ((j self.heap[j].priority or + * k self.heap[k].priority)): + * if kself.heap[k].priority: + */ __pyx_1 = (__pyx_v_k < __pyx_v_self->n); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":76 + * self.heap[i].priority > self.heap[j].priority or + * k self.heap[k].priority)): # <<<<<<<<<<<<<< + * if kself.heap[k].priority: + * l = k + */ __pyx_1 = ((__pyx_v_self->heap[__pyx_v_i]).priority > (__pyx_v_self->heap[__pyx_v_k]).priority); } } if (!__pyx_1) break; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":77 + * k self.heap[k].priority)): + * if kself.heap[k].priority: # <<<<<<<<<<<<<< + * l = k + * else: + */ __pyx_1 = (__pyx_v_k < __pyx_v_self->n); if (__pyx_1) { __pyx_1 = ((__pyx_v_self->heap[__pyx_v_j]).priority > (__pyx_v_self->heap[__pyx_v_k]).priority); } if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":78 + * self.heap[i].priority > self.heap[k].priority)): + * if kself.heap[k].priority: + * l = k # <<<<<<<<<<<<<< + * else: + * l = j + */ __pyx_v_l = __pyx_v_k; goto __pyx_L6; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":80 + * l = k + * else: + * l = j # <<<<<<<<<<<<<< + * t = self.heap[l] + * self.heap[l] = self.heap[i] + */ __pyx_v_l = __pyx_v_j; } __pyx_L6:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":81 + * else: + * l = j + * t = self.heap[l] # <<<<<<<<<<<<<< + * self.heap[l] = self.heap[i] + * self.heap[i] = t + */ __pyx_v_t = (__pyx_v_self->heap[__pyx_v_l]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":82 + * l = j + * t = self.heap[l] + * self.heap[l] = self.heap[i] # <<<<<<<<<<<<<< + * self.heap[i] = t + * i = l + */ (__pyx_v_self->heap[__pyx_v_l]) = (__pyx_v_self->heap[__pyx_v_i]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":83 + * t = self.heap[l] + * self.heap[l] = self.heap[i] + * self.heap[i] = t # <<<<<<<<<<<<<< + * i = l + * j = 2*i+1 + */ (__pyx_v_self->heap[__pyx_v_i]) = __pyx_v_t; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":84 + * self.heap[l] = self.heap[i] + * self.heap[i] = t + * i = l # <<<<<<<<<<<<<< + * j = 2*i+1 + * k = 2*i+2 + */ __pyx_v_i = __pyx_v_l; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":85 + * self.heap[i] = t + * i = l + * j = 2*i+1 # <<<<<<<<<<<<<< + * k = 2*i+2 + * + */ __pyx_v_j = ((2 * __pyx_v_i) + 1); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":86 + * i = l + * j = 2*i+1 + * k = 2*i+2 # <<<<<<<<<<<<<< + * + * cdef heapitem heappop(heap* self): + */ __pyx_v_k = ((2 * __pyx_v_i) + 2); } @@ -630,13 +1112,45 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":88 + * k = 2*i+2 + * + * cdef heapitem heappop(heap* self): # <<<<<<<<<<<<<< + * cdef heapitem it + * it = heappeek(self) + */ + static struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_f_5scipy_7spatial_7ckdtree_heappop(struct __pyx_t_5scipy_7spatial_7ckdtree_heap *__pyx_v_self) { struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_v_it; struct __pyx_t_5scipy_7spatial_7ckdtree_heapitem __pyx_r; PyObject *__pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":90 + * cdef heapitem heappop(heap* self): + * cdef heapitem it + * it = heappeek(self) # <<<<<<<<<<<<<< + * heapremove(self) + * return it + */ __pyx_v_it = __pyx_f_5scipy_7spatial_7ckdtree_heappeek(__pyx_v_self); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":91 + * cdef heapitem it + * it = heappeek(self) + * heapremove(self) # <<<<<<<<<<<<<< + * return it + * + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heapremove(__pyx_v_self); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 91; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":92 + * it = heappeek(self) + * heapremove(self) + * return it # <<<<<<<<<<<<<< + * + * + */ __pyx_r = __pyx_v_it; goto __pyx_L0; @@ -648,16 +1162,48 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":99 + * + * # utility functions + * cdef inline double dmax(double x, double y): # <<<<<<<<<<<<<< + * if x>y: + * return x + */ + static INLINE double __pyx_f_5scipy_7spatial_7ckdtree_dmax(double __pyx_v_x, double __pyx_v_y) { double __pyx_r; int __pyx_1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":100 + * # utility functions + * cdef inline double dmax(double x, double y): + * if x>y: # <<<<<<<<<<<<<< + * return x + * else: + */ __pyx_1 = (__pyx_v_x > __pyx_v_y); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":101 + * cdef inline double dmax(double x, double y): + * if x>y: + * return x # <<<<<<<<<<<<<< + * else: + * return y + */ __pyx_r = __pyx_v_x; goto __pyx_L0; goto __pyx_L3; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":103 + * return x + * else: + * return y # <<<<<<<<<<<<<< + * cdef inline double dabs(double x): + * if x>0: + */ __pyx_r = __pyx_v_y; goto __pyx_L0; } @@ -668,16 +1214,48 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":104 + * else: + * return y + * cdef inline double dabs(double x): # <<<<<<<<<<<<<< + * if x>0: + * return x + */ + static INLINE double __pyx_f_5scipy_7spatial_7ckdtree_dabs(double __pyx_v_x) { double __pyx_r; int __pyx_1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":105 + * return y + * cdef inline double dabs(double x): + * if x>0: # <<<<<<<<<<<<<< + * return x + * else: + */ __pyx_1 = (__pyx_v_x > 0); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":106 + * cdef inline double dabs(double x): + * if x>0: + * return x # <<<<<<<<<<<<<< + * else: + * return -x + */ __pyx_r = __pyx_v_x; goto __pyx_L0; goto __pyx_L3; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":108 + * return x + * else: + * return -x # <<<<<<<<<<<<<< + * cdef inline double _distance_p(double*x,double*y,double p,int k,double upperbound): + * """Compute the distance between x and y + */ __pyx_r = (-__pyx_v_x); goto __pyx_L0; } @@ -688,18 +1266,74 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":109 + * else: + * return -x + * cdef inline double _distance_p(double*x,double*y,double p,int k,double upperbound): # <<<<<<<<<<<<<< + * """Compute the distance between x and y + * + */ + static INLINE double __pyx_f_5scipy_7spatial_7ckdtree__distance_p(double *__pyx_v_x, double *__pyx_v_y, double __pyx_v_p, int __pyx_v_k, double __pyx_v_upperbound) { int __pyx_v_i; double __pyx_v_r; double __pyx_r; int __pyx_1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":118 + * cdef int i + * cdef double r + * r = 0 # <<<<<<<<<<<<<< + * if p==infinity: + * for i in range(k): + */ __pyx_v_r = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":119 + * cdef double r + * r = 0 + * if p==infinity: # <<<<<<<<<<<<<< + * for i in range(k): + * r = dmax(r,dabs(x[i]-y[i])) + */ __pyx_1 = (__pyx_v_p == __pyx_v_5scipy_7spatial_7ckdtree_infinity); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":120 + * r = 0 + * if p==infinity: + * for i in range(k): # <<<<<<<<<<<<<< + * r = dmax(r,dabs(x[i]-y[i])) + * if r>upperbound: + */ for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_k; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":121 + * if p==infinity: + * for i in range(k): + * r = dmax(r,dabs(x[i]-y[i])) # <<<<<<<<<<<<<< + * if r>upperbound: + * return r + */ __pyx_v_r = __pyx_f_5scipy_7spatial_7ckdtree_dmax(__pyx_v_r, __pyx_f_5scipy_7spatial_7ckdtree_dabs(((__pyx_v_x[__pyx_v_i]) - (__pyx_v_y[__pyx_v_i])))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":122 + * for i in range(k): + * r = dmax(r,dabs(x[i]-y[i])) + * if r>upperbound: # <<<<<<<<<<<<<< + * return r + * elif p==1: + */ __pyx_1 = (__pyx_v_r > __pyx_v_upperbound); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":123 + * r = dmax(r,dabs(x[i]-y[i])) + * if r>upperbound: + * return r # <<<<<<<<<<<<<< + * elif p==1: + * for i in range(k): + */ __pyx_r = __pyx_v_r; goto __pyx_L0; goto __pyx_L6; @@ -708,12 +1342,52 @@ } goto __pyx_L3; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":124 + * if r>upperbound: + * return r + * elif p==1: # <<<<<<<<<<<<<< + * for i in range(k): + * r += dabs(x[i]-y[i]) + */ __pyx_1 = (__pyx_v_p == 1); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":125 + * return r + * elif p==1: + * for i in range(k): # <<<<<<<<<<<<<< + * r += dabs(x[i]-y[i]) + * if r>upperbound: + */ for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_k; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":126 + * elif p==1: + * for i in range(k): + * r += dabs(x[i]-y[i]) # <<<<<<<<<<<<<< + * if r>upperbound: + * return r + */ __pyx_v_r += __pyx_f_5scipy_7spatial_7ckdtree_dabs(((__pyx_v_x[__pyx_v_i]) - (__pyx_v_y[__pyx_v_i]))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":127 + * for i in range(k): + * r += dabs(x[i]-y[i]) + * if r>upperbound: # <<<<<<<<<<<<<< + * return r + * else: + */ __pyx_1 = (__pyx_v_r > __pyx_v_upperbound); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":128 + * r += dabs(x[i]-y[i]) + * if r>upperbound: + * return r # <<<<<<<<<<<<<< + * else: + * for i in range(k): + */ __pyx_r = __pyx_v_r; goto __pyx_L0; goto __pyx_L9; @@ -723,10 +1397,42 @@ goto __pyx_L3; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":130 + * return r + * else: + * for i in range(k): # <<<<<<<<<<<<<< + * r += dabs(x[i]-y[i])**p + * if r>upperbound: + */ for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_k; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":131 + * else: + * for i in range(k): + * r += dabs(x[i]-y[i])**p # <<<<<<<<<<<<<< + * if r>upperbound: + * return r + */ __pyx_v_r += pow(__pyx_f_5scipy_7spatial_7ckdtree_dabs(((__pyx_v_x[__pyx_v_i]) - (__pyx_v_y[__pyx_v_i]))), __pyx_v_p); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":132 + * for i in range(k): + * r += dabs(x[i]-y[i])**p + * if r>upperbound: # <<<<<<<<<<<<<< + * return r + * return r + */ __pyx_1 = (__pyx_v_r > __pyx_v_upperbound); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":133 + * r += dabs(x[i]-y[i])**p + * if r>upperbound: + * return r # <<<<<<<<<<<<<< + * return r + * + */ __pyx_r = __pyx_v_r; goto __pyx_L0; goto __pyx_L12; @@ -735,6 +1441,14 @@ } } __pyx_L3:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":134 + * if r>upperbound: + * return r + * return r # <<<<<<<<<<<<<< + * + * + */ __pyx_r = __pyx_v_r; goto __pyx_L0; @@ -743,6 +1457,14 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":195 + * cdef object indices + * cdef np.int32_t* raw_indices + * def __init__(cKDTree self, data, int leafsize=10): # <<<<<<<<<<<<<< + * """Construct a kd-tree. + * + */ + static int __pyx_pf_5scipy_7spatial_7ckdtree_7cKDTree___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_5scipy_7spatial_7ckdtree_7cKDTree___init__[] = "Construct a kd-tree.\n\n Parameters:\n ===========\n\n data : array-like, shape (n,m)\n The n data points of dimension mto be indexed. This array is \n not copied unless this is necessary to produce a contiguous \n array of doubles, and so modifying this data will result in \n bogus results.\n leafsize : positive integer\n The number of points at which the algorithm switches over to\n brute-force.\n "; static int __pyx_pf_5scipy_7spatial_7ckdtree_7cKDTree___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { @@ -783,30 +1505,61 @@ PyArrayObject *__pyx_t_6 = NULL; PyArrayObject *__pyx_t_7 = NULL; PyArrayObject *__pyx_t_8 = NULL; - static char *__pyx_argnames[] = {"data","leafsize",0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_kp_data,&__pyx_kp_leafsize,0}; __pyx_v_leafsize = 10; - if (likely(!__pyx_kwds) && likely(1 <= PyTuple_GET_SIZE(__pyx_args)) && likely(PyTuple_GET_SIZE(__pyx_args) <= 2)) { - __pyx_v_data = PyTuple_GET_ITEM(__pyx_args, 0); - if (PyTuple_GET_SIZE(__pyx_args) > 1) { - __pyx_v_leafsize = __pyx_PyInt_int(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((__pyx_v_leafsize == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__pyx_kwds)) { + PyObject* values[2] = {0,0}; + Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; } + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_data); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + __pyx_v_data = values[0]; + if (values[1]) { + __pyx_v_leafsize = __pyx_PyInt_int(values[1]); if (unlikely((__pyx_v_leafsize == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: __pyx_v_leafsize = __pyx_PyInt_int(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((__pyx_v_leafsize == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + case 1: __pyx_v_data = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } } - else { - if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O|i", __pyx_argnames, &__pyx_v_data, &__pyx_v_leafsize))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4; + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 195; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("scipy.spatial.ckdtree.cKDTree.__init__"); return -1; - __pyx_L4:; + __pyx_L4_argument_unpacking_done:; __pyx_v_inner_data = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + __pyx_v_inner_maxes = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + __pyx_v_inner_mins = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); + __pyx_v_inner_indices = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); __pyx_bstruct_inner_data.buf = NULL; - __pyx_v_inner_maxes = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); __pyx_bstruct_inner_maxes.buf = NULL; - __pyx_v_inner_mins = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); __pyx_bstruct_inner_mins.buf = NULL; - __pyx_v_inner_indices = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); __pyx_bstruct_inner_indices.buf = NULL; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":214 + * cdef np.ndarray[double, ndim=1] inner_mins + * cdef np.ndarray[np.int32_t, ndim=1] inner_indices + * self.data = np.ascontiguousarray(data,dtype=np.float) # <<<<<<<<<<<<<< + * self.n, self.m = np.shape(self.data) + * self.leafsize = leafsize + */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_kp_ascontiguousarray); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; @@ -826,6 +1579,14 @@ Py_DECREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->data); ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->data = __pyx_4; __pyx_4 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":215 + * cdef np.ndarray[np.int32_t, ndim=1] inner_indices + * self.data = np.ascontiguousarray(data,dtype=np.float) + * self.n, self.m = np.shape(self.data) # <<<<<<<<<<<<<< + * self.leafsize = leafsize + * if self.leafsize<1: + */ __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_2 = PyObject_GetAttr(__pyx_5, __pyx_kp_shape); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_5); __pyx_5 = 0; @@ -863,20 +1624,52 @@ if (__Pyx_EndUnpack(__pyx_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_4); __pyx_4 = 0; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":216 + * self.data = np.ascontiguousarray(data,dtype=np.float) + * self.n, self.m = np.shape(self.data) + * self.leafsize = leafsize # <<<<<<<<<<<<<< + * if self.leafsize<1: + * raise ValueError("leafsize must be at least 1") + */ ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->leafsize = __pyx_v_leafsize; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":217 + * self.n, self.m = np.shape(self.data) + * self.leafsize = leafsize + * if self.leafsize<1: # <<<<<<<<<<<<<< + * raise ValueError("leafsize must be at least 1") + * self.maxes = np.ascontiguousarray(np.amax(self.data,axis=0)) + */ __pyx_7 = (((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->leafsize < 1); if (__pyx_7) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":218 + * self.leafsize = leafsize + * if self.leafsize<1: + * raise ValueError("leafsize must be at least 1") # <<<<<<<<<<<<<< + * self.maxes = np.ascontiguousarray(np.amax(self.data,axis=0)) + * self.mins = np.ascontiguousarray(np.amin(self.data,axis=0)) + */ __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_kp_19); - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_kp_19); + Py_INCREF(__pyx_kp_26); + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_kp_26); __pyx_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; __Pyx_Raise(__pyx_5, 0, 0); Py_DECREF(__pyx_5); __pyx_5 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + goto __pyx_L6; } - __pyx_L5:; + __pyx_L6:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":219 + * if self.leafsize<1: + * raise ValueError("leafsize must be at least 1") + * self.maxes = np.ascontiguousarray(np.amax(self.data,axis=0)) # <<<<<<<<<<<<<< + * self.mins = np.ascontiguousarray(np.amin(self.data,axis=0)) + * self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.int32)) + */ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_kp_ascontiguousarray); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; @@ -901,6 +1694,14 @@ Py_DECREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->maxes); ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->maxes = __pyx_5; __pyx_5 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":220 + * raise ValueError("leafsize must be at least 1") + * self.maxes = np.ascontiguousarray(np.amax(self.data,axis=0)) + * self.mins = np.ascontiguousarray(np.amin(self.data,axis=0)) # <<<<<<<<<<<<<< + * self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.int32)) + * + */ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_4 = PyObject_GetAttr(__pyx_2, __pyx_kp_ascontiguousarray); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; @@ -925,6 +1726,14 @@ Py_DECREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->mins); ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->mins = __pyx_5; __pyx_5 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":221 + * self.maxes = np.ascontiguousarray(np.amax(self.data,axis=0)) + * self.mins = np.ascontiguousarray(np.amin(self.data,axis=0)) + * self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.int32)) # <<<<<<<<<<<<<< + * + * inner_data = self.data + */ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_kp_ascontiguousarray); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; @@ -937,7 +1746,7 @@ __pyx_5 = 0; __pyx_4 = PyDict_New(); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_8 = PyObject_GetAttr(__pyx_5, __pyx_kp_int); if (unlikely(!__pyx_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_8 = PyObject_GetAttr(__pyx_5, __pyx_kp_27); if (unlikely(!__pyx_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_5); __pyx_5 = 0; if (PyDict_SetItem(__pyx_4, __pyx_kp_dtype, __pyx_8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 221; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_8); __pyx_8 = 0; @@ -954,14 +1763,22 @@ Py_DECREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->indices); ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->indices = __pyx_1; __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":223 + * self.indices = np.ascontiguousarray(np.arange(self.n,dtype=np.int32)) + * + * inner_data = self.data # <<<<<<<<<<<<<< + * self.raw_data = inner_data.data + * inner_maxes = self.maxes + */ if (!(__Pyx_TypeTest(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->data, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 223; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->data); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_data, &__pyx_bstruct_inner_data); - __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_1, &__pyx_bstruct_inner_data, PyBUF_FORMAT| PyBUF_STRIDES, 2); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_data); + __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_1, &__pyx_bstruct_inner_data, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0); if (unlikely(__pyx_t_2 < 0)) { PyErr_Fetch(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_inner_data, &__pyx_bstruct_inner_data, PyBUF_FORMAT| PyBUF_STRIDES, 2) == -1)) { + if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_inner_data, &__pyx_bstruct_inner_data, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0) == -1)) { Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); __Pyx_RaiseBufferFallbackError(); } else { @@ -975,15 +1792,31 @@ Py_INCREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->data); Py_DECREF(((PyObject *)__pyx_v_inner_data)); __pyx_v_inner_data = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->data); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":224 + * + * inner_data = self.data + * self.raw_data = inner_data.data # <<<<<<<<<<<<<< + * inner_maxes = self.maxes + * self.raw_maxes = inner_maxes.data + */ ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->raw_data = ((double *)__pyx_v_inner_data->data); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":225 + * inner_data = self.data + * self.raw_data = inner_data.data + * inner_maxes = self.maxes # <<<<<<<<<<<<<< + * self.raw_maxes = inner_maxes.data + * inner_mins = self.mins + */ if (!(__Pyx_TypeTest(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->maxes, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 225; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->maxes); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_maxes, &__pyx_bstruct_inner_maxes); - __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_6, &__pyx_bstruct_inner_maxes, PyBUF_FORMAT| PyBUF_STRIDES, 1); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_maxes); + __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_6, &__pyx_bstruct_inner_maxes, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0); if (unlikely(__pyx_t_2 < 0)) { PyErr_Fetch(&__pyx_t_5, &__pyx_t_4, &__pyx_t_3); - if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_inner_maxes, &__pyx_bstruct_inner_maxes, PyBUF_FORMAT| PyBUF_STRIDES, 1) == -1)) { + if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_inner_maxes, &__pyx_bstruct_inner_maxes, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0) == -1)) { Py_XDECREF(__pyx_t_5); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_3); __Pyx_RaiseBufferFallbackError(); } else { @@ -997,15 +1830,31 @@ Py_INCREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->maxes); Py_DECREF(((PyObject *)__pyx_v_inner_maxes)); __pyx_v_inner_maxes = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->maxes); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":226 + * self.raw_data = inner_data.data + * inner_maxes = self.maxes + * self.raw_maxes = inner_maxes.data # <<<<<<<<<<<<<< + * inner_mins = self.mins + * self.raw_mins = inner_mins.data + */ ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->raw_maxes = ((double *)__pyx_v_inner_maxes->data); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":227 + * inner_maxes = self.maxes + * self.raw_maxes = inner_maxes.data + * inner_mins = self.mins # <<<<<<<<<<<<<< + * self.raw_mins = inner_mins.data + * inner_indices = self.indices + */ if (!(__Pyx_TypeTest(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->mins, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->mins); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_mins, &__pyx_bstruct_inner_mins); - __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_7, &__pyx_bstruct_inner_mins, PyBUF_FORMAT| PyBUF_STRIDES, 1); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_mins); + __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_7, &__pyx_bstruct_inner_mins, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0); if (unlikely(__pyx_t_2 < 0)) { PyErr_Fetch(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_inner_mins, &__pyx_bstruct_inner_mins, PyBUF_FORMAT| PyBUF_STRIDES, 1) == -1)) { + if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_inner_mins, &__pyx_bstruct_inner_mins, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0) == -1)) { Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); __Pyx_RaiseBufferFallbackError(); } else { @@ -1019,15 +1868,31 @@ Py_INCREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->mins); Py_DECREF(((PyObject *)__pyx_v_inner_mins)); __pyx_v_inner_mins = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->mins); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":228 + * self.raw_maxes = inner_maxes.data + * inner_mins = self.mins + * self.raw_mins = inner_mins.data # <<<<<<<<<<<<<< + * inner_indices = self.indices + * self.raw_indices = inner_indices.data + */ ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->raw_mins = ((double *)__pyx_v_inner_mins->data); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":229 + * inner_mins = self.mins + * self.raw_mins = inner_mins.data + * inner_indices = self.indices # <<<<<<<<<<<<<< + * self.raw_indices = inner_indices.data + * + */ if (!(__Pyx_TypeTest(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->indices, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 229; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_8 = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->indices); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_indices, &__pyx_bstruct_inner_indices); - __pyx_t_2 = __Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t((PyObject*)__pyx_t_8, &__pyx_bstruct_inner_indices, PyBUF_FORMAT| PyBUF_STRIDES, 1); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_indices); + __pyx_t_2 = __Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t((PyObject*)__pyx_t_8, &__pyx_bstruct_inner_indices, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0); if (unlikely(__pyx_t_2 < 0)) { PyErr_Fetch(&__pyx_t_5, &__pyx_t_4, &__pyx_t_3); - if (unlikely(__Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t((PyObject*)__pyx_v_inner_indices, &__pyx_bstruct_inner_indices, PyBUF_FORMAT| PyBUF_STRIDES, 1) == -1)) { + if (unlikely(__Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t((PyObject*)__pyx_v_inner_indices, &__pyx_bstruct_inner_indices, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0) == -1)) { Py_XDECREF(__pyx_t_5); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_3); __Pyx_RaiseBufferFallbackError(); } else { @@ -1041,7 +1906,23 @@ Py_INCREF(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->indices); Py_DECREF(((PyObject *)__pyx_v_inner_indices)); __pyx_v_inner_indices = ((PyArrayObject *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->indices); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":230 + * self.raw_mins = inner_mins.data + * inner_indices = self.indices + * self.raw_indices = inner_indices.data # <<<<<<<<<<<<<< + * + * self.tree = self.__build(0, self.n, self.raw_maxes, self.raw_mins) + */ ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->raw_indices = ((__pyx_t_5numpy_int32_t *)__pyx_v_inner_indices->data); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":232 + * self.raw_indices = inner_indices.data + * + * self.tree = self.__build(0, self.n, self.raw_maxes, self.raw_mins) # <<<<<<<<<<<<<< + * + * cdef innernode* __build(cKDTree self, int start_idx, int end_idx, double* maxes, double* mins): + */ ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->tree = ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->__pyx_vtab)->__build(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self), 0, ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->n, ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->raw_maxes, ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->raw_mins); __pyx_r = 0; @@ -1054,20 +1935,20 @@ Py_XDECREF(__pyx_5); Py_XDECREF(__pyx_8); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - PyErr_Fetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_indices, &__pyx_bstruct_inner_indices); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_maxes, &__pyx_bstruct_inner_maxes); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_data, &__pyx_bstruct_inner_data); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_mins, &__pyx_bstruct_inner_mins); - PyErr_Restore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_indices); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_maxes); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_data); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_mins); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("scipy.spatial.ckdtree.cKDTree.__init__"); __pyx_r = -1; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_indices, &__pyx_bstruct_inner_indices); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_maxes, &__pyx_bstruct_inner_maxes); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_data, &__pyx_bstruct_inner_data); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_inner_mins, &__pyx_bstruct_inner_mins); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_indices); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_maxes); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_data); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_inner_mins); __pyx_L2:; Py_DECREF(__pyx_v_inner_data); Py_DECREF(__pyx_v_inner_maxes); @@ -1076,6 +1957,14 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":234 + * self.tree = self.__build(0, self.n, self.raw_maxes, self.raw_mins) + * + * cdef innernode* __build(cKDTree self, int start_idx, int end_idx, double* maxes, double* mins): # <<<<<<<<<<<<<< + * cdef leafnode* n + * cdef innernode* ni + */ + static struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *__pyx_f_5scipy_7spatial_7ckdtree_7cKDTree___build(struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *__pyx_v_self, int __pyx_v_start_idx, int __pyx_v_end_idx, double *__pyx_v_maxes, double *__pyx_v_mins) { struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode *__pyx_v_n; struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *__pyx_v_ni; @@ -1094,126 +1983,694 @@ int __pyx_1; int __pyx_2; long __pyx_3; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":240 + * cdef double size, split, minval, maxval + * cdef double*mids + * if end_idx-start_idx<=self.leafsize: # <<<<<<<<<<<<<< + * n = stdlib.malloc(sizeof(leafnode)) + * n.split_dim = -1 + */ __pyx_1 = ((__pyx_v_end_idx - __pyx_v_start_idx) <= __pyx_v_self->leafsize); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":241 + * cdef double*mids + * if end_idx-start_idx<=self.leafsize: + * n = stdlib.malloc(sizeof(leafnode)) # <<<<<<<<<<<<<< + * n.split_dim = -1 + * n.start_idx = start_idx + */ __pyx_v_n = ((struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode *)malloc((sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode)))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":242 + * if end_idx-start_idx<=self.leafsize: + * n = stdlib.malloc(sizeof(leafnode)) + * n.split_dim = -1 # <<<<<<<<<<<<<< + * n.start_idx = start_idx + * n.end_idx = end_idx + */ __pyx_v_n->split_dim = -1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":243 + * n = stdlib.malloc(sizeof(leafnode)) + * n.split_dim = -1 + * n.start_idx = start_idx # <<<<<<<<<<<<<< + * n.end_idx = end_idx + * return n + */ __pyx_v_n->start_idx = __pyx_v_start_idx; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":244 + * n.split_dim = -1 + * n.start_idx = start_idx + * n.end_idx = end_idx # <<<<<<<<<<<<<< + * return n + * else: + */ __pyx_v_n->end_idx = __pyx_v_end_idx; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":245 + * n.start_idx = start_idx + * n.end_idx = end_idx + * return n # <<<<<<<<<<<<<< + * else: + * d = 0 + */ __pyx_r = ((struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *)__pyx_v_n); goto __pyx_L0; goto __pyx_L3; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":247 + * return n + * else: + * d = 0 # <<<<<<<<<<<<<< + * size = 0 + * for i in range(self.m): + */ __pyx_v_d = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":248 + * else: + * d = 0 + * size = 0 # <<<<<<<<<<<<<< + * for i in range(self.m): + * if maxes[i]-mins[i] > size: + */ __pyx_v_size = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":249 + * d = 0 + * size = 0 + * for i in range(self.m): # <<<<<<<<<<<<<< + * if maxes[i]-mins[i] > size: + * d = i + */ __pyx_2 = __pyx_v_self->m; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":250 + * size = 0 + * for i in range(self.m): + * if maxes[i]-mins[i] > size: # <<<<<<<<<<<<<< + * d = i + * size = maxes[i]-mins[i] + */ __pyx_1 = (((__pyx_v_maxes[__pyx_v_i]) - (__pyx_v_mins[__pyx_v_i])) > __pyx_v_size); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":251 + * for i in range(self.m): + * if maxes[i]-mins[i] > size: + * d = i # <<<<<<<<<<<<<< + * size = maxes[i]-mins[i] + * maxval = maxes[d] + */ __pyx_v_d = __pyx_v_i; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":252 + * if maxes[i]-mins[i] > size: + * d = i + * size = maxes[i]-mins[i] # <<<<<<<<<<<<<< + * maxval = maxes[d] + * minval = mins[d] + */ __pyx_v_size = ((__pyx_v_maxes[__pyx_v_i]) - (__pyx_v_mins[__pyx_v_i])); goto __pyx_L6; } __pyx_L6:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":253 + * d = i + * size = maxes[i]-mins[i] + * maxval = maxes[d] # <<<<<<<<<<<<<< + * minval = mins[d] + * if maxval==minval: + */ __pyx_v_maxval = (__pyx_v_maxes[__pyx_v_d]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":254 + * size = maxes[i]-mins[i] + * maxval = maxes[d] + * minval = mins[d] # <<<<<<<<<<<<<< + * if maxval==minval: + * # all points are identical; warn user? + */ __pyx_v_minval = (__pyx_v_mins[__pyx_v_d]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":255 + * maxval = maxes[d] + * minval = mins[d] + * if maxval==minval: # <<<<<<<<<<<<<< + * # all points are identical; warn user? + * n = stdlib.malloc(sizeof(leafnode)) + */ __pyx_1 = (__pyx_v_maxval == __pyx_v_minval); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":257 + * if maxval==minval: + * # all points are identical; warn user? + * n = stdlib.malloc(sizeof(leafnode)) # <<<<<<<<<<<<<< + * n.split_dim = -1 + * n.start_idx = start_idx + */ __pyx_v_n = ((struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode *)malloc((sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode)))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":258 + * # all points are identical; warn user? + * n = stdlib.malloc(sizeof(leafnode)) + * n.split_dim = -1 # <<<<<<<<<<<<<< + * n.start_idx = start_idx + * n.end_idx = end_idx + */ __pyx_v_n->split_dim = -1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":259 + * n = stdlib.malloc(sizeof(leafnode)) + * n.split_dim = -1 + * n.start_idx = start_idx # <<<<<<<<<<<<<< + * n.end_idx = end_idx + * return n + */ __pyx_v_n->start_idx = __pyx_v_start_idx; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":260 + * n.split_dim = -1 + * n.start_idx = start_idx + * n.end_idx = end_idx # <<<<<<<<<<<<<< + * return n + * + */ __pyx_v_n->end_idx = __pyx_v_end_idx; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":261 + * n.start_idx = start_idx + * n.end_idx = end_idx + * return n # <<<<<<<<<<<<<< + * + * split = (maxval+minval)/2 + */ __pyx_r = ((struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *)__pyx_v_n); goto __pyx_L0; goto __pyx_L7; } __pyx_L7:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":263 + * return n + * + * split = (maxval+minval)/2 # <<<<<<<<<<<<<< + * + * p = start_idx + */ __pyx_v_split = ((__pyx_v_maxval + __pyx_v_minval) / 2); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":265 + * split = (maxval+minval)/2 + * + * p = start_idx # <<<<<<<<<<<<<< + * q = end_idx-1 + * while p<=q: + */ __pyx_v_p = __pyx_v_start_idx; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":266 + * + * p = start_idx + * q = end_idx-1 # <<<<<<<<<<<<<< + * while p<=q: + * if self.raw_data[self.raw_indices[p]*self.m+d]=split: + */ __pyx_1 = ((__pyx_v_self->raw_data[(((__pyx_v_self->raw_indices[__pyx_v_p]) * __pyx_v_self->m) + __pyx_v_d)]) < __pyx_v_split); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":269 + * while p<=q: + * if self.raw_data[self.raw_indices[p]*self.m+d]=split: + * q-=1 + */ __pyx_v_p += 1; goto __pyx_L10; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":270 + * if self.raw_data[self.raw_indices[p]*self.m+d]=split: # <<<<<<<<<<<<<< + * q-=1 + * else: + */ __pyx_1 = ((__pyx_v_self->raw_data[(((__pyx_v_self->raw_indices[__pyx_v_q]) * __pyx_v_self->m) + __pyx_v_d)]) >= __pyx_v_split); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":271 + * p+=1 + * elif self.raw_data[self.raw_indices[q]*self.m+d]>=split: + * q-=1 # <<<<<<<<<<<<<< + * else: + * t = self.raw_indices[p] + */ __pyx_v_q -= 1; goto __pyx_L10; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":273 + * q-=1 + * else: + * t = self.raw_indices[p] # <<<<<<<<<<<<<< + * self.raw_indices[p] = self.raw_indices[q] + * self.raw_indices[q] = t + */ __pyx_v_t = (__pyx_v_self->raw_indices[__pyx_v_p]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":274 + * else: + * t = self.raw_indices[p] + * self.raw_indices[p] = self.raw_indices[q] # <<<<<<<<<<<<<< + * self.raw_indices[q] = t + * p+=1 + */ (__pyx_v_self->raw_indices[__pyx_v_p]) = (__pyx_v_self->raw_indices[__pyx_v_q]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":275 + * t = self.raw_indices[p] + * self.raw_indices[p] = self.raw_indices[q] + * self.raw_indices[q] = t # <<<<<<<<<<<<<< + * p+=1 + * q-=1 + */ (__pyx_v_self->raw_indices[__pyx_v_q]) = __pyx_v_t; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":276 + * self.raw_indices[p] = self.raw_indices[q] + * self.raw_indices[q] = t + * p+=1 # <<<<<<<<<<<<<< + * q-=1 + * + */ __pyx_v_p += 1; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":277 + * self.raw_indices[q] = t + * p+=1 + * q-=1 # <<<<<<<<<<<<<< + * + * # slide midpoint if necessary + */ __pyx_v_q -= 1; } __pyx_L10:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":280 + * + * # slide midpoint if necessary + * if p==start_idx: # <<<<<<<<<<<<<< + * # no points less than split + * j = start_idx + */ __pyx_1 = (__pyx_v_p == __pyx_v_start_idx); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":282 + * if p==start_idx: + * # no points less than split + * j = start_idx # <<<<<<<<<<<<<< + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * for i in range(start_idx+1, end_idx): + */ __pyx_v_j = __pyx_v_start_idx; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":283 + * # no points less than split + * j = start_idx + * split = self.raw_data[self.raw_indices[j]*self.m+d] # <<<<<<<<<<<<<< + * for i in range(start_idx+1, end_idx): + * if self.raw_data[self.raw_indices[i]*self.m+d]raw_data[(((__pyx_v_self->raw_indices[__pyx_v_j]) * __pyx_v_self->m) + __pyx_v_d)]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":284 + * j = start_idx + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * for i in range(start_idx+1, end_idx): # <<<<<<<<<<<<<< + * if self.raw_data[self.raw_indices[i]*self.m+d]raw_data[(((__pyx_v_self->raw_indices[__pyx_v_i]) * __pyx_v_self->m) + __pyx_v_d)]) < __pyx_v_split); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":286 + * for i in range(start_idx+1, end_idx): + * if self.raw_data[self.raw_indices[i]*self.m+d]raw_data[(((__pyx_v_self->raw_indices[__pyx_v_j]) * __pyx_v_self->m) + __pyx_v_d)]); goto __pyx_L14; } __pyx_L14:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":288 + * j = i + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * t = self.raw_indices[start_idx] # <<<<<<<<<<<<<< + * self.raw_indices[start_idx] = self.raw_indices[j] + * self.raw_indices[j] = t + */ __pyx_v_t = (__pyx_v_self->raw_indices[__pyx_v_start_idx]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":289 + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * t = self.raw_indices[start_idx] + * self.raw_indices[start_idx] = self.raw_indices[j] # <<<<<<<<<<<<<< + * self.raw_indices[j] = t + * p = start_idx+1 + */ (__pyx_v_self->raw_indices[__pyx_v_start_idx]) = (__pyx_v_self->raw_indices[__pyx_v_j]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":290 + * t = self.raw_indices[start_idx] + * self.raw_indices[start_idx] = self.raw_indices[j] + * self.raw_indices[j] = t # <<<<<<<<<<<<<< + * p = start_idx+1 + * q = start_idx + */ (__pyx_v_self->raw_indices[__pyx_v_j]) = __pyx_v_t; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":291 + * self.raw_indices[start_idx] = self.raw_indices[j] + * self.raw_indices[j] = t + * p = start_idx+1 # <<<<<<<<<<<<<< + * q = start_idx + * elif p==end_idx: + */ __pyx_v_p = (__pyx_v_start_idx + 1); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":292 + * self.raw_indices[j] = t + * p = start_idx+1 + * q = start_idx # <<<<<<<<<<<<<< + * elif p==end_idx: + * # no points greater than split + */ __pyx_v_q = __pyx_v_start_idx; goto __pyx_L11; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":293 + * p = start_idx+1 + * q = start_idx + * elif p==end_idx: # <<<<<<<<<<<<<< + * # no points greater than split + * j = end_idx-1 + */ __pyx_1 = (__pyx_v_p == __pyx_v_end_idx); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":295 + * elif p==end_idx: + * # no points greater than split + * j = end_idx-1 # <<<<<<<<<<<<<< + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * for i in range(start_idx, end_idx-1): + */ __pyx_v_j = (__pyx_v_end_idx - 1); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":296 + * # no points greater than split + * j = end_idx-1 + * split = self.raw_data[self.raw_indices[j]*self.m+d] # <<<<<<<<<<<<<< + * for i in range(start_idx, end_idx-1): + * if self.raw_data[self.raw_indices[i]*self.m+d]>split: + */ __pyx_v_split = (__pyx_v_self->raw_data[(((__pyx_v_self->raw_indices[__pyx_v_j]) * __pyx_v_self->m) + __pyx_v_d)]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":297 + * j = end_idx-1 + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * for i in range(start_idx, end_idx-1): # <<<<<<<<<<<<<< + * if self.raw_data[self.raw_indices[i]*self.m+d]>split: + * j = i + */ __pyx_3 = (__pyx_v_end_idx - 1); for (__pyx_v_i = __pyx_v_start_idx; __pyx_v_i < __pyx_3; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":298 + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * for i in range(start_idx, end_idx-1): + * if self.raw_data[self.raw_indices[i]*self.m+d]>split: # <<<<<<<<<<<<<< + * j = i + * split = self.raw_data[self.raw_indices[j]*self.m+d] + */ __pyx_1 = ((__pyx_v_self->raw_data[(((__pyx_v_self->raw_indices[__pyx_v_i]) * __pyx_v_self->m) + __pyx_v_d)]) > __pyx_v_split); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":299 + * for i in range(start_idx, end_idx-1): + * if self.raw_data[self.raw_indices[i]*self.m+d]>split: + * j = i # <<<<<<<<<<<<<< + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * t = self.raw_indices[end_idx-1] + */ __pyx_v_j = __pyx_v_i; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":300 + * if self.raw_data[self.raw_indices[i]*self.m+d]>split: + * j = i + * split = self.raw_data[self.raw_indices[j]*self.m+d] # <<<<<<<<<<<<<< + * t = self.raw_indices[end_idx-1] + * self.raw_indices[end_idx-1] = self.raw_indices[j] + */ __pyx_v_split = (__pyx_v_self->raw_data[(((__pyx_v_self->raw_indices[__pyx_v_j]) * __pyx_v_self->m) + __pyx_v_d)]); goto __pyx_L17; } __pyx_L17:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":301 + * j = i + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * t = self.raw_indices[end_idx-1] # <<<<<<<<<<<<<< + * self.raw_indices[end_idx-1] = self.raw_indices[j] + * self.raw_indices[j] = t + */ __pyx_v_t = (__pyx_v_self->raw_indices[(__pyx_v_end_idx - 1)]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":302 + * split = self.raw_data[self.raw_indices[j]*self.m+d] + * t = self.raw_indices[end_idx-1] + * self.raw_indices[end_idx-1] = self.raw_indices[j] # <<<<<<<<<<<<<< + * self.raw_indices[j] = t + * p = end_idx-1 + */ (__pyx_v_self->raw_indices[(__pyx_v_end_idx - 1)]) = (__pyx_v_self->raw_indices[__pyx_v_j]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":303 + * t = self.raw_indices[end_idx-1] + * self.raw_indices[end_idx-1] = self.raw_indices[j] + * self.raw_indices[j] = t # <<<<<<<<<<<<<< + * p = end_idx-1 + * q = end_idx-2 + */ (__pyx_v_self->raw_indices[__pyx_v_j]) = __pyx_v_t; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":304 + * self.raw_indices[end_idx-1] = self.raw_indices[j] + * self.raw_indices[j] = t + * p = end_idx-1 # <<<<<<<<<<<<<< + * q = end_idx-2 + * + */ __pyx_v_p = (__pyx_v_end_idx - 1); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":305 + * self.raw_indices[j] = t + * p = end_idx-1 + * q = end_idx-2 # <<<<<<<<<<<<<< + * + * # construct new node representation + */ __pyx_v_q = (__pyx_v_end_idx - 2); goto __pyx_L11; } __pyx_L11:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":308 + * + * # construct new node representation + * ni = stdlib.malloc(sizeof(innernode)) # <<<<<<<<<<<<<< + * + * mids = stdlib.malloc(sizeof(double)*self.m) + */ __pyx_v_ni = ((struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *)malloc((sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_innernode)))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":310 + * ni = stdlib.malloc(sizeof(innernode)) + * + * mids = stdlib.malloc(sizeof(double)*self.m) # <<<<<<<<<<<<<< + * for i in range(self.m): + * mids[i] = maxes[i] + */ __pyx_v_mids = ((double *)malloc(((sizeof(double)) * __pyx_v_self->m))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":311 + * + * mids = stdlib.malloc(sizeof(double)*self.m) + * for i in range(self.m): # <<<<<<<<<<<<<< + * mids[i] = maxes[i] + * mids[d] = split + */ __pyx_2 = __pyx_v_self->m; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":312 + * mids = stdlib.malloc(sizeof(double)*self.m) + * for i in range(self.m): + * mids[i] = maxes[i] # <<<<<<<<<<<<<< + * mids[d] = split + * ni.less = self.__build(start_idx,p,mids,mins) + */ (__pyx_v_mids[__pyx_v_i]) = (__pyx_v_maxes[__pyx_v_i]); } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":313 + * for i in range(self.m): + * mids[i] = maxes[i] + * mids[d] = split # <<<<<<<<<<<<<< + * ni.less = self.__build(start_idx,p,mids,mins) + * + */ (__pyx_v_mids[__pyx_v_d]) = __pyx_v_split; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":314 + * mids[i] = maxes[i] + * mids[d] = split + * ni.less = self.__build(start_idx,p,mids,mins) # <<<<<<<<<<<<<< + * + * for i in range(self.m): + */ __pyx_v_ni->less = ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self->__pyx_vtab)->__build(__pyx_v_self, __pyx_v_start_idx, __pyx_v_p, __pyx_v_mids, __pyx_v_mins); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":316 + * ni.less = self.__build(start_idx,p,mids,mins) + * + * for i in range(self.m): # <<<<<<<<<<<<<< + * mids[i] = mins[i] + * mids[d] = split + */ __pyx_2 = __pyx_v_self->m; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":317 + * + * for i in range(self.m): + * mids[i] = mins[i] # <<<<<<<<<<<<<< + * mids[d] = split + * ni.greater = self.__build(p,end_idx,maxes,mids) + */ (__pyx_v_mids[__pyx_v_i]) = (__pyx_v_mins[__pyx_v_i]); } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":318 + * for i in range(self.m): + * mids[i] = mins[i] + * mids[d] = split # <<<<<<<<<<<<<< + * ni.greater = self.__build(p,end_idx,maxes,mids) + * + */ (__pyx_v_mids[__pyx_v_d]) = __pyx_v_split; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":319 + * mids[i] = mins[i] + * mids[d] = split + * ni.greater = self.__build(p,end_idx,maxes,mids) # <<<<<<<<<<<<<< + * + * stdlib.free(mids) + */ __pyx_v_ni->greater = ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self->__pyx_vtab)->__build(__pyx_v_self, __pyx_v_p, __pyx_v_end_idx, __pyx_v_maxes, __pyx_v_mids); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":321 + * ni.greater = self.__build(p,end_idx,maxes,mids) + * + * stdlib.free(mids) # <<<<<<<<<<<<<< + * + * ni.split_dim = d + */ free(__pyx_v_mids); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":323 + * stdlib.free(mids) + * + * ni.split_dim = d # <<<<<<<<<<<<<< + * ni.split = split + * + */ __pyx_v_ni->split_dim = __pyx_v_d; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":324 + * + * ni.split_dim = d + * ni.split = split # <<<<<<<<<<<<<< + * + * return ni + */ __pyx_v_ni->split = __pyx_v_split; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":326 + * ni.split = split + * + * return ni # <<<<<<<<<<<<<< + * + * cdef __free_tree(cKDTree self, innernode* node): + */ __pyx_r = __pyx_v_ni; goto __pyx_L0; } @@ -1224,19 +2681,59 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":328 + * return ni + * + * cdef __free_tree(cKDTree self, innernode* node): # <<<<<<<<<<<<<< + * if node.split_dim!=-1: + * self.__free_tree(node.less) + */ + static PyObject *__pyx_f_5scipy_7spatial_7ckdtree_7cKDTree___free_tree(struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *__pyx_v_self, struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *__pyx_v_node) { PyObject *__pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":329 + * + * cdef __free_tree(cKDTree self, innernode* node): + * if node.split_dim!=-1: # <<<<<<<<<<<<<< + * self.__free_tree(node.less) + * self.__free_tree(node.greater) + */ __pyx_1 = (__pyx_v_node->split_dim != -1); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":330 + * cdef __free_tree(cKDTree self, innernode* node): + * if node.split_dim!=-1: + * self.__free_tree(node.less) # <<<<<<<<<<<<<< + * self.__free_tree(node.greater) + * stdlib.free(node) + */ __pyx_2 = ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self->__pyx_vtab)->__free_tree(__pyx_v_self, __pyx_v_node->less); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 330; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":331 + * if node.split_dim!=-1: + * self.__free_tree(node.less) + * self.__free_tree(node.greater) # <<<<<<<<<<<<<< + * stdlib.free(node) + * + */ __pyx_2 = ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self->__pyx_vtab)->__free_tree(__pyx_v_self, __pyx_v_node->greater); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; goto __pyx_L3; } __pyx_L3:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":332 + * self.__free_tree(node.less) + * self.__free_tree(node.greater) + * stdlib.free(node) # <<<<<<<<<<<<<< + * + * def __dealloc__(cKDTree self): + */ free(__pyx_v_node); __pyx_r = Py_None; Py_INCREF(Py_None); @@ -1249,16 +2746,48 @@ return __pyx_r; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":334 + * stdlib.free(node) + * + * def __dealloc__(cKDTree self): # <<<<<<<<<<<<<< + * if (self.tree) == 0: + * # should happen only if __init__ was never called + */ + static void __pyx_pf_5scipy_7spatial_7ckdtree_7cKDTree___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_pf_5scipy_7spatial_7ckdtree_7cKDTree___dealloc__(PyObject *__pyx_v_self) { int __pyx_1; PyObject *__pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":335 + * + * def __dealloc__(cKDTree self): + * if (self.tree) == 0: # <<<<<<<<<<<<<< + * # should happen only if __init__ was never called + * return + */ __pyx_1 = (((int)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->tree) == 0); if (__pyx_1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":337 + * if (self.tree) == 0: + * # should happen only if __init__ was never called + * return # <<<<<<<<<<<<<< + * self.__free_tree(self.tree) + * + */ goto __pyx_L0; goto __pyx_L5; } __pyx_L5:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":338 + * # should happen only if __init__ was never called + * return + * self.__free_tree(self.tree) # <<<<<<<<<<<<<< + * + * cdef void __query(cKDTree self, + */ __pyx_2 = ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->__pyx_vtab)->__free_tree(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self), ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->tree); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 338; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; @@ -1269,6 +2798,14 @@ __pyx_L0:; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":340 + * self.__free_tree(self.tree) + * + * cdef void __query(cKDTree self, # <<<<<<<<<<<<<< + * double*result_distances, + * int*result_indices, + */ + static void __pyx_f_5scipy_7spatial_7ckdtree_7cKDTree___query(struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *__pyx_v_self, double *__pyx_v_result_distances, int *__pyx_v_result_indices, double *__pyx_v_x, int __pyx_v_k, double __pyx_v_eps, double __pyx_v_p, double __pyx_v_distance_upper_bound) { struct __pyx_t_5scipy_7spatial_7ckdtree_heap __pyx_v_q; struct __pyx_t_5scipy_7spatial_7ckdtree_heap __pyx_v_neighbors; @@ -1290,101 +2827,413 @@ PyObject *__pyx_1 = 0; int __pyx_2; int __pyx_3; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":371 + * # distances between the nearest side of the cell and the target + * # the head node of the cell + * heapcreate(&q,12) # <<<<<<<<<<<<<< + * + * # priority queue for the nearest neighbors + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heapcreate((&__pyx_v_q), 12); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 371; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":376 + * # furthest known neighbor first + * # entries are (-distance**p, i) + * heapcreate(&neighbors,k) # <<<<<<<<<<<<<< + * + * # set up first nodeinfo + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heapcreate((&__pyx_v_neighbors), __pyx_v_k); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":379 + * + * # set up first nodeinfo + * inf = stdlib.malloc(sizeof(nodeinfo)+self.m*sizeof(double)) # <<<<<<<<<<<<<< + * inf.node = self.tree + * for i in range(self.m): + */ __pyx_v_inf = ((struct __pyx_t_5scipy_7spatial_7ckdtree_nodeinfo *)malloc(((sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_nodeinfo)) + (__pyx_v_self->m * (sizeof(double)))))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":380 + * # set up first nodeinfo + * inf = stdlib.malloc(sizeof(nodeinfo)+self.m*sizeof(double)) + * inf.node = self.tree # <<<<<<<<<<<<<< + * for i in range(self.m): + * inf.side_distances[i] = 0 + */ __pyx_v_inf->node = __pyx_v_self->tree; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":381 + * inf = stdlib.malloc(sizeof(nodeinfo)+self.m*sizeof(double)) + * inf.node = self.tree + * for i in range(self.m): # <<<<<<<<<<<<<< + * inf.side_distances[i] = 0 + * t = x[i]-self.raw_maxes[i] + */ __pyx_2 = __pyx_v_self->m; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":382 + * inf.node = self.tree + * for i in range(self.m): + * inf.side_distances[i] = 0 # <<<<<<<<<<<<<< + * t = x[i]-self.raw_maxes[i] + * if t>inf.side_distances[i]: + */ (__pyx_v_inf->side_distances[__pyx_v_i]) = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":383 + * for i in range(self.m): + * inf.side_distances[i] = 0 + * t = x[i]-self.raw_maxes[i] # <<<<<<<<<<<<<< + * if t>inf.side_distances[i]: + * inf.side_distances[i] = t + */ __pyx_v_t = ((__pyx_v_x[__pyx_v_i]) - (__pyx_v_self->raw_maxes[__pyx_v_i])); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":384 + * inf.side_distances[i] = 0 + * t = x[i]-self.raw_maxes[i] + * if t>inf.side_distances[i]: # <<<<<<<<<<<<<< + * inf.side_distances[i] = t + * else: + */ __pyx_3 = (__pyx_v_t > (__pyx_v_inf->side_distances[__pyx_v_i])); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":385 + * t = x[i]-self.raw_maxes[i] + * if t>inf.side_distances[i]: + * inf.side_distances[i] = t # <<<<<<<<<<<<<< + * else: + * t = self.raw_mins[i]-x[i] + */ (__pyx_v_inf->side_distances[__pyx_v_i]) = __pyx_v_t; goto __pyx_L5; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":387 + * inf.side_distances[i] = t + * else: + * t = self.raw_mins[i]-x[i] # <<<<<<<<<<<<<< + * if t>inf.side_distances[i]: + * inf.side_distances[i] = t + */ __pyx_v_t = ((__pyx_v_self->raw_mins[__pyx_v_i]) - (__pyx_v_x[__pyx_v_i])); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":388 + * else: + * t = self.raw_mins[i]-x[i] + * if t>inf.side_distances[i]: # <<<<<<<<<<<<<< + * inf.side_distances[i] = t + * if p!=1 and p!=infinity: + */ __pyx_3 = (__pyx_v_t > (__pyx_v_inf->side_distances[__pyx_v_i])); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":389 + * t = self.raw_mins[i]-x[i] + * if t>inf.side_distances[i]: + * inf.side_distances[i] = t # <<<<<<<<<<<<<< + * if p!=1 and p!=infinity: + * inf.side_distances[i]=inf.side_distances[i]**p + */ (__pyx_v_inf->side_distances[__pyx_v_i]) = __pyx_v_t; goto __pyx_L6; } __pyx_L6:; } __pyx_L5:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":390 + * if t>inf.side_distances[i]: + * inf.side_distances[i] = t + * if p!=1 and p!=infinity: # <<<<<<<<<<<<<< + * inf.side_distances[i]=inf.side_distances[i]**p + * + */ __pyx_3 = (__pyx_v_p != 1); if (__pyx_3) { __pyx_3 = (__pyx_v_p != __pyx_v_5scipy_7spatial_7ckdtree_infinity); } if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":391 + * inf.side_distances[i] = t + * if p!=1 and p!=infinity: + * inf.side_distances[i]=inf.side_distances[i]**p # <<<<<<<<<<<<<< + * + * # compute first distance + */ (__pyx_v_inf->side_distances[__pyx_v_i]) = pow((__pyx_v_inf->side_distances[__pyx_v_i]), __pyx_v_p); goto __pyx_L7; } __pyx_L7:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":394 + * + * # compute first distance + * min_distance = 0. # <<<<<<<<<<<<<< + * for i in range(self.m): + * if p==infinity: + */ __pyx_v_min_distance = 0.; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":395 + * # compute first distance + * min_distance = 0. + * for i in range(self.m): # <<<<<<<<<<<<<< + * if p==infinity: + * min_distance = dmax(min_distance,inf.side_distances[i]) + */ __pyx_2 = __pyx_v_self->m; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":396 + * min_distance = 0. + * for i in range(self.m): + * if p==infinity: # <<<<<<<<<<<<<< + * min_distance = dmax(min_distance,inf.side_distances[i]) + * else: + */ __pyx_3 = (__pyx_v_p == __pyx_v_5scipy_7spatial_7ckdtree_infinity); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":397 + * for i in range(self.m): + * if p==infinity: + * min_distance = dmax(min_distance,inf.side_distances[i]) # <<<<<<<<<<<<<< + * else: + * min_distance += inf.side_distances[i] + */ __pyx_v_min_distance = __pyx_f_5scipy_7spatial_7ckdtree_dmax(__pyx_v_min_distance, (__pyx_v_inf->side_distances[__pyx_v_i])); goto __pyx_L10; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":399 + * min_distance = dmax(min_distance,inf.side_distances[i]) + * else: + * min_distance += inf.side_distances[i] # <<<<<<<<<<<<<< + * + * # fiddle approximation factor + */ __pyx_v_min_distance += (__pyx_v_inf->side_distances[__pyx_v_i]); } __pyx_L10:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":402 + * + * # fiddle approximation factor + * if eps==0: # <<<<<<<<<<<<<< + * epsfac=1 + * elif p==infinity: + */ __pyx_3 = (__pyx_v_eps == 0); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":403 + * # fiddle approximation factor + * if eps==0: + * epsfac=1 # <<<<<<<<<<<<<< + * elif p==infinity: + * epsfac = 1/(1+eps) + */ __pyx_v_epsfac = 1; goto __pyx_L11; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":404 + * if eps==0: + * epsfac=1 + * elif p==infinity: # <<<<<<<<<<<<<< + * epsfac = 1/(1+eps) + * else: + */ __pyx_3 = (__pyx_v_p == __pyx_v_5scipy_7spatial_7ckdtree_infinity); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":405 + * epsfac=1 + * elif p==infinity: + * epsfac = 1/(1+eps) # <<<<<<<<<<<<<< + * else: + * epsfac = 1/(1+eps)**p + */ __pyx_v_epsfac = (1 / (1 + __pyx_v_eps)); goto __pyx_L11; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":407 + * epsfac = 1/(1+eps) + * else: + * epsfac = 1/(1+eps)**p # <<<<<<<<<<<<<< + * + * # internally we represent all distances as distance**p + */ __pyx_v_epsfac = (1 / pow((1 + __pyx_v_eps), __pyx_v_p)); } __pyx_L11:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":410 + * + * # internally we represent all distances as distance**p + * if p!=infinity and distance_upper_bound!=infinity: # <<<<<<<<<<<<<< + * distance_upper_bound = distance_upper_bound**p + * + */ __pyx_3 = (__pyx_v_p != __pyx_v_5scipy_7spatial_7ckdtree_infinity); if (__pyx_3) { __pyx_3 = (__pyx_v_distance_upper_bound != __pyx_v_5scipy_7spatial_7ckdtree_infinity); } if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":411 + * # internally we represent all distances as distance**p + * if p!=infinity and distance_upper_bound!=infinity: + * distance_upper_bound = distance_upper_bound**p # <<<<<<<<<<<<<< + * + * while True: + */ __pyx_v_distance_upper_bound = pow(__pyx_v_distance_upper_bound, __pyx_v_p); goto __pyx_L12; } __pyx_L12:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":413 + * distance_upper_bound = distance_upper_bound**p + * + * while True: # <<<<<<<<<<<<<< + * if inf.node.split_dim==-1: + * node = inf.node + */ while (1) { __pyx_3 = 1; if (!__pyx_3) break; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":414 + * + * while True: + * if inf.node.split_dim==-1: # <<<<<<<<<<<<<< + * node = inf.node + * + */ __pyx_3 = (__pyx_v_inf->node->split_dim == -1); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":415 + * while True: + * if inf.node.split_dim==-1: + * node = inf.node # <<<<<<<<<<<<<< + * + * # brute-force + */ __pyx_v_node = ((struct __pyx_t_5scipy_7spatial_7ckdtree_leafnode *)__pyx_v_inf->node); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":418 + * + * # brute-force + * for i in range(node.start_idx,node.end_idx): # <<<<<<<<<<<<<< + * d = _distance_p( + * self.raw_data+self.raw_indices[i]*self.m, + */ __pyx_2 = __pyx_v_node->end_idx; for (__pyx_v_i = __pyx_v_node->start_idx; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":421 + * d = _distance_p( + * self.raw_data+self.raw_indices[i]*self.m, + * x,p,self.m,distance_upper_bound) # <<<<<<<<<<<<<< + * + * if draw_data + ((__pyx_v_self->raw_indices[__pyx_v_i]) * __pyx_v_self->m)), __pyx_v_x, __pyx_v_p, __pyx_v_self->m, __pyx_v_distance_upper_bound); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":423 + * x,p,self.m,distance_upper_bound) + * + * if draw_indices[__pyx_v_i]); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":429 + * neighbor.priority = -d + * neighbor.contents.intdata = self.raw_indices[i] + * heappush(&neighbors,neighbor) # <<<<<<<<<<<<<< + * + * # adjust upper bound for efficiency + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heappush((&__pyx_v_neighbors), __pyx_v_neighbor); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":432 + * + * # adjust upper bound for efficiency + * if neighbors.n==k: # <<<<<<<<<<<<<< + * distance_upper_bound = -heappeek(&neighbors).priority + * # done with this node, get another + */ __pyx_3 = (__pyx_v_neighbors.n == __pyx_v_k); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":433 + * # adjust upper bound for efficiency + * if neighbors.n==k: + * distance_upper_bound = -heappeek(&neighbors).priority # <<<<<<<<<<<<<< + * # done with this node, get another + * stdlib.free(inf) + */ __pyx_v_distance_upper_bound = (-__pyx_f_5scipy_7spatial_7ckdtree_heappeek((&__pyx_v_neighbors)).priority); goto __pyx_L20; } @@ -1393,77 +3242,357 @@ } __pyx_L18:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":435 + * distance_upper_bound = -heappeek(&neighbors).priority + * # done with this node, get another + * stdlib.free(inf) # <<<<<<<<<<<<<< + * if q.n==0: + * # no more nodes to visit + */ free(__pyx_v_inf); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":436 + * # done with this node, get another + * stdlib.free(inf) + * if q.n==0: # <<<<<<<<<<<<<< + * # no more nodes to visit + * break + */ __pyx_3 = (__pyx_v_q.n == 0); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":438 + * if q.n==0: + * # no more nodes to visit + * break # <<<<<<<<<<<<<< + * else: + * it = heappop(&q) + */ goto __pyx_L14; goto __pyx_L21; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":440 + * break + * else: + * it = heappop(&q) # <<<<<<<<<<<<<< + * inf = it.contents.ptrdata + * min_distance = it.priority + */ __pyx_v_it = __pyx_f_5scipy_7spatial_7ckdtree_heappop((&__pyx_v_q)); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":441 + * else: + * it = heappop(&q) + * inf = it.contents.ptrdata # <<<<<<<<<<<<<< + * min_distance = it.priority + * else: + */ __pyx_v_inf = ((struct __pyx_t_5scipy_7spatial_7ckdtree_nodeinfo *)__pyx_v_it.contents.ptrdata); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":442 + * it = heappop(&q) + * inf = it.contents.ptrdata + * min_distance = it.priority # <<<<<<<<<<<<<< + * else: + * inode = inf.node + */ __pyx_v_min_distance = __pyx_v_it.priority; } __pyx_L21:; goto __pyx_L15; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":444 + * min_distance = it.priority + * else: + * inode = inf.node # <<<<<<<<<<<<<< + * + * # we don't push cells that are too far onto the queue at all, + */ __pyx_v_inode = ((struct __pyx_t_5scipy_7spatial_7ckdtree_innernode *)__pyx_v_inf->node); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":449 + * # but since the distance_upper_bound decreases, we might get + * # here even if the cell's too far + * if min_distance>distance_upper_bound*epsfac: # <<<<<<<<<<<<<< + * # since this is the nearest cell, we're done, bail out + * stdlib.free(inf) + */ __pyx_3 = (__pyx_v_min_distance > (__pyx_v_distance_upper_bound * __pyx_v_epsfac)); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":451 + * if min_distance>distance_upper_bound*epsfac: + * # since this is the nearest cell, we're done, bail out + * stdlib.free(inf) # <<<<<<<<<<<<<< + * # free all the nodes still on the heap + * for i in range(q.n): + */ free(__pyx_v_inf); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":453 + * stdlib.free(inf) + * # free all the nodes still on the heap + * for i in range(q.n): # <<<<<<<<<<<<<< + * stdlib.free(q.heap[i].contents.ptrdata) + * break + */ __pyx_2 = __pyx_v_q.n; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":454 + * # free all the nodes still on the heap + * for i in range(q.n): + * stdlib.free(q.heap[i].contents.ptrdata) # <<<<<<<<<<<<<< + * break + * + */ free((__pyx_v_q.heap[__pyx_v_i]).contents.ptrdata); } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":455 + * for i in range(q.n): + * stdlib.free(q.heap[i].contents.ptrdata) + * break # <<<<<<<<<<<<<< + * + * # set up children for searching + */ goto __pyx_L14; goto __pyx_L22; } __pyx_L22:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":458 + * + * # set up children for searching + * if x[inode.split_dim]split_dim]) < __pyx_v_inode->split); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":459 + * # set up children for searching + * if x[inode.split_dim]less; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":460 + * if x[inode.split_dim]greater; goto __pyx_L25; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":462 + * far = inode.greater + * else: + * near = inode.greater # <<<<<<<<<<<<<< + * far = inode.less + * + */ __pyx_v_near = __pyx_v_inode->greater; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":463 + * else: + * near = inode.greater + * far = inode.less # <<<<<<<<<<<<<< + * + * # near child is at the same distance as the current node + */ __pyx_v_far = __pyx_v_inode->less; } __pyx_L25:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":468 + * # we're going here next, so no point pushing it on the queue + * # no need to recompute the distance or the side_distances + * inf.node = near # <<<<<<<<<<<<<< + * + * # far child is further by an amount depending only + */ __pyx_v_inf->node = __pyx_v_near; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":473 + * # on the split value; compute its distance and side_distances + * # and push it on the queue if it's near enough + * inf2 = stdlib.malloc(sizeof(nodeinfo)+self.m*sizeof(double)) # <<<<<<<<<<<<<< + * it2.contents.ptrdata = inf2 + * inf2.node = far + */ __pyx_v_inf2 = ((struct __pyx_t_5scipy_7spatial_7ckdtree_nodeinfo *)malloc(((sizeof(struct __pyx_t_5scipy_7spatial_7ckdtree_nodeinfo)) + (__pyx_v_self->m * (sizeof(double)))))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":474 + * # and push it on the queue if it's near enough + * inf2 = stdlib.malloc(sizeof(nodeinfo)+self.m*sizeof(double)) + * it2.contents.ptrdata = inf2 # <<<<<<<<<<<<<< + * inf2.node = far + * # most side distances unchanged + */ __pyx_v_it2.contents.ptrdata = ((char *)__pyx_v_inf2); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":475 + * inf2 = stdlib.malloc(sizeof(nodeinfo)+self.m*sizeof(double)) + * it2.contents.ptrdata = inf2 + * inf2.node = far # <<<<<<<<<<<<<< + * # most side distances unchanged + * for i in range(self.m): + */ __pyx_v_inf2->node = __pyx_v_far; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":477 + * inf2.node = far + * # most side distances unchanged + * for i in range(self.m): # <<<<<<<<<<<<<< + * inf2.side_distances[i] = inf.side_distances[i] + * + */ __pyx_2 = __pyx_v_self->m; for (__pyx_v_i = 0; __pyx_v_i < __pyx_2; __pyx_v_i+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":478 + * # most side distances unchanged + * for i in range(self.m): + * inf2.side_distances[i] = inf.side_distances[i] # <<<<<<<<<<<<<< + * + * # one side distance changes + */ (__pyx_v_inf2->side_distances[__pyx_v_i]) = (__pyx_v_inf->side_distances[__pyx_v_i]); } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":482 + * # one side distance changes + * # we can adjust the minimum distance without recomputing + * if p == infinity: # <<<<<<<<<<<<<< + * # we never use side_distances in the l_infinity case + * # inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) + */ __pyx_3 = (__pyx_v_p == __pyx_v_5scipy_7spatial_7ckdtree_infinity); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":485 + * # we never use side_distances in the l_infinity case + * # inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) + * far_min_distance = dmax(min_distance, dabs(inode.split-x[inode.split_dim])) # <<<<<<<<<<<<<< + * elif p == 1: + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) + */ __pyx_v_far_min_distance = __pyx_f_5scipy_7spatial_7ckdtree_dmax(__pyx_v_min_distance, __pyx_f_5scipy_7spatial_7ckdtree_dabs((__pyx_v_inode->split - (__pyx_v_x[__pyx_v_inode->split_dim])))); goto __pyx_L28; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":486 + * # inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) + * far_min_distance = dmax(min_distance, dabs(inode.split-x[inode.split_dim])) + * elif p == 1: # <<<<<<<<<<<<<< + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] + */ __pyx_3 = (__pyx_v_p == 1); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":487 + * far_min_distance = dmax(min_distance, dabs(inode.split-x[inode.split_dim])) + * elif p == 1: + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) # <<<<<<<<<<<<<< + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] + * else: + */ (__pyx_v_inf2->side_distances[__pyx_v_inode->split_dim]) = __pyx_f_5scipy_7spatial_7ckdtree_dabs((__pyx_v_inode->split - (__pyx_v_x[__pyx_v_inode->split_dim]))); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":488 + * elif p == 1: + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim]) + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] # <<<<<<<<<<<<<< + * else: + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim])**p + */ __pyx_v_far_min_distance = ((__pyx_v_min_distance - (__pyx_v_inf->side_distances[__pyx_v_inode->split_dim])) + (__pyx_v_inf2->side_distances[__pyx_v_inode->split_dim])); goto __pyx_L28; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":490 + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] + * else: + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim])**p # <<<<<<<<<<<<<< + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] + * + */ (__pyx_v_inf2->side_distances[__pyx_v_inode->split_dim]) = pow(__pyx_f_5scipy_7spatial_7ckdtree_dabs((__pyx_v_inode->split - (__pyx_v_x[__pyx_v_inode->split_dim]))), __pyx_v_p); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":491 + * else: + * inf2.side_distances[inode.split_dim] = dabs(inode.split-x[inode.split_dim])**p + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] # <<<<<<<<<<<<<< + * + * it2.priority = far_min_distance + */ __pyx_v_far_min_distance = ((__pyx_v_min_distance - (__pyx_v_inf->side_distances[__pyx_v_inode->split_dim])) + (__pyx_v_inf2->side_distances[__pyx_v_inode->split_dim])); } __pyx_L28:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":493 + * far_min_distance = min_distance - inf.side_distances[inode.split_dim] + inf2.side_distances[inode.split_dim] + * + * it2.priority = far_min_distance # <<<<<<<<<<<<<< + * + * + */ __pyx_v_it2.priority = __pyx_v_far_min_distance; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":497 + * + * # far child might be too far, if so, don't bother pushing it + * if far_min_distance<=distance_upper_bound*epsfac: # <<<<<<<<<<<<<< + * heappush(&q,it2) + * else: + */ __pyx_3 = (__pyx_v_far_min_distance <= (__pyx_v_distance_upper_bound * __pyx_v_epsfac)); if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":498 + * # far child might be too far, if so, don't bother pushing it + * if far_min_distance<=distance_upper_bound*epsfac: + * heappush(&q,it2) # <<<<<<<<<<<<<< + * else: + * stdlib.free(inf2) + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heappush((&__pyx_v_q), __pyx_v_it2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 498; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; goto __pyx_L29; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":500 + * heappush(&q,it2) + * else: + * stdlib.free(inf2) # <<<<<<<<<<<<<< + * # just in case + * it2.contents.ptrdata = 0 + */ free(__pyx_v_inf2); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":502 + * stdlib.free(inf2) + * # just in case + * it2.contents.ptrdata = 0 # <<<<<<<<<<<<<< + * + * # fill output arrays with sorted neighbors + */ __pyx_v_it2.contents.ptrdata = ((char *)0); } __pyx_L29:; @@ -1471,24 +3600,88 @@ __pyx_L15:; } __pyx_L14:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":505 + * + * # fill output arrays with sorted neighbors + * for i in range(neighbors.n-1,-1,-1): # <<<<<<<<<<<<<< + * neighbor = heappop(&neighbors) # FIXME: neighbors may be realloced + * result_indices[i] = neighbor.contents.intdata + */ for (__pyx_v_i = (__pyx_v_neighbors.n - 1); __pyx_v_i > -1; __pyx_v_i-=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":506 + * # fill output arrays with sorted neighbors + * for i in range(neighbors.n-1,-1,-1): + * neighbor = heappop(&neighbors) # FIXME: neighbors may be realloced # <<<<<<<<<<<<<< + * result_indices[i] = neighbor.contents.intdata + * if p==1 or p==infinity: + */ __pyx_v_neighbor = __pyx_f_5scipy_7spatial_7ckdtree_heappop((&__pyx_v_neighbors)); + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":507 + * for i in range(neighbors.n-1,-1,-1): + * neighbor = heappop(&neighbors) # FIXME: neighbors may be realloced + * result_indices[i] = neighbor.contents.intdata # <<<<<<<<<<<<<< + * if p==1 or p==infinity: + * result_distances[i] = -neighbor.priority + */ (__pyx_v_result_indices[__pyx_v_i]) = __pyx_v_neighbor.contents.intdata; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":508 + * neighbor = heappop(&neighbors) # FIXME: neighbors may be realloced + * result_indices[i] = neighbor.contents.intdata + * if p==1 or p==infinity: # <<<<<<<<<<<<<< + * result_distances[i] = -neighbor.priority + * else: + */ __pyx_3 = (__pyx_v_p == 1); if (!__pyx_3) { __pyx_3 = (__pyx_v_p == __pyx_v_5scipy_7spatial_7ckdtree_infinity); } if (__pyx_3) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":509 + * result_indices[i] = neighbor.contents.intdata + * if p==1 or p==infinity: + * result_distances[i] = -neighbor.priority # <<<<<<<<<<<<<< + * else: + * result_distances[i] = (-neighbor.priority)**(1./p) + */ (__pyx_v_result_distances[__pyx_v_i]) = (-__pyx_v_neighbor.priority); goto __pyx_L32; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":511 + * result_distances[i] = -neighbor.priority + * else: + * result_distances[i] = (-neighbor.priority)**(1./p) # <<<<<<<<<<<<<< + * + * heapdestroy(&q) + */ (__pyx_v_result_distances[__pyx_v_i]) = pow((-__pyx_v_neighbor.priority), (1. / __pyx_v_p)); } __pyx_L32:; } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":513 + * result_distances[i] = (-neighbor.priority)**(1./p) + * + * heapdestroy(&q) # <<<<<<<<<<<<<< + * heapdestroy(&neighbors) + * + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heapdestroy((&__pyx_v_q)); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 513; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":514 + * + * heapdestroy(&q) + * heapdestroy(&neighbors) # <<<<<<<<<<<<<< + * + * def query(cKDTree self, object x, int k=1, double eps=0, double p=2, + */ __pyx_1 = __pyx_f_5scipy_7spatial_7ckdtree_heapdestroy((&__pyx_v_neighbors)); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; @@ -1499,6 +3692,14 @@ __pyx_L0:; } +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":516 + * heapdestroy(&neighbors) + * + * def query(cKDTree self, object x, int k=1, double eps=0, double p=2, # <<<<<<<<<<<<<< + * double distance_upper_bound=infinity): + * """query the kd-tree for nearest neighbors + */ + static PyObject *__pyx_pf_5scipy_7spatial_7ckdtree_7cKDTree_query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_5scipy_7spatial_7ckdtree_7cKDTree_query[] = "query the kd-tree for nearest neighbors\n\n Parameters:\n ===========\n\n x : array-like, last dimension self.m\n An array of points to query.\n k : integer\n The number of nearest neighbors to return.\n eps : nonnegative float\n Return approximate nearest neighbors; the kth returned value \n is guaranteed to be no further than (1+eps) times the \n distance to the real kth nearest neighbor.\n p : float, 1<=p<=infinity\n Which Minkowski p-norm to use. \n 1 is the sum-of-absolute-values \"Manhattan\" distance\n 2 is the usual Euclidean distance\n infinity is the maximum-coordinate-difference distance\n distance_upper_bound : nonnegative float\n Return only neighbors within this distance. This is used to prune\n tree searches, so if you are doing a series of nearest-neighbor\n queries, it may help to supply the distance to the nearest neighbor\n of the most recent point.\n\n Returns:\n ========\n \n d : array of floats\n The distances to the nearest neighbors. \n If x has shape tuple+(self.m,), then d has shape tuple+(k,).\n Missing neighbors are indicated with infinite distances.\n i : array of integers\n The locations of the neighbors in self.data.\n If x has shape tuple+(self.m,), then i has shape tuple+(k,).\n Missing neighbors are indicated with self.n.\n "; static PyObject *__pyx_pf_5scipy_7spatial_7ckdtree_7cKDTree_query(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { @@ -1538,10 +3739,9 @@ Py_ssize_t __pyx_6 = 0; PyObject *__pyx_7 = 0; int __pyx_8; - double __pyx_9; - PyArrayObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_1 = NULL; + PyArrayObject *__pyx_t_2 = NULL; + int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; @@ -1550,44 +3750,81 @@ long __pyx_t_9; long __pyx_t_10; long __pyx_t_11; - static char *__pyx_argnames[] = {"x","k","eps","p","distance_upper_bound",0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_kp_x,&__pyx_kp_k,&__pyx_kp_eps,&__pyx_kp_p,&__pyx_kp_23,0}; __pyx_v_k = 1; __pyx_v_eps = ((double)0); __pyx_v_p = ((double)2); - __pyx_v_distance_upper_bound = __pyx_k_17; - if (likely(!__pyx_kwds) && likely(1 <= PyTuple_GET_SIZE(__pyx_args)) && likely(PyTuple_GET_SIZE(__pyx_args) <= 5)) { - __pyx_v_x = PyTuple_GET_ITEM(__pyx_args, 0); - if (PyTuple_GET_SIZE(__pyx_args) > 1) { - __pyx_v_k = __pyx_PyInt_int(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((__pyx_v_k == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - if (PyTuple_GET_SIZE(__pyx_args) > 2) { - __pyx_v_eps = __pyx_PyFloat_AsDouble(PyTuple_GET_ITEM(__pyx_args, 2)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - if (PyTuple_GET_SIZE(__pyx_args) > 3) { - __pyx_v_p = __pyx_PyFloat_AsDouble(PyTuple_GET_ITEM(__pyx_args, 3)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - if (PyTuple_GET_SIZE(__pyx_args) > 4) { - __pyx_v_distance_upper_bound = __pyx_PyFloat_AsDouble(PyTuple_GET_ITEM(__pyx_args, 4)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - } - } + __pyx_v_distance_upper_bound = __pyx_k_24; + if (unlikely(__pyx_kwds)) { + PyObject* values[5] = {0,0,0,0,0}; + Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; } + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_x); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "query") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + __pyx_v_x = values[0]; + if (values[1]) { + __pyx_v_k = __pyx_PyInt_int(values[1]); if (unlikely((__pyx_v_k == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + if (values[2]) { + __pyx_v_eps = __pyx_PyFloat_AsDouble(values[2]); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + if (values[3]) { + __pyx_v_p = __pyx_PyFloat_AsDouble(values[3]); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + if (values[4]) { + __pyx_v_distance_upper_bound = __pyx_PyFloat_AsDouble(values[4]); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } else { + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 5: __pyx_v_distance_upper_bound = __pyx_PyFloat_AsDouble(PyTuple_GET_ITEM(__pyx_args, 4)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 517; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + case 4: __pyx_v_p = __pyx_PyFloat_AsDouble(PyTuple_GET_ITEM(__pyx_args, 3)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + case 3: __pyx_v_eps = __pyx_PyFloat_AsDouble(PyTuple_GET_ITEM(__pyx_args, 2)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + case 2: __pyx_v_k = __pyx_PyInt_int(PyTuple_GET_ITEM(__pyx_args, 1)); if (unlikely((__pyx_v_k == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + case 1: __pyx_v_x = PyTuple_GET_ITEM(__pyx_args, 0); + break; + default: goto __pyx_L5_argtuple_error; + } } - else { - if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O|iddd", __pyx_argnames, &__pyx_v_x, &__pyx_v_k, &__pyx_v_eps, &__pyx_v_p, &__pyx_v_distance_upper_bound))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4; + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("query", 0, 1, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 516; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("scipy.spatial.ckdtree.cKDTree.query"); return NULL; - __pyx_L4:; + __pyx_L4_argument_unpacking_done:; Py_INCREF(__pyx_v_x); __pyx_v_ii = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - __pyx_bstruct_ii.buf = NULL; __pyx_v_dd = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - __pyx_bstruct_dd.buf = NULL; __pyx_v_xx = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - __pyx_bstruct_xx.buf = NULL; __pyx_v_single = Py_None; Py_INCREF(Py_None); __pyx_v_retshape = Py_None; Py_INCREF(Py_None); __pyx_v_n = Py_None; Py_INCREF(Py_None); + __pyx_bstruct_ii.buf = NULL; + __pyx_bstruct_dd.buf = NULL; + __pyx_bstruct_xx.buf = NULL; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":558 + * cdef np.ndarray[double, ndim=2] xx + * cdef int c + * x = np.asarray(x).astype(np.float) # <<<<<<<<<<<<<< + * if np.shape(x)[-1] != self.m: + * raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x))) + */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 558; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_kp_asarray); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 558; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; @@ -1611,6 +3848,14 @@ Py_DECREF(__pyx_v_x); __pyx_v_x = __pyx_3; __pyx_3 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":559 + * cdef int c + * x = np.asarray(x).astype(np.float) + * if np.shape(x)[-1] != self.m: # <<<<<<<<<<<<<< + * raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x))) + * if p<1: + */ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_shape); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; @@ -1629,6 +3874,14 @@ __pyx_4 = __Pyx_PyObject_IsTrue(__pyx_2); if (unlikely(__pyx_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 559; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; if (__pyx_4) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":560 + * x = np.asarray(x).astype(np.float) + * if np.shape(x)[-1] != self.m: + * raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x))) # <<<<<<<<<<<<<< + * if p<1: + * raise ValueError("Only p-norms with 1<=p<=infinity permitted") + */ __pyx_1 = PyInt_FromLong(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->m); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_2 = PyObject_GetAttr(__pyx_3, __pyx_kp_shape); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -1644,316 +3897,464 @@ PyTuple_SET_ITEM(__pyx_2, 1, __pyx_5); __pyx_1 = 0; __pyx_5 = 0; - __pyx_3 = PyNumber_Remainder(__pyx_kp_20, ((PyObject *)__pyx_2)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(__pyx_kp_28, ((PyObject *)__pyx_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); - __pyx_3 = 0; - __pyx_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - __Pyx_Raise(__pyx_5, 0, 0); - Py_DECREF(__pyx_5); __pyx_5 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_1 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __Pyx_Raise(__pyx_1, 0, 0); + Py_DECREF(__pyx_1); __pyx_1 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 560; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + goto __pyx_L6; } - __pyx_L5:; + __pyx_L6:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":561 + * if np.shape(x)[-1] != self.m: + * raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x))) + * if p<1: # <<<<<<<<<<<<<< + * raise ValueError("Only p-norms with 1<=p<=infinity permitted") + * if len(x.shape)==1: + */ __pyx_4 = (__pyx_v_p < 1); if (__pyx_4) { - __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_kp_21); - PyTuple_SET_ITEM(__pyx_2, 0, __pyx_kp_21); - __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; - __Pyx_Raise(__pyx_3, 0, 0); - Py_DECREF(__pyx_3); __pyx_3 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":562 + * raise ValueError("x must consist of vectors of length %d but has shape %s" % (self.m, np.shape(x))) + * if p<1: + * raise ValueError("Only p-norms with 1<=p<=infinity permitted") # <<<<<<<<<<<<<< + * if len(x.shape)==1: + * single = True + */ + __pyx_5 = PyTuple_New(1); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_kp_29); + PyTuple_SET_ITEM(__pyx_5, 0, __pyx_kp_29); + __pyx_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; + __Pyx_Raise(__pyx_2, 0, 0); + Py_DECREF(__pyx_2); __pyx_2 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + goto __pyx_L7; } - __pyx_L6:; - __pyx_1 = PyObject_GetAttr(__pyx_v_x, __pyx_kp_shape); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_6 = PyObject_Length(__pyx_1); if (unlikely(__pyx_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_L7:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":563 + * if p<1: + * raise ValueError("Only p-norms with 1<=p<=infinity permitted") + * if len(x.shape)==1: # <<<<<<<<<<<<<< + * single = True + * x = x[np.newaxis,:] + */ + __pyx_3 = PyObject_GetAttr(__pyx_v_x, __pyx_kp_shape); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_6 = PyObject_Length(__pyx_3); if (unlikely(__pyx_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_4 = (__pyx_6 == 1); if (__pyx_4) { - __pyx_5 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 564; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":564 + * raise ValueError("Only p-norms with 1<=p<=infinity permitted") + * if len(x.shape)==1: + * single = True # <<<<<<<<<<<<<< + * x = x[np.newaxis,:] + * else: + */ + __pyx_1 = __Pyx_PyBool_FromLong(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 564; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_v_single); - __pyx_v_single = __pyx_5; - __pyx_5 = 0; - __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_kp_newaxis); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_1 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyTuple_New(2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_3); - PyTuple_SET_ITEM(__pyx_5, 1, __pyx_1); + __pyx_v_single = __pyx_1; + __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":565 + * if len(x.shape)==1: + * single = True + * x = x[np.newaxis,:] # <<<<<<<<<<<<<< + * else: + * single = False + */ + __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetAttr(__pyx_5, __pyx_kp_newaxis); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_5); __pyx_5 = 0; + __pyx_3 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_2); + PyTuple_SET_ITEM(__pyx_1, 1, __pyx_3); + __pyx_2 = 0; __pyx_3 = 0; - __pyx_1 = 0; - __pyx_2 = PyObject_GetItem(__pyx_v_x, ((PyObject *)__pyx_5)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; + __pyx_5 = PyObject_GetItem(__pyx_v_x, ((PyObject *)__pyx_1)); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 565; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; Py_DECREF(__pyx_v_x); - __pyx_v_x = __pyx_2; - __pyx_2 = 0; - goto __pyx_L7; + __pyx_v_x = __pyx_5; + __pyx_5 = 0; + goto __pyx_L8; } /*else*/ { - __pyx_3 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":567 + * x = x[np.newaxis,:] + * else: + * single = False # <<<<<<<<<<<<<< + * retshape = np.shape(x)[:-1] + * n = np.prod(retshape) + */ + __pyx_2 = __Pyx_PyBool_FromLong(0); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 567; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_v_single); - __pyx_v_single = __pyx_3; - __pyx_3 = 0; + __pyx_v_single = __pyx_2; + __pyx_2 = 0; } - __pyx_L7:; - __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyObject_GetAttr(__pyx_1, __pyx_kp_shape); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L8:; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":568 + * else: + * single = False + * retshape = np.shape(x)[:-1] # <<<<<<<<<<<<<< + * n = np.prod(retshape) + * xx = np.reshape(x,(n,self.m)) + */ + __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyObject_GetAttr(__pyx_3, __pyx_kp_shape); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_5 = PyTuple_New(1); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_v_x); + PyTuple_SET_ITEM(__pyx_5, 0, __pyx_v_x); + __pyx_2 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_2, 0, __pyx_v_x); - __pyx_3 = PyObject_Call(__pyx_5, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; + __pyx_3 = PySequence_GetSlice(__pyx_2, 0, -1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_v_retshape); + __pyx_v_retshape = __pyx_3; + __pyx_3 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":569 + * single = False + * retshape = np.shape(x)[:-1] + * n = np.prod(retshape) # <<<<<<<<<<<<<< + * xx = np.reshape(x,(n,self.m)) + * dd = np.empty((n,k),dtype=np.float) + */ + __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_5 = PyObject_GetAttr(__pyx_1, __pyx_kp_prod); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_v_retshape); + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_v_retshape); + __pyx_3 = PyObject_Call(__pyx_5, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_5); __pyx_5 = 0; Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; - __pyx_1 = PySequence_GetSlice(__pyx_3, 0, -1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(__pyx_v_retshape); - __pyx_v_retshape = __pyx_1; - __pyx_1 = 0; - __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetAttr(__pyx_5, __pyx_kp_prod); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_v_retshape); - PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_retshape); - __pyx_1 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; Py_DECREF(__pyx_v_n); - __pyx_v_n = __pyx_1; - __pyx_1 = 0; - __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetAttr(__pyx_5, __pyx_kp_reshape); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_3 = PyInt_FromLong(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->m); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_n = __pyx_3; + __pyx_3 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":570 + * retshape = np.shape(x)[:-1] + * n = np.prod(retshape) + * xx = np.reshape(x,(n,self.m)) # <<<<<<<<<<<<<< + * dd = np.empty((n,k),dtype=np.float) + * dd.fill(infinity) + */ + __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_5 = PyObject_GetAttr(__pyx_1, __pyx_kp_reshape); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_2 = PyInt_FromLong(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->m); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_v_n); + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_n); + PyTuple_SET_ITEM(__pyx_3, 1, __pyx_2); + __pyx_2 = 0; __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_v_n); - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_n); - PyTuple_SET_ITEM(__pyx_1, 1, __pyx_3); + Py_INCREF(__pyx_v_x); + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_x); + PyTuple_SET_ITEM(__pyx_1, 1, ((PyObject *)__pyx_3)); __pyx_3 = 0; - __pyx_5 = PyTuple_New(2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_v_x); - PyTuple_SET_ITEM(__pyx_5, 1, ((PyObject *)__pyx_1)); - __pyx_1 = 0; - __pyx_3 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; - if (!(__Pyx_TypeTest(__pyx_3, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((PyArrayObject *)__pyx_3); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_xx, &__pyx_bstruct_xx); - __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_1, &__pyx_bstruct_xx, PyBUF_FORMAT| PyBUF_STRIDES, 2); - if (unlikely(__pyx_t_2 < 0)) + __pyx_2 = PyObject_Call(__pyx_5, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_5); __pyx_5 = 0; + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; + if (!(__Pyx_TypeTest(__pyx_2, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((PyArrayObject *)__pyx_2); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_xx); + __pyx_t_3 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_2, &__pyx_bstruct_xx, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0); + if (unlikely(__pyx_t_3 < 0)) { - PyErr_Fetch(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_xx, &__pyx_bstruct_xx, PyBUF_FORMAT| PyBUF_STRIDES, 2) == -1)) { - Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); + PyErr_Fetch(&__pyx_t_1, &__pyx_t_4, &__pyx_t_5); + if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_xx, &__pyx_bstruct_xx, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0) == -1)) { + Py_XDECREF(__pyx_t_1); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_3, __pyx_t_4, __pyx_t_5); + PyErr_Restore(__pyx_t_1, __pyx_t_4, __pyx_t_5); } } __pyx_bstride_0_xx = __pyx_bstruct_xx.strides[0]; __pyx_bstride_1_xx = __pyx_bstruct_xx.strides[1]; __pyx_bshape_0_xx = __pyx_bstruct_xx.shape[0]; __pyx_bshape_1_xx = __pyx_bstruct_xx.shape[1]; - if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = 0; + if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 570; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = 0; Py_DECREF(((PyObject *)__pyx_v_xx)); - __pyx_v_xx = ((PyArrayObject *)__pyx_3); - __pyx_3 = 0; - __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_kp_empty); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_5 = PyInt_FromLong(__pyx_v_k); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(__pyx_v_n); - PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_n); - PyTuple_SET_ITEM(__pyx_3, 1, __pyx_5); - __pyx_5 = 0; - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, ((PyObject *)__pyx_3)); - __pyx_3 = 0; - __pyx_5 = PyDict_New(); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_xx = ((PyArrayObject *)__pyx_2); + __pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":571 + * n = np.prod(retshape) + * xx = np.reshape(x,(n,self.m)) + * dd = np.empty((n,k),dtype=np.float) # <<<<<<<<<<<<<< + * dd.fill(infinity) + * ii = np.empty((n,k),dtype='i') + */ __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_7 = PyObject_GetAttr(__pyx_3, __pyx_kp_float); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_5 = PyObject_GetAttr(__pyx_3, __pyx_kp_empty); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; - if (PyDict_SetItem(__pyx_5, __pyx_kp_dtype, __pyx_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyInt_FromLong(__pyx_v_k); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyTuple_New(2); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_v_n); + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_v_n); + PyTuple_SET_ITEM(__pyx_2, 1, __pyx_1); + __pyx_1 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, ((PyObject *)__pyx_2)); + __pyx_2 = 0; + __pyx_1 = PyDict_New(); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_7 = PyObject_GetAttr(__pyx_2, __pyx_kp_float); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + if (PyDict_SetItem(__pyx_1, __pyx_kp_dtype, __pyx_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_7); __pyx_7 = 0; - __pyx_3 = PyEval_CallObjectWithKeywords(__pyx_2, ((PyObject *)__pyx_1), ((PyObject *)__pyx_5)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_2 = PyEval_CallObjectWithKeywords(__pyx_5, ((PyObject *)__pyx_3), ((PyObject *)__pyx_1)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_5); __pyx_5 = 0; + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; - if (!(__Pyx_TypeTest(__pyx_3, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_6 = ((PyArrayObject *)__pyx_3); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_dd, &__pyx_bstruct_dd); - __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_6, &__pyx_bstruct_dd, PyBUF_FORMAT| PyBUF_STRIDES, 2); - if (unlikely(__pyx_t_2 < 0)) + if (!(__Pyx_TypeTest(__pyx_2, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = ((PyArrayObject *)__pyx_2); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_dd); + __pyx_t_3 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_6, &__pyx_bstruct_dd, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0); + if (unlikely(__pyx_t_3 < 0)) { - PyErr_Fetch(&__pyx_t_5, &__pyx_t_4, &__pyx_t_3); - if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_dd, &__pyx_bstruct_dd, PyBUF_FORMAT| PyBUF_STRIDES, 2) == -1)) { - Py_XDECREF(__pyx_t_5); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_3); + PyErr_Fetch(&__pyx_t_5, &__pyx_t_4, &__pyx_t_1); + if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_dd, &__pyx_bstruct_dd, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0) == -1)) { + Py_XDECREF(__pyx_t_5); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_1); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_5, __pyx_t_4, __pyx_t_3); + PyErr_Restore(__pyx_t_5, __pyx_t_4, __pyx_t_1); } } __pyx_bstride_0_dd = __pyx_bstruct_dd.strides[0]; __pyx_bstride_1_dd = __pyx_bstruct_dd.strides[1]; __pyx_bshape_0_dd = __pyx_bstruct_dd.shape[0]; __pyx_bshape_1_dd = __pyx_bstruct_dd.shape[1]; - if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 571; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_6 = 0; Py_DECREF(((PyObject *)__pyx_v_dd)); - __pyx_v_dd = ((PyArrayObject *)__pyx_3); - __pyx_3 = 0; + __pyx_v_dd = ((PyArrayObject *)__pyx_2); + __pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":572 + * xx = np.reshape(x,(n,self.m)) + * dd = np.empty((n,k),dtype=np.float) + * dd.fill(infinity) # <<<<<<<<<<<<<< + * ii = np.empty((n,k),dtype='i') + * ii.fill(self.n) + */ __pyx_7 = PyObject_GetAttr(((PyObject *)__pyx_v_dd), __pyx_kp_fill); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyFloat_FromDouble(__pyx_v_5scipy_7spatial_7ckdtree_infinity); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_2); - __pyx_2 = 0; - __pyx_5 = PyObject_Call(__pyx_7, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_5 = PyFloat_FromDouble(__pyx_v_5scipy_7spatial_7ckdtree_infinity); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_5); + __pyx_5 = 0; + __pyx_1 = PyObject_Call(__pyx_7, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_7); __pyx_7 = 0; - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetAttr(__pyx_3, __pyx_kp_empty); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":573 + * dd = np.empty((n,k),dtype=np.float) + * dd.fill(infinity) + * ii = np.empty((n,k),dtype='i') # <<<<<<<<<<<<<< + * ii.fill(self.n) + * for c in range(n): + */ + __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_5 = PyObject_GetAttr(__pyx_2, __pyx_kp_empty); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_7 = PyInt_FromLong(__pyx_v_k); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_n); - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_n); - PyTuple_SET_ITEM(__pyx_1, 1, __pyx_7); + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_n); + PyTuple_SET_ITEM(__pyx_3, 1, __pyx_7); __pyx_7 = 0; - __pyx_5 = PyTuple_New(1); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_5, 0, ((PyObject *)__pyx_1)); - __pyx_1 = 0; - __pyx_3 = PyDict_New(); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyDict_SetItem(__pyx_3, __pyx_kp_dtype, __pyx_kp_22) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_7 = PyEval_CallObjectWithKeywords(__pyx_2, ((PyObject *)__pyx_5), ((PyObject *)__pyx_3)); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; - Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_1, 0, ((PyObject *)__pyx_3)); + __pyx_3 = 0; + __pyx_2 = PyDict_New(); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_2, __pyx_kp_dtype, __pyx_kp_30) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_7 = PyEval_CallObjectWithKeywords(__pyx_5, ((PyObject *)__pyx_1), ((PyObject *)__pyx_2)); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_5); __pyx_5 = 0; + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; if (!(__Pyx_TypeTest(__pyx_7, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = ((PyArrayObject *)__pyx_7); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_ii, &__pyx_bstruct_ii); - __pyx_t_2 = __Pyx_GetBuffer_int((PyObject*)__pyx_t_7, &__pyx_bstruct_ii, PyBUF_FORMAT| PyBUF_STRIDES, 2); - if (unlikely(__pyx_t_2 < 0)) + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_ii); + __pyx_t_3 = __Pyx_GetBuffer_int((PyObject*)__pyx_t_7, &__pyx_bstruct_ii, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0); + if (unlikely(__pyx_t_3 < 0)) { - PyErr_Fetch(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - if (unlikely(__Pyx_GetBuffer_int((PyObject*)__pyx_v_ii, &__pyx_bstruct_ii, PyBUF_FORMAT| PyBUF_STRIDES, 2) == -1)) { - Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); + PyErr_Fetch(&__pyx_t_1, &__pyx_t_4, &__pyx_t_5); + if (unlikely(__Pyx_GetBuffer_int((PyObject*)__pyx_v_ii, &__pyx_bstruct_ii, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0) == -1)) { + Py_XDECREF(__pyx_t_1); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_3, __pyx_t_4, __pyx_t_5); + PyErr_Restore(__pyx_t_1, __pyx_t_4, __pyx_t_5); } } __pyx_bstride_0_ii = __pyx_bstruct_ii.strides[0]; __pyx_bstride_1_ii = __pyx_bstruct_ii.strides[1]; __pyx_bshape_0_ii = __pyx_bstruct_ii.shape[0]; __pyx_bshape_1_ii = __pyx_bstruct_ii.shape[1]; - if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 573; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = 0; Py_DECREF(((PyObject *)__pyx_v_ii)); __pyx_v_ii = ((PyArrayObject *)__pyx_7); __pyx_7 = 0; - __pyx_1 = PyObject_GetAttr(((PyObject *)__pyx_v_ii), __pyx_kp_fill); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyInt_FromLong(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->n); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyTuple_New(1); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_2); - __pyx_2 = 0; - __pyx_3 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":574 + * dd.fill(infinity) + * ii = np.empty((n,k),dtype='i') + * ii.fill(self.n) # <<<<<<<<<<<<<< + * for c in range(n): + * self.__query( + */ + __pyx_3 = PyObject_GetAttr(((PyObject *)__pyx_v_ii), __pyx_kp_fill); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_5 = PyInt_FromLong(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->n); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_5); + __pyx_5 = 0; + __pyx_2 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 574; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; + Py_DECREF(__pyx_2); __pyx_2 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":575 + * ii = np.empty((n,k),dtype='i') + * ii.fill(self.n) + * for c in range(n): # <<<<<<<<<<<<<< + * self.__query( + * (dd.data)+c*k, + */ __pyx_8 = __pyx_PyInt_int(__pyx_v_n); if (unlikely((__pyx_8 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 575; __pyx_clineno = __LINE__; goto __pyx_L1_error;} for (__pyx_v_c = 0; __pyx_v_c < __pyx_8; __pyx_v_c+=1) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":583 + * eps, + * p, + * distance_upper_bound) # <<<<<<<<<<<<<< + * if single: + * if k==1: + */ ((struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree *)((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->__pyx_vtab)->__query(((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self), (((double *)__pyx_v_dd->data) + (__pyx_v_c * __pyx_v_k)), (((int *)__pyx_v_ii->data) + (__pyx_v_c * __pyx_v_k)), (((double *)__pyx_v_xx->data) + (__pyx_v_c * ((struct __pyx_obj_5scipy_7spatial_7ckdtree_cKDTree *)__pyx_v_self)->m)), __pyx_v_k, __pyx_v_eps, __pyx_v_p, __pyx_v_distance_upper_bound); } + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":584 + * p, + * distance_upper_bound) + * if single: # <<<<<<<<<<<<<< + * if k==1: + * return dd[0,0], ii[0,0] + */ __pyx_4 = __Pyx_PyObject_IsTrue(__pyx_v_single); if (unlikely(__pyx_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 584; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_4) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":585 + * distance_upper_bound) + * if single: + * if k==1: # <<<<<<<<<<<<<< + * return dd[0,0], ii[0,0] + * else: + */ __pyx_4 = (__pyx_v_k == 1); if (__pyx_4) { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":586 + * if single: + * if k==1: + * return dd[0,0], ii[0,0] # <<<<<<<<<<<<<< + * else: + * return dd[0], ii[0] + */ __pyx_t_8 = 0; __pyx_t_9 = 0; - __pyx_t_2 = -1; + __pyx_t_3 = -1; if (__pyx_t_8 < 0) { __pyx_t_8 += __pyx_bshape_0_dd; - if (unlikely(__pyx_t_8 < 0)) __pyx_t_2 = 0; - } else if (unlikely(__pyx_t_8 >= __pyx_bshape_0_dd)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_8 < 0)) __pyx_t_3 = 0; + } else if (unlikely(__pyx_t_8 >= __pyx_bshape_0_dd)) __pyx_t_3 = 0; if (__pyx_t_9 < 0) { __pyx_t_9 += __pyx_bshape_1_dd; - if (unlikely(__pyx_t_9 < 0)) __pyx_t_2 = 1; - } else if (unlikely(__pyx_t_9 >= __pyx_bshape_1_dd)) __pyx_t_2 = 1; - if (unlikely(__pyx_t_2 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_2); + if (unlikely(__pyx_t_9 < 0)) __pyx_t_3 = 1; + } else if (unlikely(__pyx_t_9 >= __pyx_bshape_1_dd)) __pyx_t_3 = 1; + if (unlikely(__pyx_t_3 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_9 = *((double *)((double *)__Pyx_BufPtrStrided2d(__pyx_bstruct_dd.buf, __pyx_t_8, __pyx_bstride_0_dd, __pyx_t_9, __pyx_bstride_1_dd))); - __pyx_7 = PyFloat_FromDouble(__pyx_9); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_7 = PyFloat_FromDouble((*__Pyx_BufPtrStrided2d(double *, __pyx_bstruct_dd.buf, __pyx_t_8, __pyx_bstride_0_dd, __pyx_t_9, __pyx_bstride_1_dd))); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = 0; __pyx_t_11 = 0; - __pyx_t_2 = -1; + __pyx_t_3 = -1; if (__pyx_t_10 < 0) { __pyx_t_10 += __pyx_bshape_0_ii; - if (unlikely(__pyx_t_10 < 0)) __pyx_t_2 = 0; - } else if (unlikely(__pyx_t_10 >= __pyx_bshape_0_ii)) __pyx_t_2 = 0; + if (unlikely(__pyx_t_10 < 0)) __pyx_t_3 = 0; + } else if (unlikely(__pyx_t_10 >= __pyx_bshape_0_ii)) __pyx_t_3 = 0; if (__pyx_t_11 < 0) { __pyx_t_11 += __pyx_bshape_1_ii; - if (unlikely(__pyx_t_11 < 0)) __pyx_t_2 = 1; - } else if (unlikely(__pyx_t_11 >= __pyx_bshape_1_ii)) __pyx_t_2 = 1; - if (unlikely(__pyx_t_2 != -1)) { - __Pyx_RaiseBufferIndexError(__pyx_t_2); + if (unlikely(__pyx_t_11 < 0)) __pyx_t_3 = 1; + } else if (unlikely(__pyx_t_11 >= __pyx_bshape_1_ii)) __pyx_t_3 = 1; + if (unlikely(__pyx_t_3 != -1)) { + __Pyx_RaiseBufferIndexError(__pyx_t_3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } - __pyx_8 = *((int *)((int *)__Pyx_BufPtrStrided2d(__pyx_bstruct_ii.buf, __pyx_t_10, __pyx_bstride_0_ii, __pyx_t_11, __pyx_bstride_1_ii))); - __pyx_2 = PyInt_FromLong(__pyx_8); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_7); - PyTuple_SET_ITEM(__pyx_1, 1, __pyx_2); + __pyx_5 = PyInt_FromLong((*__Pyx_BufPtrStrided2d(int *, __pyx_bstruct_ii.buf, __pyx_t_10, __pyx_bstride_0_ii, __pyx_t_11, __pyx_bstride_1_ii))); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 586; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_7); + PyTuple_SET_ITEM(__pyx_3, 1, __pyx_5); __pyx_7 = 0; - __pyx_2 = 0; - __pyx_r = ((PyObject *)__pyx_1); - __pyx_1 = 0; + __pyx_5 = 0; + __pyx_r = ((PyObject *)__pyx_3); + __pyx_3 = 0; goto __pyx_L0; - goto __pyx_L11; + goto __pyx_L12; } /*else*/ { - __pyx_5 = __Pyx_GetItemInt(((PyObject *)__pyx_v_dd), 0, 0); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = __Pyx_GetItemInt(((PyObject *)__pyx_v_ii), 0, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":588 + * return dd[0,0], ii[0,0] + * else: + * return dd[0], ii[0] # <<<<<<<<<<<<<< + * else: + * if k==1: + */ + __pyx_1 = __Pyx_GetItemInt(((PyObject *)__pyx_v_dd), 0, 0); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = __Pyx_GetItemInt(((PyObject *)__pyx_v_ii), 0, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_7 = PyTuple_New(2); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 588; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_7, 0, __pyx_5); - PyTuple_SET_ITEM(__pyx_7, 1, __pyx_3); - __pyx_5 = 0; - __pyx_3 = 0; + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_1); + PyTuple_SET_ITEM(__pyx_7, 1, __pyx_2); + __pyx_1 = 0; + __pyx_2 = 0; __pyx_r = ((PyObject *)__pyx_7); __pyx_7 = 0; goto __pyx_L0; } - __pyx_L11:; - goto __pyx_L10; + __pyx_L12:; + goto __pyx_L11; } /*else*/ { + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":590 + * return dd[0], ii[0] + * else: + * if k==1: # <<<<<<<<<<<<<< + * return np.reshape(dd[...,0],retshape), np.reshape(ii[...,0],retshape) + * else: + */ __pyx_4 = (__pyx_v_k == 1); if (__pyx_4) { - __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_reshape); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_5 = PyTuple_New(2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(Py_Ellipsis); - PyTuple_SET_ITEM(__pyx_5, 0, Py_Ellipsis); - Py_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_5, 1, __pyx_int_0); - __pyx_3 = PyObject_GetItem(((PyObject *)__pyx_v_dd), ((PyObject *)__pyx_5)); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; - __pyx_7 = PyTuple_New(2); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_7, 0, __pyx_3); - Py_INCREF(__pyx_v_retshape); - PyTuple_SET_ITEM(__pyx_7, 1, __pyx_v_retshape); - __pyx_3 = 0; - __pyx_2 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_7), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(((PyObject *)__pyx_7)); __pyx_7 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":591 + * else: + * if k==1: + * return np.reshape(dd[...,0],retshape), np.reshape(ii[...,0],retshape) # <<<<<<<<<<<<<< + * else: + * return np.reshape(dd,retshape+(k,)), np.reshape(ii,retshape+(k,)) + */ __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = PyObject_GetAttr(__pyx_5, __pyx_kp_reshape); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_5); __pyx_5 = 0; @@ -1962,73 +4363,98 @@ PyTuple_SET_ITEM(__pyx_1, 0, Py_Ellipsis); Py_INCREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_1, 1, __pyx_int_0); - __pyx_7 = PyObject_GetItem(((PyObject *)__pyx_v_ii), ((PyObject *)__pyx_1)); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetItem(((PyObject *)__pyx_v_dd), ((PyObject *)__pyx_1)); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - __pyx_5 = PyTuple_New(2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_7); + __pyx_7 = PyTuple_New(2); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_2); Py_INCREF(__pyx_v_retshape); - PyTuple_SET_ITEM(__pyx_5, 1, __pyx_v_retshape); + PyTuple_SET_ITEM(__pyx_7, 1, __pyx_v_retshape); + __pyx_2 = 0; + __pyx_5 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_7), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(((PyObject *)__pyx_7)); __pyx_7 = 0; + __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_kp_reshape); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(Py_Ellipsis); + PyTuple_SET_ITEM(__pyx_3, 0, Py_Ellipsis); + Py_INCREF(__pyx_int_0); + PyTuple_SET_ITEM(__pyx_3, 1, __pyx_int_0); + __pyx_7 = PyObject_GetItem(((PyObject *)__pyx_v_ii), ((PyObject *)__pyx_3)); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_7); + Py_INCREF(__pyx_v_retshape); + PyTuple_SET_ITEM(__pyx_1, 1, __pyx_v_retshape); __pyx_7 = 0; - __pyx_1 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; + __pyx_3 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; __pyx_7 = PyTuple_New(2); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 591; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_7, 0, __pyx_2); - PyTuple_SET_ITEM(__pyx_7, 1, __pyx_1); - __pyx_2 = 0; - __pyx_1 = 0; + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_5); + PyTuple_SET_ITEM(__pyx_7, 1, __pyx_3); + __pyx_5 = 0; + __pyx_3 = 0; __pyx_r = ((PyObject *)__pyx_7); __pyx_7 = 0; goto __pyx_L0; - goto __pyx_L12; + goto __pyx_L13; } /*else*/ { - __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyObject_GetAttr(__pyx_3, __pyx_kp_reshape); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - __pyx_2 = PyInt_FromLong(__pyx_v_k); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_2); - __pyx_2 = 0; - __pyx_7 = PyNumber_Add(__pyx_v_retshape, ((PyObject *)__pyx_1)); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_INCREF(((PyObject *)__pyx_v_dd)); - PyTuple_SET_ITEM(__pyx_3, 0, ((PyObject *)__pyx_v_dd)); - PyTuple_SET_ITEM(__pyx_3, 1, __pyx_7); - __pyx_7 = 0; - __pyx_2 = PyObject_Call(__pyx_5, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; - Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; - __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_7 = PyObject_GetAttr(__pyx_1, __pyx_kp_reshape); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":593 + * return np.reshape(dd[...,0],retshape), np.reshape(ii[...,0],retshape) + * else: + * return np.reshape(dd,retshape+(k,)), np.reshape(ii,retshape+(k,)) # <<<<<<<<<<<<<< + * + */ + __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_reshape); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_5 = PyInt_FromLong(__pyx_v_k); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} PyTuple_SET_ITEM(__pyx_3, 0, __pyx_5); __pyx_5 = 0; - __pyx_1 = PyNumber_Add(__pyx_v_retshape, ((PyObject *)__pyx_3)); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Add(__pyx_v_retshape, ((PyObject *)__pyx_3)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __pyx_7 = PyTuple_New(2); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(((PyObject *)__pyx_v_dd)); + PyTuple_SET_ITEM(__pyx_7, 0, ((PyObject *)__pyx_v_dd)); + PyTuple_SET_ITEM(__pyx_7, 1, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_2 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_7), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + Py_DECREF(((PyObject *)__pyx_7)); __pyx_7 = 0; + __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_GetAttr(__pyx_5, __pyx_kp_reshape); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_5); __pyx_5 = 0; + __pyx_1 = PyInt_FromLong(__pyx_v_k); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_7 = PyTuple_New(1); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_1); + __pyx_1 = 0; + __pyx_t_5 = PyNumber_Add(__pyx_v_retshape, ((PyObject *)__pyx_7)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_7)); __pyx_7 = 0; __pyx_5 = PyTuple_New(2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(((PyObject *)__pyx_v_ii)); PyTuple_SET_ITEM(__pyx_5, 0, ((PyObject *)__pyx_v_ii)); - PyTuple_SET_ITEM(__pyx_5, 1, __pyx_1); - __pyx_1 = 0; - __pyx_3 = PyObject_Call(__pyx_7, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_7); __pyx_7 = 0; + PyTuple_SET_ITEM(__pyx_5, 1, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_1 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_5), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(((PyObject *)__pyx_5)); __pyx_5 = 0; - __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_2); - PyTuple_SET_ITEM(__pyx_1, 1, __pyx_3); + __pyx_7 = PyTuple_New(2); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_2); + PyTuple_SET_ITEM(__pyx_7, 1, __pyx_1); __pyx_2 = 0; - __pyx_3 = 0; - __pyx_r = ((PyObject *)__pyx_1); __pyx_1 = 0; + __pyx_r = ((PyObject *)__pyx_7); + __pyx_7 = 0; goto __pyx_L0; } - __pyx_L12:; + __pyx_L13:; } - __pyx_L10:; + __pyx_L11:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; @@ -2039,18 +4465,18 @@ Py_XDECREF(__pyx_5); Py_XDECREF(__pyx_7); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - PyErr_Fetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_ii, &__pyx_bstruct_ii); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_xx, &__pyx_bstruct_xx); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_dd, &__pyx_bstruct_dd); - PyErr_Restore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_ii); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_xx); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_dd); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("scipy.spatial.ckdtree.cKDTree.query"); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_ii, &__pyx_bstruct_ii); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_xx, &__pyx_bstruct_xx); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_dd, &__pyx_bstruct_dd); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_ii); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_xx); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_dd); __pyx_L2:; Py_DECREF(__pyx_v_ii); Py_DECREF(__pyx_v_dd); @@ -2062,108 +4488,1242 @@ return __pyx_r; } +/* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":50 + * # experimental exception made for __getbuffer__ and __releasebuffer__ + * # -- the details of this may change. + * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fullfill the PEP. + */ + static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; int __pyx_v_t; char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + PyObject *__pyx_v_stack; + int __pyx_v_hasfields; + PyObject *__pyx_v_iterator; int __pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; + int __pyx_4; + PyObject *__pyx_5 = 0; + PyObject *__pyx_6 = 0; + PyObject *__pyx_7 = 0; + Py_ssize_t __pyx_8 = 0; + PyObject *__pyx_t_1 = NULL; + if (__pyx_v_info == NULL) return 0; + __pyx_v_info->obj = Py_None; Py_INCREF(Py_None); + __pyx_v_stack = ((PyObject *)Py_None); Py_INCREF(Py_None); + __pyx_v_iterator = Py_None; Py_INCREF(Py_None); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":56 + * # of flags + * cdef int copy_shape, i, ndim + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":58 + * ndim = PyArray_NDIM(self) + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * copy_shape = 1 + * else: + */ __pyx_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_1) { - __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":59 + * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L5; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":61 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + */ + __pyx_v_copy_shape = 0; + } + __pyx_L5:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":63 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError("ndarray is not C contiguous") + */ + __pyx_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":64 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError("ndarray is not C contiguous") + * + */ + __pyx_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + } + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":65 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError("ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_kp_1); PyTuple_SET_ITEM(__pyx_2, 0, __pyx_kp_1); - __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; __Pyx_Raise(__pyx_3, 0, 0); Py_DECREF(__pyx_3); __pyx_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L5:; + __pyx_L6:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":67 + * raise ValueError("ndarray is not C contiguous") + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError("ndarray is not Fortran contiguous") + */ + __pyx_1 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":68 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError("ndarray is not Fortran contiguous") + * + */ + __pyx_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + } + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":69 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError("ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_kp_2); + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_kp_2); + __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; + __Pyx_Raise(__pyx_3, 0, 0); + Py_DECREF(__pyx_3); __pyx_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":71 + * raise ValueError("ndarray is not Fortran contiguous") + * + * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< + * info.ndim = ndim + * if copy_shape: + */ __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); - __pyx_v_info->ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":72 + * + * info.buf = PyArray_DATA(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. This is allocated + */ + __pyx_v_info->ndim = __pyx_v_ndim; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":73 + * info.buf = PyArray_DATA(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. This is allocated + * # as one block, strides first. + */ + __pyx_4 = __pyx_v_copy_shape; + if (__pyx_4) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":76 + * # Allocate new buffer for strides and shape info. This is allocated + * # as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * __pyx_v_ndim) * 2))); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":77 + * # as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":78 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_ndim; __pyx_v_i+=1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":79 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":80 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + } + goto __pyx_L8; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":82 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + */ + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":83 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + */ + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + } + __pyx_L8:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":84 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) + */ __pyx_v_info->suboffsets = NULL; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":85 + * info.shape = PyArray_DIMS(self) + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< + * info.readonly = not PyArray_ISWRITEABLE(self) + * + */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":86 + * info.suboffsets = NULL + * info.itemsize = PyArray_ITEMSIZE(self) + * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< + * + * cdef int t + */ __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); - __pyx_v_t = PyArray_TYPE(((PyArrayObject *)__pyx_v_self)); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":89 + * + * cdef int t + * cdef char* f = NULL # <<<<<<<<<<<<<< + * cdef dtype descr = self.descr + * cdef list stack + */ __pyx_v_f = NULL; - switch (__pyx_v_t) { - case NPY_BYTE: - __pyx_v_f = __pyx_k_2; - break; - case NPY_UBYTE: - __pyx_v_f = __pyx_k_3; - break; - case NPY_SHORT: - __pyx_v_f = __pyx_k_4; - break; - case NPY_USHORT: - __pyx_v_f = __pyx_k_5; - break; - case NPY_INT: - __pyx_v_f = __pyx_k_6; - break; - case NPY_UINT: - __pyx_v_f = __pyx_k_7; - break; - case NPY_LONG: - __pyx_v_f = __pyx_k_8; - break; - case NPY_ULONG: - __pyx_v_f = __pyx_k_9; - break; - case NPY_LONGLONG: - __pyx_v_f = __pyx_k_10; - break; - case NPY_ULONGLONG: - __pyx_v_f = __pyx_k_11; - break; - case NPY_FLOAT: - __pyx_v_f = __pyx_k_12; - break; - case NPY_DOUBLE: - __pyx_v_f = __pyx_k_13; - break; - case NPY_LONGDOUBLE: - __pyx_v_f = __pyx_k_14; - break; - case NPY_OBJECT: - __pyx_v_f = __pyx_k_15; - break; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":90 + * cdef int t + * cdef char* f = NULL + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * + */ + Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); + __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":93 + * cdef list stack + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * # Ugly hack warning: + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":103 + * # functions). + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None + */ + __pyx_1 = (!__pyx_v_hasfields); + if (__pyx_1) { + __pyx_1 = (!__pyx_v_copy_shape); } - __pyx_1 = (__pyx_v_f == NULL); if (__pyx_1) { - __pyx_2 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyNumber_Remainder(__pyx_kp_16, __pyx_2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":105 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer + */ + Py_INCREF(Py_None); + Py_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L11; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":108 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: + */ + Py_INCREF(__pyx_v_self); + Py_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = __pyx_v_self; + } + __pyx_L11:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":110 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if t == NPY_BYTE: f = "b" + */ + __pyx_1 = (!__pyx_v_hasfields); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":111 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + */ + __pyx_v_t = __pyx_v_descr->type_num; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":112 + * if not hasfields: + * t = descr.type_num + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + */ + switch (__pyx_v_t) { + case NPY_BYTE: + __pyx_v_f = __pyx_k_3; + break; + case NPY_UBYTE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":113 + * t = descr.type_num + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + */ + __pyx_v_f = __pyx_k_4; + break; + case NPY_SHORT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":114 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + */ + __pyx_v_f = __pyx_k_5; + break; + case NPY_USHORT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":115 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + */ + __pyx_v_f = __pyx_k_6; + break; + case NPY_INT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":116 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + */ + __pyx_v_f = __pyx_k_7; + break; + case NPY_UINT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":117 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + */ + __pyx_v_f = __pyx_k_8; + break; + case NPY_LONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":118 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + */ + __pyx_v_f = __pyx_k_9; + break; + case NPY_ULONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":119 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + __pyx_v_f = __pyx_k_10; + break; + case NPY_LONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":120 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + __pyx_v_f = __pyx_k_11; + break; + case NPY_ULONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":121 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + __pyx_v_f = __pyx_k_12; + break; + case NPY_FLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":122 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + __pyx_v_f = __pyx_k_13; + break; + case NPY_DOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":123 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + __pyx_v_f = __pyx_k_14; + break; + case NPY_LONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":124 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + __pyx_v_f = __pyx_k_15; + break; + case NPY_CFLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":125 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + __pyx_v_f = __pyx_k_16; + break; + case NPY_CDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":126 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + __pyx_v_f = __pyx_k_17; + break; + case NPY_CLONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":127 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + __pyx_v_f = __pyx_k_18; + break; + case NPY_OBJECT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":128 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_v_f = __pyx_k_19; + break; + default: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":130 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_2 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(__pyx_kp_20, __pyx_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __Pyx_Raise(__pyx_2, 0, 0); + Py_DECREF(__pyx_2); __pyx_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":131 + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":132 + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(255) # static size + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L12; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":134 + * return + * else: + * info.format = stdlib.malloc(255) # static size # <<<<<<<<<<<<<< + * f = info.format + * stack = [iter(descr.fields.iteritems())] + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":135 + * else: + * info.format = stdlib.malloc(255) # static size + * f = info.format # <<<<<<<<<<<<<< + * stack = [iter(descr.fields.iteritems())] + * + */ + __pyx_v_f = __pyx_v_info->format; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":136 + * info.format = stdlib.malloc(255) # static size + * f = info.format + * stack = [iter(descr.fields.iteritems())] # <<<<<<<<<<<<<< + * + * while True: + */ + __pyx_3 = PyObject_GetAttr(__pyx_v_descr->fields, __pyx_kp_iteritems); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_3 = PyObject_GetIter(__pyx_2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_2, 0, __pyx_3); + __pyx_2 = PyList_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyList_SET_ITEM(__pyx_2, 0, __pyx_3); __pyx_3 = 0; - __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; - __Pyx_Raise(__pyx_3, 0, 0); - Py_DECREF(__pyx_3); __pyx_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; + Py_DECREF(((PyObject *)__pyx_v_stack)); + __pyx_v_stack = __pyx_2; + __pyx_2 = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":138 + * stack = [iter(descr.fields.iteritems())] + * + * while True: # <<<<<<<<<<<<<< + * iterator = stack[-1] + * descr = None + */ + while (1) { + __pyx_1 = 1; + if (!__pyx_1) break; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":139 + * + * while True: + * iterator = stack[-1] # <<<<<<<<<<<<<< + * descr = None + * while descr is None: + */ + __pyx_3 = __Pyx_GetItemInt(((PyObject *)__pyx_v_stack), -1, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_v_iterator); + __pyx_v_iterator = __pyx_3; + __pyx_3 = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":140 + * while True: + * iterator = stack[-1] + * descr = None # <<<<<<<<<<<<<< + * while descr is None: + * try: + */ + Py_INCREF(Py_None); + Py_DECREF(((PyObject *)__pyx_v_descr)); + __pyx_v_descr = ((PyArray_Descr *)Py_None); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":141 + * iterator = stack[-1] + * descr = None + * while descr is None: # <<<<<<<<<<<<<< + * try: + * descr = iterator.next()[1][0] + */ + while (1) { + __pyx_1 = (((PyObject *)__pyx_v_descr) == Py_None); + if (!__pyx_1) break; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":142 + * descr = None + * while descr is None: + * try: # <<<<<<<<<<<<<< + * descr = iterator.next()[1][0] + * except StopIteration: + */ + { + PyObject *__pyx_save_exc_type, *__pyx_save_exc_value, *__pyx_save_exc_tb; + __Pyx_ExceptionSave(&__pyx_save_exc_type, &__pyx_save_exc_value, &__pyx_save_exc_tb); + /*try:*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":143 + * while descr is None: + * try: + * descr = iterator.next()[1][0] # <<<<<<<<<<<<<< + * except StopIteration: + * stack.pop() + */ + __pyx_2 = PyObject_GetAttr(__pyx_v_iterator, __pyx_kp_next); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + __pyx_3 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_2 = __Pyx_GetItemInt(__pyx_3, 1, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_3 = __Pyx_GetItemInt(__pyx_2, 0, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + if (!(__Pyx_TypeTest(__pyx_3, __pyx_ptype_5numpy_dtype))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(((PyObject *)__pyx_v_descr)); + __pyx_v_descr = ((PyArray_Descr *)__pyx_3); + __pyx_3 = 0; + } + goto __pyx_L21_try; + __pyx_L17_error:; + Py_XDECREF(__pyx_2); __pyx_2 = 0; + Py_XDECREF(__pyx_3); __pyx_3 = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":144 + * try: + * descr = iterator.next()[1][0] + * except StopIteration: # <<<<<<<<<<<<<< + * stack.pop() + * if len(stack) > 0: + */ + __pyx_4 = PyErr_ExceptionMatches(__pyx_builtin_StopIteration); + if (__pyx_4) { + __Pyx_AddTraceback("numpy.__getbuffer__"); + if (__Pyx_GetException(&__pyx_2, &__pyx_3, &__pyx_5) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":145 + * descr = iterator.next()[1][0] + * except StopIteration: + * stack.pop() # <<<<<<<<<<<<<< + * if len(stack) > 0: + * f[0] = 125 #"}" + */ + __pyx_6 = PyObject_GetAttr(((PyObject *)__pyx_v_stack), __pyx_kp_pop); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + __pyx_7 = PyObject_Call(__pyx_6, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + Py_DECREF(__pyx_6); __pyx_6 = 0; + Py_DECREF(__pyx_7); __pyx_7 = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":146 + * except StopIteration: + * stack.pop() + * if len(stack) > 0: # <<<<<<<<<<<<<< + * f[0] = 125 #"}" + * f += 1 + */ + __pyx_8 = PyObject_Length(((PyObject *)__pyx_v_stack)); if (unlikely(__pyx_8 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + __pyx_1 = (__pyx_8 > 0); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":147 + * stack.pop() + * if len(stack) > 0: + * f[0] = 125 #"}" # <<<<<<<<<<<<<< + * f += 1 + * iterator = stack[-1] + */ + (__pyx_v_f[0]) = 125; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":148 + * if len(stack) > 0: + * f[0] = 125 #"}" + * f += 1 # <<<<<<<<<<<<<< + * iterator = stack[-1] + * else: + */ + __pyx_v_f += 1; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":149 + * f[0] = 125 #"}" + * f += 1 + * iterator = stack[-1] # <<<<<<<<<<<<<< + * else: + * f[0] = 0 # Terminate string! + */ + __pyx_6 = __Pyx_GetItemInt(((PyObject *)__pyx_v_stack), -1, 0); if (!__pyx_6) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + Py_DECREF(__pyx_v_iterator); + __pyx_v_iterator = __pyx_6; + __pyx_6 = 0; + goto __pyx_L22; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":151 + * iterator = stack[-1] + * else: + * f[0] = 0 # Terminate string! # <<<<<<<<<<<<<< + * return + * + */ + (__pyx_v_f[0]) = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":152 + * else: + * f[0] = 0 # Terminate string! + * return # <<<<<<<<<<<<<< + * + * hasfields = PyDataType_HASFIELDS(descr) + */ + __pyx_r = 0; + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(__pyx_5); __pyx_5 = 0; + goto __pyx_L20_except_return; + } + __pyx_L22:; + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(__pyx_5); __pyx_5 = 0; + goto __pyx_L18_exception_handled; + } + __pyx_L19_except_error:; + Py_XDECREF(__pyx_save_exc_type); + Py_XDECREF(__pyx_save_exc_value); + Py_XDECREF(__pyx_save_exc_tb); + goto __pyx_L1_error; + __pyx_L20_except_return:; + __Pyx_ExceptionReset(__pyx_save_exc_type, __pyx_save_exc_value, __pyx_save_exc_tb); + goto __pyx_L0; + __pyx_L18_exception_handled:; + __Pyx_ExceptionReset(__pyx_save_exc_type, __pyx_save_exc_value, __pyx_save_exc_tb); + __pyx_L21_try:; + } + } + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":154 + * return + * + * hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * if not hasfields: + * t = descr.type_num + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":155 + * + * hasfields = PyDataType_HASFIELDS(descr) + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if f - info.format > 240: # this should leave room for "T{" and "}" as well + */ + __pyx_1 = (!__pyx_v_hasfields); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":156 + * hasfields = PyDataType_HASFIELDS(descr) + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if f - info.format > 240: # this should leave room for "T{" and "}" as well + * raise RuntimeError("Format string allocated too short.") + */ + __pyx_v_t = __pyx_v_descr->type_num; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":157 + * if not hasfields: + * t = descr.type_num + * if f - info.format > 240: # this should leave room for "T{" and "}" as well # <<<<<<<<<<<<<< + * raise RuntimeError("Format string allocated too short.") + * + */ + __pyx_1 = ((__pyx_v_f - __pyx_v_info->format) > 240); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":158 + * t = descr.type_num + * if f - info.format > 240: # this should leave room for "T{" and "}" as well + * raise RuntimeError("Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_7 = PyTuple_New(1); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_kp_21); + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_kp_21); + __pyx_6 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_7), NULL); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_7)); __pyx_7 = 0; + __Pyx_Raise(__pyx_6, 0, 0); + Py_DECREF(__pyx_6); __pyx_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L24; + } + __pyx_L24:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":161 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + switch (__pyx_v_t) { + case NPY_BYTE: + (__pyx_v_f[0]) = 98; + break; + case NPY_UBYTE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":162 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + (__pyx_v_f[0]) = 66; + break; + case NPY_SHORT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":163 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + (__pyx_v_f[0]) = 104; + break; + case NPY_USHORT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":164 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + (__pyx_v_f[0]) = 72; + break; + case NPY_INT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":165 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + (__pyx_v_f[0]) = 105; + break; + case NPY_UINT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":166 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + (__pyx_v_f[0]) = 73; + break; + case NPY_LONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":167 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + (__pyx_v_f[0]) = 108; + break; + case NPY_ULONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":168 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + (__pyx_v_f[0]) = 76; + break; + case NPY_LONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":169 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + (__pyx_v_f[0]) = 113; + break; + case NPY_ULONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":170 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + (__pyx_v_f[0]) = 81; + break; + case NPY_FLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":171 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + (__pyx_v_f[0]) = 102; + break; + case NPY_DOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":172 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + */ + (__pyx_v_f[0]) = 100; + break; + case NPY_LONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":173 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + */ + (__pyx_v_f[0]) = 103; + break; + case NPY_CFLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":174 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 + */ + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f += 1; + break; + case NPY_CDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":175 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f += 1; + break; + case NPY_CLONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":176 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f += 1; + break; + case NPY_OBJECT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":177 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + */ + (__pyx_v_f[0]) = 79; + break; + default: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":179 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_2 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(__pyx_kp_22, __pyx_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __Pyx_Raise(__pyx_5, 0, 0); + Py_DECREF(__pyx_5); __pyx_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":180 + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * f[0] = 84 #"T" + */ + __pyx_v_f += 1; + goto __pyx_L23; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":182 + * f += 1 + * else: + * f[0] = 84 #"T" # <<<<<<<<<<<<<< + * f[1] = 123 #"{" + * f += 2 + */ + (__pyx_v_f[0]) = 84; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":183 + * else: + * f[0] = 84 #"T" + * f[1] = 123 #"{" # <<<<<<<<<<<<<< + * f += 2 + * stack.append(iter(descr.fields.iteritems())) + */ + (__pyx_v_f[1]) = 123; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":184 + * f[0] = 84 #"T" + * f[1] = 123 #"{" + * f += 2 # <<<<<<<<<<<<<< + * stack.append(iter(descr.fields.iteritems())) + * + */ + __pyx_v_f += 2; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":185 + * f[1] = 123 #"{" + * f += 2 + * stack.append(iter(descr.fields.iteritems())) # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + __pyx_7 = PyObject_GetAttr(__pyx_v_descr->fields, __pyx_kp_iteritems); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_6 = PyObject_Call(__pyx_7, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_7); __pyx_7 = 0; + __pyx_2 = PyObject_GetIter(__pyx_6); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_6); __pyx_6 = 0; + __pyx_4 = PyList_Append(((PyObject *)__pyx_v_stack), __pyx_2); if (unlikely(__pyx_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + } + __pyx_L23:; + } } - __pyx_L6:; - __pyx_v_info->format = __pyx_v_f; + __pyx_L12:; __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); + Py_XDECREF(__pyx_5); + Py_XDECREF(__pyx_6); + Py_XDECREF(__pyx_7); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__"); __pyx_r = -1; + Py_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + goto __pyx_L2; __pyx_L0:; + if (__pyx_v_info->obj == Py_None) { Py_DECREF(Py_None); __pyx_v_info->obj = NULL; } + __pyx_L2:; + Py_XDECREF(__pyx_v_descr); + Py_DECREF(__pyx_v_stack); + Py_DECREF(__pyx_v_iterator); return __pyx_r; } + +/* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":187 + * stack.append(iter(descr.fields.iteritems())) + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray___releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static void __pyx_pf_5numpy_7ndarray___releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + int __pyx_1; + int __pyx_2; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":188 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":189 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L5; + } + __pyx_L5:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":190 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_2 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + if (__pyx_2) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":191 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L6; + } + __pyx_L6:; + +} static struct __pyx_vtabstruct_5scipy_7spatial_7ckdtree_cKDTree __pyx_vtable_5scipy_7spatial_7ckdtree_cKDTree; static PyObject *__pyx_tp_new_5scipy_7spatial_7ckdtree_cKDTree(PyTypeObject *t, PyObject *a, PyObject *k) { @@ -2334,10 +5894,10 @@ #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif - #if (PY_MAJOR_VERSION >= 3) || (Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER) + #if PY_VERSION_HEX >= 0x02060000 0, /*bf_getbuffer*/ #endif - #if (PY_MAJOR_VERSION >= 3) || (Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER) + #if PY_VERSION_HEX >= 0x02060000 0, /*bf_releasebuffer*/ #endif }; @@ -2362,7 +5922,7 @@ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_cKDTree, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ "kd-tree for quick nearest-neighbor lookup\n\n This class provides an index into a set of k-dimensional points\n which can be used to rapidly look up the nearest neighbors of any\n point. \n\n The algorithm used is described in Maneewongvatana and Mount 1999. \n The general idea is that the kd-tree is a binary trie, each of whose\n nodes represents an axis-aligned hyperrectangle. Each node specifies\n an axis and splits the set of points based on whether their coordinate\n along that axis is greater than or less than a particular value. \n\n During construction, the axis and splitting point are chosen by the \n \"sliding midpoint\" rule, which ensures that the cells do not all\n become long and thin. \n\n The tree can be queried for the r closest neighbors of any given point \n (optionally returning only those within some maximum distance of the \n point). It can also be queried, with a substantial gain in efficiency, \n for the r approximate closest neighbors.\n\n For large dimensions (20 is already large) do not expect this to run \n significantly faster than brute force. High-dimensional nearest-neighbor\n queries are a substantial open problem in computer science.\n ", /*tp_doc*/ __pyx_tp_traverse_5scipy_7spatial_7ckdtree_cKDTree, /*tp_traverse*/ __pyx_tp_clear_5scipy_7spatial_7ckdtree_cKDTree, /*tp_clear*/ @@ -2411,9 +5971,16 @@ #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp___init__, __pyx_k___init__, sizeof(__pyx_k___init__), 0, 1, 1}, - {&__pyx_kp___dealloc__, __pyx_k___dealloc__, sizeof(__pyx_k___dealloc__), 0, 1, 1}, - {&__pyx_kp_query, __pyx_k_query, sizeof(__pyx_k_query), 0, 1, 1}, + {&__pyx_kp___init__, __pyx_k___init__, sizeof(__pyx_k___init__), 1, 1, 1}, + {&__pyx_kp___dealloc__, __pyx_k___dealloc__, sizeof(__pyx_k___dealloc__), 1, 1, 1}, + {&__pyx_kp_query, __pyx_k_query, sizeof(__pyx_k_query), 1, 1, 1}, + {&__pyx_kp_data, __pyx_k_data, sizeof(__pyx_k_data), 1, 1, 1}, + {&__pyx_kp_leafsize, __pyx_k_leafsize, sizeof(__pyx_k_leafsize), 1, 1, 1}, + {&__pyx_kp_x, __pyx_k_x, sizeof(__pyx_k_x), 1, 1, 1}, + {&__pyx_kp_k, __pyx_k_k, sizeof(__pyx_k_k), 1, 1, 1}, + {&__pyx_kp_eps, __pyx_k_eps, sizeof(__pyx_k_eps), 1, 1, 1}, + {&__pyx_kp_p, __pyx_k_p, sizeof(__pyx_k_p), 1, 1, 1}, + {&__pyx_kp_23, __pyx_k_23, sizeof(__pyx_k_23), 1, 1, 1}, {&__pyx_kp_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 1, 1, 1}, {&__pyx_kp_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 1, 1}, {&__pyx_kp_kdtree, __pyx_k_kdtree, sizeof(__pyx_k_kdtree), 1, 1, 1}, @@ -2427,7 +5994,7 @@ {&__pyx_kp_axis, __pyx_k_axis, sizeof(__pyx_k_axis), 1, 1, 1}, {&__pyx_kp_amin, __pyx_k_amin, sizeof(__pyx_k_amin), 1, 1, 1}, {&__pyx_kp_arange, __pyx_k_arange, sizeof(__pyx_k_arange), 1, 1, 1}, - {&__pyx_kp_int, __pyx_k_int, sizeof(__pyx_k_int), 1, 1, 1}, + {&__pyx_kp_27, __pyx_k_27, sizeof(__pyx_k_27), 1, 1, 1}, {&__pyx_kp_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 1, 1, 1}, {&__pyx_kp_astype, __pyx_k_astype, sizeof(__pyx_k_astype), 1, 1, 1}, {&__pyx_kp_newaxis, __pyx_k_newaxis, sizeof(__pyx_k_newaxis), 1, 1, 1}, @@ -2435,20 +6002,31 @@ {&__pyx_kp_reshape, __pyx_k_reshape, sizeof(__pyx_k_reshape), 1, 1, 1}, {&__pyx_kp_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 1, 1, 1}, {&__pyx_kp_fill, __pyx_k_fill, sizeof(__pyx_k_fill), 1, 1, 1}, - {&__pyx_kp_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 1, 0}, - {&__pyx_kp_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 0}, - {&__pyx_kp_19, __pyx_k_19, sizeof(__pyx_k_19), 0, 0, 0}, + {&__pyx_kp_30, __pyx_k_30, sizeof(__pyx_k_30), 0, 1, 0}, + {&__pyx_kp_25, __pyx_k_25, sizeof(__pyx_k_25), 0, 0, 0}, + {&__pyx_kp_26, __pyx_k_26, sizeof(__pyx_k_26), 0, 0, 0}, + {&__pyx_kp_28, __pyx_k_28, sizeof(__pyx_k_28), 0, 0, 0}, + {&__pyx_kp_29, __pyx_k_29, sizeof(__pyx_k_29), 0, 0, 0}, + {&__pyx_kp___getbuffer__, __pyx_k___getbuffer__, sizeof(__pyx_k___getbuffer__), 1, 1, 1}, + {&__pyx_kp___releasebuffer__, __pyx_k___releasebuffer__, sizeof(__pyx_k___releasebuffer__), 1, 1, 1}, + {&__pyx_kp_info, __pyx_k_info, sizeof(__pyx_k_info), 1, 1, 1}, + {&__pyx_kp_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 1, 1, 1}, + {&__pyx_kp_iteritems, __pyx_k_iteritems, sizeof(__pyx_k_iteritems), 1, 1, 1}, + {&__pyx_kp_next, __pyx_k_next, sizeof(__pyx_k_next), 1, 1, 1}, + {&__pyx_kp_StopIteration, __pyx_k_StopIteration, sizeof(__pyx_k_StopIteration), 1, 1, 1}, + {&__pyx_kp_pop, __pyx_k_pop, sizeof(__pyx_k_pop), 1, 1, 1}, + {&__pyx_kp_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 1, 1, 1}, + {&__pyx_kp_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 0}, + {&__pyx_kp_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 0}, {&__pyx_kp_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 0}, {&__pyx_kp_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 0}, - {&__pyx_kp___getbuffer__, __pyx_k___getbuffer__, sizeof(__pyx_k___getbuffer__), 0, 1, 1}, - {&__pyx_kp_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 1, 1, 1}, - {&__pyx_kp_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 0}, - {&__pyx_kp_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 0}, + {&__pyx_kp_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 0}, {0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_kp_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 38; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_kp_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_StopIteration = __Pyx_GetName(__pyx_b, __pyx_kp_StopIteration); if (!__pyx_builtin_StopIteration) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_kp_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -2474,7 +6052,7 @@ PyObject *__pyx_2 = 0; double __pyx_3; __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Libary function declarations ---*/ + /*--- Library function declarations ---*/ __pyx_init_filenames(); /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -2506,22 +6084,62 @@ if (PyObject_SetAttrString(__pyx_m, "cKDTree", (PyObject *)&__pyx_type_5scipy_7spatial_7ckdtree_cKDTree) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 157; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5scipy_7spatial_7ckdtree_cKDTree = &__pyx_type_5scipy_7spatial_7ckdtree_cKDTree; /*--- Type import code ---*/ - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject)); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr)); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject)); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Function import code ---*/ /*--- Execution code ---*/ + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":3 + * # Copyright Anne M. Archibald 2008 + * # Released under the scipy license + * import numpy as np # <<<<<<<<<<<<<< + * cimport numpy as np + * cimport stdlib + */ __pyx_1 = __Pyx_Import(__pyx_kp_numpy, 0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (PyObject_SetAttr(__pyx_m, __pyx_kp_np, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":7 + * cimport stdlib + * + * import kdtree # <<<<<<<<<<<<<< + * + * cdef double infinity = np.inf + */ __pyx_1 = __Pyx_Import(__pyx_kp_kdtree, 0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (PyObject_SetAttr(__pyx_m, __pyx_kp_kdtree, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":9 + * import kdtree + * + * cdef double infinity = np.inf # <<<<<<<<<<<<<< + * + * + */ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_kp_inf); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; __pyx_3 = __pyx_PyFloat_AsDouble(__pyx_2); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_v_5scipy_7spatial_7ckdtree_infinity = __pyx_3; - __pyx_k_17 = __pyx_v_5scipy_7spatial_7ckdtree_infinity; + + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/spatial/ckdtree.pyx":517 + * + * def query(cKDTree self, object x, int k=1, double eps=0, double p=2, + * double distance_upper_bound=infinity): # <<<<<<<<<<<<<< + * """query the kd-tree for nearest neighbors + * + */ + __pyx_k_24 = __pyx_v_5scipy_7spatial_7ckdtree_infinity; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/stdlib.pxd":2 + * + * cdef extern from "stdlib.h": # <<<<<<<<<<<<<< + * ctypedef unsigned long size_t + * void free(void *ptr) + */ #if PY_MAJOR_VERSION < 3 return; #else @@ -2547,14 +6165,140 @@ __pyx_f = __pyx_filenames; } -static INLINE void __Pyx_SafeReleaseBuffer(PyObject* obj, Py_buffer* info) { +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AS_STRING(kw_name)); + #endif +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *number, *more_or_less; + + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + number = (num_expected == 1) ? "" : "s"; + PyErr_Format(PyExc_TypeError, + #if PY_VERSION_HEX < 0x02050000 + "%s() takes %s %d positional argument%s (%d given)", + #else + "%s() takes %s %zd positional argument%s (%zd given)", + #endif + func_name, more_or_less, num_expected, number, num_found); +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + + while (PyDict_Next(kwds, &pos, &key, &value)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { + #else + if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { + #endif + goto invalid_keyword_type; + } else { + name = argnames; + while (*name && (**name != key)) name++; + if (*name) { + if (name < first_kw_arg) goto arg_passed_twice; + values[name-argnames] = value; + } else { + for (name = first_kw_arg; *name; name++) { + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) break; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + strcmp(PyString_AS_STRING(**name), + PyString_AS_STRING(key)) == 0) break; + #endif + } + if (*name) { + values[name-argnames] = value; + } else { + /* unexpected keyword found */ + for (name=argnames; name != first_kw_arg; name++) { + if (**name == key) goto arg_passed_twice; + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + strcmp(PyString_AS_STRING(**name), + PyString_AS_STRING(key)) == 0) goto arg_passed_twice; + #endif + } + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + } + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, **name); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(obj, info); + __Pyx_ReleaseBuffer(info); } static INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; + buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; @@ -2563,58 +6307,72 @@ static INLINE const char* __Pyx_ConsumeWhitespace(const char* ts) { while (1) { switch (*ts) { + case '@': case 10: case 13: case ' ': ++ts; + break; + case '=': + case '<': + case '>': + case '!': + PyErr_SetString(PyExc_ValueError, "Buffer acquisition error: Only native byte order, size and alignment supported."); + return NULL; default: return ts; } } } -static INLINE const char* __Pyx_BufferTypestringCheckEndian(const char* ts) { - int num = 1; - int little_endian = ((char*)&num)[0]; - int ok = 1; - switch (*ts) { - case '@': - case '=': - ++ts; break; - case '<': - if (little_endian) ++ts; - else ok = 0; - break; - case '>': - case '!': - if (!little_endian) ++ts; - else ok = 0; - break; - } - if (!ok) { - PyErr_Format(PyExc_ValueError, "Buffer has wrong endianness (rejecting on '%s')", ts); - return NULL; - } - return ts; -} - static void __Pyx_BufferNdimError(Py_buffer* buffer, int expected_ndim) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", expected_ndim, buffer->ndim); } +static const char* __Pyx_DescribeTokenInFormatString(const char* ts) { + switch (*ts) { + case 'b': return "char"; + case 'B': return "unsigned char"; + case 'h': return "short"; + case 'H': return "unsigned short"; + case 'i': return "int"; + case 'I': return "unsigned int"; + case 'l': return "long"; + case 'L': return "unsigned long"; + case 'q': return "long long"; + case 'Q': return "unsigned long long"; + case 'f': return "float"; + case 'd': return "double"; + case 'g': return "long double"; + case 'Z': switch (*(ts+1)) { + case 'f': return "complex float"; + case 'd': return "complex double"; + case 'g': return "complex long double"; + default: return "unparseable format string"; + } + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + default: return "unparseable format string"; + } +} -static const char* __Pyx_BufferTypestringCheck_item_double(const char* ts) { - if (*ts == '1') ++ts; - if (*ts != 'd') { - PyErr_Format(PyExc_ValueError, "Buffer datatype mismatch (expected 'd', got '%s')", ts); - return NULL; - } else return ts + 1; +static const char* __Pyx_CheckTypestring_double(const char* ts) { + int ok; + ts = __Pyx_ConsumeWhitespace(ts); if (!ts) return NULL; + if (*ts == '1') ++ts; + ok = (*ts == 'd'); + if (!(ok)) { + PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch (expected double, got %s)", __Pyx_DescribeTokenInFormatString(ts)); + return NULL; + } + ++ts; + return ts; + } -} - -static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd) { +static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast) { const char* ts; if (obj == Py_None) { __Pyx_ZeroBuffer(buf); @@ -2626,18 +6384,26 @@ __Pyx_BufferNdimError(buf, nd); goto fail; } - ts = buf->format; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheckEndian(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheck_item_double(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - if (*ts != 0) { - PyErr_Format(PyExc_ValueError, - "Expected non-struct buffer data type (expected end, got '%s')", ts); - goto fail; + if (!cast) { + ts = buf->format; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + ts = __Pyx_CheckTypestring_double(ts); + if (!ts) goto fail; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + if (*ts != 0) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch (expected end, got %s)", + __Pyx_DescribeTokenInFormatString(ts)); + goto fail; + } + } else { + if (buf->itemsize != sizeof(double)) { + PyErr_SetString(PyExc_ValueError, + "Attempted cast of buffer to datatype of different size."); + goto fail; + } } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; @@ -2650,25 +6416,27 @@ "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); } - -static const char* __Pyx_BufferTypestringCheck_item_nn___pyx_t_5numpy_int32_t(const char* ts) { - int ok; - if (*ts == '1') ++ts; - switch (*ts) { - case 'b': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(char) && (__pyx_t_5numpy_int32_t)-1 < 0); break; - case 'h': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(short) && (__pyx_t_5numpy_int32_t)-1 < 0); break; - case 'i': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(int) && (__pyx_t_5numpy_int32_t)-1 < 0); break; - case 'l': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(long) && (__pyx_t_5numpy_int32_t)-1 < 0); break; - case 'q': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(long long) && (__pyx_t_5numpy_int32_t)-1 < 0); break; default: ok = 0; +static const char* __Pyx_CheckTypestring_nn___pyx_t_5numpy_int32_t(const char* ts) { + int ok; + ts = __Pyx_ConsumeWhitespace(ts); if (!ts) return NULL; + if (*ts == '1') ++ts; + switch (*ts) { + case 'b': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(char) && (__pyx_t_5numpy_int32_t)-1 < 0); break; + case 'h': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(short) && (__pyx_t_5numpy_int32_t)-1 < 0); break; + case 'i': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(int) && (__pyx_t_5numpy_int32_t)-1 < 0); break; + case 'l': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(long) && (__pyx_t_5numpy_int32_t)-1 < 0); break; + case 'q': ok = (sizeof(__pyx_t_5numpy_int32_t) == sizeof(long long) && (__pyx_t_5numpy_int32_t)-1 < 0); break; + default: ok = 0; + } + if (!(ok)) { + PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch (expected numpy.int32_t, got %s)", __Pyx_DescribeTokenInFormatString(ts)); + return NULL; + } + ++ts; + return ts; } - if (!ok) { - PyErr_Format(PyExc_ValueError, "Buffer datatype mismatch (rejecting on '%s')", ts); - return NULL; - } else return ts + 1; -} - -static int __Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t(PyObject* obj, Py_buffer* buf, int flags, int nd) { +static int __Pyx_GetBuffer_nn___pyx_t_5numpy_int32_t(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast) { const char* ts; if (obj == Py_None) { __Pyx_ZeroBuffer(buf); @@ -2680,18 +6448,26 @@ __Pyx_BufferNdimError(buf, nd); goto fail; } - ts = buf->format; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheckEndian(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheck_item_nn___pyx_t_5numpy_int32_t(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - if (*ts != 0) { - PyErr_Format(PyExc_ValueError, - "Expected non-struct buffer data type (expected end, got '%s')", ts); - goto fail; + if (!cast) { + ts = buf->format; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + ts = __Pyx_CheckTypestring_nn___pyx_t_5numpy_int32_t(ts); + if (!ts) goto fail; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + if (*ts != 0) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch (expected end, got %s)", + __Pyx_DescribeTokenInFormatString(ts)); + goto fail; + } + } else { + if (buf->itemsize != sizeof(__pyx_t_5numpy_int32_t)) { + PyErr_SetString(PyExc_ValueError, + "Attempted cast of buffer to datatype of different size."); + goto fail; + } } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; @@ -2699,16 +6475,47 @@ __Pyx_ZeroBuffer(buf); return -1; } -static const char* __Pyx_BufferTypestringCheck_item_int(const char* ts) { - if (*ts == '1') ++ts; - if (*ts != 'i') { - PyErr_Format(PyExc_ValueError, "Buffer datatype mismatch (expected 'i', got '%s')", ts); - return NULL; - } else return ts + 1; - +static INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); } -static int __Pyx_GetBuffer_int(PyObject* obj, Py_buffer* buf, int flags, int nd) { +static INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +} + + +static const char* __Pyx_CheckTypestring_int(const char* ts) { + int ok; + ts = __Pyx_ConsumeWhitespace(ts); if (!ts) return NULL; + if (*ts == '1') ++ts; + ok = (*ts == 'i'); + if (!(ok)) { + PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch (expected int, got %s)", __Pyx_DescribeTokenInFormatString(ts)); + return NULL; + } + ++ts; + return ts; + } + +static int __Pyx_GetBuffer_int(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast) { const char* ts; if (obj == Py_None) { __Pyx_ZeroBuffer(buf); @@ -2720,18 +6527,26 @@ __Pyx_BufferNdimError(buf, nd); goto fail; } - ts = buf->format; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheckEndian(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheck_item_int(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - if (*ts != 0) { - PyErr_Format(PyExc_ValueError, - "Expected non-struct buffer data type (expected end, got '%s')", ts); - goto fail; + if (!cast) { + ts = buf->format; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + ts = __Pyx_CheckTypestring_int(ts); + if (!ts) goto fail; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + if (*ts != 0) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch (expected end, got %s)", + __Pyx_DescribeTokenInFormatString(ts)); + goto fail; + } + } else { + if (buf->itemsize != sizeof(int)) { + PyErr_SetString(PyExc_ValueError, + "Attempted cast of buffer to datatype of different size."); + goto fail; + } } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; @@ -2744,21 +6559,12 @@ } -static INLINE void __Pyx_RaiseArgtupleTooLong( - Py_ssize_t num_expected, - Py_ssize_t num_found) -{ - const char* error_message = - #if PY_VERSION_HEX < 0x02050000 - "function takes at most %d positional arguments (%d given)"; - #else - "function takes at most %zd positional arguments (%zd given)"; - #endif - PyErr_Format(PyExc_TypeError, error_message, num_expected, num_found); -} - -#if (PY_MAJOR_VERSION < 3) && !(Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER) +#if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (Py_TYPE(obj)->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER) + return PyObject_GetBuffer(obj, view, flags); + #endif if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); else { PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); @@ -2766,8 +6572,13 @@ } } -static void __Pyx_ReleaseBuffer(PyObject *obj, Py_buffer *view) { - +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject* obj = view->obj; + if (obj) { +if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray___releasebuffer__(obj, view); + Py_DECREF(obj); + view->obj = NULL; + } } #endif @@ -2868,7 +6679,7 @@ } #endif } - PyErr_Restore(type, value, tb); + __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); @@ -2917,20 +6728,76 @@ return 0; } +static INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +} + +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + __Pyx_ErrFetch(type, value, tb); + PyErr_NormalizeException(type, value, tb); + if (PyErr_Occurred()) + goto bad; + Py_INCREF(*type); + Py_INCREF(*value); + Py_INCREF(*tb); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + /* Make sure tstate is in a consistent state when we XDECREF + these objects (XDECREF may run arbitrary code). */ + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + return 0; +bad: + Py_XDECREF(*type); + Py_XDECREF(*value); + Py_XDECREF(*tb); + return -1; +} + + static void __Pyx_WriteUnraisable(const char *name) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; - PyErr_Fetch(&old_exc, &old_val, &old_tb); + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); #if PY_MAJOR_VERSION < 3 ctx = PyString_FromString(name); #else ctx = PyUnicode_FromString(name); #endif - PyErr_Restore(old_exc, old_val, old_tb); - if (!ctx) - ctx = Py_None; - PyErr_WriteUnraisable(ctx); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } } static int __Pyx_SetVtable(PyObject *dict, void *vtable) { @@ -2954,25 +6821,28 @@ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(module_name); + py_name = PyString_FromString(class_name); #else - py_name = PyUnicode_FromString(module_name); + py_name = PyUnicode_FromString(class_name); #endif if (!py_name) goto bad; - - py_module = __Pyx_ImportModule(module_name); - if (!py_module) - goto bad; - result = PyObject_GetAttrString(py_module, class_name); + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { @@ -2989,7 +6859,7 @@ } return (PyTypeObject *)result; bad: - Py_XDECREF(py_name); + Py_XDECREF(py_module); Py_XDECREF(result); return 0; } @@ -2997,7 +6867,7 @@ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(char *name) { +static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; @@ -3079,7 +6949,7 @@ ); if (!py_code) goto bad; py_frame = PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ + PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ Modified: trunk/scipy/stats/vonmises_cython.c =================================================================== --- trunk/scipy/stats/vonmises_cython.c 2008-11-10 12:36:01 UTC (rev 5037) +++ trunk/scipy/stats/vonmises_cython.c 2008-11-10 13:20:36 UTC (rev 5038) @@ -1,4 +1,4 @@ -/* Generated by Cython 0.9.8.1.1 on Thu Oct 9 03:26:22 2008 */ +/* Generated by Cython 0.10 on Mon Nov 10 22:16:41 2008 */ #define PY_SSIZE_T_CLEAN #include "Python.h" @@ -31,14 +31,15 @@ typedef struct { void *buf; + PyObject *obj; Py_ssize_t len; + Py_ssize_t itemsize; int readonly; - const char *format; int ndim; + char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; - Py_ssize_t itemsize; void *internal; } Py_buffer; @@ -63,6 +64,9 @@ #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #endif +#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3) + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyString_Type PyBytes_Type @@ -105,6 +109,7 @@ #include #define __PYX_HAVE_API__scipy__stats__vonmises_cython #include "math.h" +#include "stdlib.h" #include "numpy/arrayobject.h" @@ -175,39 +180,26 @@ static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char **__pyx_f; -static INLINE void __Pyx_SafeReleaseBuffer(PyObject* obj, Py_buffer* info); + +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, PyObject* kw_name); /*proto*/ + +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/ + +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/ +static INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static INLINE void __Pyx_ZeroBuffer(Py_buffer* buf); /*proto*/ static INLINE const char* __Pyx_ConsumeWhitespace(const char* ts); /*proto*/ -static INLINE const char* __Pyx_BufferTypestringCheckEndian(const char* ts); /*proto*/ static void __Pyx_BufferNdimError(Py_buffer* buffer, int expected_ndim); /*proto*/ -static const char* __Pyx_BufferTypestringCheck_item_double(const char* ts); /*proto*/ +static const char* __Pyx_DescribeTokenInFormatString(const char* ts); /*proto*/ +static const char* __Pyx_CheckTypestring_double(const char* ts); /*proto*/ -static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd); /*proto*/ +static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast); /*proto*/ static void __Pyx_RaiseBufferFallbackError(void); /*proto*/ -#define __Pyx_BufPtrStrided1d(buf, i0, s0) ((char*)buf + i0 * s0) +#define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) -static INLINE void __Pyx_RaiseArgtupleTooLong(Py_ssize_t num_expected, Py_ssize_t num_found); /*proto*/ -#if (PY_MAJOR_VERSION < 3) && !(Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER) -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); -static void __Pyx_ReleaseBuffer(PyObject *obj, Py_buffer *view); -#else -#define __Pyx_GetBuffer PyObject_GetBuffer -#define __Pyx_ReleaseBuffer PyObject_ReleaseBuffer -#endif - -Py_ssize_t __Pyx_zeros[] = {0}; -Py_ssize_t __Pyx_minusones[] = {-1}; - -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ - -static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ - -static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/ -static int __Pyx_EndUnpack(PyObject *); /*proto*/ - -static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ - static INLINE PyObject *__Pyx_GetItemInt(PyObject *o, Py_ssize_t i, int is_unsigned) { PyObject *r; if (PyList_CheckExact(o) && 0 <= i && i < PyList_GET_SIZE(o)) { @@ -230,13 +222,40 @@ return r; } +static INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); +static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else +#define __Pyx_GetBuffer PyObject_GetBuffer +#define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + +Py_ssize_t __Pyx_zeros[] = {0}; +Py_ssize_t __Pyx_minusones[] = {-1}; + +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/ + +static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/ + +static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/ +static int __Pyx_EndUnpack(PyObject *); /*proto*/ + +static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/ + +static INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ + static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/ +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/ + static void __Pyx_WriteUnraisable(const char *name); /*proto*/ -static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, long size); /*proto*/ +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size); /*proto*/ -static PyObject *__Pyx_ImportModule(char *name); /*proto*/ +static PyObject *__Pyx_ImportModule(const char *name); /*proto*/ static void __Pyx_AddTraceback(const char *funcname); /*proto*/ @@ -277,10 +296,21 @@ typedef npy_double __pyx_t_5numpy_double_t; typedef npy_longdouble __pyx_t_5numpy_longdouble_t; + +typedef npy_cfloat __pyx_t_5numpy_cfloat_t; + +typedef npy_cdouble __pyx_t_5numpy_cdouble_t; + +typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; +/* Module declarations from python_buffer */ + +/* Module declarations from stdlib */ + /* Module declarations from numpy */ /* Module declarations from numpy */ +static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; /* Module declarations from cython */ @@ -296,20 +326,26 @@ static PyObject *__pyx_int_16; static PyObject *__pyx_int_4; static PyObject *__pyx_int_0; +static char __pyx_k_k[] = "k"; +static PyObject *__pyx_kp_k; +static char __pyx_k_x[] = "x"; +static PyObject *__pyx_kp_x; +static char __pyx_k_23[] = "C1"; +static PyObject *__pyx_kp_23; static char __pyx_k_numpy[] = "numpy"; static PyObject *__pyx_kp_numpy; static char __pyx_k_np[] = "np"; static PyObject *__pyx_kp_np; -static char __pyx_k_17[] = "scipy.stats"; -static PyObject *__pyx_kp_17; +static char __pyx_k_24[] = "scipy.stats"; +static PyObject *__pyx_kp_24; static char __pyx_k_scipy[] = "scipy"; static PyObject *__pyx_kp_scipy; -static char __pyx_k_18[] = "scipy.special"; -static PyObject *__pyx_kp_18; +static char __pyx_k_25[] = "scipy.special"; +static PyObject *__pyx_kp_25; static char __pyx_k_i0[] = "i0"; static PyObject *__pyx_kp_i0; -static char __pyx_k_19[] = "numpy.testing"; -static PyObject *__pyx_kp_19; +static char __pyx_k_26[] = "numpy.testing"; +static PyObject *__pyx_kp_26; static char __pyx_k_pi[] = "pi"; static PyObject *__pyx_kp_pi; static char __pyx_k_sqrt[] = "sqrt"; @@ -328,8 +364,8 @@ static PyObject *__pyx_kp_asarray; static char __pyx_k_ndim[] = "ndim"; static PyObject *__pyx_kp_ndim; -static char __pyx_k_20[] = "atleast_1d"; -static PyObject *__pyx_kp_20; +static char __pyx_k_27[] = "atleast_1d"; +static PyObject *__pyx_kp_27; static char __pyx_k_round[] = "round"; static PyObject *__pyx_kp_round; static char __pyx_k_broadcast_arrays[] = "broadcast_arrays"; @@ -344,36 +380,60 @@ static PyObject *__pyx_kp_float; static char __pyx_k_astype[] = "astype"; static PyObject *__pyx_kp_astype; -static char __pyx_k_21[] = "von_mises_cdf_normalapprox"; -static PyObject *__pyx_kp_21; +static char __pyx_k_28[] = "von_mises_cdf_normalapprox"; +static PyObject *__pyx_kp_28; static char __pyx_k___getbuffer__[] = "__getbuffer__"; static PyObject *__pyx_kp___getbuffer__; +static char __pyx_k___releasebuffer__[] = "__releasebuffer__"; +static PyObject *__pyx_kp___releasebuffer__; +static char __pyx_k_info[] = "info"; +static PyObject *__pyx_kp_info; +static char __pyx_k_flags[] = "flags"; +static PyObject *__pyx_kp_flags; +static char __pyx_k_ValueError[] = "ValueError"; +static PyObject *__pyx_kp_ValueError; +static char __pyx_k_iteritems[] = "iteritems"; +static PyObject *__pyx_kp_iteritems; +static char __pyx_k_next[] = "next"; +static PyObject *__pyx_kp_next; +static char __pyx_k_StopIteration[] = "StopIteration"; +static PyObject *__pyx_kp_StopIteration; +static char __pyx_k_pop[] = "pop"; +static PyObject *__pyx_kp_pop; static char __pyx_k_RuntimeError[] = "RuntimeError"; static PyObject *__pyx_kp_RuntimeError; -static char __pyx_k_ValueError[] = "ValueError"; -static PyObject *__pyx_kp_ValueError; static PyObject *__pyx_kp_1; -static PyObject *__pyx_kp_16; +static PyObject *__pyx_kp_2; +static PyObject *__pyx_kp_20; +static PyObject *__pyx_kp_21; +static PyObject *__pyx_kp_22; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_StopIteration; static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_builtin_ValueError; -static char __pyx_k_1[] = "Py_intptr_t and Py_ssize_t differs in size, numpy.pxd does not support this"; -static char __pyx_k_2[] = "b"; -static char __pyx_k_3[] = "B"; -static char __pyx_k_4[] = "h"; -static char __pyx_k_5[] = "H"; -static char __pyx_k_6[] = "i"; -static char __pyx_k_7[] = "I"; -static char __pyx_k_8[] = "l"; -static char __pyx_k_9[] = "L"; -static char __pyx_k_10[] = "q"; -static char __pyx_k_11[] = "Q"; -static char __pyx_k_12[] = "f"; -static char __pyx_k_13[] = "d"; -static char __pyx_k_14[] = "g"; -static char __pyx_k_15[] = "O"; -static char __pyx_k_16[] = "only objects, int and float dtypes supported for ndarray buffer access so far (dtype is %d)"; +static char __pyx_k_1[] = "ndarray is not C contiguous"; +static char __pyx_k_2[] = "ndarray is not Fortran contiguous"; +static char __pyx_k_3[] = "b"; +static char __pyx_k_4[] = "B"; +static char __pyx_k_5[] = "h"; +static char __pyx_k_6[] = "H"; +static char __pyx_k_7[] = "i"; +static char __pyx_k_8[] = "I"; +static char __pyx_k_9[] = "l"; +static char __pyx_k_10[] = "L"; +static char __pyx_k_11[] = "q"; +static char __pyx_k_12[] = "Q"; +static char __pyx_k_13[] = "f"; +static char __pyx_k_14[] = "d"; +static char __pyx_k_15[] = "g"; +static char __pyx_k_16[] = "Zf"; +static char __pyx_k_17[] = "Zd"; +static char __pyx_k_18[] = "Zg"; +static char __pyx_k_19[] = "O"; +static char __pyx_k_20[] = "unknown dtype code in numpy.pxd (%d)"; +static char __pyx_k_21[] = "Format string allocated too short."; +static char __pyx_k_22[] = "unknown dtype code in numpy.pxd (%d)"; -/* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":12 +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":12 * * * cdef double von_mises_cdf_series(double k,double x,unsigned int p): # <<<<<<<<<<<<<< @@ -396,8 +456,11 @@ PyObject *__pyx_4 = 0; PyObject *__pyx_5 = 0; PyObject *__pyx_6 = 0; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":15 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":15 * cdef double s, c, sn, cn, R, V * cdef unsigned int n * s = sin(x) # <<<<<<<<<<<<<< @@ -406,7 +469,7 @@ */ __pyx_v_s = sin(__pyx_v_x); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":16 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":16 * cdef unsigned int n * s = sin(x) * c = cos(x) # <<<<<<<<<<<<<< @@ -415,7 +478,7 @@ */ __pyx_v_c = cos(__pyx_v_x); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":17 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":17 * s = sin(x) * c = cos(x) * sn = sin(p*x) # <<<<<<<<<<<<<< @@ -424,7 +487,7 @@ */ __pyx_v_sn = sin((__pyx_v_p * __pyx_v_x)); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":18 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":18 * c = cos(x) * sn = sin(p*x) * cn = cos(p*x) # <<<<<<<<<<<<<< @@ -433,7 +496,7 @@ */ __pyx_v_cn = cos((__pyx_v_p * __pyx_v_x)); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":19 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":19 * sn = sin(p*x) * cn = cos(p*x) * R = 0 # <<<<<<<<<<<<<< @@ -442,7 +505,7 @@ */ __pyx_v_R = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":20 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":20 * cn = cos(p*x) * R = 0 * V = 0 # <<<<<<<<<<<<<< @@ -451,7 +514,7 @@ */ __pyx_v_V = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":21 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":21 * R = 0 * V = 0 * for n in range(p-1,0,-1): # <<<<<<<<<<<<<< @@ -460,7 +523,7 @@ */ for (__pyx_v_n = (__pyx_v_p - 1); __pyx_v_n > 0; __pyx_v_n-=1) { - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":22 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":22 * V = 0 * for n in range(p-1,0,-1): * sn, cn = sn*c - cn*s, cn*c + sn*s # <<<<<<<<<<<<<< @@ -472,7 +535,7 @@ __pyx_v_sn = __pyx_1; __pyx_v_cn = __pyx_2; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":23 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":23 * for n in range(p-1,0,-1): * sn, cn = sn*c - cn*s, cn*c + sn*s * R = 1./(2*n/k + R) # <<<<<<<<<<<<<< @@ -481,7 +544,7 @@ */ __pyx_v_R = (1. / (((2 * __pyx_v_n) / __pyx_v_k) + __pyx_v_R)); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":24 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":24 * sn, cn = sn*c - cn*s, cn*c + sn*s * R = 1./(2*n/k + R) * V = R*(sn/n+V) # <<<<<<<<<<<<<< @@ -491,7 +554,7 @@ __pyx_v_V = (__pyx_v_R * ((__pyx_v_sn / __pyx_v_n) + __pyx_v_V)); } - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":26 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":26 * V = R*(sn/n+V) * * return 0.5+x/(2*np.pi) + V/np.pi # <<<<<<<<<<<<<< @@ -503,26 +566,26 @@ __pyx_5 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_6 = PyObject_GetAttr(__pyx_5, __pyx_kp_pi); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_5 = PyNumber_Multiply(__pyx_int_2, __pyx_6); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Multiply(__pyx_int_2, __pyx_6); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_6); __pyx_6 = 0; - __pyx_6 = __Pyx_PyNumber_Divide(__pyx_4, __pyx_5); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_4); __pyx_4 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_4 = PyNumber_Add(__pyx_3, __pyx_6); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Add(__pyx_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_5 = PyFloat_FromDouble(__pyx_v_V); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_6 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_4 = PyObject_GetAttr(__pyx_6, __pyx_kp_pi); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_6); __pyx_6 = 0; - __pyx_5 = PyFloat_FromDouble(__pyx_v_V); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_6 = PyObject_GetAttr(__pyx_3, __pyx_kp_pi); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - __pyx_3 = __Pyx_PyNumber_Divide(__pyx_5, __pyx_6); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_5, __pyx_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_5); __pyx_5 = 0; - Py_DECREF(__pyx_6); __pyx_6 = 0; - __pyx_5 = PyNumber_Add(__pyx_4, __pyx_3); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_4); __pyx_4 = 0; - Py_DECREF(__pyx_3); __pyx_3 = 0; - __pyx_1 = __pyx_PyFloat_AsDouble(__pyx_5); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + Py_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_1 = __pyx_PyFloat_AsDouble(__pyx_t_3); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_1; goto __pyx_L0; @@ -539,7 +602,7 @@ return __pyx_r; } -/* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":28 +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":28 * return 0.5+x/(2*np.pi) + V/np.pi * * def von_mises_cdf_normalapprox(k,x,C1): # <<<<<<<<<<<<<< @@ -561,29 +624,68 @@ PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; - PyObject *__pyx_5 = 0; - PyObject *__pyx_6 = 0; - static char *__pyx_argnames[] = {"k","x","C1",0}; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + static PyObject **__pyx_pyargnames[] = {&__pyx_kp_k,&__pyx_kp_x,&__pyx_kp_23,0}; __pyx_self = __pyx_self; - if (likely(!__pyx_kwds) && likely(PyTuple_GET_SIZE(__pyx_args) == 3)) { + if (unlikely(__pyx_kwds)) { + PyObject* values[3] = {0,0,0}; + Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_k); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_kp_x); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("von_mises_cdf_normalapprox", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + case 2: + values[2] = PyDict_GetItem(__pyx_kwds, __pyx_kp_23); + if (likely(values[2])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("von_mises_cdf_normalapprox", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "von_mises_cdf_normalapprox") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + __pyx_v_k = values[0]; + __pyx_v_x = values[1]; + __pyx_v_C1 = values[2]; + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { __pyx_v_k = PyTuple_GET_ITEM(__pyx_args, 0); __pyx_v_x = PyTuple_GET_ITEM(__pyx_args, 1); __pyx_v_C1 = PyTuple_GET_ITEM(__pyx_args, 2); } - else { - if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OOO", __pyx_argnames, &__pyx_v_k, &__pyx_v_x, &__pyx_v_C1))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4; + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("von_mises_cdf_normalapprox", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 28; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("scipy.stats.vonmises_cython.von_mises_cdf_normalapprox"); return NULL; - __pyx_L4:; + __pyx_L4_argument_unpacking_done:; __pyx_v_b = Py_None; Py_INCREF(Py_None); __pyx_v_z = Py_None; Py_INCREF(Py_None); __pyx_v_C = Py_None; Py_INCREF(Py_None); __pyx_v_chi = Py_None; Py_INCREF(Py_None); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":29 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":29 * * def von_mises_cdf_normalapprox(k,x,C1): * b = np.sqrt(2/np.pi)*np.exp(k)/i0(k) # <<<<<<<<<<<<<< @@ -596,155 +698,155 @@ __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_kp_pi); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_1 = __Pyx_PyNumber_Divide(__pyx_int_2, __pyx_3); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_int_2, __pyx_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; - __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_3, 0, __pyx_1); - __pyx_1 = 0; - __pyx_1 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_3 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_kp_exp); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_exp); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_k); PyTuple_SET_ITEM(__pyx_2, 0, __pyx_v_k); - __pyx_4 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_4 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; + __pyx_t_1 = PyNumber_Multiply(__pyx_3, __pyx_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; - __pyx_3 = PyNumber_Multiply(__pyx_1, __pyx_4); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_4); __pyx_4 = 0; - __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_i0); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_i0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_k); - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_k); - __pyx_4 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - __pyx_2 = __Pyx_PyNumber_Divide(__pyx_3, __pyx_4); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_v_k); + __pyx_3 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; + __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_t_1, __pyx_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 29; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_v_b); - __pyx_v_b = __pyx_2; - __pyx_2 = 0; + __pyx_v_b = __pyx_t_2; + __pyx_t_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":30 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":30 * def von_mises_cdf_normalapprox(k,x,C1): * b = np.sqrt(2/np.pi)*np.exp(k)/i0(k) * z = b*np.sin(x/2.) # <<<<<<<<<<<<<< * C = 24*k * chi = z - z**3/((C-2*z**2-16)/3.-(z**4+7/4.*z**2+167./2)/(C+C1-z**2+3))**2 */ - __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_kp_sin); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyObject_GetAttr(__pyx_4, __pyx_kp_sin); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_4); __pyx_4 = 0; + __pyx_2 = PyFloat_FromDouble(2.); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_v_x, __pyx_2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_t_2); + __pyx_t_2 = 0; + __pyx_4 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_4 = PyFloat_FromDouble(2.); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = __Pyx_PyNumber_Divide(__pyx_v_x, __pyx_4); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __pyx_t_2 = PyNumber_Multiply(__pyx_v_b, __pyx_4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_4); __pyx_4 = 0; - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_2); - __pyx_2 = 0; - __pyx_4 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; - __pyx_2 = PyNumber_Multiply(__pyx_v_b, __pyx_4); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_4); __pyx_4 = 0; Py_DECREF(__pyx_v_z); - __pyx_v_z = __pyx_2; - __pyx_2 = 0; + __pyx_v_z = __pyx_t_2; + __pyx_t_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":31 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":31 * b = np.sqrt(2/np.pi)*np.exp(k)/i0(k) * z = b*np.sin(x/2.) * C = 24*k # <<<<<<<<<<<<<< * chi = z - z**3/((C-2*z**2-16)/3.-(z**4+7/4.*z**2+167./2)/(C+C1-z**2+3))**2 * return scipy.stats.norm.cdf(z) */ - __pyx_3 = PyNumber_Multiply(__pyx_int_24, __pyx_v_k); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyNumber_Multiply(__pyx_int_24, __pyx_v_k); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 31; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_v_C); - __pyx_v_C = __pyx_3; - __pyx_3 = 0; + __pyx_v_C = __pyx_t_2; + __pyx_t_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":32 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":32 * z = b*np.sin(x/2.) * C = 24*k * chi = z - z**3/((C-2*z**2-16)/3.-(z**4+7/4.*z**2+167./2)/(C+C1-z**2+3))**2 # <<<<<<<<<<<<<< * return scipy.stats.norm.cdf(z) * */ - __pyx_1 = PyNumber_Power(__pyx_v_z, __pyx_int_3, Py_None); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_4 = PyNumber_Power(__pyx_v_z, __pyx_int_2, Py_None); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyNumber_Multiply(__pyx_int_2, __pyx_4); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_4); __pyx_4 = 0; - __pyx_3 = PyNumber_Subtract(__pyx_v_C, __pyx_2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_4 = PyNumber_Subtract(__pyx_3, __pyx_int_16); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_t_2 = PyNumber_Power(__pyx_v_z, __pyx_int_3, Py_None); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Power(__pyx_v_z, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Multiply(__pyx_int_2, __pyx_t_1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_Subtract(__pyx_v_C, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_int_16); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_2 = PyFloat_FromDouble(3.); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = __Pyx_PyNumber_Divide(__pyx_4, __pyx_2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_4); __pyx_4 = 0; + __pyx_t_1 = __Pyx_PyNumber_Divide(__pyx_t_3, __pyx_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_4 = PyNumber_Power(__pyx_v_z, __pyx_int_4, Py_None); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyFloat_FromDouble((7 / 4.)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyNumber_Power(__pyx_v_z, __pyx_int_2, Py_None); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_6 = PyNumber_Multiply(__pyx_2, __pyx_5); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_2 = PyNumber_Add(__pyx_4, __pyx_6); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_4); __pyx_4 = 0; - Py_DECREF(__pyx_6); __pyx_6 = 0; - __pyx_5 = PyFloat_FromDouble((167. / 2)); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_4 = PyNumber_Add(__pyx_2, __pyx_5); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_6 = PyNumber_Add(__pyx_v_C, __pyx_v_C1); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyNumber_Power(__pyx_v_z, __pyx_int_2, Py_None); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyNumber_Subtract(__pyx_6, __pyx_2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_6); __pyx_6 = 0; - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_6 = PyNumber_Add(__pyx_5, __pyx_int_3); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_2 = __Pyx_PyNumber_Divide(__pyx_4, __pyx_6); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_4); __pyx_4 = 0; - Py_DECREF(__pyx_6); __pyx_6 = 0; - __pyx_5 = PyNumber_Subtract(__pyx_3, __pyx_2); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Power(__pyx_v_z, __pyx_int_4, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyFloat_FromDouble((7 / 4.)); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyNumber_Power(__pyx_v_z, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Multiply(__pyx_1, __pyx_t_4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + Py_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; + Py_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_3 = PyFloat_FromDouble((167. / 2)); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyNumber_Add(__pyx_t_4, __pyx_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_4); __pyx_t_4 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_4 = PyNumber_Power(__pyx_5, __pyx_int_2, Py_None); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_6 = __Pyx_PyNumber_Divide(__pyx_1, __pyx_4); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(__pyx_4); __pyx_4 = 0; - __pyx_3 = PyNumber_Subtract(__pyx_v_z, __pyx_6); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_6); __pyx_6 = 0; + __pyx_t_4 = PyNumber_Add(__pyx_v_C, __pyx_v_C1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Power(__pyx_v_z, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyNumber_Subtract(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_4); __pyx_t_4 = 0; + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Add(__pyx_t_6, __pyx_int_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyNumber_Divide(__pyx_t_5, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_5); __pyx_t_5 = 0; + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = PyNumber_Subtract(__pyx_t_1, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + Py_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Power(__pyx_t_3, __pyx_int_2, Py_None); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_3 = __Pyx_PyNumber_Divide(__pyx_t_2, __pyx_t_6); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_2); __pyx_t_2 = 0; + Py_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyNumber_Subtract(__pyx_v_z, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_3); __pyx_t_3 = 0; Py_DECREF(__pyx_v_chi); - __pyx_v_chi = __pyx_3; - __pyx_3 = 0; + __pyx_v_chi = __pyx_t_6; + __pyx_t_6 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":33 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":33 * C = 24*k * chi = z - z**3/((C-2*z**2-16)/3.-(z**4+7/4.*z**2+167./2)/(C+C1-z**2+3))**2 * return scipy.stats.norm.cdf(z) # <<<<<<<<<<<<<< * * cimport cython */ - __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_scipy); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_5 = PyObject_GetAttr(__pyx_2, __pyx_kp_stats); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_4 = __Pyx_GetName(__pyx_m, __pyx_kp_scipy); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetAttr(__pyx_4, __pyx_kp_stats); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_4); __pyx_4 = 0; + __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_norm); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_1 = PyObject_GetAttr(__pyx_5, __pyx_kp_norm); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_4 = PyObject_GetAttr(__pyx_1, __pyx_kp_cdf); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_GetAttr(__pyx_1, __pyx_kp_cdf); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_6 = PyTuple_New(1); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_4 = PyTuple_New(1); if (unlikely(!__pyx_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_z); - PyTuple_SET_ITEM(__pyx_6, 0, __pyx_v_z); - __pyx_3 = PyObject_Call(__pyx_4, ((PyObject *)__pyx_6), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_4); __pyx_4 = 0; - Py_DECREF(((PyObject *)__pyx_6)); __pyx_6 = 0; - __pyx_r = __pyx_3; - __pyx_3 = 0; + PyTuple_SET_ITEM(__pyx_4, 0, __pyx_v_z); + __pyx_2 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_4), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(((PyObject *)__pyx_4)); __pyx_4 = 0; + __pyx_r = __pyx_2; + __pyx_2 = 0; goto __pyx_L0; __pyx_r = Py_None; Py_INCREF(Py_None); @@ -754,8 +856,6 @@ Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); - Py_XDECREF(__pyx_5); - Py_XDECREF(__pyx_6); __Pyx_AddTraceback("scipy.stats.vonmises_cython.von_mises_cdf_normalapprox"); __pyx_r = NULL; __pyx_L0:; @@ -766,7 +866,7 @@ return __pyx_r; } -/* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":37 +/* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":37 * cimport cython * @cython.boundscheck(False) * def von_mises_cdf(k,x): # <<<<<<<<<<<<<< @@ -817,10 +917,10 @@ PyObject *__pyx_10 = 0; Py_ssize_t __pyx_11 = 0; int __pyx_12; - PyArrayObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyArrayObject *__pyx_t_3 = NULL; + int __pyx_t_4; PyObject *__pyx_t_5 = NULL; unsigned int __pyx_t_6; unsigned int __pyx_t_7; @@ -831,36 +931,63 @@ unsigned int __pyx_t_12; unsigned int __pyx_t_13; unsigned int __pyx_t_14; - static char *__pyx_argnames[] = {"k","x",0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_kp_k,&__pyx_kp_x,0}; __pyx_self = __pyx_self; - if (likely(!__pyx_kwds) && likely(PyTuple_GET_SIZE(__pyx_args) == 2)) { + if (unlikely(__pyx_kwds)) { + PyObject* values[2] = {0,0}; + Py_ssize_t kw_args = PyDict_Size(__pyx_kwds); + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + switch (PyTuple_GET_SIZE(__pyx_args)) { + case 0: + values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_k); + if (likely(values[0])) kw_args--; + else goto __pyx_L5_argtuple_error; + case 1: + values[1] = PyDict_GetItem(__pyx_kwds, __pyx_kp_x); + if (likely(values[1])) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("von_mises_cdf", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "von_mises_cdf") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + } + __pyx_v_k = values[0]; + __pyx_v_x = values[1]; + } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { + goto __pyx_L5_argtuple_error; + } else { __pyx_v_k = PyTuple_GET_ITEM(__pyx_args, 0); __pyx_v_x = PyTuple_GET_ITEM(__pyx_args, 1); } - else { - if (unlikely(!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "OO", __pyx_argnames, &__pyx_v_k, &__pyx_v_x))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - } - goto __pyx_L4; + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("von_mises_cdf", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 37; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("scipy.stats.vonmises_cython.von_mises_cdf"); return NULL; - __pyx_L4:; + __pyx_L4_argument_unpacking_done:; Py_INCREF(__pyx_v_k); Py_INCREF(__pyx_v_x); __pyx_v_temp = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - __pyx_bstruct_temp.buf = NULL; __pyx_v_temp_xs = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - __pyx_bstruct_temp_xs.buf = NULL; __pyx_v_temp_ks = ((PyArrayObject *)Py_None); Py_INCREF(Py_None); - __pyx_bstruct_temp_ks.buf = NULL; __pyx_v_zerodim = Py_None; Py_INCREF(Py_None); __pyx_v_ix = Py_None; Py_INCREF(Py_None); __pyx_v_bx = Py_None; Py_INCREF(Py_None); __pyx_v_bk = Py_None; Py_INCREF(Py_None); __pyx_v_result = Py_None; Py_INCREF(Py_None); __pyx_v_c_small_k = Py_None; Py_INCREF(Py_None); + __pyx_bstruct_temp.buf = NULL; + __pyx_bstruct_temp_xs.buf = NULL; + __pyx_bstruct_temp_ks.buf = NULL; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":42 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":42 * cdef double a1, a2, a3, a4, C1, CK * #k,x = np.broadcast_arrays(np.asarray(k),np.asarray(x)) * k = np.asarray(k) # <<<<<<<<<<<<<< @@ -880,7 +1007,7 @@ __pyx_v_k = __pyx_3; __pyx_3 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":43 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":43 * #k,x = np.broadcast_arrays(np.asarray(k),np.asarray(x)) * k = np.asarray(k) * x = np.asarray(x) # <<<<<<<<<<<<<< @@ -900,7 +1027,7 @@ __pyx_v_x = __pyx_2; __pyx_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":44 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":44 * k = np.asarray(k) * x = np.asarray(x) * zerodim = k.ndim==0 and x.ndim==0 # <<<<<<<<<<<<<< @@ -921,7 +1048,7 @@ __pyx_v_zerodim = __pyx_1; __pyx_1 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":46 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":46 * zerodim = k.ndim==0 and x.ndim==0 * * k = np.atleast_1d(k) # <<<<<<<<<<<<<< @@ -929,7 +1056,7 @@ * ix = np.round(x/(2*np.pi)) */ __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetAttr(__pyx_3, __pyx_kp_20); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetAttr(__pyx_3, __pyx_kp_27); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 46; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_k); @@ -941,7 +1068,7 @@ __pyx_v_k = __pyx_3; __pyx_3 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":47 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":47 * * k = np.atleast_1d(k) * x = np.atleast_1d(x) # <<<<<<<<<<<<<< @@ -949,7 +1076,7 @@ * x = x-ix */ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_20); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_27); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 47; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_x); @@ -961,7 +1088,7 @@ __pyx_v_x = __pyx_2; __pyx_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":48 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":48 * k = np.atleast_1d(k) * x = np.atleast_1d(x) * ix = np.round(x/(2*np.pi)) # <<<<<<<<<<<<<< @@ -974,13 +1101,13 @@ __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_pi); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_2 = PyNumber_Multiply(__pyx_int_2, __pyx_1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Multiply(__pyx_int_2, __pyx_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_1 = __Pyx_PyNumber_Divide(__pyx_v_x, __pyx_2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_t_2 = __Pyx_PyNumber_Divide(__pyx_v_x, __pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_2, 0, __pyx_1); - __pyx_1 = 0; + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_t_2); + __pyx_t_2 = 0; __pyx_1 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 48; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; @@ -988,19 +1115,19 @@ __pyx_v_ix = __pyx_1; __pyx_1 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":49 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":49 * x = np.atleast_1d(x) * ix = np.round(x/(2*np.pi)) * x = x-ix # <<<<<<<<<<<<<< * * # These values should give 12 decimal digits */ - __pyx_3 = PyNumber_Subtract(__pyx_v_x, __pyx_v_ix); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyNumber_Subtract(__pyx_v_x, __pyx_v_ix); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 49; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_v_x); - __pyx_v_x = __pyx_3; - __pyx_3 = 0; + __pyx_v_x = __pyx_t_2; + __pyx_t_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":52 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":52 * * # These values should give 12 decimal digits * CK=50 # <<<<<<<<<<<<<< @@ -1009,7 +1136,7 @@ */ __pyx_v_CK = 50; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":53 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":53 * # These values should give 12 decimal digits * CK=50 * a1, a2, a3, a4 = [28., 0.5, 100., 5.0] # <<<<<<<<<<<<<< @@ -1025,7 +1152,7 @@ __pyx_v_a3 = __pyx_7; __pyx_v_a4 = __pyx_8; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":54 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":54 * CK=50 * a1, a2, a3, a4 = [28., 0.5, 100., 5.0] * C1 = 50.1 # <<<<<<<<<<<<<< @@ -1034,82 +1161,82 @@ */ __pyx_v_C1 = 50.1; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":56 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":56 * C1 = 50.1 * * bx, bk = np.broadcast_arrays(x,k) # <<<<<<<<<<<<<< * result = np.empty(bx.shape,dtype=np.float) * */ - __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_broadcast_arrays); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_3 = PyTuple_New(2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetAttr(__pyx_3, __pyx_kp_broadcast_arrays); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_1 = PyTuple_New(2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_v_x); - PyTuple_SET_ITEM(__pyx_3, 0, __pyx_v_x); + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_x); Py_INCREF(__pyx_v_k); - PyTuple_SET_ITEM(__pyx_3, 1, __pyx_v_k); - __pyx_2 = PyObject_Call(__pyx_1, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; - if (PyTuple_CheckExact(__pyx_2) && PyTuple_GET_SIZE(__pyx_2) == 2) { - PyObject* tuple = __pyx_2; - __pyx_3 = PyTuple_GET_ITEM(tuple, 0); - Py_INCREF(__pyx_3); + PyTuple_SET_ITEM(__pyx_1, 1, __pyx_v_k); + __pyx_3 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; + if (PyTuple_CheckExact(__pyx_3) && PyTuple_GET_SIZE(__pyx_3) == 2) { + PyObject* tuple = __pyx_3; + __pyx_1 = PyTuple_GET_ITEM(tuple, 0); + Py_INCREF(__pyx_1); Py_DECREF(__pyx_v_bx); - __pyx_v_bx = __pyx_3; - __pyx_3 = 0; - __pyx_3 = PyTuple_GET_ITEM(tuple, 1); - Py_INCREF(__pyx_3); + __pyx_v_bx = __pyx_1; + __pyx_1 = 0; + __pyx_1 = PyTuple_GET_ITEM(tuple, 1); + Py_INCREF(__pyx_1); Py_DECREF(__pyx_v_bk); - __pyx_v_bk = __pyx_3; - __pyx_3 = 0; - Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_v_bk = __pyx_1; + __pyx_1 = 0; + Py_DECREF(__pyx_3); __pyx_3 = 0; } else { - __pyx_1 = PyObject_GetIter(__pyx_2); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_3 = __Pyx_UnpackItem(__pyx_1, 0); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_GetIter(__pyx_3); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_1 = __Pyx_UnpackItem(__pyx_2, 0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_v_bx); - __pyx_v_bx = __pyx_3; - __pyx_3 = 0; - __pyx_3 = __Pyx_UnpackItem(__pyx_1, 1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_bx = __pyx_1; + __pyx_1 = 0; + __pyx_1 = __Pyx_UnpackItem(__pyx_2, 1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_v_bk); - __pyx_v_bk = __pyx_3; - __pyx_3 = 0; - if (__Pyx_EndUnpack(__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_v_bk = __pyx_1; + __pyx_1 = 0; + if (__Pyx_EndUnpack(__pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 56; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; } - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":57 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":57 * * bx, bk = np.broadcast_arrays(x,k) * result = np.empty(bx.shape,dtype=np.float) # <<<<<<<<<<<<<< * * c_small_k = bk(1+a1+a2*temp_ks[i]-a3/(temp_ks[i]+a4)) */ __pyx_10 = PyObject_GetItem(__pyx_v_bk, __pyx_v_c_small_k); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetAttr(__pyx_10, __pyx_kp_astype); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_GetAttr(__pyx_10, __pyx_kp_astype); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_10); __pyx_10 = 0; __pyx_9 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyObject_GetAttr(__pyx_9, __pyx_kp_float); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = PyObject_GetAttr(__pyx_9, __pyx_kp_float); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_9); __pyx_9 = 0; - __pyx_1 = PyTuple_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_3); - __pyx_3 = 0; - __pyx_10 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_1); + __pyx_1 = 0; + __pyx_10 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; if (!(__Pyx_TypeTest(__pyx_10, __pyx_ptype_5numpy_ndarray))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((PyArrayObject *)__pyx_10); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp_ks, &__pyx_bstruct_temp_ks); - __pyx_t_2 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_1, &__pyx_bstruct_temp_ks, PyBUF_FORMAT| PyBUF_STRIDES, 1); - if (unlikely(__pyx_t_2 < 0)) + __pyx_t_3 = ((PyArrayObject *)__pyx_10); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp_ks); + __pyx_t_4 = __Pyx_GetBuffer_double((PyObject*)__pyx_t_3, &__pyx_bstruct_temp_ks, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0); + if (unlikely(__pyx_t_4 < 0)) { - PyErr_Fetch(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); - if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_temp_ks, &__pyx_bstruct_temp_ks, PyBUF_FORMAT| PyBUF_STRIDES, 1) == -1)) { - Py_XDECREF(__pyx_t_3); Py_XDECREF(__pyx_t_4); Py_XDECREF(__pyx_t_5); + PyErr_Fetch(&__pyx_t_2, &__pyx_t_1, &__pyx_t_5); + if (unlikely(__Pyx_GetBuffer_double((PyObject*)__pyx_v_temp_ks, &__pyx_bstruct_temp_ks, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0) == -1)) { + Py_XDECREF(__pyx_t_2); Py_XDECREF(__pyx_t_1); Py_XDECREF(__pyx_t_5); __Pyx_RaiseBufferFallbackError(); } else { - PyErr_Restore(__pyx_t_3, __pyx_t_4, __pyx_t_5); + PyErr_Restore(__pyx_t_2, __pyx_t_1, __pyx_t_5); } } __pyx_bstride_0_temp_ks = __pyx_bstruct_temp_ks.strides[0]; __pyx_bshape_0_temp_ks = __pyx_bstruct_temp_ks.shape[0]; - if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = 0; + if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 62; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = 0; Py_DECREF(((PyObject *)__pyx_v_temp_ks)); __pyx_v_temp_ks = ((PyArrayObject *)__pyx_10); __pyx_10 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":63 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":63 * temp_xs = bx[c_small_k].astype(np.float) * temp_ks = bk[c_small_k].astype(np.float) * for i in range(len(temp)): # <<<<<<<<<<<<<< @@ -1245,7 +1372,7 @@ __pyx_11 = PyObject_Length(((PyObject *)__pyx_v_temp)); if (unlikely(__pyx_11 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 63; __pyx_clineno = __LINE__; goto __pyx_L1_error;} for (__pyx_v_i = 0; __pyx_v_i < __pyx_11; __pyx_v_i+=1) { - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":64 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":64 * temp_ks = bk[c_small_k].astype(np.float) * for i in range(len(temp)): * p = (1+a1+a2*temp_ks[i]-a3/(temp_ks[i]+a4)) # <<<<<<<<<<<<<< @@ -1253,12 +1380,10 @@ * if temp[i]<0: */ __pyx_t_6 = __pyx_v_i; - __pyx_5 = *((double *)((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp_ks.buf, __pyx_t_6, __pyx_bstride_0_temp_ks))); __pyx_t_7 = __pyx_v_i; - __pyx_6 = *((double *)((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp_ks.buf, __pyx_t_7, __pyx_bstride_0_temp_ks))); - __pyx_v_p = ((int)(((1 + __pyx_v_a1) + (__pyx_v_a2 * __pyx_5)) - (__pyx_v_a3 / (__pyx_6 + __pyx_v_a4)))); + __pyx_v_p = ((int)(((1 + __pyx_v_a1) + (__pyx_v_a2 * (*__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp_ks.buf, __pyx_t_6, __pyx_bstride_0_temp_ks)))) - (__pyx_v_a3 / ((*__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp_ks.buf, __pyx_t_7, __pyx_bstride_0_temp_ks)) + __pyx_v_a4)))); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":65 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":65 * for i in range(len(temp)): * p = (1+a1+a2*temp_ks[i]-a3/(temp_ks[i]+a4)) * temp[i] = von_mises_cdf_series(temp_ks[i],temp_xs[i],p) # <<<<<<<<<<<<<< @@ -1266,13 +1391,11 @@ * temp[i]=0 */ __pyx_t_8 = __pyx_v_i; - __pyx_7 = *((double *)((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp_ks.buf, __pyx_t_8, __pyx_bstride_0_temp_ks))); __pyx_t_9 = __pyx_v_i; - __pyx_8 = *((double *)((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp_xs.buf, __pyx_t_9, __pyx_bstride_0_temp_xs))); __pyx_t_10 = __pyx_v_i; - *((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp.buf, __pyx_t_10, __pyx_bstride_0_temp)) = __pyx_f_5scipy_5stats_15vonmises_cython_von_mises_cdf_series(__pyx_7, __pyx_8, __pyx_v_p); + *__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp.buf, __pyx_t_10, __pyx_bstride_0_temp) = __pyx_f_5scipy_5stats_15vonmises_cython_von_mises_cdf_series((*__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp_ks.buf, __pyx_t_8, __pyx_bstride_0_temp_ks)), (*__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp_xs.buf, __pyx_t_9, __pyx_bstride_0_temp_xs)), __pyx_v_p); - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":66 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":66 * p = (1+a1+a2*temp_ks[i]-a3/(temp_ks[i]+a4)) * temp[i] = von_mises_cdf_series(temp_ks[i],temp_xs[i],p) * if temp[i]<0: # <<<<<<<<<<<<<< @@ -1280,11 +1403,10 @@ * elif temp[i]>1: */ __pyx_t_11 = __pyx_v_i; - __pyx_5 = *((double *)((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp.buf, __pyx_t_11, __pyx_bstride_0_temp))); - __pyx_4 = (__pyx_5 < 0); + __pyx_4 = ((*__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp.buf, __pyx_t_11, __pyx_bstride_0_temp)) < 0); if (__pyx_4) { - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":67 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":67 * temp[i] = von_mises_cdf_series(temp_ks[i],temp_xs[i],p) * if temp[i]<0: * temp[i]=0 # <<<<<<<<<<<<<< @@ -1292,11 +1414,11 @@ * temp[i]=1 */ __pyx_t_12 = __pyx_v_i; - *((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp.buf, __pyx_t_12, __pyx_bstride_0_temp)) = 0; - goto __pyx_L7; + *__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp.buf, __pyx_t_12, __pyx_bstride_0_temp) = 0; + goto __pyx_L8; } - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":68 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":68 * if temp[i]<0: * temp[i]=0 * elif temp[i]>1: # <<<<<<<<<<<<<< @@ -1304,11 +1426,10 @@ * result[c_small_k] = temp */ __pyx_t_13 = __pyx_v_i; - __pyx_6 = *((double *)((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp.buf, __pyx_t_13, __pyx_bstride_0_temp))); - __pyx_4 = (__pyx_6 > 1); + __pyx_4 = ((*__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp.buf, __pyx_t_13, __pyx_bstride_0_temp)) > 1); if (__pyx_4) { - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":69 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":69 * temp[i]=0 * elif temp[i]>1: * temp[i]=1 # <<<<<<<<<<<<<< @@ -1316,13 +1437,13 @@ * result[~c_small_k] = von_mises_cdf_normalapprox(bk[~c_small_k],bx[~c_small_k],C1) */ __pyx_t_14 = __pyx_v_i; - *((double *)__Pyx_BufPtrStrided1d(__pyx_bstruct_temp.buf, __pyx_t_14, __pyx_bstride_0_temp)) = 1; - goto __pyx_L7; + *__Pyx_BufPtrStrided1d(double *, __pyx_bstruct_temp.buf, __pyx_t_14, __pyx_bstride_0_temp) = 1; + goto __pyx_L8; } - __pyx_L7:; + __pyx_L8:; } - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":70 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":70 * elif temp[i]>1: * temp[i]=1 * result[c_small_k] = temp # <<<<<<<<<<<<<< @@ -1331,37 +1452,37 @@ */ if (PyObject_SetItem(__pyx_v_result, __pyx_v_c_small_k, ((PyObject *)__pyx_v_temp)) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 70; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":71 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":71 * temp[i]=1 * result[c_small_k] = temp * result[~c_small_k] = von_mises_cdf_normalapprox(bk[~c_small_k],bx[~c_small_k],C1) # <<<<<<<<<<<<<< * * if not zerodim: */ - __pyx_9 = __Pyx_GetName(__pyx_m, __pyx_kp_21); if (unlikely(!__pyx_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyNumber_Invert(__pyx_v_c_small_k); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_2 = PyObject_GetItem(__pyx_v_bk, __pyx_3); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_9 = __Pyx_GetName(__pyx_m, __pyx_kp_28); if (unlikely(!__pyx_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_1 = PyNumber_Invert(__pyx_v_c_small_k); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_10 = PyObject_GetItem(__pyx_v_bx, __pyx_1); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_GetItem(__pyx_v_bk, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_3 = PyFloat_FromDouble(__pyx_v_C1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_1 = PyTuple_New(3); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_2); - PyTuple_SET_ITEM(__pyx_1, 1, __pyx_10); - PyTuple_SET_ITEM(__pyx_1, 2, __pyx_3); - __pyx_2 = 0; + __pyx_2 = PyNumber_Invert(__pyx_v_c_small_k); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_10 = PyObject_GetItem(__pyx_v_bx, __pyx_2); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_1 = PyFloat_FromDouble(__pyx_v_C1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyTuple_New(3); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_3); + PyTuple_SET_ITEM(__pyx_2, 1, __pyx_10); + PyTuple_SET_ITEM(__pyx_2, 2, __pyx_1); + __pyx_3 = 0; __pyx_10 = 0; - __pyx_3 = 0; - __pyx_2 = PyObject_Call(__pyx_9, ((PyObject *)__pyx_1), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = 0; + __pyx_3 = PyObject_Call(__pyx_9, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_9); __pyx_9 = 0; - Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; __pyx_10 = PyNumber_Invert(__pyx_v_c_small_k); if (unlikely(!__pyx_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - if (PyObject_SetItem(__pyx_v_result, __pyx_10, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyObject_SetItem(__pyx_v_result, __pyx_10, __pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 71; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_10); __pyx_10 = 0; - Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_3); __pyx_3 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":73 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":73 * result[~c_small_k] = von_mises_cdf_normalapprox(bk[~c_small_k],bx[~c_small_k],C1) * * if not zerodim: # <<<<<<<<<<<<<< @@ -1372,50 +1493,50 @@ __pyx_12 = (!__pyx_4); if (__pyx_12) { - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":74 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":74 * * if not zerodim: * return result+(2*np.pi)*ix # <<<<<<<<<<<<<< * else: * return (result+(2*np.pi)*ix)[0] */ - __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_9 = PyObject_GetAttr(__pyx_3, __pyx_kp_pi); if (unlikely(!__pyx_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - __pyx_1 = PyNumber_Multiply(__pyx_int_2, __pyx_9); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_9 = PyObject_GetAttr(__pyx_1, __pyx_kp_pi); if (unlikely(!__pyx_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_t_5 = PyNumber_Multiply(__pyx_int_2, __pyx_9); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_9); __pyx_9 = 0; - __pyx_2 = PyNumber_Multiply(__pyx_1, __pyx_v_ix); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_10 = PyNumber_Add(__pyx_v_result, __pyx_2); if (unlikely(!__pyx_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_r = __pyx_10; - __pyx_10 = 0; + __pyx_t_1 = PyNumber_Multiply(__pyx_t_5, __pyx_v_ix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyNumber_Add(__pyx_v_result, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 74; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; goto __pyx_L0; - goto __pyx_L8; + goto __pyx_L9; } /*else*/ { - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":76 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":76 * return result+(2*np.pi)*ix * else: * return (result+(2*np.pi)*ix)[0] # <<<<<<<<<<<<<< */ - __pyx_3 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_9 = PyObject_GetAttr(__pyx_3, __pyx_kp_pi); if (unlikely(!__pyx_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_kp_np); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_kp_pi); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_t_5 = PyNumber_Multiply(__pyx_int_2, __pyx_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_3); __pyx_3 = 0; - __pyx_1 = PyNumber_Multiply(__pyx_int_2, __pyx_9); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_9); __pyx_9 = 0; - __pyx_2 = PyNumber_Multiply(__pyx_1, __pyx_v_ix); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - __pyx_10 = PyNumber_Add(__pyx_v_result, __pyx_2); if (unlikely(!__pyx_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_3 = __Pyx_GetItemInt(__pyx_10, 0, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(__pyx_10); __pyx_10 = 0; - __pyx_r = __pyx_3; - __pyx_3 = 0; + __pyx_t_1 = PyNumber_Multiply(__pyx_t_5, __pyx_v_ix); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_5 = PyNumber_Add(__pyx_v_result, __pyx_t_1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_10 = __Pyx_GetItemInt(__pyx_t_5, 0, 0); if (!__pyx_10) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 76; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_r = __pyx_10; + __pyx_10 = 0; goto __pyx_L0; } - __pyx_L8:; + __pyx_L9:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; @@ -1426,18 +1547,18 @@ Py_XDECREF(__pyx_9); Py_XDECREF(__pyx_10); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - PyErr_Fetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp, &__pyx_bstruct_temp); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp_xs, &__pyx_bstruct_temp_xs); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp_ks, &__pyx_bstruct_temp_ks); - PyErr_Restore(__pyx_type, __pyx_value, __pyx_tb);} + __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp_xs); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp_ks); + __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("scipy.stats.vonmises_cython.von_mises_cdf"); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp, &__pyx_bstruct_temp); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp_xs, &__pyx_bstruct_temp_xs); - __Pyx_SafeReleaseBuffer((PyObject*)__pyx_v_temp_ks, &__pyx_bstruct_temp_ks); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp_xs); + __Pyx_SafeReleaseBuffer(&__pyx_bstruct_temp_ks); __pyx_L2:; Py_DECREF(__pyx_v_temp); Py_DECREF(__pyx_v_temp_xs); @@ -1453,99 +1574,270 @@ return __pyx_r; } -/* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":36 +/* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":50 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP (specifically, + * # requirements, and does not yet fullfill the PEP. */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + int __pyx_v_copy_shape; + int __pyx_v_i; + int __pyx_v_ndim; int __pyx_v_t; char *__pyx_v_f; + PyArray_Descr *__pyx_v_descr = 0; + PyObject *__pyx_v_stack; + int __pyx_v_hasfields; + PyObject *__pyx_v_iterator; int __pyx_r; int __pyx_1; PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; + int __pyx_4; + PyObject *__pyx_5 = 0; + PyObject *__pyx_6 = 0; + PyObject *__pyx_7 = 0; + Py_ssize_t __pyx_8 = 0; + PyObject *__pyx_t_1 = NULL; + if (__pyx_v_info == NULL) return 0; + __pyx_v_info->obj = Py_None; Py_INCREF(Py_None); + __pyx_v_stack = ((PyObject *)Py_None); Py_INCREF(Py_None); + __pyx_v_iterator = Py_None; Py_INCREF(Py_None); - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":42 - * # so the flags are not even checked). + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":56 + * # of flags + * cdef int copy_shape, i, ndim + * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_v_ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":58 + * ndim = PyArray_NDIM(self) + * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * raise RuntimeError("Py_intptr_t and Py_ssize_t differs in size, numpy.pxd does not support this") - * + * copy_shape = 1 + * else: */ __pyx_1 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); if (__pyx_1) { - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":43 + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":59 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * raise RuntimeError("Py_intptr_t and Py_ssize_t differs in size, numpy.pxd does not support this") # <<<<<<<<<<<<<< + * copy_shape = 1 # <<<<<<<<<<<<<< + * else: + * copy_shape = 0 + */ + __pyx_v_copy_shape = 1; + goto __pyx_L5; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":61 + * copy_shape = 1 + * else: + * copy_shape = 0 # <<<<<<<<<<<<<< * - * info.buf = PyArray_DATA(self) + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ - __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_v_copy_shape = 0; + } + __pyx_L5:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":63 + * copy_shape = 0 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError("ndarray is not C contiguous") + */ + __pyx_1 = ((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":64 + * + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError("ndarray is not C contiguous") + * + */ + __pyx_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_C_CONTIGUOUS)); + } + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":65 + * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): + * raise ValueError("ndarray is not C contiguous") # <<<<<<<<<<<<<< + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + */ + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_kp_1); PyTuple_SET_ITEM(__pyx_2, 0, __pyx_kp_1); - __pyx_3 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; __Pyx_Raise(__pyx_3, 0, 0); Py_DECREF(__pyx_3); __pyx_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L6; } - __pyx_L5:; + __pyx_L6:; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":45 - * raise RuntimeError("Py_intptr_t and Py_ssize_t differs in size, numpy.pxd does not support this") + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":67 + * raise ValueError("ndarray is not C contiguous") * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError("ndarray is not Fortran contiguous") + */ + __pyx_1 = ((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":68 + * + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< + * raise ValueError("ndarray is not Fortran contiguous") + * + */ + __pyx_1 = (!PyArray_CHKFLAGS(((PyArrayObject *)__pyx_v_self), NPY_F_CONTIGUOUS)); + } + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":69 + * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) + * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): + * raise ValueError("ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< + * + * info.buf = PyArray_DATA(self) + */ + __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_kp_2); + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_kp_2); + __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; + __Pyx_Raise(__pyx_3, 0, 0); + Py_DECREF(__pyx_3); __pyx_3 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 69; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L7; + } + __pyx_L7:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":71 + * raise ValueError("ndarray is not Fortran contiguous") + * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = PyArray_NDIM(self) - * info.strides = PyArray_STRIDES(self) + * info.ndim = ndim + * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(((PyArrayObject *)__pyx_v_self)); - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":46 + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":72 * * info.buf = PyArray_DATA(self) - * info.ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) + * info.ndim = ndim # <<<<<<<<<<<<<< + * if copy_shape: + * # Allocate new buffer for strides and shape info. This is allocated */ - __pyx_v_info->ndim = PyArray_NDIM(((PyArrayObject *)__pyx_v_self)); + __pyx_v_info->ndim = __pyx_v_ndim; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":47 + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":73 * info.buf = PyArray_DATA(self) - * info.ndim = PyArray_NDIM(self) - * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< - * info.shape = PyArray_DIMS(self) + * info.ndim = ndim + * if copy_shape: # <<<<<<<<<<<<<< + * # Allocate new buffer for strides and shape info. This is allocated + * # as one block, strides first. + */ + __pyx_4 = __pyx_v_copy_shape; + if (__pyx_4) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":76 + * # Allocate new buffer for strides and shape info. This is allocated + * # as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< + * info.shape = info.strides + ndim + * for i in range(ndim): + */ + __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * __pyx_v_ndim) * 2))); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":77 + * # as one block, strides first. + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim # <<<<<<<<<<<<<< + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + */ + __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":78 + * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) + * info.shape = info.strides + ndim + * for i in range(ndim): # <<<<<<<<<<<<<< + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] + */ + for (__pyx_v_i = 0; __pyx_v_i < __pyx_v_ndim; __pyx_v_i+=1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":79 + * info.shape = info.strides + ndim + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + */ + (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":80 + * for i in range(ndim): + * info.strides[i] = PyArray_STRIDES(self)[i] + * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< + * else: + * info.strides = PyArray_STRIDES(self) + */ + (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(((PyArrayObject *)__pyx_v_self))[__pyx_v_i]); + } + goto __pyx_L8; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":82 + * info.shape[i] = PyArray_DIMS(self)[i] + * else: + * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< + * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(((PyArrayObject *)__pyx_v_self))); - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":48 - * info.ndim = PyArray_NDIM(self) - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":83 + * else: + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(((PyArrayObject *)__pyx_v_self))); + } + __pyx_L8:; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":49 - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":84 + * info.strides = PyArray_STRIDES(self) + * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":50 - * info.shape = PyArray_DIMS(self) + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":85 + * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) @@ -1553,241 +1845,972 @@ */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_self)); - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":51 + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":86 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * - * # Formats that are not tested and working in Cython are not + * cdef int t */ __pyx_v_info->readonly = (!PyArray_ISWRITEABLE(((PyArrayObject *)__pyx_v_self))); - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":55 - * # Formats that are not tested and working in Cython are not - * # made available from this pxd file yet. - * cdef int t = PyArray_TYPE(self) # <<<<<<<<<<<<<< - * cdef char* f = NULL - * if t == NPY_BYTE: f = "b" - */ - __pyx_v_t = PyArray_TYPE(((PyArrayObject *)__pyx_v_self)); - - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":56 - * # made available from this pxd file yet. - * cdef int t = PyArray_TYPE(self) + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":89 + * + * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" + * cdef dtype descr = self.descr + * cdef list stack */ __pyx_v_f = NULL; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":57 - * cdef int t = PyArray_TYPE(self) + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":90 + * cdef int t * cdef char* f = NULL - * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" + * cdef dtype descr = self.descr # <<<<<<<<<<<<<< + * cdef list stack + * */ - switch (__pyx_v_t) { - case NPY_BYTE: - __pyx_v_f = __pyx_k_2; - break; - case NPY_UBYTE: + Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_self)->descr)); + __pyx_v_descr = ((PyArrayObject *)__pyx_v_self)->descr; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":58 - * cdef char* f = NULL - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":93 + * cdef list stack + * + * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * + * # Ugly hack warning: */ - __pyx_v_f = __pyx_k_3; - break; - case NPY_SHORT: + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":59 - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":103 + * # functions). + * + * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< + * # do not call releasebuffer + * info.obj = None */ - __pyx_v_f = __pyx_k_4; - break; - case NPY_USHORT: + __pyx_1 = (!__pyx_v_hasfields); + if (__pyx_1) { + __pyx_1 = (!__pyx_v_copy_shape); + } + if (__pyx_1) { - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":60 - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":105 + * if not hasfields and not copy_shape: + * # do not call releasebuffer + * info.obj = None # <<<<<<<<<<<<<< + * else: + * # need to call releasebuffer */ - __pyx_v_f = __pyx_k_5; - break; - case NPY_INT: + Py_INCREF(Py_None); + Py_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = Py_None; + goto __pyx_L11; + } + /*else*/ { - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":61 - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":108 + * else: + * # need to call releasebuffer + * info.obj = self # <<<<<<<<<<<<<< + * + * if not hasfields: */ - __pyx_v_f = __pyx_k_6; - break; - case NPY_UINT: + Py_INCREF(__pyx_v_self); + Py_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = __pyx_v_self; + } + __pyx_L11:; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":62 - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":110 + * info.obj = self + * + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if t == NPY_BYTE: f = "b" */ - __pyx_v_f = __pyx_k_7; - break; - case NPY_LONG: + __pyx_1 = (!__pyx_v_hasfields); + if (__pyx_1) { - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":63 - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":111 + * + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" */ - __pyx_v_f = __pyx_k_8; - break; - case NPY_ULONG: + __pyx_v_t = __pyx_v_descr->type_num; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":64 - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":112 + * if not hasfields: + * t = descr.type_num + * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" */ - __pyx_v_f = __pyx_k_9; - break; - case NPY_LONGLONG: + switch (__pyx_v_t) { + case NPY_BYTE: + __pyx_v_f = __pyx_k_3; + break; + case NPY_UBYTE: - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":65 - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":113 + * t = descr.type_num + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" */ - __pyx_v_f = __pyx_k_10; - break; - case NPY_ULONGLONG: + __pyx_v_f = __pyx_k_4; + break; + case NPY_SHORT: - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":66 - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":114 + * if t == NPY_BYTE: f = "b" + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" */ - __pyx_v_f = __pyx_k_11; - break; - case NPY_FLOAT: + __pyx_v_f = __pyx_k_5; + break; + case NPY_USHORT: - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":67 - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":115 + * elif t == NPY_UBYTE: f = "B" + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" */ - __pyx_v_f = __pyx_k_12; - break; - case NPY_DOUBLE: + __pyx_v_f = __pyx_k_6; + break; + case NPY_INT: - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":68 - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_OBJECT: f = "O" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":116 + * elif t == NPY_SHORT: f = "h" + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" */ - __pyx_v_f = __pyx_k_13; - break; - case NPY_LONGDOUBLE: + __pyx_v_f = __pyx_k_7; + break; + case NPY_UINT: - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":69 - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f = "O" - * + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":117 + * elif t == NPY_USHORT: f = "H" + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" */ - __pyx_v_f = __pyx_k_14; - break; - case NPY_OBJECT: + __pyx_v_f = __pyx_k_8; + break; + case NPY_LONG: - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":70 - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< - * - * if f == NULL: + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":118 + * elif t == NPY_INT: f = "i" + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" */ - __pyx_v_f = __pyx_k_15; - break; + __pyx_v_f = __pyx_k_9; + break; + case NPY_ULONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":119 + * elif t == NPY_UINT: f = "I" + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + */ + __pyx_v_f = __pyx_k_10; + break; + case NPY_LONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":120 + * elif t == NPY_LONG: f = "l" + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + */ + __pyx_v_f = __pyx_k_11; + break; + case NPY_ULONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":121 + * elif t == NPY_ULONG: f = "L" + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + */ + __pyx_v_f = __pyx_k_12; + break; + case NPY_FLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":122 + * elif t == NPY_LONGLONG: f = "q" + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + */ + __pyx_v_f = __pyx_k_13; + break; + case NPY_DOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":123 + * elif t == NPY_ULONGLONG: f = "Q" + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + */ + __pyx_v_f = __pyx_k_14; + break; + case NPY_LONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":124 + * elif t == NPY_FLOAT: f = "f" + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + */ + __pyx_v_f = __pyx_k_15; + break; + case NPY_CFLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":125 + * elif t == NPY_DOUBLE: f = "d" + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + */ + __pyx_v_f = __pyx_k_16; + break; + case NPY_CDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":126 + * elif t == NPY_LONGDOUBLE: f = "g" + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" + */ + __pyx_v_f = __pyx_k_17; + break; + case NPY_CLONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":127 + * elif t == NPY_CFLOAT: f = "Zf" + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f = "O" + * else: + */ + __pyx_v_f = __pyx_k_18; + break; + case NPY_OBJECT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":128 + * elif t == NPY_CDOUBLE: f = "Zd" + * elif t == NPY_CLONGDOUBLE: f = "Zg" + * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + */ + __pyx_v_f = __pyx_k_19; + break; + default: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":130 + * elif t == NPY_OBJECT: f = "O" + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * info.format = f + * return + */ + __pyx_2 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(__pyx_kp_20, __pyx_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_2 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __Pyx_Raise(__pyx_2, 0, 0); + Py_DECREF(__pyx_2); __pyx_2 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":131 + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f # <<<<<<<<<<<<<< + * return + * else: + */ + __pyx_v_info->format = __pyx_v_f; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":132 + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + * info.format = f + * return # <<<<<<<<<<<<<< + * else: + * info.format = stdlib.malloc(255) # static size + */ + __pyx_r = 0; + goto __pyx_L0; + goto __pyx_L12; } + /*else*/ { - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":72 - * elif t == NPY_OBJECT: f = "O" + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":134 + * return + * else: + * info.format = stdlib.malloc(255) # static size # <<<<<<<<<<<<<< + * f = info.format + * stack = [iter(descr.fields.iteritems())] + */ + __pyx_v_info->format = ((char *)malloc(255)); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":135 + * else: + * info.format = stdlib.malloc(255) # static size + * f = info.format # <<<<<<<<<<<<<< + * stack = [iter(descr.fields.iteritems())] * - * if f == NULL: # <<<<<<<<<<<<<< - * raise ValueError("only objects, int and float dtypes supported for ndarray buffer access so far (dtype is %d)" % t) - * info.format = f */ - __pyx_1 = (__pyx_v_f == NULL); - if (__pyx_1) { + __pyx_v_f = __pyx_v_info->format; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":73 + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":136 + * info.format = stdlib.malloc(255) # static size + * f = info.format + * stack = [iter(descr.fields.iteritems())] # <<<<<<<<<<<<<< * - * if f == NULL: - * raise ValueError("only objects, int and float dtypes supported for ndarray buffer access so far (dtype is %d)" % t) # <<<<<<<<<<<<<< - * info.format = f - * + * while True: */ - __pyx_2 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_3 = PyNumber_Remainder(__pyx_kp_16, __pyx_2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_3 = PyObject_GetAttr(__pyx_v_descr->fields, __pyx_kp_iteritems); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = PyObject_Call(__pyx_3, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_3 = PyObject_GetIter(__pyx_2); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_2 = PyTuple_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - PyTuple_SET_ITEM(__pyx_2, 0, __pyx_3); + __pyx_2 = PyList_New(1); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 136; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyList_SET_ITEM(__pyx_2, 0, __pyx_3); __pyx_3 = 0; - __pyx_3 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_2), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - Py_DECREF(((PyObject *)__pyx_2)); __pyx_2 = 0; - __Pyx_Raise(__pyx_3, 0, 0); - Py_DECREF(__pyx_3); __pyx_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L6; - } - __pyx_L6:; + Py_DECREF(((PyObject *)__pyx_v_stack)); + __pyx_v_stack = __pyx_2; + __pyx_2 = 0; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":74 - * if f == NULL: - * raise ValueError("only objects, int and float dtypes supported for ndarray buffer access so far (dtype is %d)" % t) - * info.format = f # <<<<<<<<<<<<<< + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":138 + * stack = [iter(descr.fields.iteritems())] * + * while True: # <<<<<<<<<<<<<< + * iterator = stack[-1] + * descr = None + */ + while (1) { + __pyx_1 = 1; + if (!__pyx_1) break; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":139 * + * while True: + * iterator = stack[-1] # <<<<<<<<<<<<<< + * descr = None + * while descr is None: */ - __pyx_v_info->format = __pyx_v_f; + __pyx_3 = __Pyx_GetItemInt(((PyObject *)__pyx_v_stack), -1, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 139; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_v_iterator); + __pyx_v_iterator = __pyx_3; + __pyx_3 = 0; + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":140 + * while True: + * iterator = stack[-1] + * descr = None # <<<<<<<<<<<<<< + * while descr is None: + * try: + */ + Py_INCREF(Py_None); + Py_DECREF(((PyObject *)__pyx_v_descr)); + __pyx_v_descr = ((PyArray_Descr *)Py_None); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":141 + * iterator = stack[-1] + * descr = None + * while descr is None: # <<<<<<<<<<<<<< + * try: + * descr = iterator.next()[1][0] + */ + while (1) { + __pyx_1 = (((PyObject *)__pyx_v_descr) == Py_None); + if (!__pyx_1) break; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":142 + * descr = None + * while descr is None: + * try: # <<<<<<<<<<<<<< + * descr = iterator.next()[1][0] + * except StopIteration: + */ + { + PyObject *__pyx_save_exc_type, *__pyx_save_exc_value, *__pyx_save_exc_tb; + __Pyx_ExceptionSave(&__pyx_save_exc_type, &__pyx_save_exc_value, &__pyx_save_exc_tb); + /*try:*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":143 + * while descr is None: + * try: + * descr = iterator.next()[1][0] # <<<<<<<<<<<<<< + * except StopIteration: + * stack.pop() + */ + __pyx_2 = PyObject_GetAttr(__pyx_v_iterator, __pyx_kp_next); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + __pyx_3 = PyObject_Call(__pyx_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_2 = __Pyx_GetItemInt(__pyx_3, 1, 0); if (!__pyx_2) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(__pyx_3); __pyx_3 = 0; + __pyx_3 = __Pyx_GetItemInt(__pyx_2, 0, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + if (!(__Pyx_TypeTest(__pyx_3, __pyx_ptype_5numpy_dtype))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 143; __pyx_clineno = __LINE__; goto __pyx_L17_error;} + Py_DECREF(((PyObject *)__pyx_v_descr)); + __pyx_v_descr = ((PyArray_Descr *)__pyx_3); + __pyx_3 = 0; + } + goto __pyx_L21_try; + __pyx_L17_error:; + Py_XDECREF(__pyx_2); __pyx_2 = 0; + Py_XDECREF(__pyx_3); __pyx_3 = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":144 + * try: + * descr = iterator.next()[1][0] + * except StopIteration: # <<<<<<<<<<<<<< + * stack.pop() + * if len(stack) > 0: + */ + __pyx_4 = PyErr_ExceptionMatches(__pyx_builtin_StopIteration); + if (__pyx_4) { + __Pyx_AddTraceback("numpy.__getbuffer__"); + if (__Pyx_GetException(&__pyx_2, &__pyx_3, &__pyx_5) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":145 + * descr = iterator.next()[1][0] + * except StopIteration: + * stack.pop() # <<<<<<<<<<<<<< + * if len(stack) > 0: + * f[0] = 125 #"}" + */ + __pyx_6 = PyObject_GetAttr(((PyObject *)__pyx_v_stack), __pyx_kp_pop); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + __pyx_7 = PyObject_Call(__pyx_6, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + Py_DECREF(__pyx_6); __pyx_6 = 0; + Py_DECREF(__pyx_7); __pyx_7 = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":146 + * except StopIteration: + * stack.pop() + * if len(stack) > 0: # <<<<<<<<<<<<<< + * f[0] = 125 #"}" + * f += 1 + */ + __pyx_8 = PyObject_Length(((PyObject *)__pyx_v_stack)); if (unlikely(__pyx_8 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + __pyx_1 = (__pyx_8 > 0); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":147 + * stack.pop() + * if len(stack) > 0: + * f[0] = 125 #"}" # <<<<<<<<<<<<<< + * f += 1 + * iterator = stack[-1] + */ + (__pyx_v_f[0]) = 125; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":148 + * if len(stack) > 0: + * f[0] = 125 #"}" + * f += 1 # <<<<<<<<<<<<<< + * iterator = stack[-1] + * else: + */ + __pyx_v_f += 1; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":149 + * f[0] = 125 #"}" + * f += 1 + * iterator = stack[-1] # <<<<<<<<<<<<<< + * else: + * f[0] = 0 # Terminate string! + */ + __pyx_6 = __Pyx_GetItemInt(((PyObject *)__pyx_v_stack), -1, 0); if (!__pyx_6) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L19_except_error;} + Py_DECREF(__pyx_v_iterator); + __pyx_v_iterator = __pyx_6; + __pyx_6 = 0; + goto __pyx_L22; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":151 + * iterator = stack[-1] + * else: + * f[0] = 0 # Terminate string! # <<<<<<<<<<<<<< + * return + * + */ + (__pyx_v_f[0]) = 0; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":152 + * else: + * f[0] = 0 # Terminate string! + * return # <<<<<<<<<<<<<< + * + * hasfields = PyDataType_HASFIELDS(descr) + */ + __pyx_r = 0; + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(__pyx_5); __pyx_5 = 0; + goto __pyx_L20_except_return; + } + __pyx_L22:; + Py_DECREF(__pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_3); __pyx_3 = 0; + Py_DECREF(__pyx_5); __pyx_5 = 0; + goto __pyx_L18_exception_handled; + } + __pyx_L19_except_error:; + Py_XDECREF(__pyx_save_exc_type); + Py_XDECREF(__pyx_save_exc_value); + Py_XDECREF(__pyx_save_exc_tb); + goto __pyx_L1_error; + __pyx_L20_except_return:; + __Pyx_ExceptionReset(__pyx_save_exc_type, __pyx_save_exc_value, __pyx_save_exc_tb); + goto __pyx_L0; + __pyx_L18_exception_handled:; + __Pyx_ExceptionReset(__pyx_save_exc_type, __pyx_save_exc_value, __pyx_save_exc_tb); + __pyx_L21_try:; + } + } + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":154 + * return + * + * hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< + * if not hasfields: + * t = descr.type_num + */ + __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":155 + * + * hasfields = PyDataType_HASFIELDS(descr) + * if not hasfields: # <<<<<<<<<<<<<< + * t = descr.type_num + * if f - info.format > 240: # this should leave room for "T{" and "}" as well + */ + __pyx_1 = (!__pyx_v_hasfields); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":156 + * hasfields = PyDataType_HASFIELDS(descr) + * if not hasfields: + * t = descr.type_num # <<<<<<<<<<<<<< + * if f - info.format > 240: # this should leave room for "T{" and "}" as well + * raise RuntimeError("Format string allocated too short.") + */ + __pyx_v_t = __pyx_v_descr->type_num; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":157 + * if not hasfields: + * t = descr.type_num + * if f - info.format > 240: # this should leave room for "T{" and "}" as well # <<<<<<<<<<<<<< + * raise RuntimeError("Format string allocated too short.") + * + */ + __pyx_1 = ((__pyx_v_f - __pyx_v_info->format) > 240); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":158 + * t = descr.type_num + * if f - info.format > 240: # this should leave room for "T{" and "}" as well + * raise RuntimeError("Format string allocated too short.") # <<<<<<<<<<<<<< + * + * # Until ticket #99 is fixed, use integers to avoid warnings + */ + __pyx_7 = PyTuple_New(1); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_INCREF(__pyx_kp_21); + PyTuple_SET_ITEM(__pyx_7, 0, __pyx_kp_21); + __pyx_6 = PyObject_Call(__pyx_builtin_RuntimeError, ((PyObject *)__pyx_7), NULL); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_7)); __pyx_7 = 0; + __Pyx_Raise(__pyx_6, 0, 0); + Py_DECREF(__pyx_6); __pyx_6 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + goto __pyx_L24; + } + __pyx_L24:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":161 + * + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + */ + switch (__pyx_v_t) { + case NPY_BYTE: + (__pyx_v_f[0]) = 98; + break; + case NPY_UBYTE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":162 + * # Until ticket #99 is fixed, use integers to avoid warnings + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + */ + (__pyx_v_f[0]) = 66; + break; + case NPY_SHORT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":163 + * if t == NPY_BYTE: f[0] = 98 #"b" + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + */ + (__pyx_v_f[0]) = 104; + break; + case NPY_USHORT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":164 + * elif t == NPY_UBYTE: f[0] = 66 #"B" + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + */ + (__pyx_v_f[0]) = 72; + break; + case NPY_INT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":165 + * elif t == NPY_SHORT: f[0] = 104 #"h" + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + */ + (__pyx_v_f[0]) = 105; + break; + case NPY_UINT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":166 + * elif t == NPY_USHORT: f[0] = 72 #"H" + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + */ + (__pyx_v_f[0]) = 73; + break; + case NPY_LONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":167 + * elif t == NPY_INT: f[0] = 105 #"i" + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + */ + (__pyx_v_f[0]) = 108; + break; + case NPY_ULONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":168 + * elif t == NPY_UINT: f[0] = 73 #"I" + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + */ + (__pyx_v_f[0]) = 76; + break; + case NPY_LONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":169 + * elif t == NPY_LONG: f[0] = 108 #"l" + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + */ + (__pyx_v_f[0]) = 113; + break; + case NPY_ULONGLONG: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":170 + * elif t == NPY_ULONG: f[0] = 76 #"L" + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + */ + (__pyx_v_f[0]) = 81; + break; + case NPY_FLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":171 + * elif t == NPY_LONGLONG: f[0] = 113 #"q" + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + */ + (__pyx_v_f[0]) = 102; + break; + case NPY_DOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":172 + * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + */ + (__pyx_v_f[0]) = 100; + break; + case NPY_LONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":173 + * elif t == NPY_FLOAT: f[0] = 102 #"f" + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + */ + (__pyx_v_f[0]) = 103; + break; + case NPY_CFLOAT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":174 + * elif t == NPY_DOUBLE: f[0] = 100 #"d" + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # <<<<<<<<<<<<<< + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 + */ + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 102; + __pyx_v_f += 1; + break; + case NPY_CDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":175 + * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # <<<<<<<<<<<<<< + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + */ + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 100; + __pyx_v_f += 1; + break; + case NPY_CLONGDOUBLE: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":176 + * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # <<<<<<<<<<<<<< + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + */ + (__pyx_v_f[0]) = 90; + (__pyx_v_f[1]) = 103; + __pyx_v_f += 1; + break; + case NPY_OBJECT: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":177 + * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 + * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 + * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + */ + (__pyx_v_f[0]) = 79; + break; + default: + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":179 + * elif t == NPY_OBJECT: f[0] = 79 #"O" + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< + * f += 1 + * else: + */ + __pyx_2 = PyInt_FromLong(__pyx_v_t); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyNumber_Remainder(__pyx_kp_22, __pyx_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_3 = PyTuple_New(1); if (unlikely(!__pyx_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_5 = PyObject_Call(__pyx_builtin_ValueError, ((PyObject *)__pyx_3), NULL); if (unlikely(!__pyx_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(((PyObject *)__pyx_3)); __pyx_3 = 0; + __Pyx_Raise(__pyx_5, 0, 0); + Py_DECREF(__pyx_5); __pyx_5 = 0; + {__pyx_filename = __pyx_f[1]; __pyx_lineno = 179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":180 + * else: + * raise ValueError("unknown dtype code in numpy.pxd (%d)" % t) + * f += 1 # <<<<<<<<<<<<<< + * else: + * f[0] = 84 #"T" + */ + __pyx_v_f += 1; + goto __pyx_L23; + } + /*else*/ { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":182 + * f += 1 + * else: + * f[0] = 84 #"T" # <<<<<<<<<<<<<< + * f[1] = 123 #"{" + * f += 2 + */ + (__pyx_v_f[0]) = 84; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":183 + * else: + * f[0] = 84 #"T" + * f[1] = 123 #"{" # <<<<<<<<<<<<<< + * f += 2 + * stack.append(iter(descr.fields.iteritems())) + */ + (__pyx_v_f[1]) = 123; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":184 + * f[0] = 84 #"T" + * f[1] = 123 #"{" + * f += 2 # <<<<<<<<<<<<<< + * stack.append(iter(descr.fields.iteritems())) + * + */ + __pyx_v_f += 2; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":185 + * f[1] = 123 #"{" + * f += 2 + * stack.append(iter(descr.fields.iteritems())) # <<<<<<<<<<<<<< + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + */ + __pyx_7 = PyObject_GetAttr(__pyx_v_descr->fields, __pyx_kp_iteritems); if (unlikely(!__pyx_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_6 = PyObject_Call(__pyx_7, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_7); __pyx_7 = 0; + __pyx_2 = PyObject_GetIter(__pyx_6); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_6); __pyx_6 = 0; + __pyx_4 = PyList_Append(((PyObject *)__pyx_v_stack), __pyx_2); if (unlikely(__pyx_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + Py_DECREF(__pyx_2); __pyx_2 = 0; + } + __pyx_L23:; + } + } + __pyx_L12:; + __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); + Py_XDECREF(__pyx_5); + Py_XDECREF(__pyx_6); + Py_XDECREF(__pyx_7); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__"); __pyx_r = -1; + Py_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; + goto __pyx_L2; __pyx_L0:; + if (__pyx_v_info->obj == Py_None) { Py_DECREF(Py_None); __pyx_v_info->obj = NULL; } + __pyx_L2:; + Py_XDECREF(__pyx_v_descr); + Py_DECREF(__pyx_v_stack); + Py_DECREF(__pyx_v_iterator); return __pyx_r; } +/* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":187 + * stack.append(iter(descr.fields.iteritems())) + * + * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + */ + +static void __pyx_pf_5numpy_7ndarray___releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +static void __pyx_pf_5numpy_7ndarray___releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + int __pyx_1; + int __pyx_2; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":188 + * + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + */ + __pyx_1 = PyArray_HASFIELDS(((PyArrayObject *)__pyx_v_self)); + if (__pyx_1) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":189 + * def __releasebuffer__(ndarray self, Py_buffer* info): + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) # <<<<<<<<<<<<<< + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) + */ + free(__pyx_v_info->format); + goto __pyx_L5; + } + __pyx_L5:; + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":190 + * if PyArray_HASFIELDS(self): + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< + * stdlib.free(info.strides) + * # info.shape was stored after info.strides in the same block + */ + __pyx_2 = ((sizeof(npy_intp)) != (sizeof(Py_ssize_t))); + if (__pyx_2) { + + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/numpy.pxd":191 + * stdlib.free(info.format) + * if sizeof(npy_intp) != sizeof(Py_ssize_t): + * stdlib.free(info.strides) # <<<<<<<<<<<<<< + * # info.shape was stored after info.strides in the same block + * + */ + free(__pyx_v_info->strides); + goto __pyx_L6; + } + __pyx_L6:; + +} + static struct PyMethodDef __pyx_methods[] = { {"von_mises_cdf_normalapprox", (PyCFunction)__pyx_pf_5scipy_5stats_15vonmises_cython_von_mises_cdf_normalapprox, METH_VARARGS|METH_KEYWORDS, 0}, {"von_mises_cdf", (PyCFunction)__pyx_pf_5scipy_5stats_15vonmises_cython_von_mises_cdf, METH_VARARGS|METH_KEYWORDS, 0}, @@ -1811,13 +2834,16 @@ #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { + {&__pyx_kp_k, __pyx_k_k, sizeof(__pyx_k_k), 1, 1, 1}, + {&__pyx_kp_x, __pyx_k_x, sizeof(__pyx_k_x), 1, 1, 1}, + {&__pyx_kp_23, __pyx_k_23, sizeof(__pyx_k_23), 1, 1, 1}, {&__pyx_kp_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 1, 1, 1}, {&__pyx_kp_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 1, 1}, - {&__pyx_kp_17, __pyx_k_17, sizeof(__pyx_k_17), 1, 1, 1}, + {&__pyx_kp_24, __pyx_k_24, sizeof(__pyx_k_24), 1, 1, 1}, {&__pyx_kp_scipy, __pyx_k_scipy, sizeof(__pyx_k_scipy), 0, 1, 1}, - {&__pyx_kp_18, __pyx_k_18, sizeof(__pyx_k_18), 1, 1, 1}, + {&__pyx_kp_25, __pyx_k_25, sizeof(__pyx_k_25), 1, 1, 1}, {&__pyx_kp_i0, __pyx_k_i0, sizeof(__pyx_k_i0), 1, 1, 1}, - {&__pyx_kp_19, __pyx_k_19, sizeof(__pyx_k_19), 1, 1, 1}, + {&__pyx_kp_26, __pyx_k_26, sizeof(__pyx_k_26), 1, 1, 1}, {&__pyx_kp_pi, __pyx_k_pi, sizeof(__pyx_k_pi), 1, 1, 1}, {&__pyx_kp_sqrt, __pyx_k_sqrt, sizeof(__pyx_k_sqrt), 1, 1, 1}, {&__pyx_kp_exp, __pyx_k_exp, sizeof(__pyx_k_exp), 1, 1, 1}, @@ -1827,7 +2853,7 @@ {&__pyx_kp_cdf, __pyx_k_cdf, sizeof(__pyx_k_cdf), 1, 1, 1}, {&__pyx_kp_asarray, __pyx_k_asarray, sizeof(__pyx_k_asarray), 1, 1, 1}, {&__pyx_kp_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 1, 1, 1}, - {&__pyx_kp_20, __pyx_k_20, sizeof(__pyx_k_20), 1, 1, 1}, + {&__pyx_kp_27, __pyx_k_27, sizeof(__pyx_k_27), 1, 1, 1}, {&__pyx_kp_round, __pyx_k_round, sizeof(__pyx_k_round), 1, 1, 1}, {&__pyx_kp_broadcast_arrays, __pyx_k_broadcast_arrays, sizeof(__pyx_k_broadcast_arrays), 1, 1, 1}, {&__pyx_kp_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 1, 1, 1}, @@ -1835,17 +2861,28 @@ {&__pyx_kp_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 1, 1, 1}, {&__pyx_kp_float, __pyx_k_float, sizeof(__pyx_k_float), 1, 1, 1}, {&__pyx_kp_astype, __pyx_k_astype, sizeof(__pyx_k_astype), 1, 1, 1}, - {&__pyx_kp_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 1, 1}, - {&__pyx_kp___getbuffer__, __pyx_k___getbuffer__, sizeof(__pyx_k___getbuffer__), 0, 1, 1}, + {&__pyx_kp_28, __pyx_k_28, sizeof(__pyx_k_28), 1, 1, 1}, + {&__pyx_kp___getbuffer__, __pyx_k___getbuffer__, sizeof(__pyx_k___getbuffer__), 1, 1, 1}, + {&__pyx_kp___releasebuffer__, __pyx_k___releasebuffer__, sizeof(__pyx_k___releasebuffer__), 1, 1, 1}, + {&__pyx_kp_info, __pyx_k_info, sizeof(__pyx_k_info), 1, 1, 1}, + {&__pyx_kp_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 1, 1, 1}, + {&__pyx_kp_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 1, 1, 1}, + {&__pyx_kp_iteritems, __pyx_k_iteritems, sizeof(__pyx_k_iteritems), 1, 1, 1}, + {&__pyx_kp_next, __pyx_k_next, sizeof(__pyx_k_next), 1, 1, 1}, + {&__pyx_kp_StopIteration, __pyx_k_StopIteration, sizeof(__pyx_k_StopIteration), 1, 1, 1}, + {&__pyx_kp_pop, __pyx_k_pop, sizeof(__pyx_k_pop), 1, 1, 1}, {&__pyx_kp_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 1, 1, 1}, - {&__pyx_kp_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 1, 1, 1}, {&__pyx_kp_1, __pyx_k_1, sizeof(__pyx_k_1), 0, 0, 0}, - {&__pyx_kp_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 0}, + {&__pyx_kp_2, __pyx_k_2, sizeof(__pyx_k_2), 0, 0, 0}, + {&__pyx_kp_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 0}, + {&__pyx_kp_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 0}, + {&__pyx_kp_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 0}, {0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_kp_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 43; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_kp_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 73; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_ValueError = __Pyx_GetName(__pyx_b, __pyx_kp_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_StopIteration = __Pyx_GetName(__pyx_b, __pyx_kp_StopIteration); if (!__pyx_builtin_StopIteration) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 144; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_RuntimeError = __Pyx_GetName(__pyx_b, __pyx_kp_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; @@ -1875,7 +2912,7 @@ PyObject *__pyx_1 = 0; PyObject *__pyx_2 = 0; __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - /*--- Libary function declarations ---*/ + /*--- Library function declarations ---*/ __pyx_init_filenames(); /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} @@ -1899,11 +2936,12 @@ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject)); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr)); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 30; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject)); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 36; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Function import code ---*/ /*--- Execution code ---*/ - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":1 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * import scipy.stats * from scipy.special import i0 @@ -1912,17 +2950,17 @@ if (PyObject_SetAttr(__pyx_m, __pyx_kp_np, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":2 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":2 * import numpy as np * import scipy.stats # <<<<<<<<<<<<<< * from scipy.special import i0 * import numpy.testing */ - __pyx_1 = __Pyx_Import(__pyx_kp_17, 0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_1 = __Pyx_Import(__pyx_kp_24, 0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (PyObject_SetAttr(__pyx_m, __pyx_kp_scipy, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 2; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":3 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":3 * import numpy as np * import scipy.stats * from scipy.special import i0 # <<<<<<<<<<<<<< @@ -1932,30 +2970,29 @@ __pyx_1 = PyList_New(1); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_kp_i0); PyList_SET_ITEM(__pyx_1, 0, __pyx_kp_i0); - __pyx_2 = __Pyx_Import(__pyx_kp_18, ((PyObject *)__pyx_1)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = __Pyx_Import(__pyx_kp_25, ((PyObject *)__pyx_1)); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(((PyObject *)__pyx_1)); __pyx_1 = 0; __pyx_1 = PyObject_GetAttr(__pyx_2, __pyx_kp_i0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (PyObject_SetAttr(__pyx_m, __pyx_kp_i0, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_2); __pyx_2 = 0; - /* "/home/peridot/software/scipy/svn/trunk/scipy/stats/vonmises_cython.pyx":4 + /* "/usr/data/david/src/dsp/scipy/trunk/scipy/stats/vonmises_cython.pyx":4 * import scipy.stats * from scipy.special import i0 * import numpy.testing # <<<<<<<<<<<<<< * cimport numpy as np * */ - __pyx_2 = __Pyx_Import(__pyx_kp_19, 0); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_2 = __Pyx_Import(__pyx_kp_26, 0); if (unlikely(!__pyx_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (PyObject_SetAttr(__pyx_m, __pyx_kp_numpy, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_DECREF(__pyx_2); __pyx_2 = 0; - /* "/home/peridot/devlib/lib/python2.5/site-packages/Cython-0.9.8.1.1-py2.5-linux-i686.egg/Cython/Includes/numpy.pxd":36 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fullfill the PEP (specifically, + /* "/usr/data/david/local/lib64/python2.4/site-packages/Cython/Includes/stdlib.pxd":2 + * + * cdef extern from "stdlib.h": # <<<<<<<<<<<<<< + * ctypedef unsigned long size_t + * void free(void *ptr) */ #if PY_MAJOR_VERSION < 3 return; @@ -1982,14 +3019,140 @@ __pyx_f = __pyx_filenames; } -static INLINE void __Pyx_SafeReleaseBuffer(PyObject* obj, Py_buffer* info) { +static void __Pyx_RaiseDoubleKeywordsError( + const char* func_name, + PyObject* kw_name) +{ + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION >= 3 + "%s() got multiple values for keyword argument '%U'", func_name, kw_name); + #else + "%s() got multiple values for keyword argument '%s'", func_name, + PyString_AS_STRING(kw_name)); + #endif +} + +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *number, *more_or_less; + + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + number = (num_expected == 1) ? "" : "s"; + PyErr_Format(PyExc_TypeError, + #if PY_VERSION_HEX < 0x02050000 + "%s() takes %s %d positional argument%s (%d given)", + #else + "%s() takes %s %zd positional argument%s (%zd given)", + #endif + func_name, more_or_less, num_expected, number, num_found); +} + +static int __Pyx_ParseOptionalKeywords( + PyObject *kwds, + PyObject **argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject *key = 0, *value = 0; + Py_ssize_t pos = 0; + PyObject*** name; + PyObject*** first_kw_arg = argnames + num_pos_args; + + while (PyDict_Next(kwds, &pos, &key, &value)) { + #if PY_MAJOR_VERSION < 3 + if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) { + #else + if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) { + #endif + goto invalid_keyword_type; + } else { + name = argnames; + while (*name && (**name != key)) name++; + if (*name) { + if (name < first_kw_arg) goto arg_passed_twice; + values[name-argnames] = value; + } else { + for (name = first_kw_arg; *name; name++) { + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) break; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + strcmp(PyString_AS_STRING(**name), + PyString_AS_STRING(key)) == 0) break; + #endif + } + if (*name) { + values[name-argnames] = value; + } else { + /* unexpected keyword found */ + for (name=argnames; name != first_kw_arg; name++) { + if (**name == key) goto arg_passed_twice; + #if PY_MAJOR_VERSION >= 3 + if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) && + PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice; + #else + if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) && + strcmp(PyString_AS_STRING(**name), + PyString_AS_STRING(key)) == 0) goto arg_passed_twice; + #endif + } + if (kwds2) { + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else { + goto invalid_keyword; + } + } + } + } + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, **name); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%s() keywords must be strings", function_name); + goto bad; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + #if PY_MAJOR_VERSION < 3 + "%s() got an unexpected keyword argument '%s'", + function_name, PyString_AsString(key)); + #else + "%s() got an unexpected keyword argument '%U'", + function_name, key); + #endif +bad: + return -1; +} + +static INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(obj, info); + __Pyx_ReleaseBuffer(info); } static INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; + buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; @@ -1998,58 +3161,72 @@ static INLINE const char* __Pyx_ConsumeWhitespace(const char* ts) { while (1) { switch (*ts) { + case '@': case 10: case 13: case ' ': ++ts; + break; + case '=': + case '<': + case '>': + case '!': + PyErr_SetString(PyExc_ValueError, "Buffer acquisition error: Only native byte order, size and alignment supported."); + return NULL; default: return ts; } } } -static INLINE const char* __Pyx_BufferTypestringCheckEndian(const char* ts) { - int num = 1; - int little_endian = ((char*)&num)[0]; - int ok = 1; - switch (*ts) { - case '@': - case '=': - ++ts; break; - case '<': - if (little_endian) ++ts; - else ok = 0; - break; - case '>': - case '!': - if (!little_endian) ++ts; - else ok = 0; - break; - } - if (!ok) { - PyErr_Format(PyExc_ValueError, "Buffer has wrong endianness (rejecting on '%s')", ts); - return NULL; - } - return ts; -} - static void __Pyx_BufferNdimError(Py_buffer* buffer, int expected_ndim) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", expected_ndim, buffer->ndim); } +static const char* __Pyx_DescribeTokenInFormatString(const char* ts) { + switch (*ts) { + case 'b': return "char"; + case 'B': return "unsigned char"; + case 'h': return "short"; + case 'H': return "unsigned short"; + case 'i': return "int"; + case 'I': return "unsigned int"; + case 'l': return "long"; + case 'L': return "unsigned long"; + case 'q': return "long long"; + case 'Q': return "unsigned long long"; + case 'f': return "float"; + case 'd': return "double"; + case 'g': return "long double"; + case 'Z': switch (*(ts+1)) { + case 'f': return "complex float"; + case 'd': return "complex double"; + case 'g': return "complex long double"; + default: return "unparseable format string"; + } + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + default: return "unparseable format string"; + } +} -static const char* __Pyx_BufferTypestringCheck_item_double(const char* ts) { - if (*ts == '1') ++ts; - if (*ts != 'd') { - PyErr_Format(PyExc_ValueError, "Buffer datatype mismatch (expected 'd', got '%s')", ts); - return NULL; - } else return ts + 1; +static const char* __Pyx_CheckTypestring_double(const char* ts) { + int ok; + ts = __Pyx_ConsumeWhitespace(ts); if (!ts) return NULL; + if (*ts == '1') ++ts; + ok = (*ts == 'd'); + if (!(ok)) { + PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch (expected double, got %s)", __Pyx_DescribeTokenInFormatString(ts)); + return NULL; + } + ++ts; + return ts; + } -} - -static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd) { +static int __Pyx_GetBuffer_double(PyObject* obj, Py_buffer* buf, int flags, int nd, int cast) { const char* ts; if (obj == Py_None) { __Pyx_ZeroBuffer(buf); @@ -2061,18 +3238,26 @@ __Pyx_BufferNdimError(buf, nd); goto fail; } - ts = buf->format; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheckEndian(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - ts = __Pyx_BufferTypestringCheck_item_double(ts); - if (!ts) goto fail; - ts = __Pyx_ConsumeWhitespace(ts); - if (*ts != 0) { - PyErr_Format(PyExc_ValueError, - "Expected non-struct buffer data type (expected end, got '%s')", ts); - goto fail; + if (!cast) { + ts = buf->format; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + ts = __Pyx_CheckTypestring_double(ts); + if (!ts) goto fail; + ts = __Pyx_ConsumeWhitespace(ts); + if (!ts) goto fail; + if (*ts != 0) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch (expected end, got %s)", + __Pyx_DescribeTokenInFormatString(ts)); + goto fail; + } + } else { + if (buf->itemsize != sizeof(double)) { + PyErr_SetString(PyExc_ValueError, + "Attempted cast of buffer to datatype of different size."); + goto fail; + } } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; @@ -2086,21 +3271,40 @@ } -static INLINE void __Pyx_RaiseArgtupleTooLong( - Py_ssize_t num_expected, - Py_ssize_t num_found) -{ - const char* error_message = - #if PY_VERSION_HEX < 0x02050000 - "function takes at most %d positional arguments (%d given)"; - #else - "function takes at most %zd positional arguments (%zd given)"; - #endif - PyErr_Format(PyExc_TypeError, error_message, num_expected, num_found); + +static INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); } -#if (PY_MAJOR_VERSION < 3) && !(Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_NEWBUFFER) +static INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +} + + +#if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + #if PY_VERSION_HEX >= 0x02060000 + if (Py_TYPE(obj)->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER) + return PyObject_GetBuffer(obj, view, flags); + #endif if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pf_5numpy_7ndarray___getbuffer__(obj, view, flags); else { PyErr_Format(PyExc_TypeError, "'%100s' does not have the buffer interface", Py_TYPE(obj)->tp_name); @@ -2108,8 +3312,13 @@ } } -static void __Pyx_ReleaseBuffer(PyObject *obj, Py_buffer *view) { - +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject* obj = view->obj; + if (obj) { +if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pf_5numpy_7ndarray___releasebuffer__(obj, view); + Py_DECREF(obj); + view->obj = NULL; + } } #endif @@ -2195,7 +3404,30 @@ return 0; } +static INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { + PyThreadState *tstate = PyThreadState_GET(); + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +} +static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +} + static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) { Py_XINCREF(type); Py_XINCREF(value); @@ -2251,7 +3483,7 @@ } #endif } - PyErr_Restore(type, value, tb); + __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); @@ -2260,42 +3492,78 @@ return; } +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyThreadState *tstate = PyThreadState_GET(); + __Pyx_ErrFetch(type, value, tb); + PyErr_NormalizeException(type, value, tb); + if (PyErr_Occurred()) + goto bad; + Py_INCREF(*type); + Py_INCREF(*value); + Py_INCREF(*tb); + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = *type; + tstate->exc_value = *value; + tstate->exc_traceback = *tb; + /* Make sure tstate is in a consistent state when we XDECREF + these objects (XDECREF may run arbitrary code). */ + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + return 0; +bad: + Py_XDECREF(*type); + Py_XDECREF(*value); + Py_XDECREF(*tb); + return -1; +} + + static void __Pyx_WriteUnraisable(const char *name) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; - PyErr_Fetch(&old_exc, &old_val, &old_tb); + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); #if PY_MAJOR_VERSION < 3 ctx = PyString_FromString(name); #else ctx = PyUnicode_FromString(name); #endif - PyErr_Restore(old_exc, old_val, old_tb); - if (!ctx) - ctx = Py_None; - PyErr_WriteUnraisable(ctx); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } } #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(char *module_name, char *class_name, +static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, long size) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; + py_module = __Pyx_ImportModule(module_name); + if (!py_module) + goto bad; #if PY_MAJOR_VERSION < 3 - py_name = PyString_FromString(module_name); + py_name = PyString_FromString(class_name); #else - py_name = PyUnicode_FromString(module_name); + py_name = PyUnicode_FromString(class_name); #endif if (!py_name) goto bad; - - py_module = __Pyx_ImportModule(module_name); - if (!py_module) - goto bad; - result = PyObject_GetAttrString(py_module, class_name); + result = PyObject_GetAttr(py_module, py_name); + Py_DECREF(py_name); + py_name = 0; + Py_DECREF(py_module); + py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { @@ -2312,7 +3580,7 @@ } return (PyTypeObject *)result; bad: - Py_XDECREF(py_name); + Py_XDECREF(py_module); Py_XDECREF(result); return 0; } @@ -2320,7 +3588,7 @@ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(char *name) { +static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; @@ -2402,7 +3670,7 @@ ); if (!py_code) goto bad; py_frame = PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ + PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ From scipy-svn at scipy.org Mon Nov 10 09:54:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 08:54:33 -0600 (CST) Subject: [Scipy-svn] r5039 - trunk/scipy/lib/lapack/tests Message-ID: <20081110145433.65C2139C05F@scipy.org> Author: cdavid Date: 2008-11-10 08:54:25 -0600 (Mon, 10 Nov 2008) New Revision: 5039 Added: trunk/scipy/lib/lapack/tests/test_esv.py Log: Refactor syev* tests in scipy.lib.lapack. Added: trunk/scipy/lib/lapack/tests/test_esv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-10 13:20:36 UTC (rev 5038) +++ trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-10 14:54:25 UTC (rev 5039) @@ -0,0 +1,162 @@ +import numpy as np +from numpy.testing import TestCase, assert_array_almost_equal, dec, \ + assert_equal + +from scipy.lib.lapack import flapack, clapack + +SYEV_ARG = np.array([[1,2,3],[2,2,3],[3,3,6]]) +SYEV_REF = np.array([-0.6699243371851365, 0.4876938861533345, + 9.182230451031804]) + +FUNCS_TP = {'ssyev' : np.float32, + 'dsyev': np.float, + 'ssyevr' : np.float32, + 'dsyevr' : np.float} + +# Test FLAPACK if not empty +if hasattr(flapack, 'empty_module'): + FLAPACK_IS_EMPTY = True +else: + FLAPACK_IS_EMPTY = False + +# Test CLAPACK if not empty and not the same as clapack +if hasattr(clapack, 'empty_module') or (clapack == flapack): + CLAPACK_IS_EMPTY = True +else: + CLAPACK_IS_EMPTY = False + +if not FLAPACK_IS_EMPTY: + FUNCS_FLAPACK = {'ssyev' : flapack.ssyev, + 'dsyev': flapack.dsyev, + 'ssyevr' : flapack.ssyevr, + 'dsyevr' : flapack.dsyevr} + +if not CLAPACK_IS_EMPTY: + FUNCS_CLAPACK = {'ssyev' : clapack.ssyev, + 'dsyev': clapack.dsyev, + 'ssyevr' : clapack.ssyevr, + 'dsyevr' : clapack.dsyevr} + +PREC = {np.float32: 5, np.float: 12} + +class TestEsv(TestCase): + def _test_base(self, func, lang): + tp = FUNCS_TP[func] + a = SYEV_ARG.astype(tp) + if lang == 'C': + f = FUNCS_CLAPACK[func] + elif lang == 'F': + f = FUNCS_FLAPACK[func] + else: + raise ValueError("Lang %s ??" % lang) + + w, v, info = f(a) + + assert not info, `info` + assert_array_almost_equal(w, SYEV_REF, decimal=PREC[tp]) + for i in range(3): + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], + decimal=PREC[tp]) + + def _test_base_irange(self, func, irange, lang): + tp = FUNCS_TP[func] + a = SYEV_ARG.astype(tp) + if lang == 'C': + f = FUNCS_CLAPACK[func] + elif lang == 'F': + f = FUNCS_FLAPACK[func] + else: + raise ValueError("Lang %s ??" % lang) + + w, v, info = f(a, irange=irange) + rslice = slice(irange[0], irange[1]+1) + m = irange[1] - irange[0] + 1 + assert not info, `info` + + assert_equal(len(w),m) + assert_array_almost_equal(w, SYEV_REF[rslice], decimal=PREC[tp]) + + for i in range(m): + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], + decimal=PREC[tp]) + + def _test_base_vrange(self, func, vrange, lang): + tp = FUNCS_TP[func] + a = SYEV_ARG.astype(tp) + ew = [value for value in SYEV_REF if vrange[0] < value <= vrange[1]] + + if lang == 'C': + f = FUNCS_CLAPACK[func] + elif lang == 'F': + f = FUNCS_FLAPACK[func] + else: + raise ValueError("Lang %s ??" % lang) + + w, v, info = f(a, vrange=vrange) + assert not info, `info` + + assert_array_almost_equal(w, ew, decimal=PREC[tp]) + + for i in range(len(w)): + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], + decimal=PREC[tp]) + + def _test_syevr_ranges(self, func, lang): + for irange in ([0, 2], [0, 1], [1, 1], [1, 2]): + self._test_base_irange(func, irange, lang) + + for vrange in ([-1, 10], [-1, 1], [0, 1], [1, 10]): + self._test_base_vrange(func, vrange, lang) + + # Flapack tests + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_ssyev(self): + self._test_base('ssyev', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dsyev(self): + self._test_base('dsyev', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_ssyevr(self): + self._test_base('ssyevr', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dsyevr(self): + self._test_base('dsyevr', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_ssyevr_ranges(self): + self._test_syevr_ranges('ssyevr', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dsyevr_ranges(self): + self._test_syevr_ranges('dsyevr', 'F') + + # Clapack tests + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_ssyev(self): + self._test_base('ssyev', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_dsyev(self): + self._test_base('dsyev', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_ssyevr(self): + self._test_base('ssyevr', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_dsyevr(self): + self._test_base('dsyevr', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_ssyevr_ranges(self): + self._test_syevr_ranges('ssyevr', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_dsyevr_ranges(self): + self._test_syevr_ranges('dsyevr', 'C') + +if __name__=="__main__": + run_module_suite() From scipy-svn at scipy.org Mon Nov 10 09:54:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 08:54:57 -0600 (CST) Subject: [Scipy-svn] r5040 - trunk/scipy/lib/lapack/tests Message-ID: <20081110145457.8669839C1EC@scipy.org> Author: cdavid Date: 2008-11-10 08:54:44 -0600 (Mon, 10 Nov 2008) New Revision: 5040 Added: trunk/scipy/lib/lapack/tests/test_gesv.py Log: refactor gesv tests. Added: trunk/scipy/lib/lapack/tests/test_gesv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-10 14:54:25 UTC (rev 5039) +++ trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-10 14:54:44 UTC (rev 5040) @@ -0,0 +1,119 @@ +import numpy as np +from numpy.testing import TestCase, assert_array_almost_equal, dec, \ + assert_equal + +from scipy.lib.lapack import flapack, clapack + +A = np.array([[1,2,3],[2,2,3],[3,3,6]]) +B = np.array([[10,-1,1],[-1,8,-2],[1,-2,6]]) + +FUNCS_TP = {'ssygv' : np.float32, + 'dsygv': np.float, + 'ssygvd' : np.float32, + 'dsygvd' : np.float} + +# Test FLAPACK if not empty +if hasattr(flapack, 'empty_module'): + FLAPACK_IS_EMPTY = True +else: + FLAPACK_IS_EMPTY = False + +# Test CLAPACK if not empty and not the same as clapack +if hasattr(clapack, 'empty_module') or (clapack == flapack): + CLAPACK_IS_EMPTY = True +else: + CLAPACK_IS_EMPTY = False + +if not FLAPACK_IS_EMPTY: + FUNCS_FLAPACK = {'ssygv' : flapack.ssygv, + 'dsygv': flapack.dsygv, + 'ssygvd' : flapack.ssygvd, + 'dsygvd' : flapack.dsygvd} + +if not CLAPACK_IS_EMPTY: + FUNCS_CLAPACK = {'ssygv' : clapack.ssygv, + 'dsygv': clapack.dsygv, + 'ssygvd' : clapack.ssygvd, + 'dsygvd' : clapack.dsygvd} + + +PREC = {np.float32: 5, np.float: 12} + +class TestSygv(TestCase): + def _test_base(self, func, lang, itype): + tp = FUNCS_TP[func] + a = A.astype(tp) + b = B.astype(tp) + if lang == 'C': + f = FUNCS_CLAPACK[func] + elif lang == 'F': + f = FUNCS_FLAPACK[func] + else: + raise ValueError("Lang %s ??" % lang) + + w, v, info = f(a, b, itype=itype) + + assert not info, `info` + for i in range(3): + if itype == 1: + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*np.dot(b,v[:,i]), + decimal=PREC[tp]) + elif itype == 2: + assert_array_almost_equal(np.dot(a,np.dot(b,v[:,i])), w[i]*v[:,i], + decimal=PREC[tp]) + elif itype == 3: + assert_array_almost_equal(np.dot(b,np.dot(a,v[:,i])), + w[i]*v[:,i], decimal=PREC[tp] - 1) + else: + raise ValueError, `itype` + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_ssygv_1(self): + self._test_base('ssygv', 'F', 1) + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_ssygv_2(self): + self._test_base('ssygv', 'F', 2) + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_ssygv_3(self): + self._test_base('ssygv', 'F', 3) + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dsygv_1(self): + self._test_base('dsygv', 'F', 1) + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dsygv_2(self): + self._test_base('dsygv', 'F', 2) + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dsygv_3(self): + self._test_base('dsygv', 'F', 3) + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + def test_clapack_ssygv_1(self): + self._test_base('ssygv', 'C', 1) + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + def test_clapack_ssygv_2(self): + self._test_base('ssygv', 'C', 2) + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + def test_clapack_ssygv_3(self): + self._test_base('ssygv', 'C', 3) + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + def test_clapack_dsygv_1(self): + self._test_base('dsygv', 'C', 1) + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + def test_clapack_dsygv_2(self): + self._test_base('dsygv', 'C', 2) + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + def test_clapack_dsygv_3(self): + self._test_base('dsygv', 'C', 3) + +if __name__=="__main__": + run_module_suite() From scipy-svn at scipy.org Mon Nov 10 09:55:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 08:55:20 -0600 (CST) Subject: [Scipy-svn] r5041 - trunk/scipy/lib/lapack/tests Message-ID: <20081110145520.8DFF139C088@scipy.org> Author: cdavid Date: 2008-11-10 08:55:08 -0600 (Mon, 10 Nov 2008) New Revision: 5041 Added: trunk/scipy/lib/lapack/tests/common.py Modified: trunk/scipy/lib/lapack/tests/test_esv.py trunk/scipy/lib/lapack/tests/test_gesv.py Log: Refactor a bit more the tests From scipy-svn at scipy.org Mon Nov 10 09:55:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 08:55:51 -0600 (CST) Subject: [Scipy-svn] r5042 - trunk/scipy/lib/lapack/tests Message-ID: <20081110145551.E290339C088@scipy.org> Author: cdavid Date: 2008-11-10 08:55:31 -0600 (Mon, 10 Nov 2008) New Revision: 5042 Removed: trunk/scipy/lib/lapack/tests/esv_tests.py trunk/scipy/lib/lapack/tests/gesv_tests.py Modified: trunk/scipy/lib/lapack/tests/common.py trunk/scipy/lib/lapack/tests/test_lapack.py Log: Finish refactoring of lapack.lib tests. Modified: trunk/scipy/lib/lapack/tests/common.py =================================================================== --- trunk/scipy/lib/lapack/tests/common.py 2008-11-10 14:55:08 UTC (rev 5041) +++ trunk/scipy/lib/lapack/tests/common.py 2008-11-10 14:55:31 UTC (rev 5042) @@ -9,7 +9,13 @@ 'ssyev' : np.float32, 'dsyev': np.float, 'ssyevr' : np.float32, - 'dsyevr' : np.float} + 'dsyevr' : np.float, + 'ssyevr' : np.float32, + 'dsyevr' : np.float, + 'sgehrd' : np.float32, + 'dgehrd' : np.float, + 'sgebal' : np.float32, + 'dgebal': np.float} # Test FLAPACK if not empty if hasattr(flapack, 'empty_module'): @@ -31,7 +37,11 @@ 'ssyev' : flapack.ssyev, 'dsyev': flapack.dsyev, 'ssyevr' : flapack.ssyevr, - 'dsyevr' : flapack.dsyevr} + 'dsyevr' : flapack.dsyevr, + 'sgehrd' : flapack.sgehrd, + 'dgehrd' : flapack.dgehrd, + 'sgebal' : flapack.sgebal, + 'dgebal': flapack.dgebal} else: FUNCS_FLAPACK = None @@ -43,7 +53,11 @@ 'ssyev' : clapack.ssyev, 'dsyev': clapack.dsyev, 'ssyevr' : clapack.ssyevr, - 'dsyevr' : clapack.dsyevr} + 'dsyevr' : clapack.dsyevr, + 'sgehrd' : flapack.sgehrd, + 'dgehrd' : flapack.dgehrd, + 'sgebal' : clapack.sgebal, + 'dgebal': clapack.dgebal} else: FUNCS_CLAPACK = None Deleted: trunk/scipy/lib/lapack/tests/esv_tests.py =================================================================== --- trunk/scipy/lib/lapack/tests/esv_tests.py 2008-11-10 14:55:08 UTC (rev 5041) +++ trunk/scipy/lib/lapack/tests/esv_tests.py 2008-11-10 14:55:31 UTC (rev 5042) @@ -1,116 +0,0 @@ -import numpy as np -from numpy.testing import * -from numpy import dot - -class _test_ev(object): - - def check_syev(self,sym='sy',suffix=''): - a = [[1,2,3],[2,2,3],[3,3,6]] - exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] - f = getattr(self.lapack,sym+'ev'+suffix) - w,v,info=f(a) - assert not info,`info` - assert_array_almost_equal(w,exact_w) - for i in range(3): - assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i]) - - def check_syevd(self): self.check_syev(suffix='d') - - #def check_heev(self): self.check_syev(sym='he') - - #def check_heevd(self): self.check_syev(sym='he',suffix='d') - -## def check_heev_complex(self,suffix=''): -## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] -## exact_w=[-6.305141710654834,2.797880950890922,11.50726075976392] -## f = getattr(self.lapack,'heev'+suffix) -## w,v,info=f(a) -## assert not info,`info` -## assert_array_almost_equal(w,exact_w) -## for i in range(3): -## assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i],self.decimal) - - #def check_heevd_complex(self): self.check_heev_complex(suffix='d') - - def check_syevr(self,sym='sy'): - a = [[1,2,3],[2,2,3],[3,3,6]] - if self.lapack.prefix == 's': - exact_dtype = np.float32 - else: - exact_dtype = np.float - exact_w = np.array([-0.6699243371851365, 0.4876938861533345, - 9.182230451031804], exact_dtype) - f = getattr(self.lapack,sym+'evr') - w,v,info = f(a) - assert not info,`info` - assert_array_almost_equal(w,exact_w, decimal=self.decimal) - for i in range(3): - assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i], decimal=self.decimal) - -## def check_heevr_complex(self): -## a= [[1,2-2j,3+7j],[2+2j,2,3],[3-7j,3,5]] -## exact_w=[-6.305141710654834,2.797880950890922,11.50726075976392] -## f = self.lapack.heevr -## w,v,info = f(a) -## assert not info,`info` -## assert_array_almost_equal(w,exact_w) -## for i in range(3): -## assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i]) - -## def check_heevr(self): self.check_syevr(sym='he') - - def check_syevr_irange(self,sym='sy',irange=[0,2]): - a = [[1,2,3],[2,2,3],[3,3,6]] - if self.lapack.prefix == 's': - exact_dtype = np.float32 - else: - exact_dtype = np.float - exact_w = np.array([-0.6699243371851365, 0.4876938861533345, - 9.182230451031804], exact_dtype) - f = getattr(self.lapack,sym+'evr') - w,v,info = f(a,irange=irange) - assert not info,`info` - rslice = slice(irange[0],irange[1]+1) - m = irange[1] - irange[0] + 1 - assert_equal(len(w),m) - assert_array_almost_equal(w,exact_w[rslice], decimal=self.decimal) - for i in range(m): - assert_array_almost_equal(dot(a,v[:,i]),w[i]*v[:,i], decimal=self.decimal) - - def check_syevr_irange_low(self): self.check_syevr_irange(irange=[0,1]) - - def check_syevr_irange_mid(self): self.check_syevr_irange(irange=[1,1]) - - def check_syevr_irange_high(self): self.check_syevr_irange(irange=[1,2]) - -## def check_heevr_irange(self): self.check_syevr_irange(sym='he') - -## def check_heevr_irange_low(self): self.check_syevr_irange(sym='he',irange=[0,1]) - -## def check_heevr_irange_high(self): self.check_syevr_irange(sym='he',irange=[1,2]) - - def check_syevr_vrange(self,sym='sy',vrange=None): - a = [[1,2,3],[2,2,3],[3,3,6]] - exact_w = [-0.6699243371851365,0.4876938861533345,9.182230451031804] - if vrange is None: - vrange = [-1,10] - ew = [value for value in exact_w if vrange[0]1 and l[0]=='check': - return hasattr(self.lapack,l[1]) - return 2 + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_sgebal(self): + self._test_gebal_base('sgebal', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") + def test_dgebal(self): + self._test_gebal_base('dgebal', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip clapack test") + def test_sgehrd(self): + self._test_gehrd_base('sgehrd', 'F') + + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip clapack test") + def test_dgehrd(self): + self._test_gehrd_base('dgehrd', 'F') -class PrefixWrapper(object): - def __init__(self,module,prefix): - self.module = module - self.prefix = prefix - self.__doc__ = module.__doc__ - - def __getattr__(self, name): - class A: pass - a = getattr(self.module,self.prefix+name,getattr(self.module,name,A())) - if isinstance(a,A): - raise AttributeError,'%s has no attribute %r' % (self.module,name) - return a - -if hasattr(flapack,'empty_module'): - print """ -**************************************************************** -WARNING: flapack module is empty ------------ -See scipy/INSTALL.txt for troubleshooting. -**************************************************************** -""" -else: - class TestFlapackDouble(_TestLapack): - lapack = PrefixWrapper(flapack,'d') - decimal = 12 - class TestFlapackFloat(_TestLapack): - lapack = PrefixWrapper(flapack,'s') - decimal = 5 - class TestFlapackComplex(_TestLapack): - lapack = PrefixWrapper(flapack,'c') - decimal = 5 - class TestFlapackDoubleComplex(_TestLapack): - lapack = PrefixWrapper(flapack,'z') - decimal = 12 - -if hasattr(clapack,'empty_module') or clapack is flapack: - print """ -**************************************************************** -WARNING: clapack module is empty ------------ -See scipy/INSTALL.txt for troubleshooting. -Notes: -* If atlas library is not found by numpy/distutils/system_info.py, - then scipy uses flapack instead of clapack. -**************************************************************** -""" -else: - class TestClapackDouble(_TestLapack): - lapack = PrefixWrapper(clapack,'d') - decimal = 12 - class TestClapackFloat(_TestLapack): - lapack = PrefixWrapper(clapack,'s') - decimal = 5 - class TestClapackComplex(_TestLapack): - lapack = PrefixWrapper(clapack,'c') - decimal = 5 - class TestClapackDoubleComplex(_TestLapack): - lapack = PrefixWrapper(clapack,'z') - decimal = 12 - -# Collect test classes and methods with generator -# This is a moderate hack replicating some obscure numpy testing -# functionality for use with nose - -def test_all_lapack(): - methods = [] - for name, value in globals().items(): - if not (name.startswith('Test') - and issubclass(value, _TestLapack)): - continue - o = value() - methods += [getattr(o, n) for n in dir(o) if o.isrunnable(n) is True] - for method in methods: - yield (method, ) + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_sgebal(self): + self._test_gebal_base('sgebal', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_dgebal(self): + self._test_gebal_base('dgebal', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_sgehrd(self): + self._test_gehrd_base('sgehrd', 'C') + + @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + def test_clapack_dgehrd(self): + self._test_gehrd_base('dgehrd', 'C') From scipy-svn at scipy.org Mon Nov 10 10:34:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 09:34:39 -0600 (CST) Subject: [Scipy-svn] r5043 - trunk/scipy/linalg Message-ID: <20081110153439.619F739C0EA@scipy.org> Author: cdavid Date: 2008-11-10 09:34:27 -0600 (Mon, 10 Nov 2008) New Revision: 5043 Modified: trunk/scipy/linalg/decomp.py Log: Warn about econ argument for qr. Modified: trunk/scipy/linalg/decomp.py =================================================================== --- trunk/scipy/linalg/decomp.py 2008-11-10 14:55:31 UTC (rev 5042) +++ trunk/scipy/linalg/decomp.py 2008-11-10 15:34:27 UTC (rev 5043) @@ -1043,6 +1043,9 @@ ((9, 6), (6, 6)) """ + warn("""\ +qr econ argument will be removed after scipy 0.7. The economy transform will +then be available through the mode='economic' argument.""", DeprecationWarning) a1 = asarray_chkfinite(a) if len(a1.shape) != 2: raise ValueError("expected 2D array") From scipy-svn at scipy.org Mon Nov 10 10:35:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 09:35:00 -0600 (CST) Subject: [Scipy-svn] r5044 - trunk/scipy/lib/lapack/tests Message-ID: <20081110153500.99E2A39C0EA@scipy.org> Author: cdavid Date: 2008-11-10 09:34:50 -0600 (Mon, 10 Nov 2008) New Revision: 5044 Modified: trunk/scipy/lib/lapack/tests/common.py Log: Simplify funcs getter logic to make sure clapack and flapack have the same sets. Modified: trunk/scipy/lib/lapack/tests/common.py =================================================================== --- trunk/scipy/lib/lapack/tests/common.py 2008-11-10 15:34:27 UTC (rev 5043) +++ trunk/scipy/lib/lapack/tests/common.py 2008-11-10 15:34:50 UTC (rev 5044) @@ -29,35 +29,20 @@ else: CLAPACK_IS_EMPTY = False +funcs = ['ssygv', 'dsygv', 'ssygvd', 'dsygvd', 'ssyev', 'dsyev', 'ssyevr', + 'dsyevr', 'sgehrd', 'dgehrd', 'sgebal', 'dgebal'] + if not FLAPACK_IS_EMPTY: - FUNCS_FLAPACK = {'ssygv' : flapack.ssygv, - 'dsygv': flapack.dsygv, - 'ssygvd' : flapack.ssygvd, - 'dsygvd' : flapack.dsygvd, - 'ssyev' : flapack.ssyev, - 'dsyev': flapack.dsyev, - 'ssyevr' : flapack.ssyevr, - 'dsyevr' : flapack.dsyevr, - 'sgehrd' : flapack.sgehrd, - 'dgehrd' : flapack.dgehrd, - 'sgebal' : flapack.sgebal, - 'dgebal': flapack.dgebal} + FUNCS_FLAPACK = {} + for f in funcs: + FUNCS_FLAPACK[f] = getattr(flapack, f) else: FUNCS_FLAPACK = None if not CLAPACK_IS_EMPTY: - FUNCS_CLAPACK = {'ssygv' : clapack.ssygv, - 'dsygv': clapack.dsygv, - 'ssygvd' : clapack.ssygvd, - 'dsygvd' : clapack.dsygvd, - 'ssyev' : clapack.ssyev, - 'dsyev': clapack.dsyev, - 'ssyevr' : clapack.ssyevr, - 'dsyevr' : clapack.dsyevr, - 'sgehrd' : flapack.sgehrd, - 'dgehrd' : flapack.dgehrd, - 'sgebal' : clapack.sgebal, - 'dgebal': clapack.dgebal} + FUNCS_CLAPACK = {} + for f in funcs: + FUNCS_CLAPACK[f] = getattr(clapack, f) else: FUNCS_CLAPACK = None From scipy-svn at scipy.org Mon Nov 10 10:46:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 09:46:40 -0600 (CST) Subject: [Scipy-svn] r5045 - trunk/scipy/io/matlab/tests Message-ID: <20081110154640.C4E8939C05F@scipy.org> Author: cdavid Date: 2008-11-10 09:46:35 -0600 (Mon, 10 Nov 2008) New Revision: 5045 Modified: trunk/scipy/io/matlab/tests/test_mio.py Log: Mark regression test for #653 as a knownfailure. Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-10 15:34:50 UTC (rev 5044) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-10 15:46:35 UTC (rev 5045) @@ -13,7 +13,7 @@ from numpy.testing import \ assert_array_almost_equal, \ assert_equal, \ - assert_raises + assert_raises, dec from nose.tools import assert_true @@ -338,6 +338,8 @@ yield assert_raises, FutureWarning, savemat, StringIO(), {} warnings.resetwarnings() + at dec.knownfailureif(True, "Infinite recursion when writing a simple "\ + "dictionary to matlab file.") def test_regression_653(): """Regression test for #653.""" savemat(StringIO(), {'d':{1:2}}, format='5') From scipy-svn at scipy.org Mon Nov 10 10:49:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 09:49:11 -0600 (CST) Subject: [Scipy-svn] r5046 - trunk/scipy/linalg/tests Message-ID: <20081110154911.B17A539C05F@scipy.org> Author: tzito Date: 2008-11-10 09:48:31 -0600 (Mon, 10 Nov 2008) New Revision: 5046 Modified: trunk/scipy/linalg/tests/test_decomp.py Log: Added tests for linalg.eigh. Added functions in linalg/tests/test_decomp.py that should better go somewhere else: assert_dtype_equal -> numpy.testing hermitian, symrand, random_rot -> scipy.linalg Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-11-10 15:46:35 UTC (rev 5045) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-11-10 15:48:31 UTC (rev 5046) @@ -18,17 +18,97 @@ from scipy.linalg import eig,eigvals,lu,svd,svdvals,cholesky,qr, \ schur,rsf2csf, lu_solve,lu_factor,solve,diagsvd,hessenberg,rq, \ - eig_banded, eigvals_banded + eig_banded, eigvals_banded, eigh from scipy.linalg.flapack import dgbtrf, dgbtrs, zgbtrf, zgbtrs, \ dsbev, dsbevd, dsbevx, zhbevd, zhbevx from numpy import array, transpose, sometrue, diag, ones, linalg, \ argsort, zeros, arange, float32, complex64, dot, conj, identity, \ ravel, sqrt, iscomplex, shape, sort, conjugate, bmat, sign, \ - asarray, matrix, isfinite, all + asarray, matrix, isfinite, all, ndarray, outer, eye, dtype -from numpy.random import rand +from numpy.random import rand, normal +# digit precision to use in asserts for different types +DIGITS = {'d':12, 'D':12, 'f':6, 'F':6} + +# matrix dimension in tests +DIM = 5 + +# XXX: This function should be available through numpy.testing +def assert_dtype_equal(act, des): + if isinstance(act, ndarray): + act = act.dtype + else: + act = dtype(act) + + if isinstance(des, ndarray): + des = des.dtype + else: + des = dtype(des) + + assert act == des, 'dtype mismatch: "%s" (should be "%s") '%(act, des) + +# XXX: This function should not be defined here, but somewhere in +# scipy.linalg namespace +def hermitian(x): + """Return the Hermitian, i.e. conjugate transpose, of x.""" + return x.T.conj() + +# XXX: This function should not be defined here, but somewhere in +# scipy.linalg namespace +def symrand(dim_or_eigv, dtype="d"): + """Return a random symmetric (Hermitian) matrix. + + If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues + uniformly distributed on (0.1,1]. + + If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose + eigenvalues are sort(a). + """ + if isinstance(dim_or_eigv, int): + dim = dim_or_eigv + d = (rand(dim)*0.9)+0.1 + elif (isinstance(dim_or_eigv, ndarray) and + len(dim_or_eigv.shape) == 1): + dim = dim_or_eigv.shape[0] + d = dim_or_eigv + else: + raise TypeError("input type not supported.") + + v = random_rot(dim, dtype=dtype) + h = dot(dot(hermitian(v), diag(d)), v) + # to avoid roundoff errors, symmetrize the matrix (again) + return (0.5*(hermitian(h)+h)).astype(dtype) + +# XXX: This function should not be defined here, but somewhere in +# scipy.linalg namespace +def random_rot(dim, dtype='d'): + """Return a random rotation matrix, drawn from the Haar distribution + (the only uniform distribution on SO(n)). + The algorithm is described in the paper + Stewart, G.W., 'The efficient generation of random orthogonal + matrices with an application to condition estimators', SIAM Journal + on Numerical Analysis, 17(3), pp. 403-409, 1980. + For more information see + http://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization""" + H = eye(dim, dtype=dtype) + D = ones((dim, ), dtype=dtype) + for n in range(1, dim): + x = normal(size=(dim-n+1, )).astype(dtype) + D[n-1] = sign(x[0]) + x[0] -= D[n-1]*sqrt((x*x).sum()) + # Householder transformation + + Hx = eye(dim-n+1, dtype=dtype) - 2.*outer(x, x)/(x*x).sum() + mat = eye(dim, dtype=dtype) + mat[n-1:,n-1:] = Hx + H = dot(H, mat) + # Fix the last sign such that the determinant is 1 + D[-1] = -D.prod() + H = (D*H.T).T + return H + def random(size): return rand(*size) @@ -413,9 +493,37 @@ y_lin = linalg.solve(self.comp_mat, self.bc) assert_array_almost_equal(y, y_lin) +class TestEigH(TestCase): + def eigenproblem_standard(self, dim, dtype, overwrite, lower): + """Solve a standard eigenvalue problem.""" + a = symrand(dim, dtype) + if overwrite: + a_c = a.copy() + else: + a_c = a + w, z = eigh(a, lower=lower, overwrite_a = overwrite) + assert_dtype_equal(z.dtype, dtype) + w = w.astype(dtype) + diag_ = diag(dot(hermitian(z), dot(a_c, z))).real + assert_array_almost_equal(diag_, w, DIGITS[dtype]) + def test_eigh_real_standard(self): + self.eigenproblem_standard(DIM, 'd', False, False) + self.eigenproblem_standard(DIM, 'd', False, True) + self.eigenproblem_standard(DIM, 'd', True, True) + self.eigenproblem_standard(DIM, 'f', False, False) + self.eigenproblem_standard(DIM, 'f', False, True) + self.eigenproblem_standard(DIM, 'f', True, True) + + def test_eigh_complex_standard(self): + self.eigenproblem_standard(DIM, 'D', False, False) + self.eigenproblem_standard(DIM, 'D', False, True) + self.eigenproblem_standard(DIM, 'D', True, True) + self.eigenproblem_standard(DIM, 'F', False, False) + self.eigenproblem_standard(DIM, 'F', False, True) + self.eigenproblem_standard(DIM, 'F', True, True) - + class TestLU(TestCase): def __init__(self, *args, **kw): From scipy-svn at scipy.org Mon Nov 10 11:46:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 10:46:29 -0600 (CST) Subject: [Scipy-svn] r5047 - trunk/scipy/lib/lapack/tests Message-ID: <20081110164629.DA37D39C05F@scipy.org> Author: cdavid Date: 2008-11-10 10:46:24 -0600 (Mon, 10 Nov 2008) New Revision: 5047 Modified: trunk/scipy/lib/lapack/tests/common.py trunk/scipy/lib/lapack/tests/test_gesv.py Log: Handle missing ssygv in ATLAS clapack. Modified: trunk/scipy/lib/lapack/tests/common.py =================================================================== --- trunk/scipy/lib/lapack/tests/common.py 2008-11-10 15:48:31 UTC (rev 5046) +++ trunk/scipy/lib/lapack/tests/common.py 2008-11-10 16:46:24 UTC (rev 5047) @@ -42,7 +42,10 @@ if not CLAPACK_IS_EMPTY: FUNCS_CLAPACK = {} for f in funcs: - FUNCS_CLAPACK[f] = getattr(clapack, f) + try: + FUNCS_CLAPACK[f] = getattr(clapack, f) + except AttributeError: + FUNCS_CLAPACK[f] = None else: FUNCS_CLAPACK = None Modified: trunk/scipy/lib/lapack/tests/test_gesv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-10 15:48:31 UTC (rev 5046) +++ trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-10 16:46:24 UTC (rev 5047) @@ -60,15 +60,18 @@ def test_dsygv_3(self): self._test_base('dsygv', 'F', 3) - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], + "Clapack empty, skip flapack test") def test_clapack_ssygv_1(self): self._test_base('ssygv', 'C', 1) - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], + "Clapack empty, skip flapack test") def test_clapack_ssygv_2(self): self._test_base('ssygv', 'C', 2) - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], + "Clapack empty, skip flapack test") def test_clapack_ssygv_3(self): self._test_base('ssygv', 'C', 3) From scipy-svn at scipy.org Mon Nov 10 11:49:13 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 10:49:13 -0600 (CST) Subject: [Scipy-svn] r5048 - trunk/scipy/lib/lapack/tests Message-ID: <20081110164913.6DF6739C05F@scipy.org> Author: cdavid Date: 2008-11-10 10:49:08 -0600 (Mon, 10 Nov 2008) New Revision: 5048 Modified: trunk/scipy/lib/lapack/tests/test_esv.py Log: Handle missing dsyev in ATLAS clapack. Modified: trunk/scipy/lib/lapack/tests/test_esv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-10 16:46:24 UTC (rev 5047) +++ trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-10 16:49:08 UTC (rev 5048) @@ -108,7 +108,8 @@ def test_clapack_ssyev(self): self._test_base('ssyev', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyev"], + "Clapack empty, skip clapack test") def test_clapack_dsyev(self): self._test_base('dsyev', 'C') From scipy-svn at scipy.org Mon Nov 10 11:53:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 10:53:06 -0600 (CST) Subject: [Scipy-svn] r5049 - trunk/scipy/lib/lapack/tests Message-ID: <20081110165306.7005D39C05F@scipy.org> Author: cdavid Date: 2008-11-10 10:52:13 -0600 (Mon, 10 Nov 2008) New Revision: 5049 Modified: trunk/scipy/lib/lapack/tests/test_esv.py Log: Handle more missing funcs in ATLAS 3.6.0 clapack. Modified: trunk/scipy/lib/lapack/tests/test_esv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-10 16:49:08 UTC (rev 5048) +++ trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-10 16:52:13 UTC (rev 5049) @@ -104,7 +104,8 @@ self._test_syevr_ranges('dsyevr', 'F') # Clapack tests - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyev"], + "Clapack empty, skip clapack test") def test_clapack_ssyev(self): self._test_base('ssyev', 'C') @@ -113,19 +114,23 @@ def test_clapack_dsyev(self): self._test_base('dsyev', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyevr"], + "Clapack empty, skip clapack test") def test_clapack_ssyevr(self): self._test_base('ssyevr', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyevr"], + "Clapack empty, skip clapack test") def test_clapack_dsyevr(self): self._test_base('dsyevr', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyevr"], + "Clapack empty, skip clapack test") def test_clapack_ssyevr_ranges(self): self._test_syevr_ranges('ssyevr', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyevr"], + "Clapack empty, skip clapack test") def test_clapack_dsyevr_ranges(self): self._test_syevr_ranges('dsyevr', 'C') From scipy-svn at scipy.org Mon Nov 10 11:54:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 10:54:06 -0600 (CST) Subject: [Scipy-svn] r5050 - trunk/scipy/lib/lapack/tests Message-ID: <20081110165406.6526439C05F@scipy.org> Author: cdavid Date: 2008-11-10 10:54:01 -0600 (Mon, 10 Nov 2008) New Revision: 5050 Modified: trunk/scipy/lib/lapack/tests/test_gesv.py Log: Handle more missing funcs in ATLAS 3.6.0 clapack. Modified: trunk/scipy/lib/lapack/tests/test_gesv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-10 16:52:13 UTC (rev 5049) +++ trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-10 16:54:01 UTC (rev 5050) @@ -75,15 +75,18 @@ def test_clapack_ssygv_3(self): self._test_base('ssygv', 'C', 3) - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], + "Clapack empty, skip flapack test") def test_clapack_dsygv_1(self): self._test_base('dsygv', 'C', 1) - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], + "Clapack empty, skip flapack test") def test_clapack_dsygv_2(self): self._test_base('dsygv', 'C', 2) - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip flapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], + "Clapack empty, skip flapack test") def test_clapack_dsygv_3(self): self._test_base('dsygv', 'C', 3) From scipy-svn at scipy.org Mon Nov 10 11:55:44 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 10:55:44 -0600 (CST) Subject: [Scipy-svn] r5051 - trunk/scipy/lib/lapack/tests Message-ID: <20081110165544.D90FB39C05F@scipy.org> Author: cdavid Date: 2008-11-10 10:55:40 -0600 (Mon, 10 Nov 2008) New Revision: 5051 Modified: trunk/scipy/lib/lapack/tests/test_lapack.py Log: Handle last missing funcs in ATLAS 3.6.0 clapack. Modified: trunk/scipy/lib/lapack/tests/test_lapack.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_lapack.py 2008-11-10 16:54:01 UTC (rev 5050) +++ trunk/scipy/lib/lapack/tests/test_lapack.py 2008-11-10 16:55:40 UTC (rev 5051) @@ -67,18 +67,22 @@ def test_dgehrd(self): self._test_gehrd_base('dgehrd', 'F') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["sgebal"], + "Clapack empty, skip flapack test") def test_clapack_sgebal(self): self._test_gebal_base('sgebal', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dgebal"], + "Clapack empty, skip flapack test") def test_clapack_dgebal(self): self._test_gebal_base('dgebal', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["sgehrd"], + "Clapack empty, skip flapack test") def test_clapack_sgehrd(self): self._test_gehrd_base('sgehrd', 'C') - @dec.skipif(CLAPACK_IS_EMPTY, "Clapack empty, skip clapack test") + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dgehrd"], + "Clapack empty, skip flapack test") def test_clapack_dgehrd(self): self._test_gehrd_base('dgehrd', 'C') From scipy-svn at scipy.org Mon Nov 10 12:45:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 11:45:51 -0600 (CST) Subject: [Scipy-svn] r5052 - trunk/scipy/cluster/tests Message-ID: <20081110174551.C8AE639C0F1@scipy.org> Author: damian.eads Date: 2008-11-10 11:45:49 -0600 (Mon, 10 Nov 2008) New Revision: 5052 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Casted expected array from data file from float to int. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-10 16:55:40 UTC (rev 5051) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-10 17:45:49 UTC (rev 5052) @@ -428,28 +428,28 @@ def test_fclusterdata_maxclusts_2(self): "Tests fclusterdata(X, criterion='maxclust', t=2) on a random 3-cluster data set." - expectedT = eo['fclusterdata-maxclusts-2'] + expectedT = np.int_(eo['fclusterdata-maxclusts-2']) X = eo['Q-X'] T = fclusterdata(X, criterion='maxclust', t=2) self.failUnless(is_isomorphic(T, expectedT)) def test_fclusterdata_maxclusts_3(self): "Tests fclusterdata(X, criterion='maxclust', t=3) on a random 3-cluster data set." - expectedT = eo['fclusterdata-maxclusts-3'] + expectedT = np.int_(eo['fclusterdata-maxclusts-3']) X = eo['Q-X'] T = fclusterdata(X, criterion='maxclust', t=3) self.failUnless(is_isomorphic(T, expectedT)) def test_fclusterdata_maxclusts_4(self): "Tests fclusterdata(X, criterion='maxclust', t=4) on a random 3-cluster data set." - expectedT = eo['fclusterdata-maxclusts-4'] + expectedT = np.int_(eo['fclusterdata-maxclusts-4']) X = eo['Q-X'] T = fclusterdata(X, criterion='maxclust', t=4) self.failUnless(is_isomorphic(T, expectedT)) def test_fcluster_maxclusts_2(self): "Tests fcluster(Z, criterion='maxclust', t=2) on a random 3-cluster data set." - expectedT = eo['fclusterdata-maxclusts-2'] + expectedT = np.int_(eo['fclusterdata-maxclusts-2']) X = eo['Q-X'] Y = pdist(X) Z = linkage(Y) @@ -458,7 +458,7 @@ def test_fcluster_maxclusts_3(self): "Tests fcluster(Z, criterion='maxclust', t=3) on a random 3-cluster data set." - expectedT = eo['fclusterdata-maxclusts-3'] + expectedT = np.int_(eo['fclusterdata-maxclusts-3']) X = eo['Q-X'] Y = pdist(X) Z = linkage(Y) @@ -467,7 +467,7 @@ def test_fcluster_maxclusts_4(self): "Tests fcluster(Z, criterion='maxclust', t=4) on a random 3-cluster data set." - expectedT = eo['fclusterdata-maxclusts-4'] + expectedT = np.int_(eo['fclusterdata-maxclusts-4']) X = eo['Q-X'] Y = pdist(X) Z = linkage(Y) @@ -484,6 +484,7 @@ T = fcluster(Z, criterion='maxclust', t=3) Lright = (np.array([53, 55, 56]), np.array([2, 3, 1])) L = leaders(Z, T) + print L, Lright, T self.failUnless((L[0] == Lright[0]).all() and (L[1] == Lright[1]).all()) def help_single_inconsistent_depth(self, i): From scipy-svn at scipy.org Mon Nov 10 12:48:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 11:48:27 -0600 (CST) Subject: [Scipy-svn] r5053 - trunk/scipy/cluster Message-ID: <20081110174827.9EA4E39C0F1@scipy.org> Author: damian.eads Date: 2008-11-10 11:48:25 -0600 (Mon, 10 Nov 2008) New Revision: 5053 Modified: trunk/scipy/cluster/hierarchy.py Log: Changed np.int to 'i'. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-10 17:45:49 UTC (rev 5052) +++ trunk/scipy/cluster/hierarchy.py 2008-11-10 17:48:25 UTC (rev 5053) @@ -787,19 +787,23 @@ :Parameters: - Z : ndarray - The linkage matrix in proper form (see the ``linkage`` - function documentation). + - Z : ndarray + The linkage matrix in proper form (see the ``linkage`` + function documentation). - r : bool - When ``False``, a reference to the root ClusterNode object is - returned. Otherwise, a tuple (r,d) is returned. ``r`` is a - reference to the root node while ``d`` is a dictionary - mapping cluster ids to ClusterNode references. If a cluster id is - less than n, then it corresponds to a singleton cluster - (leaf node). See ``linkage`` for more information on the - assignment of cluster ids to clusters. + - r : bool + When ``False``, a reference to the root ClusterNode object is + returned. Otherwise, a tuple (r,d) is returned. ``r`` is a + reference to the root node while ``d`` is a dictionary + mapping cluster ids to ClusterNode references. If a cluster id is + less than n, then it corresponds to a singleton cluster + (leaf node). See ``linkage`` for more information on the + assignment of cluster ids to clusters. + :Returns: + - L : list + The pre-order traversal. + Note: This function is provided for the convenience of the library user. ClusterNodes are not used as input to any of the functions in this library. @@ -869,7 +873,7 @@ X = X.copy() return X -def cophenet(*args, **kwargs): +def cophenet(*args): """ Calculates the cophenetic distances between each observation in the hierarchical clustering defined by the linkage ``Z``. @@ -892,7 +896,7 @@ dimensions. ``Y`` is the condensed distance matrix from which ``Z`` was generated. - :Returns: + :Returns: (c, {d}) - c : ndarray The cophentic correlation distance (if ``y`` is passed). @@ -901,19 +905,6 @@ :math:`$ij$`th entry is the cophenetic distance between original observations :math:`$i$` and :math:`$j$`. - Calling Conventions - ------------------- - - 1. ``d = cophenet(Z)`` - Returns just the cophentic distance matrix. - - 2. ``c = cophenet(Z, Y)`` - Returns just the cophentic correlation coefficient. - - 3. ``(c, d) = cophenet(Z, Y, [])`` - Returns a tuple, ``(c, d)`` where ``c`` is the cophenetic - correlation coefficient and ``d`` is the condensed cophentic - distance matrix (upper triangular form). """ nargs = len(args) @@ -1342,7 +1333,7 @@ is_valid_linkage(Z, throw=True, name='Z') n = Z.shape[0] + 1 - T = np.zeros((n,), dtype=np.int) + T = np.zeros((n,), dtype='i') # Since the C code does not support striding using strides. # The dimensions are used instead. @@ -1446,7 +1437,7 @@ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') n = Z.shape[0] + 1 - ML = np.zeros((n,), dtype=np.int) + ML = np.zeros((n,), dtype='i') [Z] = _copy_arrays_if_base_present([Z]) _hierarchy_wrap.prelist_wrap(Z, ML, int(n)) return ML @@ -2368,7 +2359,7 @@ """ Z = np.asarray(Z, order='c') T = np.asarray(T, order='c') - if type(T) != np.ndarray or T.dtype != np.int: + if type(T) != np.ndarray or T.dtype != 'i': raise TypeError('T must be a one-dimensional numpy array of integers.') is_valid_linkage(Z, throw=True, name='Z') if len(T) != Z.shape[0] + 1: @@ -2376,8 +2367,8 @@ Cl = np.unique(T) kk = len(Cl) - L = np.zeros((kk,), dtype=np.int) - M = np.zeros((kk,), dtype=np.int) + L = np.zeros((kk,), dtype='i') + M = np.zeros((kk,), dtype='i') n = Z.shape[0] + 1 [Z, T] = _copy_arrays_if_base_present([Z, T]) s = _hierarchy_wrap.leaders_wrap(Z, T, L, M, int(kk), int(n)) From scipy-svn at scipy.org Mon Nov 10 14:01:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 13:01:16 -0600 (CST) Subject: [Scipy-svn] r5054 - in trunk/scipy/sparse: . tests Message-ID: <20081110190116.D5AC239C05F@scipy.org> Author: wnbell Date: 2008-11-10 13:01:13 -0600 (Mon, 10 Nov 2008) New Revision: 5054 Modified: trunk/scipy/sparse/construct.py trunk/scipy/sparse/sputils.py trunk/scipy/sparse/tests/test_construct.py Log: fixed bug in eye(1,1) caused by isshape([[1]]) returning True Modified: trunk/scipy/sparse/construct.py =================================================================== --- trunk/scipy/sparse/construct.py 2008-11-10 17:48:25 UTC (rev 5053) +++ trunk/scipy/sparse/construct.py 2008-11-10 19:01:13 UTC (rev 5054) @@ -103,7 +103,8 @@ """eye(m, n) returns a sparse (m x n) matrix where the k-th diagonal is all ones and everything else is zeros. """ - diags = np.ones((1, m), dtype=dtype) + m,n = int(m),int(n) + diags = np.ones((1, min(m,n)), dtype=dtype) return spdiags(diags, k, m, n).asformat(format) def kron(A, B, format=None): @@ -111,10 +112,10 @@ Parameters ---------- - A - matrix - B - matrix + A : sparse or dense matrix + first matrix of the product + B : sparse or dense matrix + second matrix of the product format : string format of the result (e.g. "csr") Modified: trunk/scipy/sparse/sputils.py =================================================================== --- trunk/scipy/sparse/sputils.py 2008-11-10 17:48:25 UTC (rev 5053) +++ trunk/scipy/sparse/sputils.py 2008-11-10 19:01:13 UTC (rev 5054) @@ -99,12 +99,14 @@ try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = x - assert isintlike(M) and isintlike(N) # raises TypeError unless integers - #assert M > 0 and N > 0 - except (ValueError, TypeError, AssertionError): + except: return False else: - return True + if isintlike(M) and isintlike(N): + if np.rank(M) == 0 and np.rank(N) == 0: + return True + return False + def issequence(t): return isinstance(t, (list, tuple))\ Modified: trunk/scipy/sparse/tests/test_construct.py =================================================================== --- trunk/scipy/sparse/tests/test_construct.py 2008-11-10 17:48:25 UTC (rev 5053) +++ trunk/scipy/sparse/tests/test_construct.py 2008-11-10 19:01:13 UTC (rev 5054) @@ -76,18 +76,13 @@ assert_equal( I.toarray(), [[1,0,0],[0,1,0],[0,0,1]]) def test_eye(self): - a = eye(2, 3 ) - b = array([[1, 0, 0], [0, 1, 0]], dtype='d') - assert_array_equal(a.toarray(), b) + assert_equal(eye(1,1).toarray(), [[1]]) + assert_equal(eye(2,3).toarray(), [[1,0,0],[0,1,0]]) + assert_equal(eye(3,2).toarray(), [[1,0],[0,1],[0,0]]) + assert_equal(eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]]) - a = eye(3, 2) - b = array([[1, 0], [0, 1], [0, 0]], dtype='d') - assert_array_equal( a.toarray(), b) + assert_equal(eye(3,3,dtype='int16').dtype, 'int16') - a = eye(3, 3) - b = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='d') - assert_array_equal(a.toarray(), b) - def test_kron(self): cases = [] From scipy-svn at scipy.org Mon Nov 10 17:50:42 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 16:50:42 -0600 (CST) Subject: [Scipy-svn] r5055 - in trunk/scipy/interpolate: . tests Message-ID: <20081110225042.71CEF39C05F@scipy.org> Author: ptvirtan Date: 2008-11-10 16:50:30 -0600 (Mon, 10 Nov 2008) New Revision: 5055 Modified: trunk/scipy/interpolate/interpolate.py trunk/scipy/interpolate/tests/test_interpolate.py Log: Make interp1d treat scalars differently from 1-d arrays (fixes #660) Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-10 19:01:13 UTC (rev 5054) +++ trunk/scipy/interpolate/interpolate.py 2008-11-10 22:50:30 UTC (rev 5055) @@ -286,7 +286,7 @@ return result.reshape(x_new.shape+result.shape[1:]) def __call__(self, x_new): - """ Find linearly interpolated y_new = f(x_new). + """Find interpolated y_new = f(x_new). Parameters ---------- @@ -296,13 +296,14 @@ Returns ------- y_new : number or array - Linearly interpolated value(s) corresponding to x_new. + Interpolated value(s) corresponding to x_new. + """ # 1. Handle values in x_new that are outside of x. Throw error, # or return a list of mask array indicating the outofbounds values. # The behavior is set by the bounds_error variable. - x_new = atleast_1d(x_new) + x_new = asarray(x_new) out_of_bounds = self._check_bounds(x_new) y_new = self._call(x_new) @@ -318,7 +319,15 @@ # and # 7. Rotate the values back to their proper place. - if self._kind == 'linear': + if nx == 0: + # special case: x is a scalar + if out_of_bounds: + if ny == 0: + return self.fill_value + else: + y_new[...] = self.fill_value + return y_new + elif self._kind == 'linear': y_new[..., out_of_bounds] = self.fill_value axes = range(ny - nx) axes[self.axis:self.axis] = range(ny - nx, ny) @@ -330,7 +339,7 @@ return y_new.transpose(axes) def _check_bounds(self, x_new): - """ Check the inputs for being in the bounds of the interpolated data. + """Check the inputs for being in the bounds of the interpolated data. Parameters ---------- Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-10 19:01:13 UTC (rev 5054) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-10 22:50:30 UTC (rev 5055) @@ -158,13 +158,17 @@ bounds_error=False, kind=kind) assert_array_equal( extrap10(11.2), - np.array([self.fill_value]), + np.array(self.fill_value), ) assert_array_equal( extrap10(-3.4), - np.array([self.fill_value]), + np.array(self.fill_value), ) assert_array_equal( + extrap10([[[11.2], [-3.4], [12.6], [19.3]]]), + np.array(self.fill_value), + ) + assert_array_equal( extrap10._check_bounds(np.array([-1.0, 0.0, 5.0, 9.0, 11.0])), np.array([True, False, False, False, True]), ) @@ -193,7 +197,7 @@ interp210 = interp1d(self.x10, self.y210, kind=kind) assert_array_almost_equal( interp210(1.5), - np.array([[1.5], [11.5]]), + np.array([1.5, 11.5]), ) assert_array_almost_equal( interp210(np.array([1.5, 2.4])), @@ -204,7 +208,7 @@ interp102 = interp1d(self.x10, self.y102, axis=0, kind=kind) assert_array_almost_equal( interp102(1.5), - np.array([[3.0, 4.0]]), + np.array([3.0, 4.0]), ) assert_array_almost_equal( interp102(np.array([1.5, 2.4])), From scipy-svn at scipy.org Mon Nov 10 18:03:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 17:03:52 -0600 (CST) Subject: [Scipy-svn] r5056 - in trunk/scipy/interpolate: . tests Message-ID: <20081110230352.17A3C39C05F@scipy.org> Author: ptvirtan Date: 2008-11-10 17:03:38 -0600 (Mon, 10 Nov 2008) New Revision: 5056 Modified: trunk/scipy/interpolate/interpolate.py trunk/scipy/interpolate/tests/test_interpolate.py Log: Ensure interp1d.__call__ always returns an ndarray, not an array scalar, for 0-dim output. Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-10 22:50:30 UTC (rev 5055) +++ trunk/scipy/interpolate/interpolate.py 2008-11-10 23:03:38 UTC (rev 5056) @@ -295,7 +295,7 @@ Returns ------- - y_new : number or array + y_new : ndarray Interpolated value(s) corresponding to x_new. """ @@ -323,10 +323,10 @@ # special case: x is a scalar if out_of_bounds: if ny == 0: - return self.fill_value + return asarray(self.fill_value) else: y_new[...] = self.fill_value - return y_new + return asarray(y_new) elif self._kind == 'linear': y_new[..., out_of_bounds] = self.fill_value axes = range(ny - nx) Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-10 22:50:30 UTC (rev 5055) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-10 23:03:38 UTC (rev 5056) @@ -186,6 +186,7 @@ def _nd_check(self, kind='linear'): """ Check the behavior when the inputs and outputs are multidimensional. """ + # Multidimensional input. interp10 = interp1d(self.x10, self.y10, kind=kind) assert_array_almost_equal( @@ -193,6 +194,10 @@ np.array([[3.4, 5.6], [2.4, 7.8]]), ) + # Scalar input -> 0-dim scalar array output + self.failUnless(isinstance(interp10(1.2), np.ndarray)) + assert_equal(interp10(1.2).shape, ()) + # Multidimensional outputs. interp210 = interp1d(self.x10, self.y210, kind=kind) assert_array_almost_equal( From scipy-svn at scipy.org Mon Nov 10 22:21:00 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 10 Nov 2008 21:21:00 -0600 (CST) Subject: [Scipy-svn] r5057 - trunk/scipy/sparse/linalg/dsolve Message-ID: <20081111032100.687FA39C0EA@scipy.org> Author: jarrod.millman Date: 2008-11-10 21:20:57 -0600 (Mon, 10 Nov 2008) New Revision: 5057 Modified: trunk/scipy/sparse/linalg/dsolve/_csuperlumodule.c trunk/scipy/sparse/linalg/dsolve/_dsuperlumodule.c trunk/scipy/sparse/linalg/dsolve/_ssuperlumodule.c trunk/scipy/sparse/linalg/dsolve/_zsuperlumodule.c Log: relicensing LGPL code under the revised BSD license per personal correspondance with the copyright holder, Travis Oliphant Modified: trunk/scipy/sparse/linalg/dsolve/_csuperlumodule.c =================================================================== --- trunk/scipy/sparse/linalg/dsolve/_csuperlumodule.c 2008-11-10 23:03:38 UTC (rev 5056) +++ trunk/scipy/sparse/linalg/dsolve/_csuperlumodule.c 2008-11-11 03:20:57 UTC (rev 5057) @@ -1,6 +1,6 @@ /* Copyright 1999 Travis Oliphant - Permision to copy and modified this file is granted under the LGPL. + Permision to copy and modified this file is granted under the revised BSD license. No warranty is expressed or IMPLIED */ Modified: trunk/scipy/sparse/linalg/dsolve/_dsuperlumodule.c =================================================================== --- trunk/scipy/sparse/linalg/dsolve/_dsuperlumodule.c 2008-11-10 23:03:38 UTC (rev 5056) +++ trunk/scipy/sparse/linalg/dsolve/_dsuperlumodule.c 2008-11-11 03:20:57 UTC (rev 5057) @@ -1,6 +1,6 @@ /* Copyright 1999 Travis Oliphant - Permision to copy and modified this file is granted under the LGPL. + Permision to copy and modified this file is granted under the revised BSD license. No warranty is expressed or IMPLIED */ Modified: trunk/scipy/sparse/linalg/dsolve/_ssuperlumodule.c =================================================================== --- trunk/scipy/sparse/linalg/dsolve/_ssuperlumodule.c 2008-11-10 23:03:38 UTC (rev 5056) +++ trunk/scipy/sparse/linalg/dsolve/_ssuperlumodule.c 2008-11-11 03:20:57 UTC (rev 5057) @@ -1,6 +1,6 @@ /* Copyright 1999 Travis Oliphant - Permision to copy and modified this file is granted under the LGPL. + Permision to copy and modified this file is granted under the revised BSD license. No warranty is expressed or IMPLIED */ Modified: trunk/scipy/sparse/linalg/dsolve/_zsuperlumodule.c =================================================================== --- trunk/scipy/sparse/linalg/dsolve/_zsuperlumodule.c 2008-11-10 23:03:38 UTC (rev 5056) +++ trunk/scipy/sparse/linalg/dsolve/_zsuperlumodule.c 2008-11-11 03:20:57 UTC (rev 5057) @@ -1,6 +1,6 @@ /* Copyright 1999 Travis Oliphant - Permision to copy and modified this file is granted under the LGPL. + Permision to copy and modified this file is granted under the revised BSD license. No warranty is expressed or IMPLIED Changes: 2004 converted to SuperLU_3.0 and added factor and solve routines for From scipy-svn at scipy.org Tue Nov 11 02:33:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 11 Nov 2008 01:33:10 -0600 (CST) Subject: [Scipy-svn] r5058 - trunk/scipy/weave/blitz/blitz Message-ID: <20081111073310.34FE539C05F@scipy.org> Author: jarrod.millman Date: 2008-11-11 01:32:57 -0600 (Tue, 11 Nov 2008) New Revision: 5058 Removed: trunk/scipy/weave/blitz/blitz/rand-mt.h Log: removed older Mersenne Twister LGPL code since it isn't used anywhere. if this needs to be re-added, we should add the newer BSD licensed version Deleted: trunk/scipy/weave/blitz/blitz/rand-mt.h =================================================================== --- trunk/scipy/weave/blitz/blitz/rand-mt.h 2008-11-11 03:20:57 UTC (rev 5057) +++ trunk/scipy/weave/blitz/blitz/rand-mt.h 2008-11-11 07:32:57 UTC (rev 5058) @@ -1,167 +0,0 @@ -/* A C-program for MT19937: Integer version (1998/4/6) */ -/* genrand() generates one pseudorandom unsigned integer (32bit) */ -/* which is uniformly distributed among 0 to 2^32-1 for each */ -/* call. sgenrand(seed) set initial values to the working area */ -/* of 624 words. Before genrand(), sgenrand(seed) must be */ -/* called once. (seed is any 32-bit integer except for 0). */ -/* Coded by Takuji Nishimura, considering the suggestions by */ -/* Topher Cooper and Marc Rieffel in July-Aug. 1997. */ - -/* This library is free software; you can redistribute it and/or */ -/* modify it under the terms of the GNU Library General Public */ -/* License as published by the Free Software Foundation; either */ -/* version 2 of the License, or (at your option) any later */ -/* version. */ -/* This library is distributed in the hope that it will be useful, */ -/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ -/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ -/* See the GNU Library General Public License for more details. */ -/* You should have received a copy of the GNU Library General */ -/* Public License along with this library; if not, write to the */ -/* Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA */ -/* 02111-1307 USA */ - -/* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */ -/* When you use this, send an email to: matumoto at math.keio.ac.jp */ -/* with an appropriate reference to your work. */ - -/* REFERENCE */ -/* M. Matsumoto and T. Nishimura, */ -/* "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform */ -/* Pseudo-Random Number Generator", */ -/* ACM Transactions on Modeling and Computer Simulation, */ -/* Vol. 8, No. 1, January 1998, pp 3--30. */ - -// See http://www.math.keio.ac.jp/~matumoto/emt.html - -// 1999-01-25 adapted to STL-like idiom -// allan at stokes.ca (Allan Stokes) www.stokes.ca - -#ifndef BZ_RAND_MT -#define BZ_RAND_MT - -#ifndef BZ_BLITZ_H - #include -#endif - -#include - -BZ_NAMESPACE(blitz) - -// decomposition issues: -// machine representation of integer types -// output buffer option verses inline post-conditioning - -class MersenneTwister -{ -private: - typedef unsigned int twist_int; // must be at least 32 bits - // larger might be faster - typedef vector State; - typedef State::iterator Iter; - - struct BitMixer { - enum { K = 0x9908b0df }; - BitMixer() : s0(0) {} - inline friend twist_int low_mask (twist_int s1) { - return (s1&1u) ? K : 0u; - } - inline twist_int high_mask (twist_int s1) const { - return ((s0&0x80000000)|(s1&0x7fffffff))>>1; - } - inline twist_int operator() (twist_int s1) { - twist_int r = high_mask(s1) ^ low_mask(s1); - s0 = s1; - return r; - } - twist_int s0; - }; - -enum { N = 624, PF = 397, reference_seed = 4357 }; - -public: - MersenneTwister () {} // S empty will trigger auto-seed - - void seed (twist_int seed = reference_seed) - { - if (!S.size()) S.resize(N); - enum { Knuth_A = 69069 }; - twist_int x = seed & 0xFFFFFFFF; - Iter s = S.begin(); - twist_int mask = (seed == reference_seed) ? 0 : 0xFFFFFFFF; - for (int j = 0; j < N; ++j) { - // adding j here avoids the risk of all zeros - // we suppress this term in "compatibility" mode - *s++ = (x + (mask & j)) & 0xFFFFFFFF; - x *= Knuth_A; - } - reload(); - } - - void reload (void) - { - if (!S.size()) seed (); // auto-seed detection - - Iter p0 = S.begin(); - Iter pM = p0 + PF; - BitMixer twist; - twist (S[0]); // prime the pump - for (Iter pf_end = S.begin()+(N-PF); p0 != pf_end; ++p0, ++pM) - *p0 = *pM ^ twist (p0[1]); - pM = S.begin(); - for (Iter s_end = S.begin()+(N-1); p0 != s_end; ++p0, ++pM) - *p0 = *pM ^ twist (p0[1]); - *p0 = *pM ^ twist (S[0]); - - I = S.begin(); - } - - inline twist_int random (void) - { - if (I >= S.end()) reload(); - twist_int y = *I++; - y ^= (y >> 11); - y ^= (y << 7) & 0x9D2C5680; - y ^= (y << 15) & 0xEFC60000; - y ^= (y >> 18); - return y; - } - -private: - State S; - Iter I; -}; - - -// This version returns a double in the range [0,1). - -class MersenneTwisterDouble { - -public: - MersenneTwisterDouble() - { - // f = 1/(2^32); - f = (1.0 / 65536) / 65536; - } - - void randomize(unsigned int seed) - { - gen_.seed(seed); - } - - double random() - { - unsigned long y1 = gen_.random(); - unsigned long y2 = gen_.random(); - - return ((y1 * f) * y2 * f); - } - -private: - MersenneTwister gen_; - double f; -}; - -BZ_NAMESPACE_END - -#endif // BZ_RAND_MT From scipy-svn at scipy.org Tue Nov 11 04:03:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 11 Nov 2008 03:03:29 -0600 (CST) Subject: [Scipy-svn] r5059 - in trunk/scipy/io/matlab: . tests Message-ID: <20081111090329.1F2C539C05F@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-11 03:03:27 -0600 (Tue, 11 Nov 2008) New Revision: 5059 Modified: trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/tests/test_mio.py Log: Further checks on input types for writing, to fix recursion write error. Moved function as well as object to own array class Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-11-11 07:32:57 UTC (rev 5058) +++ trunk/scipy/io/matlab/mio5.py 2008-11-11 09:03:27 UTC (rev 5059) @@ -173,91 +173,28 @@ pass -class MatlabObject(object): - ''' Class to contain data read from matlab objects +class MatlabFunction(np.ndarray): + ''' class to signal this is a matlab function ''' + def __new__(cls, input_array): + return np.asarray(input_array).view(cls) - Contains classname, and record array for field names and values - Attribute access fetches and sets record array fields if present +class MatlabObject(np.ndarray): + def __new__(cls, input_array, classname=None): + # Input array is an already formed ndarray instance + # We first cast to be our class type + obj = np.asarray(input_array).view(cls) + # add the new attribute to the created instance + obj.classname = classname + # Finally, we must return the newly created object: + return obj - ''' - def __init__(self, classname, fields): - """ Initialize MatlabObject + def __array_finalize__(self,obj): + # reset the attribute from passed original object + self.classname = getattr(obj, 'classname', None) + # We do not need to return anything - Parameters - ---------- - self : object - classname : string - class name for matlab object - fields : {recarray, string list} - either a recarray or a list of field names - >>> import numpy as np - >>> arr = np.zeros((1,1),dtype=[('field1','i2'),('field2','i2')]) - >>> obj = MatlabObject('myclass', arr) - >>> obj = MatlabObject('myclass', ['field1', 'field2']) - - """ - # Initialize to make field setting work with __setattr__ - self.__dict__['_fields'] = [] - self.classname = classname - try: # recarray - fdict = fields.dtype.fields - except AttributeError: # something else - fields = tuple(fields) - else: # recarray again - self._fields = fdict.keys() - self.mobj_recarray = fields - return - # something else again - self._fields = fields - dtype = [(field, object) for field in fields] - self.mobj_recarray = np.zeros((1,1), dtype) - - def __getattr__(self, name): - ''' get attributes from object - - Get attribute if present, otherwise field from recarray - - >>> import numpy as np - >>> arr = np.zeros((1,1),dtype=[('field1','i2'),('field2','i2')]) - >>> obj = MatlabObject('myclass', arr) - >>> obj.field1 - array([[0]], dtype=int16) - >>> obj = MatlabObject('myclass', ['field1', 'field2']) - >>> obj.field1 - array([[0]], dtype=object) - >>> obj.classname - 'myclass' - ''' - if name in self.__dict__: - return self.__dict__[name] - mobj_recarray = self.__dict__['mobj_recarray'] - if name in self.__dict__['_fields']: - return mobj_recarray[name] - else: - raise AttributeError( - "no field named %s in MatlabObject" % name) - - def __setattr__(self, name, value): - ''' set attributes in object - - Set field value from recarray, if present, else attribute - - >>> import numpy as np - >>> arr = np.zeros((1,1),dtype=[('field1','i2'),('field2','i2')]) - >>> obj = MatlabObject('myclass', arr) - >>> obj.field1[0,0] = 1 - >>> obj.strangename = 'test' - >>> obj.strangename - 'test' - ''' - if name in self._fields: - self.mobj_recarray[name] = value - else: - self.__dict__[name] = value - - class Mat5ArrayReader(MatArrayReader): ''' Class to get Mat5 arrays @@ -265,7 +202,13 @@ factory function ''' - def __init__(self, mat_stream, dtypes, processor_func, codecs, class_dtypes, struct_as_record): + def __init__(self, + mat_stream, + dtypes, + processor_func, + codecs, + class_dtypes, + struct_as_record): super(Mat5ArrayReader, self).__init__(mat_stream, dtypes, processor_func) @@ -508,6 +451,7 @@ def get_item(self): return self.read_element() + class Mat5StructMatrixGetter(Mat5MatrixGetter): def __init__(self, array_reader, header): super(Mat5StructMatrixGetter, self).__init__(array_reader, header) @@ -535,34 +479,21 @@ for name in field_names: item.__dict__[name] = self.read_element() result[i] = item - return result.reshape(tupdims).T -class Mat5ObjectMatrixGetter(Mat5MatrixGetter): - def get_array(self): +class Mat5ObjectMatrixGetter(Mat5StructMatrixGetter): + def get_raw_array(self): '''Matlab ojects are essentially structs, with an extra field, the classname.''' classname = self.read_element().tostring() - namelength = self.read_element()[0] - names = self.read_element() - field_names = [names[i:i+namelength].tostring().strip('\x00') - for i in xrange(0,len(names),namelength)] - result = MatlabObject(classname, field_names) + result = super(Mat5ObjectMatrixGetter, self).get_raw_array() + return MatlabObject(result, classname) - for field_name in field_names: - result.__setattr__(field_name, self.read_element()) - return result - - -class MatlabFunctionMatrix: - ''' Opaque object representing an array of function handles. ''' - def __init__(self, arr): - self.arr = arr - class Mat5FunctionMatrixGetter(Mat5CellMatrixGetter): - def get_array(self): - return MatlabFunctionMatrix(self.get_raw_array()) + def get_raw_array(self): + result = super(Mat5ObjectMatrixGetter, self).get_raw_array() + return MatlabFunction(result) class MatFile5Reader(MatFileReader): @@ -688,10 +619,16 @@ mat_tag = np.zeros((), mdtypes_template['tag_full']) mat_tag['mdtype'] = miMATRIX - def __init__(self, file_stream, arr, name, is_global=False): + def __init__(self, + file_stream, + arr, + name, + is_global=False, + unicode_strings=False): super(Mat5MatrixWriter, self).__init__(file_stream, arr, name) self.is_global = is_global - + self.unicode_strings = unicode_strings + def write_dtype(self, arr): self.file_stream.write(arr.tostring()) @@ -838,13 +775,7 @@ self.update_matrix_tag() -class Mat5CompositeWriter(Mat5MatrixWriter): - def __init__(self, file_stream, arr, name, is_global=False, unicode_strings=False): - super(Mat5CompositeWriter, self).__init__(file_stream, arr, name, is_global) - self.unicode_strings = unicode_strings - - -class Mat5CellWriter(Mat5CompositeWriter): +class Mat5CellWriter(Mat5MatrixWriter): def write(self): self.write_header(mclass=mxCELL_CLASS) # loop over data, column major @@ -855,10 +786,8 @@ MW.write() self.update_matrix_tag() -class Mat5FunctionWriter(Mat5CompositeWriter): - def __init__(self, file_stream, arr, name, is_global=False, unicode_strings=False): - super(Mat5FunctionWriter, self).__init__(file_stream, arr.arr, name, is_global) +class Mat5FunctionWriter(Mat5MatrixWriter): def write(self): self.write_header(mclass=mxFUNCTION_CLASS) # loop over data, column major @@ -870,48 +799,35 @@ self.update_matrix_tag() -class Mat5StructWriter(Mat5CompositeWriter): +class Mat5StructWriter(Mat5MatrixWriter): def write(self): self.write_header(mclass=mxSTRUCT_CLASS) + self.write_fields() + def write_fields(self): # write fieldnames fieldnames = [f[0] for f in self.arr.dtype.descr] self.write_element(np.array([32], dtype='i4')) - self.write_element(np.array(fieldnames, dtype='S32'), mdtype=miINT8) - + self.write_element(np.array(fieldnames, dtype='S32'), + mdtype=miINT8) A = np.atleast_2d(self.arr).flatten('F') - MWG = Mat5WriterGetter(self.file_stream, self.unicode_strings) + MWG = Mat5WriterGetter(self.file_stream, + self.unicode_strings) for el in A: for f in fieldnames: MW = MWG.matrix_writer_factory(el[f], '') MW.write() self.update_matrix_tag() -class Mat5ObjectWriter(Mat5CompositeWriter): - def __init__(self, file_stream, arr, name, is_global=False, unicode_strings=False): - super(Mat5ObjectWriter, self).__init__(file_stream, arr.__dict__['mobj_recarray'], name, is_global) - self.classname = arr.classname +class Mat5ObjectWriter(Mat5StructWriter): def write(self): self.write_header(mclass=mxOBJECT_CLASS) + self.write_element(np.array(self.arr.classname, dtype='S'), + mdtype=miINT8) + self.write_fields() - # write classnames - self.write_element(np.array(self.classname, dtype='S'), mdtype=miINT8) - # write fieldnames - fieldnames = [f[0] for f in self.arr.dtype.descr] - self.write_element(np.array([32], dtype='i4')) - self.write_element(np.array(fieldnames, dtype='S32'), mdtype=miINT8) - - A = np.atleast_2d(self.arr).flatten('F') - MWG = Mat5WriterGetter(self.file_stream, self.unicode_strings) - for el in A: - for f in fieldnames: - MW = MWG.matrix_writer_factory(el[f], '') - MW.write() - self.update_matrix_tag() - - class Mat5WriterGetter(object): ''' Wraps stream and options, provides methods for getting Writer objects ''' def __init__(self, stream, unicode_strings): @@ -923,33 +839,46 @@ def matrix_writer_factory(self, arr, name, is_global=False): ''' Factory function to return matrix writer given variable to write - stream - file or file-like stream to write to - arr - array to write - name - name in matlab (TM) workspace + + Parameters + ---------- + arr : array-like + array-like object to create writer for + name : string + name as it will appear in matlab workspace + is_global : {False, True} optional + whether variable will be global on load into matlab ''' + # First check if these are sparse if spsparse: if spsparse.issparse(arr): return Mat5SparseWriter(self.stream, arr, name, is_global) - - if isinstance(arr, MatlabFunctionMatrix): - return Mat5FunctionWriter(self.stream, arr, name, is_global, self.unicode_strings) - if isinstance(arr, MatlabObject): - return Mat5ObjectWriter(self.stream, arr, name, is_global, self.unicode_strings) - - arr = np.array(arr) - if arr.dtype.hasobject: - if arr.dtype.fields == None: - return Mat5CellWriter(self.stream, arr, name, is_global, self.unicode_strings) + # Next try and convert to an array + narr = np.asanyarray(arr) + if narr.dtype.type in (np.object, np.object_) and \ + narr.size == 1 and narr == arr: + # No interesting conversion possible + raise TypeError('Could not convert %s (type %s) to array' + % (arr, type(arr))) + args = (self.stream, narr, name, is_global, self.unicode_strings) + if isinstance(narr, MatlabFunction): + return Mat5FunctionWriter(*args) + if isinstance(narr, MatlabObject): + return Mat5ObjectWriter(*args) + if narr.dtype.hasobject: # cell or struct array + if narr.dtype.fields == None: + return Mat5CellWriter(*args) else: - return Mat5StructWriter(self.stream, arr, name, is_global, self.unicode_strings) - if arr.dtype.kind in ('U', 'S'): + return Mat5StructWriter(*args) + if narr.dtype.kind in ('U', 'S'): if self.unicode_strings: - return Mat5UniCharWriter(self.stream, arr, name, is_global) + return Mat5UniCharWriter(*args) else: - return Mat5CharWriter(self.stream, arr, name, is_global) + return Mat5CharWriter(*args) else: - return Mat5NumericWriter(self.stream, arr, name, is_global) + return Mat5NumericWriter(*args) + class MatFile5Writer(MatFileWriter): ''' Class for writing mat5 files ''' def __init__(self, file_stream, Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-11 07:32:57 UTC (rev 5058) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-11 09:03:27 UTC (rev 5059) @@ -1,6 +1,8 @@ #!/usr/bin/env python ''' Nose test generators +Need function load / save / roundtrip tests + ''' from os.path import join, dirname from glob import glob @@ -9,6 +11,7 @@ import warnings import shutil import gzip +import copy from numpy.testing import \ assert_array_almost_equal, \ @@ -151,15 +154,17 @@ {'name': 'structarr', 'expected': {'teststructarr': a} }) -MO = MatlabObject('inline', +ODT = np.dtype([(n, object) for n in ['expr', 'inputExpr', 'args', - 'isEmpty', 'numArgs', 'version']) -MO.expr = u'x' -MO.inputExpr = u' x = INLINE_INPUTS_{1};' -MO.args = u'x' -MO.isEmpty = mlarr(0) -MO.numArgs = mlarr(1) -MO.version = mlarr(1) + 'isEmpty', 'numArgs', 'version']]) +MO = MatlabObject(np.zeros((1,1), dtype=ODT), 'inline') +m0 = MO[0,0] +m0['expr'] = array([u'x']) +m0['inputExpr'] = array([u' x = INLINE_INPUTS_{1};']) +m0['args'] = array([u'x']) +m0['isEmpty'] = mlarr(0) +m0['numArgs'] = mlarr(1) +m0['version'] = mlarr(1) case_table5.append( {'name': 'object', 'expected': {'testobject': MO} @@ -171,7 +176,8 @@ {'name': 'unicode', 'expected': {'testunicode': array([u_str])} }) -# These should also have matlab load equivalents, but I can't get to matlab at the moment +# These should also have matlab load equivalents, +# but I can't get to matlab at the moment case_table5_rt = case_table5[:] case_table5_rt.append( {'name': 'sparsefloat', @@ -183,8 +189,10 @@ 'expected': {'testsparsecomplex': SP.coo_matrix(array([[-1+2j,0,2],[0,-3j,0]]))}, }) +case_table5_rt.append( + {'name': 'objectarray', + 'expected': {'testobjectarray': np.repeat(MO, 2).reshape(1,2)}}) - def _check_level(label, expected, actual): """ Check one level of a potentially nested array """ if SP.issparse(expected): # allow different types of sparse matrices @@ -199,26 +207,13 @@ typac = type(actual) assert typex is typac, \ "Expected type %s, got %s at %s" % (typex, typac, label) - # object, as container for matlab objects - if isinstance(expected, MatlabObject): - ex_fields = dir(expected) - ac_fields = dir(actual) - for k in ex_fields: - if k.startswith('__') and k.endswith('__'): - continue - assert k in ac_fields, \ - "Missing expected property %s for %s" % (k, label) - ev = expected.__dict__[k] - v = actual.__dict__[k] - level_label = "%s, property %s, " % (label, k) - _check_level(level_label, ev, v) - return # A field in a record array may not be an ndarray # A scalar from a record array will be type np.void - if not isinstance(expected, (np.void, np.ndarray)): + if not isinstance(expected, + (np.void, np.ndarray, MatlabObject)): assert_equal(expected, actual) return - # This is an ndarray + # This is an ndarray-like thing assert_true(expected.shape == actual.shape, msg='Expected shape %s, got %s at %s' % (expected.shape, actual.shape, @@ -226,6 +221,8 @@ ) ex_dtype = expected.dtype if ex_dtype.hasobject: # array of objects + if isinstance(expected, MatlabObject): + assert_equal(expected.classname, actual.classname) for i, ev in enumerate(expected): level_label = "%s, [%d], " % (label, i) _check_level(level_label, ev, actual[i]) @@ -311,7 +308,10 @@ join(test_data_path, 'testhdf5*.mat')) assert len(filenames) for filename in filenames: - assert_raises(NotImplementedError, loadmat, filename, struct_as_record=True) + assert_raises(NotImplementedError, + loadmat, + filename, + struct_as_record=True) def test_warnings(): @@ -326,20 +326,16 @@ # This too yield assert_raises, FutureWarning, find_mat_file, fname # we need kwargs for this one - try: - mres = loadmat(fname, struct_as_record=False, basename='raw') - except DeprecationWarning: - pass - else: - assert False, 'Did not raise deprecation warning' + yield (lambda a, k: assert_raises(*a, **k), + (DeprecationWarning, loadmat, fname), + {'struct_as_record':True, 'basename':'raw'}) # Test warning for default format change savemat(StringIO(), {}, False, '4') savemat(StringIO(), {}, False, '5') yield assert_raises, FutureWarning, savemat, StringIO(), {} warnings.resetwarnings() - at dec.knownfailureif(True, "Infinite recursion when writing a simple "\ - "dictionary to matlab file.") + def test_regression_653(): """Regression test for #653.""" - savemat(StringIO(), {'d':{1:2}}, format='5') + assert_raises(TypeError, savemat, StringIO(), {'d':{1:2}}, format='5') From scipy-svn at scipy.org Tue Nov 11 21:17:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 11 Nov 2008 20:17:33 -0600 (CST) Subject: [Scipy-svn] r5060 - trunk/scipy/sparse/linalg/isolve Message-ID: <20081112021733.5AD7439C05F@scipy.org> Author: wnbell Date: 2008-11-11 20:17:26 -0600 (Tue, 11 Nov 2008) New Revision: 5060 Modified: trunk/scipy/sparse/linalg/isolve/iterative.py trunk/scipy/sparse/linalg/isolve/minres.py Log: updated iterative solver docstrings resolves ticket #652 Modified: trunk/scipy/sparse/linalg/isolve/iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-11 09:03:27 UTC (rev 5059) +++ trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-12 02:17:26 UTC (rev 5060) @@ -10,41 +10,67 @@ _type_conv = {'f':'s', 'd':'d', 'F':'c', 'D':'z'} -def bicg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None): - """Use BIConjugate Gradient iteration to solve A x = b - Inputs: +# Part of the docstring common to all iterative solvers +common_doc = \ +""" +Parameters +---------- +A : {sparse matrix, dense matrix, LinearOperator} + The N-by-N matrix of the linear system. +b : {array, matrix} + Right hand side of the linear system. Has shape (N,) or (N,1). - A -- An array or an object with matvec(x) and rmatvec(x) methods - to represent A * x and A^H * x respectively. May also have - psolve(b) and rpsolve(b) methods for representing solutions - to the preconditioning equations M * x = b and - M^H * x = b respectively. - b -- An n-length vector +Optional Parameters +------------------- +x0 : {array, matrix} + Starting guess for the solution. +tol : float + Relative tolerance to achieve before terminating. +maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. +M : {sparse matrix, dense matrix, LinearOperator} + Preconditioner for A. The preconditioner should approximate the + inverse of A. Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. +callback : function + User-supplied function to call after each iteration. It is called + as callback(xk), where xk is the current solution vector. - Outputs: +Outputs +------- +x : {array, matrix} + The converged solution. +info : integer + Provides convergence information: + 0 : successful exit + >0 : convergence to tolerance not achieved, number of iterations + <0 : illegal input or breakdown - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown +Deprecated Parameters +---------------------- +xtype : {'f','d','F','D'} + The type of the result. If None, then it will be determined from + A.dtype.char and b. If A does not have a typecode method then it + will compute A.matvec(x0) to get a typecode. To save the extra + computation when A does not have a typecode attribute use xtype=0 + for the same type as b or use xtype='f','d','F',or 'D'. + This parameter has been superceeded by LinearOperator. +""" - Optional Inputs: - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ +def set_docstring(header, footer): + def combine(fn): + fn.__doc__ = header + '\n' + common_doc + '\n' + footer + return fn + return combine + + + + at set_docstring('Use BIConjugate Gradient iteration to solve A x = b','') +def bicg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None): A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) n = len(b) @@ -104,41 +130,8 @@ return postprocess(x), info - + at set_docstring('Use BIConjugate Gradient STABilized iteration to solve A x = b','') def bicgstab(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None): - """Use BIConjugate Gradient STABilized iteration to solve A x = b - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) n = len(b) @@ -199,42 +192,8 @@ return postprocess(x), info - + at set_docstring('Use Conjugate Gradient iteration to solve A x = b','') def cg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None): - """Use Conjugate Gradient iteration to solve A x = b (A^H = A) - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) n = len(b) @@ -291,41 +250,8 @@ return postprocess(x), info + at set_docstring('Use Conjugate Gradient Squared iteration to solve A x = b','') def cgs(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None): - """Use Conjugate Gradient Squared iteration to solve A x = b - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - - Outputs: - - x -- The converged solution - info -- output result - 0 : successful exit - >0 : convergence to tolerance not achieved, number of iterations - <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. - """ A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) n = len(b) @@ -379,44 +305,63 @@ info = iter_ return postprocess(x), info + - def gmres(A, b, x0=None, tol=1e-5, restrt=20, maxiter=None, xtype=None, M=None, callback=None): """Use Generalized Minimal RESidual iteration to solve A x = b - - Inputs: - - A -- An array or an object with a matvec(x) method - to represent A * x. May also have a psolve(b) methods for - representing solution to the preconditioning equation - M * x = b. - b -- An n-length vector - - - Outputs: - - x -- The converged solution - info -- output result + + Parameters + ---------- + A : {sparse matrix, dense matrix, LinearOperator} + The N-by-N matrix of the linear system. + b : {array, matrix} + Right hand side of the linear system. Has shape (N,) or (N,1). + + Optional Parameters + ------------------- + x0 : {array, matrix} + Starting guess for the solution. + tol : float + Relative tolerance to achieve before terminating. + restrt : integer + Number of iterations between restarts. Larger values increase + iteration cost, but may be necessary for convergence. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M : {sparse matrix, dense matrix, LinearOperator} + Preconditioner for A. The preconditioner should approximate the + inverse of A. Effective preconditioning dramatically improves the + rate of convergence, which implies that fewer iterations are needed + to reach a given error tolerance. + callback : function + User-supplied function to call after each iteration. It is called + as callback(rk), where rk is the current residual vector. + + Outputs + ------- + x : {array, matrix} + The converged solution. + info : integer + Provides convergence information: 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - restrt -- (10) When to restart (change this to get faster performance -- but - may not converge). - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(rk), where rk is the - the current relative residual + + See Also + -------- + LinearOperator + + Deprecated Parameters + --------------------- + xtype : {'f','d','F','D'} + The type of the result. If None, then it will be determined from + A.dtype.char and b. If A does not have a typecode method then it + will compute A.matvec(x0) to get a typecode. To save the extra + computation when A does not have a typecode attribute use xtype=0 + for the same type as b or use xtype='f','d','F',or 'D'. + This parameter has been superceeded by LinearOperator. + """ A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) @@ -499,38 +444,56 @@ def qmr(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M1=None, M2=None, callback=None): """Use Quasi-Minimal Residual iteration to solve A x = b - Inputs: - - A -- An array or an object with matvec(x) and rmatvec(x) methods - to represent A * x and A^H * x respectively. May also have - psolve(b,) and rpsolve(b,) methods for - representing solutions to the preconditioning equations - M * x = b and M^H * x = b respectively. The argument - may be given to specify 'left' or 'right' preconditioning. - b -- An n-length vector - - Outputs: - - x -- The converged solution - info -- output result + Parameters + ---------- + A : {sparse matrix, dense matrix, LinearOperator} + The N-by-N matrix of the linear system. + b : {array, matrix} + Right hand side of the linear system. Has shape (N,) or (N,1). + + Optional Parameters + ------------------- + x0 : {array, matrix} + Starting guess for the solution. + tol : float + Relative tolerance to achieve before terminating. + maxiter : integer + Maximum number of iterations. Iteration will stop after maxiter + steps even if the specified tolerance has not been achieved. + M1 : {sparse matrix, dense matrix, LinearOperator} + Left preconditioner for A. + M2 : {sparse matrix, dense matrix, LinearOperator} + Right preconditioner for A. Used together with the left + preconditioner M1. The matrix M1*A*M2 should have better + conditioned than A alone. + callback : function + User-supplied function to call after each iteration. It is called + as callback(xk), where xk is the current solution vector. + + Outputs + ------- + x : {array, matrix} + The converged solution. + info : integer + Provides convergence information: 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown - - Optional Inputs: - - x0 -- (0) default starting guess. - tol -- (1e-5) relative tolerance to achieve - maxiter -- (10*n) maximum number of iterations - xtype -- The type of the result. If None, then it will be - determined from A.dtype.char and b. If A does not have a - typecode method then it will compute A.matvec(x0) to get a - typecode. To save the extra computation when A does not - have a typecode attribute use xtype=0 for the same type as - b or use xtype='f','d','F',or 'D' - callback -- an optional user-supplied function to call after each - iteration. It is called as callback(xk), where xk is the - current parameter vector. + + See Also + -------- + LinearOperator + + Deprecated Parameters + --------------------- + xtype : {'f','d','F','D'} + The type of the result. If None, then it will be determined from + A.dtype.char and b. If A does not have a typecode method then it + will compute A.matvec(x0) to get a typecode. To save the extra + computation when A does not have a typecode attribute use xtype=0 + for the same type as b or use xtype='f','d','F',or 'D'. + This parameter has been superceeded by LinearOperator. + """ A_ = A A,M,x,b,postprocess = make_system(A,None,x0,b,xtype) Modified: trunk/scipy/sparse/linalg/isolve/minres.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/minres.py 2008-11-11 09:03:27 UTC (rev 5059) +++ trunk/scipy/sparse/linalg/isolve/minres.py 2008-11-12 02:17:26 UTC (rev 5060) @@ -2,35 +2,40 @@ from numpy.linalg import norm from utils import make_system +from iterative import set_docstring __all__ = ['minres'] -def minres(A, b, x0=None, shift=0.0, tol=1e-5, maxiter=None, xtype=None, - M=None, callback=None, show=False, check=False): - """Use the Minimum Residual Method (MINRES) to solve Ax=b + +header = \ +"""Use MINimum RESidual iteration to solve Ax=b - MINRES minimizes norm(A*x - b) for the symmetric matrix A. Unlike - the Conjugate Gradient method, A can be indefinite or singular. +MINRES minimizes norm(A*x - b) for the symmetric matrix A. Unlike +the Conjugate Gradient method, A can be indefinite or singular. - If shift != 0 then the method solves (A - shift*I)x = b +If shift != 0 then the method solves (A - shift*I)x = b +""" +footer = \ +""" +Notes +----- +THIS FUNCTION IS EXPERIMENTAL AND SUBJECT TO CHANGE! - Parameters - ========== - TODO +References +---------- +Solution of sparse indefinite systems of linear equations, + C. C. Paige and M. A. Saunders (1975), + SIAM J. Numer. Anal. 12(4), pp. 617-629. + http://www.stanford.edu/group/SOL/software/minres.html - References - ========== +This file is a translation of the following MATLAB implementation: + http://www.stanford.edu/group/SOL/software/minres/matlab/ +""" - Solution of sparse indefinite systems of linear equations, - C. C. Paige and M. A. Saunders (1975), - SIAM J. Numer. Anal. 12(4), pp. 617-629. - http://www.stanford.edu/group/SOL/software/minres.html - - This file is a translation of the following MATLAB implementation: - http://www.stanford.edu/group/SOL/software/minres/matlab/ - - """ + at set_docstring(header,footer) +def minres(A, b, x0=None, shift=0.0, tol=1e-5, maxiter=None, xtype=None, + M=None, callback=None, show=False, check=False): A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) matvec = A.matvec From scipy-svn at scipy.org Tue Nov 11 23:11:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 11 Nov 2008 22:11:36 -0600 (CST) Subject: [Scipy-svn] r5061 - trunk/scipy/cluster Message-ID: <20081112041136.3EDE239C088@scipy.org> Author: damian.eads Date: 2008-11-11 22:11:34 -0600 (Tue, 11 Nov 2008) New Revision: 5061 Modified: trunk/scipy/cluster/hierarchy.py Log: Fixed typo in docs to close ticket 780. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-12 02:17:26 UTC (rev 5060) +++ trunk/scipy/cluster/hierarchy.py 2008-11-12 04:11:34 UTC (rev 5061) @@ -974,7 +974,7 @@ ``R[i,3]`` is the inconsistency coefficient, .. math: \frac{\mathtt{Z[i,2]}-\mathtt{R[i,0]}} - {R[i,2]}. + {R[i,1]}. This function behaves similarly to the MATLAB(TM) inconsistent function. From scipy-svn at scipy.org Wed Nov 12 02:26:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 01:26:06 -0600 (CST) Subject: [Scipy-svn] r5062 - in trunk/scipy/io/matlab: . tests Message-ID: <20081112072606.6D09439C05F@scipy.org> Author: matthew.brett at gmail.com Date: 2008-11-12 01:26:02 -0600 (Wed, 12 Nov 2008) New Revision: 5062 Modified: trunk/scipy/io/matlab/mio.py trunk/scipy/io/matlab/mio4.py trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py trunk/scipy/io/matlab/tests/test_mio.py Log: Removed checked for scipy.sparse and assume instead; change default save format to 5 Modified: trunk/scipy/io/matlab/mio.py =================================================================== --- trunk/scipy/io/matlab/mio.py 2008-11-12 04:11:34 UTC (rev 5061) +++ trunk/scipy/io/matlab/mio.py 2008-11-12 07:26:02 UTC (rev 5062) @@ -116,7 +116,7 @@ return mdict @filldoc -def savemat(file_name, mdict, appendmat=True, format=None): +def savemat(file_name, mdict, appendmat=True, format='5'): """Save a dictionary of names and arrays into the MATLAB-style .mat file. This saves the arrayobjects in the given dictionary to a matlab @@ -128,15 +128,10 @@ m_dict : dict dictionary from which to save matfile variables %(append_arg)s - format : {'4', '5'} string, optional - '4' for matlab 4 mat files, '5' for matlab 5 (up to matlab - 7.2) + format : {'5', '4'} string, optional + '5' for matlab 5 (up to matlab 7.2) + '4' for matlab 4 mat files, """ - if format is None: - warnings.warn( - "Using default format '4'. Default will change to '5' in future versions of scipy", - FutureWarning, stacklevel=2) - format = '4' file_is_string = isinstance(file_name, basestring) if file_is_string: if appendmat and file_name[-4:] != ".mat": Modified: trunk/scipy/io/matlab/mio4.py =================================================================== --- trunk/scipy/io/matlab/mio4.py 2008-11-12 04:11:34 UTC (rev 5061) +++ trunk/scipy/io/matlab/mio4.py 2008-11-12 07:26:02 UTC (rev 5062) @@ -4,9 +4,12 @@ import numpy as np +import scipy.sparse + from miobase import MatFileReader, MatArrayReader, MatMatrixGetter, \ - MatFileWriter, MatStreamWriter, spsparse, filldoc + MatFileWriter, MatStreamWriter, filldoc + SYS_LITTLE_ENDIAN = sys.byteorder == 'little' miDOUBLE = 0 @@ -179,9 +182,7 @@ else: V = np.ascontiguousarray(tmp[:,2],dtype='complex') V.imag = tmp[:,3] - if spsparse: - return spsparse.coo_matrix((V,(I,J)), dims) - return (dims, I, J, V) + return scipy.sparse.coo_matrix((V,(I,J)), dims) class MatFile4Reader(MatFileReader): @@ -324,9 +325,8 @@ arr - array to write name - name in matlab (TM) workspace ''' - if spsparse: - if spsparse.issparse(arr): - return Mat4SparseWriter(stream, arr, name) + if scipy.sparse.issparse(arr): + return Mat4SparseWriter(stream, arr, name) arr = np.array(arr) dtt = arr.dtype.type if dtt is np.object_: Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-11-12 04:11:34 UTC (rev 5061) +++ trunk/scipy/io/matlab/mio5.py 2008-11-12 07:26:02 UTC (rev 5062) @@ -12,8 +12,10 @@ import numpy as np +import scipy.sparse + from miobase import MatFileReader, MatArrayReader, MatMatrixGetter, \ - MatFileWriter, MatStreamWriter, spsparse, filldoc + MatFileWriter, MatStreamWriter, filldoc miINT8 = 1 miUINT8 = 2 @@ -173,13 +175,8 @@ pass -class MatlabFunction(np.ndarray): - ''' class to signal this is a matlab function ''' - def __new__(cls, input_array): - return np.asarray(input_array).view(cls) - - class MatlabObject(np.ndarray): + ''' ndarray Subclass to contain matlab object ''' def __new__(cls, input_array, classname=None): # Input array is an already formed ndarray instance # We first cast to be our class type @@ -195,6 +192,12 @@ # We do not need to return anything +class MatlabFunction(np.ndarray): + ''' Subclass to signal this is a matlab function ''' + def __new__(cls, input_array): + obj = np.asarray(input_array).view(cls) + + class Mat5ArrayReader(MatArrayReader): ''' Class to get Mat5 arrays @@ -412,12 +415,10 @@ nnz = indptr[-1] rowind = rowind[:nnz] data = data[:nnz] - if spsparse: - return spsparse.csc_matrix((data,rowind,indptr), shape=(M,N)) - else: - return ((M,N), data, rowind, indptr) + return scipy.sparse.csc_matrix( + (data,rowind,indptr), + shape=(M,N)) - class Mat5CharMatrixGetter(Mat5MatrixGetter): def get_raw_array(self): res = self.read_element() @@ -850,9 +851,8 @@ whether variable will be global on load into matlab ''' # First check if these are sparse - if spsparse: - if spsparse.issparse(arr): - return Mat5SparseWriter(self.stream, arr, name, is_global) + if scipy.sparse.issparse(arr): + return Mat5SparseWriter(self.stream, arr, name, is_global) # Next try and convert to an array narr = np.asanyarray(arr) if narr.dtype.type in (np.object, np.object_) and \ Modified: trunk/scipy/io/matlab/miobase.py =================================================================== --- trunk/scipy/io/matlab/miobase.py 2008-11-12 04:11:34 UTC (rev 5061) +++ trunk/scipy/io/matlab/miobase.py 2008-11-12 07:26:02 UTC (rev 5062) @@ -8,12 +8,6 @@ import byteordercodes as boc -# sparse module if available -try: - import scipy.sparse as spsparse -except ImportError: - spsparse = None - def filldoc(func): ''' Decorator to put recurring doc elements into mio doc strings ''' doc_dict = \ Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-12 04:11:34 UTC (rev 5061) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-12 07:26:02 UTC (rev 5062) @@ -267,6 +267,7 @@ assert files, "No files for test %s using filter %s" % (name, filt) yield _load_check_case, name, files, expected + # generator for round trip tests def test_round_trip(): for case in case_table4 + case_table5_rt: @@ -275,6 +276,7 @@ format = case in case_table4 and '4' or '5' yield _rt_check_case, name, expected, format + def test_gzip_simple(): xdense = np.zeros((20,20)) xdense[2,3]=2.3 @@ -329,13 +331,10 @@ yield (lambda a, k: assert_raises(*a, **k), (DeprecationWarning, loadmat, fname), {'struct_as_record':True, 'basename':'raw'}) - # Test warning for default format change - savemat(StringIO(), {}, False, '4') - savemat(StringIO(), {}, False, '5') - yield assert_raises, FutureWarning, savemat, StringIO(), {} warnings.resetwarnings() def test_regression_653(): """Regression test for #653.""" assert_raises(TypeError, savemat, StringIO(), {'d':{1:2}}, format='5') + From scipy-svn at scipy.org Wed Nov 12 14:33:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 13:33:20 -0600 (CST) Subject: [Scipy-svn] r5063 - in trunk/scipy/cluster: . tests Message-ID: <20081112193320.A68B239C089@scipy.org> Author: damian.eads Date: 2008-11-12 13:33:13 -0600 (Wed, 12 Nov 2008) New Revision: 5063 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Made cophenet return behavior less confusing. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-12 07:26:02 UTC (rev 5062) +++ trunk/scipy/cluster/hierarchy.py 2008-11-12 19:33:13 UTC (rev 5063) @@ -873,21 +873,22 @@ X = X.copy() return X -def cophenet(*args): +def cophenet(Z, Y=None): """ Calculates the cophenetic distances between each observation in the hierarchical clustering defined by the linkage ``Z``. - Suppose :math:`$p$` and :math:`$q$` are original observations in - disjoint clusters :math:`$s$` and :math:`$t$`, respectively and - :math:`$s$` and :math:`$t$` are joined by a direct parent cluster - :math:`$u$`. The cophenetic distance between observations - :math:`$i$` and :math:`$j$` is simply the distance between - clusters :math:`$s$` and :math:`$t$`. + Suppose ``p`` and ``q`` are original observations in + disjoint clusters ``s`` and ``t``, respectively and + ``s`` and ``t`` are joined by a direct parent cluster + ``u``. The cophenetic distance between observations + ``i`` and ``j`` is simply the distance between + clusters ``s`` and ``t``. :Parameters: - Z : ndarray - The encoded linkage matrix on which to perform the calculation. + The hierarchical clustering encoded as an array + (see ``linkage`` function). - Y : ndarray (optional) Calculates the cophenetic correlation coefficient ``c`` of a @@ -902,16 +903,11 @@ - d : ndarray The cophenetic distance matrix in condensed form. The - :math:`$ij$`th entry is the cophenetic distance between + :math:`$ij$` th entry is the cophenetic distance between original observations :math:`$i$` and :math:`$j$`. """ - nargs = len(args) - if nargs < 1: - raise ValueError('At least one argument must be passed to cophenet.') - - Z = args[0] Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') Zs = Z.shape @@ -923,10 +919,9 @@ Z = _convert_to_double(Z) _hierarchy_wrap.cophenetic_distances_wrap(Z, zz, int(n)) - if nargs == 1: + if Y is None: return zz - Y = args[1] Y = np.asarray(Y, order='c') Ys = Y.shape distance.is_valid_y(Y, throw=True, name='Y') @@ -941,12 +936,8 @@ denomB = Zz ** 2 c = numerator.sum() / np.sqrt((denomA.sum() * denomB.sum())) #print c, numerator.sum() - if nargs == 2: - return c + return (c, zz) - if nargs == 3: - return (c, zz) - def inconsistent(Z, d=2): """ Calculates inconsistency statistics on a linkage. @@ -2308,7 +2299,7 @@ n = Z.shape[0] + 1 MI = np.zeros((n-1,)) [Z, R] = _copy_arrays_if_base_present([Z, R]) - _hierarchy_wrap.get_max_Rfield_for_each_hierarchy_wrap(Z, R, MI, int(n), 3) + _hierarchy_wrap.get_max_Rfield_for_each_cluster_wrap(Z, R, MI, int(n), 3) return MI def maxRstat(Z, R, i): @@ -2332,7 +2323,7 @@ n = Z.shape[0] + 1 MR = np.zeros((n-1,)) [Z, R] = _copy_arrays_if_base_present([Z, R]) - _hierarchy_wrap.get_max_Rfield_for_each_hierarchy_wrap(Z, R, MR, int(n), i) + _hierarchy_wrap.get_max_Rfield_for_each_cluster_wrap(Z, R, MR, int(n), i) return MR def leaders(Z, T): Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 07:26:02 UTC (rev 5062) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 19:33:13 UTC (rev 5063) @@ -350,19 +350,11 @@ def test_linkage_cophenet_tdist_Z_Y(self): "Testing cophenet(Z, Y) on tdist data set." Z = linkage(_ytdist, 'single') - c = cophenet(Z, _ytdist) + (c, M) = cophenet(Z, _ytdist) + expectedM = np.array([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, 295, 138, 219, 295, 295]); expectedc = 0.639931296433393415057366837573 eps = 1e-10 self.failUnless(np.abs(c - expectedc) <= eps) - - def test_linkage_cophenet_tdist_Z_Y_EL(self): - "Testing cophenet(Z, Y, []) on tdist data set." - Z = linkage(_ytdist, 'single') - (c, M) = cophenet(Z, _ytdist, []) - eps = 1e-10 - expectedM = np.array([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, 295, 138, 219, 295, 295]); - expectedc = 0.639931296433393415057366837573 - self.failUnless(np.abs(c - expectedc) <= eps) self.failUnless(within_tol(M, expectedM, eps)) class TestFromMLabLinkage(TestCase): From scipy-svn at scipy.org Wed Nov 12 17:20:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 16:20:39 -0600 (CST) Subject: [Scipy-svn] r5064 - in trunk/scipy/cluster: . tests Message-ID: <20081112222039.6216B39C05F@scipy.org> Author: damian.eads Date: 2008-11-12 16:20:34 -0600 (Wed, 12 Nov 2008) New Revision: 5064 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for hierarchy.is_isomorphic. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-12 19:33:13 UTC (rev 5063) +++ trunk/scipy/cluster/hierarchy.py 2008-11-12 22:20:34 UTC (rev 5064) @@ -154,43 +154,42 @@ """ -_copyingtxt=""" -cluster.py -Author: Damian Eads -Date: September 22, 2007 +# hierarchy.py (derived from cluster.py, http://scipy-cluster.googlecode.com) +# +# Author: Damian Eads +# Date: September 22, 2007 +# +# Copyright (c) 2007, 2008, Damian Eads +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# - Redistributions of source code must retain the above +# copyright notice, this list of conditions and the +# following disclaimer. +# - Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# - Neither the name of the author nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -Copyright (c) 2007, 2008, Damian Eads - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - Redistributions of source code must retain the above - copyright notice, this list of conditions and the - following disclaimer. - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - Neither the name of the author nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -""" - import numpy as np import _hierarchy_wrap, types import scipy.spatial.distance as distance Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 19:33:13 UTC (rev 5063) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 22:20:34 UTC (rev 5064) @@ -479,6 +479,73 @@ print L, Lright, T self.failUnless((L[0] == Lright[0]).all() and (L[1] == Lright[1]).all()) +class TestIsIsomorphic(TestCase): + + def test_is_isomorphic_1(self): + "Tests is_isomorphic on test case #1 (one flat cluster, different labellings)" + a = [1, 1, 1] + b = [2, 2, 2] + self.failUnless(is_isomorphic(a, b) == True) + self.failUnless(is_isomorphic(b, a) == True) + + def test_is_isomorphic_2(self): + "Tests is_isomorphic on test case #2 (two flat clusters, different labelings)" + a = [1, 7, 1] + b = [2, 3, 2] + self.failUnless(is_isomorphic(a, b) == True) + self.failUnless(is_isomorphic(b, a) == True) + + def test_is_isomorphic_3(self): + "Tests is_isomorphic on test case #3 (no flat clusters)" + a = [] + b = [] + self.failUnless(is_isomorphic(a, b) == True) + + def test_is_isomorphic_4A(self): + "Tests is_isomorphic on test case #4A (3 flat clusters, different labelings, isomorphic)" + a = [1, 2, 3] + b = [1, 3, 2] + self.failUnless(is_isomorphic(a, b) == True) + self.failUnless(is_isomorphic(b, a) == True) + + def test_is_isomorphic_4B(self): + "Tests is_isomorphic on test case #4B (3 flat clusters, different labelings, nonisomorphic)" + a = [1, 2, 3, 3] + b = [1, 3, 2, 3] + self.failUnless(is_isomorphic(a, b) == False) + self.failUnless(is_isomorphic(b, a) == False) + + def test_is_isomorphic_4C(self): + "Tests is_isomorphic on test case #4C (3 flat clusters, different labelings, isomorphic)" + a = [7, 2, 3] + b = [6, 3, 2] + self.failUnless(is_isomorphic(a, b) == True) + self.failUnless(is_isomorphic(b, a) == True) + + def test_is_isomorphic_5A(self): + "Tests is_isomorphic on test case #5A (1000 observations, 2 random clusters, random permutation of the labeling). Run 3 times." + for k in xrange(0, 3): + self.help_is_isomorphic_randperm(1000, 2) + + def test_is_isomorphic_5B(self): + "Tests is_isomorphic on test case #5B (1000 observations, 3 random clusters, random permutation of the labeling). Run 3 times." + for k in xrange(0, 3): + self.help_is_isomorphic_randperm(1000, 3) + + def test_is_isomorphic_5C(self): + "Tests is_isomorphic on test case #5C (1000 observations, 5 random clusters, random permutation of the labeling). Run 3 times." + for k in xrange(0, 3): + self.help_is_isomorphic_randperm(1000, 5) + + def help_is_isomorphic_randperm(self, nobs, nclusters): + a = np.int_(np.random.rand(nobs) * nclusters) + b = np.zeros(a.size, dtype=np.int_) + q = {} + P = np.random.permutation(nclusters) + for i in xrange(0, a.shape[0]): + b[i] = P[a[i]] + self.failUnless(is_isomorphic(a, b) == True) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Wed Nov 12 17:27:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 16:27:17 -0600 (CST) Subject: [Scipy-svn] r5065 - trunk/scipy/cluster/tests Message-ID: <20081112222717.D6C8F39C05F@scipy.org> Author: damian.eads Date: 2008-11-12 16:27:16 -0600 (Wed, 12 Nov 2008) New Revision: 5065 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote more tests for hierarchy.is_isomorphic. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 22:20:34 UTC (rev 5064) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 22:27:16 UTC (rev 5065) @@ -537,14 +537,35 @@ for k in xrange(0, 3): self.help_is_isomorphic_randperm(1000, 5) - def help_is_isomorphic_randperm(self, nobs, nclusters): + + def test_is_isomorphic_6A(self): + "Tests is_isomorphic on test case #5A (1000 observations, 2 random clusters, random permutation of the labeling, slightly nonisomorphic.) Run 3 times." + for k in xrange(0, 3): + self.help_is_isomorphic_randperm(1000, 2, True, 5) + + def test_is_isomorphic_6B(self): + "Tests is_isomorphic on test case #5B (1000 observations, 3 random clusters, random permutation of the labeling, slightly nonisomorphic.) Run 3 times." + for k in xrange(0, 3): + self.help_is_isomorphic_randperm(1000, 3, True, 5) + + def test_is_isomorphic_6C(self): + "Tests is_isomorphic on test case #5C (1000 observations, 5 random clusters, random permutation of the labeling, slightly non-isomorphic.) Run 3 times." + for k in xrange(0, 3): + self.help_is_isomorphic_randperm(1000, 5, True, 5) + + def help_is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0): a = np.int_(np.random.rand(nobs) * nclusters) b = np.zeros(a.size, dtype=np.int_) q = {} P = np.random.permutation(nclusters) for i in xrange(0, a.shape[0]): b[i] = P[a[i]] - self.failUnless(is_isomorphic(a, b) == True) + if noniso: + Q = np.random.permutation(nobs) + b[Q[0:nerrors]] += 1 + b[Q[0:nerrors]] %= nclusters + self.failUnless(is_isomorphic(a, b) == (not noniso)) + self.failUnless(is_isomorphic(b, a) == (not noniso)) def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) From scipy-svn at scipy.org Wed Nov 12 17:28:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 16:28:03 -0600 (CST) Subject: [Scipy-svn] r5066 - trunk/scipy/cluster/tests Message-ID: <20081112222803.0146439C05F@scipy.org> Author: damian.eads Date: 2008-11-12 16:28:02 -0600 (Wed, 12 Nov 2008) New Revision: 5066 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote more tests for hierarchy.is_isomorphic. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 22:27:16 UTC (rev 5065) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-12 22:28:02 UTC (rev 5066) @@ -214,7 +214,7 @@ class TestInconsistent(TestCase): def test_single_inconsistent_tdist_1(self): - "Testing inconsistency matrix calculation (depth=1) on a single linkage." + "Tests inconsistency matrix calculation (depth=1) on a single linkage." Y = squareform(_tdist) Z = linkage(Y, 'single') R = inconsistent(Z, 1) @@ -224,7 +224,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_tdist_2(self): - "Testing inconsistency matrix calculation (depth=2) on a single linkage." + "Tests inconsistency matrix calculation (depth=2) on a single linkage." Y = squareform(_tdist) Z = linkage(Y, 'single') R = inconsistent(Z, 2) @@ -234,7 +234,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_tdist_3(self): - "Testing inconsistency matrix calculation (depth=3) on a single linkage." + "Tests inconsistency matrix calculation (depth=3) on a single linkage." Y = squareform(_tdist) Z = linkage(Y, 'single') R = inconsistent(Z, 3) @@ -244,7 +244,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_tdist_4(self): - "Testing inconsistency matrix calculation (depth=4) on a single linkage." + "Tests inconsistency matrix calculation (depth=4) on a single linkage." Y = squareform(_tdist) Z = linkage(Y, 'single') R = inconsistent(Z, 4) @@ -256,7 +256,7 @@ # with complete linkage... def test_complete_inconsistent_tdist_1(self): - "Testing inconsistency matrix calculation (depth=1) on a complete linkage." + "Tests inconsistency matrix calculation (depth=1) on a complete linkage." Y = squareform(_tdist) Z = linkage(Y, 'complete') R = inconsistent(Z, 1) @@ -266,7 +266,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_complete_inconsistent_tdist_2(self): - "Testing inconsistency matrix calculation (depth=2) on a complete linkage." + "Tests inconsistency matrix calculation (depth=2) on a complete linkage." Y = squareform(_tdist) Z = linkage(Y, 'complete') R = inconsistent(Z, 2) @@ -276,7 +276,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_complete_inconsistent_tdist_3(self): - "Testing inconsistency matrix calculation (depth=3) on a complete linkage." + "Tests inconsistency matrix calculation (depth=3) on a complete linkage." Y = squareform(_tdist) Z = linkage(Y, 'complete') R = inconsistent(Z, 3) @@ -286,7 +286,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_complete_inconsistent_tdist_4(self): - "Testing inconsistency matrix calculation (depth=4) on a complete linkage." + "Tests inconsistency matrix calculation (depth=4) on a complete linkage." Y = squareform(_tdist) Z = linkage(Y, 'complete') R = inconsistent(Z, 4) @@ -298,7 +298,7 @@ # with single linkage and Q data set def test_single_inconsistent_Q_1(self): - "Testing inconsistency matrix calculation (depth=1, dataset=Q) with single linkage." + "Tests inconsistency matrix calculation (depth=1, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 1) @@ -308,7 +308,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_Q_2(self): - "Testing inconsistency matrix calculation (depth=2, dataset=Q) with single linkage." + "Tests inconsistency matrix calculation (depth=2, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 2) @@ -318,7 +318,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_Q_3(self): - "Testing inconsistency matrix calculation (depth=3, dataset=Q) with single linkage." + "Tests inconsistency matrix calculation (depth=3, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 3) @@ -328,7 +328,7 @@ self.failUnless(within_tol(R, Rright, eps)) def test_single_inconsistent_Q_4(self): - "Testing inconsistency matrix calculation (depth=4, dataset=Q) with single linkage." + "Tests inconsistency matrix calculation (depth=4, dataset=Q) with single linkage." X = eo['Q-X'] Z = linkage(X, 'single', 'euclidean') R = inconsistent(Z, 4) @@ -340,7 +340,7 @@ class TestCopheneticDistance(TestCase): def test_linkage_cophenet_tdist_Z(self): - "Testing cophenet(Z) on tdist data set." + "Tests cophenet(Z) on tdist data set." expectedM = np.array([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, 295, 138, 219, 295, 295]); Z = linkage(_ytdist, 'single') M = cophenet(Z) @@ -348,7 +348,7 @@ self.failUnless(within_tol(M, expectedM, eps)) def test_linkage_cophenet_tdist_Z_Y(self): - "Testing cophenet(Z, Y) on tdist data set." + "Tests cophenet(Z, Y) on tdist data set." Z = linkage(_ytdist, 'single') (c, M) = cophenet(Z, _ytdist) expectedM = np.array([268, 295, 255, 255, 295, 295, 268, 268, 295, 295, 295, 138, 219, 295, 295]); @@ -360,20 +360,20 @@ class TestFromMLabLinkage(TestCase): def test_from_mlab_linkage_empty(self): - "Testing from_mlab_linkage on empty linkage array." + "Tests from_mlab_linkage on empty linkage array." X = np.asarray([]) R = from_mlab_linkage([]) self.failUnless((R == X).all()) def test_from_mlab_linkage_single_row(self): - "Testing from_mlab_linkage on linkage array with single row." + "Tests from_mlab_linkage on linkage array with single row." expectedZP = np.asarray([[ 0., 1., 3., 2.]]) Z = [[1,2,3]] ZP = from_mlab_linkage(Z) return self.failUnless((ZP == expectedZP).all()) def test_from_mlab_linkage_multiple_rows(self): - "Testing from_mlab_linkage on linkage array with multiple rows." + "Tests from_mlab_linkage on linkage array with multiple rows." Z = np.asarray([[3, 6, 138], [4, 5, 219], [1, 8, 255], [2, 9, 268], [7, 10, 295]]) expectedZS = np.array([[ 2., 5., 138., 2.], @@ -390,20 +390,20 @@ class TestToMLabLinkage(TestCase): def test_to_mlab_linkage_empty(self): - "Testing to_mlab_linkage on empty linkage array." + "Tests to_mlab_linkage on empty linkage array." X = np.asarray([]) R = to_mlab_linkage([]) self.failUnless((R == X).all()) def test_to_mlab_linkage_single_row(self): - "Testing to_mlab_linkage on linkage array with single row." + "Tests to_mlab_linkage on linkage array with single row." Z = np.asarray([[ 0., 1., 3., 2.]]) expectedZP = np.asarray([[1,2,3]]) ZP = to_mlab_linkage(Z) return self.failUnless((ZP == expectedZP).all()) def test_from_mlab_linkage_multiple_rows(self): - "Testing to_mlab_linkage on linkage array with multiple rows." + "Tests to_mlab_linkage on linkage array with multiple rows." expectedZM = np.asarray([[3, 6, 138], [4, 5, 219], [1, 8, 255], [2, 9, 268], [7, 10, 295]]) Z = np.array([[ 2., 5., 138., 2.], From scipy-svn at scipy.org Wed Nov 12 18:10:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 17:10:39 -0600 (CST) Subject: [Scipy-svn] r5067 - in trunk/scipy: cluster spatial spatial/tests Message-ID: <20081112231039.42B5639C2EB@scipy.org> Author: damian.eads Date: 2008-11-12 17:10:34 -0600 (Wed, 12 Nov 2008) New Revision: 5067 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/spatial/distance.py trunk/scipy/spatial/tests/test_distance.py Log: Added tests for scipy.spatial.distance.numobs_y. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-12 22:28:02 UTC (rev 5066) +++ trunk/scipy/cluster/hierarchy.py 2008-11-12 23:10:34 UTC (rev 5067) @@ -1260,7 +1260,7 @@ """ Z = np.asarray(Z, order='c') Y = np.asarray(Y, order='c') - return numobs_y(Y) == numobs_linkage(Z) + return distance.numobs_y(Y) == numobs_linkage(Z) def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None): """ Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-12 22:28:02 UTC (rev 5066) +++ trunk/scipy/spatial/distance.py 2008-11-12 23:10:34 UTC (rev 5067) @@ -32,6 +32,9 @@ +------------------+-------------------------------------------------+ |numobs_dm | # of observations in a distance matrix. | +------------------+-------------------------------------------------+ +|numobs_y | # of observations in a condensed distance | +| | matrix. | ++------------------+-------------------------------------------------+ Distance functions between two vectors ``u`` and ``v``. Computing distances over a large collection of vectors is inefficient for these @@ -1550,7 +1553,12 @@ """ Y = np.asarray(Y, order='c') is_valid_y(Y, throw=True, name='Y') - d = int(np.ceil(np.sqrt(Y.shape[0] * 2))) + k = Y.shape[0] + if k == 0: + raise ValueError("The number of observations cannot be determined on an empty distance matrix.") + d = int(np.ceil(np.sqrt(k * 2))) + if (d*(d-1)/2) != k: + raise ValueError("Invalid condensed distance matrix passed. Must be some k where k=(n choose 2) for some n >= 2.") return d Modified: trunk/scipy/spatial/tests/test_distance.py =================================================================== --- trunk/scipy/spatial/tests/test_distance.py 2008-11-12 22:28:02 UTC (rev 5066) +++ trunk/scipy/spatial/tests/test_distance.py 2008-11-12 23:10:34 UTC (rev 5067) @@ -39,7 +39,8 @@ import numpy as np from numpy.testing import * from scipy.spatial.distance import squareform, pdist, cdist, matching, \ - jaccard, dice, sokalsneath, rogerstanimoto, russellrao, yule + jaccard, dice, sokalsneath, rogerstanimoto, \ + russellrao, yule, numobs_y _filenames = ["iris.txt", "cdist-X1.txt", @@ -81,6 +82,7 @@ eo = {} def load_testing_files(): + "Loading test data files for the scipy.spatial.distance tests." for fn in _filenames: name = fn.replace(".txt", "").replace("-ml", "") fqfn = os.path.join(os.path.dirname(__file__), fn) @@ -1372,6 +1374,7 @@ self.failUnless(rA.shape == (0,)) def test_squareform_empty_vector(self): + "Tests squareform on an empty vector." v = np.zeros((0,)) rv = squareform(np.array(v, dtype='double')) self.failUnless(rv.shape == (1,1)) @@ -1426,3 +1429,50 @@ k += 1 else: self.failUnless(A[i, j] == 0) + +class TestNumObsY(TestCase): + + def test_num_obs_y_1(self): + "Tests numobs_y(y) on a condensed distance matrix over 1 observations. Expecting exception." + self.failUnlessRaises(ValueError, self.check_y, 1) + + def test_num_obs_y_2(self): + "Tests numobs_y(y) on a condensed distance matrix over 2 observations." + self.failUnless(self.check_y(2)) + + def test_num_obs_y_3(self): + "Tests numobs_y(y) on a condensed distance matrix over 3 observations." + self.failUnless(self.check_y(3)) + + def test_num_obs_y_4(self): + "Tests numobs_y(y) on a condensed distance matrix over 4 observations." + self.failUnless(self.check_y(4)) + + def test_num_obs_y_5_10(self): + "Tests numobs_y(y) on a condensed distance matrix between 5 and 15 observations." + for i in xrange(5, 16): + self.minit(i) + + def test_num_obs_y_2_100(self): + "Tests numobs_y(y) on 100 improper condensed distance matrices. Expecting exception." + a = set([]) + for n in xrange(2, 16): + a.add(n*(n-1)/2) + print a + for i in xrange(5, 105): + if i not in a: + self.failUnlessRaises(ValueError, self.bad_y, i) + + def minit(self, n): + self.failUnless(self.check_y(n)) + + def bad_y(self, n): + y = np.random.rand(n) + return numobs_y(y) + + def check_y(self, n): + return numobs_y(self.make_y(n)) == n + + def make_y(self, n): + return np.random.rand((n*(n-1)/2)) + From scipy-svn at scipy.org Wed Nov 12 18:18:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 17:18:18 -0600 (CST) Subject: [Scipy-svn] r5068 - in trunk/scipy/spatial: . tests Message-ID: <20081112231818.5261739C089@scipy.org> Author: damian.eads Date: 2008-11-12 17:18:14 -0600 (Wed, 12 Nov 2008) New Revision: 5068 Modified: trunk/scipy/spatial/distance.py trunk/scipy/spatial/tests/test_distance.py Log: Added tests for scipy.spatial.distance.numobs_dm. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-12 23:10:34 UTC (rev 5067) +++ trunk/scipy/spatial/distance.py 2008-11-12 23:18:14 UTC (rev 5068) @@ -1534,6 +1534,8 @@ """ d = np.asarray(d, order='c') is_valid_dm(d, tol=np.inf, throw=True, name='d') + if d.shape[0] == 0: + raise ValueError("The number of observations cannot be determined on an empty distance matrix.") return d.shape[0] def numobs_y(Y): Modified: trunk/scipy/spatial/tests/test_distance.py =================================================================== --- trunk/scipy/spatial/tests/test_distance.py 2008-11-12 23:10:34 UTC (rev 5067) +++ trunk/scipy/spatial/tests/test_distance.py 2008-11-12 23:18:14 UTC (rev 5068) @@ -40,7 +40,7 @@ from numpy.testing import * from scipy.spatial.distance import squareform, pdist, cdist, matching, \ jaccard, dice, sokalsneath, rogerstanimoto, \ - russellrao, yule, numobs_y + russellrao, yule, numobs_y, numobs_dm _filenames = ["iris.txt", "cdist-X1.txt", @@ -1432,28 +1432,28 @@ class TestNumObsY(TestCase): - def test_num_obs_y_1(self): + def test_numobs_y_1(self): "Tests numobs_y(y) on a condensed distance matrix over 1 observations. Expecting exception." self.failUnlessRaises(ValueError, self.check_y, 1) - def test_num_obs_y_2(self): + def test_numobs_y_2(self): "Tests numobs_y(y) on a condensed distance matrix over 2 observations." self.failUnless(self.check_y(2)) - def test_num_obs_y_3(self): + def test_numobs_y_3(self): "Tests numobs_y(y) on a condensed distance matrix over 3 observations." self.failUnless(self.check_y(3)) - def test_num_obs_y_4(self): + def test_numobs_y_4(self): "Tests numobs_y(y) on a condensed distance matrix over 4 observations." self.failUnless(self.check_y(4)) - def test_num_obs_y_5_10(self): + def test_numobs_y_5_10(self): "Tests numobs_y(y) on a condensed distance matrix between 5 and 15 observations." for i in xrange(5, 16): self.minit(i) - def test_num_obs_y_2_100(self): + def test_numobs_y_2_100(self): "Tests numobs_y(y) on 100 improper condensed distance matrices. Expecting exception." a = set([]) for n in xrange(2, 16): @@ -1476,3 +1476,30 @@ def make_y(self, n): return np.random.rand((n*(n-1)/2)) +class TestNumObsDM(TestCase): + + def test_numobs_dm_0(self): + "Tests numobs_dm(D) on a 0x0 distance matrix. Expecting exception." + self.failUnlessRaises(ValueError, self.check_D, 0) + + def test_numobs_dm_1(self): + "Tests numobs_dm(D) on a 1x1 distance matrix." + self.failUnless(self.check_D(1)) + + def test_numobs_dm_2(self): + "Tests numobs_dm(D) on a 2x2 distance matrix." + self.failUnless(self.check_D(2)) + + def test_numobs_dm_3(self): + "Tests numobs_dm(D) on a 3x3 distance matrix." + self.failUnless(self.check_D(2)) + + def test_numobs_dm_4(self): + "Tests numobs_dm(D) on a 4x4 distance matrix." + self.failUnless(self.check_D(4)) + + def check_D(self, n): + return numobs_dm(self.make_D(n)) == n + + def make_D(self, n): + return np.random.rand(n, n) From scipy-svn at scipy.org Wed Nov 12 18:48:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 17:48:08 -0600 (CST) Subject: [Scipy-svn] r5069 - in trunk/scipy/spatial: . tests Message-ID: <20081112234808.97CC539C089@scipy.org> Author: damian.eads Date: 2008-11-12 17:48:03 -0600 (Wed, 12 Nov 2008) New Revision: 5069 Modified: trunk/scipy/spatial/distance.py trunk/scipy/spatial/tests/test_distance.py Log: Added tests for scipy.spatial.distance.is_valid_dm. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-12 23:18:14 UTC (rev 5068) +++ trunk/scipy/spatial/distance.py 2008-11-12 23:48:03 UTC (rev 5069) @@ -1414,11 +1414,6 @@ D = np.asarray(D, order='c') valid = True try: - if type(D) != np.ndarray: - if name: - raise TypeError('\'%s\' passed as a distance matrix is not a numpy array.' % name) - else: - raise TypeError('Variable is not a numpy array.') s = D.shape if D.dtype != np.double: if name: @@ -1438,7 +1433,7 @@ raise ValueError('Distance matrix must be symmetric.') if not (D[xrange(0, s[0]), xrange(0, s[0])] == 0).all(): if name: - raise ValueError('Distance matrix \'%s\' diagonal must be zero.' % name) + raise ValueError('Distance matrix \'%s\' diagonal must be zero.' % name) else: raise ValueError('Distance matrix diagonal must be zero.') else: @@ -1534,8 +1529,6 @@ """ d = np.asarray(d, order='c') is_valid_dm(d, tol=np.inf, throw=True, name='d') - if d.shape[0] == 0: - raise ValueError("The number of observations cannot be determined on an empty distance matrix.") return d.shape[0] def numobs_y(Y): Modified: trunk/scipy/spatial/tests/test_distance.py =================================================================== --- trunk/scipy/spatial/tests/test_distance.py 2008-11-12 23:18:14 UTC (rev 5068) +++ trunk/scipy/spatial/tests/test_distance.py 2008-11-12 23:48:03 UTC (rev 5069) @@ -40,7 +40,8 @@ from numpy.testing import * from scipy.spatial.distance import squareform, pdist, cdist, matching, \ jaccard, dice, sokalsneath, rogerstanimoto, \ - russellrao, yule, numobs_y, numobs_dm + russellrao, yule, numobs_y, numobs_dm, \ + is_valid_dm _filenames = ["iris.txt", "cdist-X1.txt", @@ -1480,7 +1481,7 @@ def test_numobs_dm_0(self): "Tests numobs_dm(D) on a 0x0 distance matrix. Expecting exception." - self.failUnlessRaises(ValueError, self.check_D, 0) + self.failUnless(self.check_D(0)) def test_numobs_dm_1(self): "Tests numobs_dm(D) on a 1x1 distance matrix." @@ -1503,3 +1504,98 @@ def make_D(self, n): return np.random.rand(n, n) + +def is_valid_dm_throw(D): + return is_valid_dm(D, throw=True) + +class TestIsValidDM(TestCase): + + def test_is_valid_dm_int16_array_E(self): + "Tests is_valid_dm on an int16 array. Exception expected." + D = np.zeros((5, 5), dtype='i') + self.failUnlessRaises(TypeError, is_valid_dm_throw, (D)) + + def test_is_valid_dm_int16_array_F(self): + "Tests is_valid_dm on an int16 array. False expected." + D = np.zeros((5, 5), dtype='i') + self.failUnless(is_valid_dm(D) == False) + + def test_is_valid_dm_improper_shape_1D_E(self): + "Tests is_valid_dm on a 1D array. Exception expected." + D = np.zeros((5,), dtype=np.double) + self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) + + def test_is_valid_dm_improper_shape_1D_F(self): + "Tests is_valid_dm on a 1D array. False expected." + D = np.zeros((5,), dtype=np.double) + self.failUnless(is_valid_dm(D) == False) + + def test_is_valid_dm_improper_shape_3D_E(self): + "Tests is_valid_dm on a 3D array. Exception expected." + D = np.zeros((3,3,3), dtype=np.double) + self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) + + def test_is_valid_dm_improper_shape_3D_F(self): + "Tests is_valid_dm on a 3D array. False expected." + D = np.zeros((3,3,3), dtype=np.double) + self.failUnless(is_valid_dm(D) == False) + + def test_is_valid_dm_nonzero_diagonal_E(self): + "Tests is_valid_dm on a distance matrix with a nonzero diagonal. Exception expected." + y = np.random.rand(10) + D = squareform(y) + for i in xrange(0, 5): + D[i, i] = 2.0 + self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) + + def test_is_valid_dm_nonzero_diagonal_F(self): + "Tests is_valid_dm on a distance matrix with a nonzero diagonal. False expected." + y = np.random.rand(10) + D = squareform(y) + for i in xrange(0, 5): + D[i, i] = 2.0 + self.failUnless(is_valid_dm(D) == False) + + def test_is_valid_dm_assymetric_E(self): + "Tests is_valid_dm on an assymetric distance matrix. Exception expected." + y = np.random.rand(10) + D = squareform(y) + D[1,3] = D[3,1] + 1 + self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) + + def test_is_valid_dm_assymetric_F(self): + "Tests is_valid_dm on an assymetric distance matrix. False expected." + y = np.random.rand(10) + D = squareform(y) + D[1,3] = D[3,1] + 1 + self.failUnless(is_valid_dm(D) == False) + + def test_is_valid_dm_correct_1_by_1(self): + "Tests is_valid_dm on a correct 1x1. True expected." + D = np.zeros((1,1), dtype=np.double) + self.failUnless(is_valid_dm(D) == True) + + def test_is_valid_dm_correct_2_by_2(self): + "Tests is_valid_dm on a correct 2x2. True expected." + y = np.random.rand(1) + D = squareform(y) + self.failUnless(is_valid_dm(D) == True) + + def test_is_valid_dm_correct_3_by_3(self): + "Tests is_valid_dm on a correct 3x3. True expected." + y = np.random.rand(3) + D = squareform(y) + self.failUnless(is_valid_dm(D) == True) + + def test_is_valid_dm_correct_4_by_4(self): + "Tests is_valid_dm on a correct 4x4. True expected." + y = np.random.rand(6) + D = squareform(y) + self.failUnless(is_valid_dm(D) == True) + + def test_is_valid_dm_correct_5_by_5(self): + "Tests is_valid_dm on a correct 5x5. True expected." + y = np.random.rand(10) + D = squareform(y) + self.failUnless(is_valid_dm(D) == True) + From scipy-svn at scipy.org Wed Nov 12 19:03:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 18:03:11 -0600 (CST) Subject: [Scipy-svn] r5070 - trunk/scipy/spatial/tests Message-ID: <20081113000311.1BEB939C05F@scipy.org> Author: damian.eads Date: 2008-11-12 18:03:06 -0600 (Wed, 12 Nov 2008) New Revision: 5070 Modified: trunk/scipy/spatial/tests/test_distance.py Log: Added tests for scipy.spatial.distance.is_valid_y. Modified: trunk/scipy/spatial/tests/test_distance.py =================================================================== --- trunk/scipy/spatial/tests/test_distance.py 2008-11-12 23:48:03 UTC (rev 5069) +++ trunk/scipy/spatial/tests/test_distance.py 2008-11-13 00:03:06 UTC (rev 5070) @@ -41,7 +41,7 @@ from scipy.spatial.distance import squareform, pdist, cdist, matching, \ jaccard, dice, sokalsneath, rogerstanimoto, \ russellrao, yule, numobs_y, numobs_dm, \ - is_valid_dm + is_valid_dm, is_valid_y _filenames = ["iris.txt", "cdist-X1.txt", @@ -1511,37 +1511,37 @@ class TestIsValidDM(TestCase): def test_is_valid_dm_int16_array_E(self): - "Tests is_valid_dm on an int16 array. Exception expected." + "Tests is_valid_dm(*) on an int16 array. Exception expected." D = np.zeros((5, 5), dtype='i') self.failUnlessRaises(TypeError, is_valid_dm_throw, (D)) def test_is_valid_dm_int16_array_F(self): - "Tests is_valid_dm on an int16 array. False expected." + "Tests is_valid_dm(*) on an int16 array. False expected." D = np.zeros((5, 5), dtype='i') self.failUnless(is_valid_dm(D) == False) def test_is_valid_dm_improper_shape_1D_E(self): - "Tests is_valid_dm on a 1D array. Exception expected." + "Tests is_valid_dm(*) on a 1D array. Exception expected." D = np.zeros((5,), dtype=np.double) self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) def test_is_valid_dm_improper_shape_1D_F(self): - "Tests is_valid_dm on a 1D array. False expected." + "Tests is_valid_dm(*) on a 1D array. False expected." D = np.zeros((5,), dtype=np.double) self.failUnless(is_valid_dm(D) == False) def test_is_valid_dm_improper_shape_3D_E(self): - "Tests is_valid_dm on a 3D array. Exception expected." + "Tests is_valid_dm(*) on a 3D array. Exception expected." D = np.zeros((3,3,3), dtype=np.double) self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) def test_is_valid_dm_improper_shape_3D_F(self): - "Tests is_valid_dm on a 3D array. False expected." + "Tests is_valid_dm(*) on a 3D array. False expected." D = np.zeros((3,3,3), dtype=np.double) self.failUnless(is_valid_dm(D) == False) def test_is_valid_dm_nonzero_diagonal_E(self): - "Tests is_valid_dm on a distance matrix with a nonzero diagonal. Exception expected." + "Tests is_valid_dm(*) on a distance matrix with a nonzero diagonal. Exception expected." y = np.random.rand(10) D = squareform(y) for i in xrange(0, 5): @@ -1549,7 +1549,7 @@ self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) def test_is_valid_dm_nonzero_diagonal_F(self): - "Tests is_valid_dm on a distance matrix with a nonzero diagonal. False expected." + "Tests is_valid_dm(*) on a distance matrix with a nonzero diagonal. False expected." y = np.random.rand(10) D = squareform(y) for i in xrange(0, 5): @@ -1557,45 +1557,117 @@ self.failUnless(is_valid_dm(D) == False) def test_is_valid_dm_assymetric_E(self): - "Tests is_valid_dm on an assymetric distance matrix. Exception expected." + "Tests is_valid_dm(*) on an assymetric distance matrix. Exception expected." y = np.random.rand(10) D = squareform(y) D[1,3] = D[3,1] + 1 self.failUnlessRaises(ValueError, is_valid_dm_throw, (D)) def test_is_valid_dm_assymetric_F(self): - "Tests is_valid_dm on an assymetric distance matrix. False expected." + "Tests is_valid_dm(*) on an assymetric distance matrix. False expected." y = np.random.rand(10) D = squareform(y) D[1,3] = D[3,1] + 1 self.failUnless(is_valid_dm(D) == False) def test_is_valid_dm_correct_1_by_1(self): - "Tests is_valid_dm on a correct 1x1. True expected." + "Tests is_valid_dm(*) on a correct 1x1. True expected." D = np.zeros((1,1), dtype=np.double) self.failUnless(is_valid_dm(D) == True) def test_is_valid_dm_correct_2_by_2(self): - "Tests is_valid_dm on a correct 2x2. True expected." + "Tests is_valid_dm(*) on a correct 2x2. True expected." y = np.random.rand(1) D = squareform(y) self.failUnless(is_valid_dm(D) == True) def test_is_valid_dm_correct_3_by_3(self): - "Tests is_valid_dm on a correct 3x3. True expected." + "Tests is_valid_dm(*) on a correct 3x3. True expected." y = np.random.rand(3) D = squareform(y) self.failUnless(is_valid_dm(D) == True) def test_is_valid_dm_correct_4_by_4(self): - "Tests is_valid_dm on a correct 4x4. True expected." + "Tests is_valid_dm(*) on a correct 4x4. True expected." y = np.random.rand(6) D = squareform(y) self.failUnless(is_valid_dm(D) == True) def test_is_valid_dm_correct_5_by_5(self): - "Tests is_valid_dm on a correct 5x5. True expected." + "Tests is_valid_dm(*) on a correct 5x5. True expected." y = np.random.rand(10) D = squareform(y) self.failUnless(is_valid_dm(D) == True) +def is_valid_y_throw(y): + return is_valid_y(y, throw=True) + +class TestIsValidY(TestCase): + + def test_is_valid_y_int16_array_E(self): + "Tests is_valid_y(*) on an int16 array. Exception expected." + y = np.zeros((10,), dtype='i') + self.failUnlessRaises(TypeError, is_valid_y_throw, (y)) + + def test_is_valid_y_int16_array_F(self): + "Tests is_valid_y(*) on an int16 array. False expected." + y = np.zeros((10,), dtype='i') + self.failUnless(is_valid_y(y) == False) + + def test_is_valid_y_improper_shape_2D_E(self): + "Tests is_valid_y(*) on a 2D array. Exception expected." + y = np.zeros((3,3,), dtype=np.double) + self.failUnlessRaises(ValueError, is_valid_y_throw, (y)) + + def test_is_valid_y_improper_shape_2D_F(self): + "Tests is_valid_y(*) on a 2D array. False expected." + y = np.zeros((3,3,), dtype=np.double) + self.failUnless(is_valid_y(y) == False) + + def test_is_valid_y_improper_shape_3D_E(self): + "Tests is_valid_y(*) on a 3D array. Exception expected." + y = np.zeros((3,3,3), dtype=np.double) + self.failUnlessRaises(ValueError, is_valid_y_throw, (y)) + + def test_is_valid_y_improper_shape_3D_F(self): + "Tests is_valid_y(*) on a 3D array. False expected." + y = np.zeros((3,3,3), dtype=np.double) + self.failUnless(is_valid_y(y) == False) + + def test_is_valid_y_correct_2_by_2(self): + "Tests is_valid_y(*) on a correct 2x2 condensed. True expected." + y = self.correct_n_by_n(2) + self.failUnless(is_valid_y(y) == True) + + def test_is_valid_y_correct_3_by_3(self): + "Tests is_valid_y(*) on a correct 3x3 condensed. True expected." + y = self.correct_n_by_n(3) + self.failUnless(is_valid_y(y) == True) + + def test_is_valid_y_correct_4_by_4(self): + "Tests is_valid_y(*) on a correct 4x4 condensed. True expected." + y = self.correct_n_by_n(4) + self.failUnless(is_valid_y(y) == True) + + def test_is_valid_y_correct_5_by_5(self): + "Tests is_valid_y(*) on a correct 5x5 condensed. True expected." + y = self.correct_n_by_n(5) + self.failUnless(is_valid_y(y) == True) + + def test_is_valid_y_2_100(self): + "Tests is_valid_y(*) on 100 improper condensed distance matrices. Expecting exception." + a = set([]) + for n in xrange(2, 16): + a.add(n*(n-1)/2) + print a + for i in xrange(5, 105): + if i not in a: + self.failUnlessRaises(ValueError, self.bad_y, i) + + def bad_y(self, n): + y = np.random.rand(n) + return is_valid_y(y, throw=True) + + def correct_n_by_n(self, n): + y = np.random.rand(n*(n-1)/2) + return y From scipy-svn at scipy.org Wed Nov 12 19:04:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 18:04:46 -0600 (CST) Subject: [Scipy-svn] r5071 - trunk/scipy/cluster/tests Message-ID: <20081113000446.6477539C05F@scipy.org> Author: damian.eads Date: 2008-11-12 18:04:43 -0600 (Wed, 12 Nov 2008) New Revision: 5071 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Minor tweak in hierarchy test code. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 00:03:06 UTC (rev 5070) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 00:04:43 UTC (rev 5071) @@ -581,3 +581,4 @@ if __name__ == "__main__": run_module_suite() + From scipy-svn at scipy.org Wed Nov 12 19:08:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 18:08:27 -0600 (CST) Subject: [Scipy-svn] r5072 - trunk/scipy/cluster Message-ID: <20081113000827.EA14039C05F@scipy.org> Author: damian.eads Date: 2008-11-12 18:08:24 -0600 (Wed, 12 Nov 2008) New Revision: 5072 Modified: trunk/scipy/cluster/hierarchy.py Log: Fixed heading in hierarchy documentation index. Added additional function in the index that didn't appear before. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-13 00:04:43 UTC (rev 5071) +++ trunk/scipy/cluster/hierarchy.py 2008-11-13 00:08:24 UTC (rev 5072) @@ -82,7 +82,8 @@ +------------------+-------------------------------------------------+ These are predicates for checking the validity of linkage and -inconsistency matrices, both condensed and redundant. +inconsistency matrices as well as for checking isomorphism of two +flat cluster assignments. +------------------+-------------------------------------------------+ |*Function* | *Description* | @@ -98,6 +99,9 @@ |Z_y_correspond |checks for validity of distance matrix given a | | |linkage. | +------------------+-------------------------------------------------+ +|numobs_linkage |the number of observations corresponding to a | +| |linkage matrix. | ++------------------+-------------------------------------------------+ * MATLAB and MathWorks are registered trademarks of The MathWorks, Inc. From scipy-svn at scipy.org Wed Nov 12 20:46:19 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 19:46:19 -0600 (CST) Subject: [Scipy-svn] r5073 - trunk/scipy/stats/tests Message-ID: <20081113014619.05B2239C05F@scipy.org> Author: josef Date: 2008-11-12 19:45:30 -0600 (Wed, 12 Nov 2008) New Revision: 5073 Added: trunk/scipy/stats/tests/test_discrete_chisquare.py Log: add chisquare test comparing random sample with cdf (first try of commit) Added: trunk/scipy/stats/tests/test_discrete_chisquare.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-13 00:08:24 UTC (rev 5072) +++ trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-13 01:45:30 UTC (rev 5073) @@ -0,0 +1,102 @@ + +import numpy as np +from scipy import stats + +debug = False + + +def check_discrete_chisquare(distname, arg, alpha = 0.01): + '''perform chisquare test for random sample of a discrete distribution + + Parameters + ---------- + distname : string + name of distribution function + arg : sequence + parameters of distribution + alpha : float + significance level, threshold for p-value + + Returns + ------- + result : bool + 0 if test passes, 1 if test fails + + uses global variable debug for printing results + ''' + + # define parameters for test + n=50000 + nsupp = 20 + wsupp = 1.0/nsupp + + distfn = getattr(stats, distname) + rvs = distfn.rvs(size=n,*arg) + + # construct intervals with minimum mass 1/nsupp + # intervalls are left-half-open as in a cdf difference + distsupport = xrange(max(distfn.a, -1000), min(distfn.b, 1000) + 1) + last = 0 + distsupp = [max(distfn.a, -1000)] + distmass = [] + for ii in distsupport: + current = distfn.cdf(ii,*arg) + if current - last >= wsupp-1e-14: + distsupp.append(ii) + distmass.append(current - last) + last = current + if current > (1-wsupp): + break + if distsupp[-1] < distfn.b: + distsupp.append(distfn.b) + distmass.append(1-last) + distsupp = np.array(distsupp) + distmass = np.array(distmass) + + # convert intervals to right-half-open as required by histogram + histsupp = distsupp+1e-8 + histsupp[0] = distfn.a + + # find sample frequencies and perform chisquare test + freq,hsupp = np.histogram(rvs,histsupp,new=True) + cdfs = distfn.cdf(distsupp,*arg) + (chis,pval) = stats.chisquare(np.array(freq),n*distmass) + + # print and return results + if debug: + print 'chis,pval:', chis, pval + print 'len(distsupp), len(distmass), len(hsupp), len(freq)' + print len(distsupp), len(distmass), len(hsupp), len(freq) + print 'distsupp', distsupp + print 'distmass', n*np.array(distmass) + print 'freq', freq + print 'itemfreq', stats.itemfreq(rvs) + print 'n*pmf', n*distfn.pmf(list(distsupport)[:10],*arg) + + assert (pval > alpha), 'chisquare - test for %s' \ + 'at arg = %s' % (distname,str(arg)) + + +def test_discrete_rvs_cdf(): + distdiscrete = [ + ['bernoulli',(0.3,)], + ['binom', (5, 0.4)], + ['boltzmann',(1.4, 19)], + ['dlaplace', (0.8,)], + ['geom', (0.5,)], + ['hypergeom',(30, 12, 6)], + ['logser', (0.6,)], + ['nbinom', (5, 0.5)], + ['planck', (4.1,)], + ['poisson', (0.6,)], + ['randint', (7, 31)], + ['zipf', (2,)] ] + + for distname, arg in distdiscrete: + if debug: + print distname + yield check_discrete_chisquare, distname, arg + +if __name__ == '__main__': + import nose + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Wed Nov 12 21:30:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 20:30:47 -0600 (CST) Subject: [Scipy-svn] r5074 - trunk/scipy/stats Message-ID: <20081113023047.8AFC839C05F@scipy.org> Author: josef Date: 2008-11-12 20:30:45 -0600 (Wed, 12 Nov 2008) New Revision: 5074 Modified: trunk/scipy/stats/distributions.py Log: correct function _drv2_moment which didn't do anything before Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 01:45:30 UTC (rev 5073) +++ trunk/scipy/stats/distributions.py 2008-11-13 02:30:45 UTC (rev 5074) @@ -3267,15 +3267,36 @@ return sum(exp(self.xk * t[newaxis,...]) * self.pk, axis=0) def _drv2_moment(self, n, *args): + '''non-central moment of discrete distribution''' + #many changes, originally not even a return tot = 0.0 diff = 1e100 - pos = self.a + #pos = self.a + pos = max(0, self.a) count = 0 - while (pos <= self.b) and ((pos >= (self.b + self.a)/2.0) and \ + #handle cases with infinite support + ulimit = max(1000, (min(self.b,1000) + max(self.a,-1000))/2.0 ) + llimit = min(-1000, (min(self.b,1000) + max(self.a,-1000))/2.0 ) + + while (pos <= self.b) and ((pos <= ulimit) or \ (diff > self.moment_tol)): - diff = pos**n * self._pdf(pos,*args) + diff = pos**n * self.pmf(pos,*args) + # use pmf because _pmf does not check support in randint + # and there might be problems ? with correct self.a, self.b at this stage tot += diff pos += self.inc + count += 1 + + if self.a < 0: #handle case when self.a = -inf + diff = 1e100 + pos = -self.inc + while (pos >= self.a) and ((pos >= llimit) or \ + (diff > self.moment_tol)): + diff = pos**n * self.pmf(pos,*args) #using pmf instead of _pmf + tot += diff + pos -= self.inc + count += 1 + return tot def _drv2_ppfsingle(self, q, *args): # Use basic bisection algorithm b = self.invcdf_b From scipy-svn at scipy.org Wed Nov 12 21:38:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 20:38:12 -0600 (CST) Subject: [Scipy-svn] r5075 - trunk/scipy/stats Message-ID: <20081113023812.3A35839C05F@scipy.org> Author: josef Date: 2008-11-12 20:38:10 -0600 (Wed, 12 Nov 2008) New Revision: 5075 Modified: trunk/scipy/stats/distributions.py Log: correct error at lower bound in _drv2_ppfsingle Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 02:30:45 UTC (rev 5074) +++ trunk/scipy/stats/distributions.py 2008-11-13 02:38:10 UTC (rev 5075) @@ -3326,7 +3326,14 @@ if (qb == q): return b if b == a+1: - return b + #testcase: return wrong number at lower index + #python -c "from scipy.stats import zipf;print zipf.ppf(0.01,2)" wrong + #python -c "from scipy.stats import zipf;print zipf.ppf([0.01,0.61,0.77,0.83],2)" + #python -c "from scipy.stats import logser;print logser.ppf([0.1,0.66, 0.86,0.93],0.6)" + if qa > q: + return a + else: + return b c = int((a+b)/2.0) qc = self._cdf(c, *args) if (qc < q): From scipy-svn at scipy.org Wed Nov 12 21:42:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 20:42:36 -0600 (CST) Subject: [Scipy-svn] r5076 - trunk/scipy/stats Message-ID: <20081113024236.E67BB39C05F@scipy.org> Author: josef Date: 2008-11-12 20:42:35 -0600 (Wed, 12 Nov 2008) New Revision: 5076 Modified: trunk/scipy/stats/distributions.py Log: add missing keyword argument in stats of frozen distribution Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 02:38:10 UTC (rev 5075) +++ trunk/scipy/stats/distributions.py 2008-11-13 02:42:35 UTC (rev 5076) @@ -105,7 +105,7 @@ self.args = args self.kwds = kwds self.dist = dist - def pdf(self,x): + def pdf(self,x): #raises AttributeError in frozen discrete distribution return self.dist.pdf(x,*self.args,**self.kwds) def cdf(self,x): return self.dist.cdf(x,*self.args,**self.kwds) @@ -119,8 +119,10 @@ return self.dist.rvs(*self.args,**kwds) def sf(self,x): return self.dist.sf(x,*self.args,**self.kwds) - def stats(self): - return self.dist.stats(*self.args,**self.kwds) + def stats(self,moments='mv'): + kwds = self.kwds + kwds.update({'moments':moments}) + return self.dist.stats(*self.args,**kwds) def moment(self,n): return self.dist.moment(n,*self.args,**self.kwds) def entropy(self): From scipy-svn at scipy.org Wed Nov 12 22:37:41 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 21:37:41 -0600 (CST) Subject: [Scipy-svn] r5077 - trunk/scipy/stats Message-ID: <20081113033741.C3B1239C05F@scipy.org> Author: josef Date: 2008-11-12 21:37:39 -0600 (Wed, 12 Nov 2008) New Revision: 5077 Modified: trunk/scipy/stats/distributions.py Log: fixing broken generic methods in rv_discrete Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 02:42:35 UTC (rev 5076) +++ trunk/scipy/stats/distributions.py 2008-11-13 03:37:39 UTC (rev 5077) @@ -8,6 +8,8 @@ from scipy.misc import comb, derivative from scipy import special from scipy import optimize +import scipy.integrate + import inspect from numpy import alltrue, where, arange, put, putmask, \ ravel, take, ones, sum, shape, product, repeat, reshape, \ @@ -17,6 +19,7 @@ any, argsort, argmax, vectorize, r_, asarray, nan, inf, pi, isnan, isinf, \ power import numpy +import numpy as np import numpy.random as mtrand from numpy import flatnonzero as nonzero from scipy.special import gammaln as gamln @@ -3421,7 +3424,7 @@ self.badvalue = badvalue self.a = a self.b = b - self.invcdf_a = a + self.invcdf_a = a # what's the difference to self.a, .b self.invcdf_b = b self.name = name self.moment_tol = moment_tol @@ -3457,17 +3460,30 @@ self, rv_discrete) self.numargs=0 else: - self._vecppf = new.instancemethod(sgf(_drv2_ppfsingle,otypes='d'), - self, rv_discrete) - self.generic_moment = new.instancemethod(sgf(_drv2_moment, - otypes='d'), - self, rv_discrete) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pmf_signature = inspect.getargspec(self._pmf.im_func) numargs2 = len(pmf_signature[0]) - 2 self.numargs = max(numargs1, numargs2) + #nin correction needs to be after we know numargs + #correct nin for generic moment vectorization + self.vec_generic_moment = sgf(_drv2_moment, otypes='d') + self.vec_generic_moment.nin = self.numargs + 2 + self.generic_moment = new.instancemethod(self.vec_generic_moment, + self, rv_discrete) + + #correct nin for ppf vectorization + _vppf = sgf(_drv2_ppfsingle,otypes='d') + _vppf.nin = self.numargs + 2 # +1 is for self + self._vecppf = new.instancemethod(_vppf, + self, rv_discrete) + + + + #now that self.numargs is defined, we can adjust nin + self._cdfvec.nin = self.numargs + 1 + if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " @@ -3523,7 +3539,7 @@ return None, None, None, None def _munp(self, n, *args): - return self.generic_moment(n) + return self.generic_moment(n, *args) def rvs(self, *args, **kwargs): @@ -3582,8 +3598,10 @@ output = zeros(shape(cond),'d') place(output,(1-cond0)*(cond1==cond1),self.badvalue) place(output,cond2*(cond0==cond0), 1.0) - goodargs = argsreduce(cond, *((k,)+args)) - place(output,cond,self._cdf(*goodargs)) + + if any(cond): + goodargs = argsreduce(cond, *((k,)+args)) + place(output,cond,self._cdf(*goodargs)) if output.ndim == 0: return output[()] return output @@ -3638,12 +3656,15 @@ cond1 = (q > 0) & (q < 1) cond2 = (q==1) & cond0 cond = cond0 & cond1 - output = valarray(shape(cond),value=self.a-1) - place(output,(1-cond0)*(cond1==cond1), self.badvalue) + output = valarray(shape(cond),value=self.badvalue,typecode='d') + #output type 'd' to handle nin and inf + place(output,(q==0)*(cond==cond), self.a-1) place(output,cond2,self.b) - goodargs = argsreduce(cond, *((q,)+args+(loc,))) - loc, goodargs = goodargs[-1], goodargs[:-1] - place(output,cond,self._ppf(*goodargs) + loc) + if any(cond): + goodargs = argsreduce(cond, *((q,)+args+(loc,))) + loc, goodargs = goodargs[-1], goodargs[:-1] + place(output,cond,self._ppf(*goodargs) + loc) + if output.ndim == 0: return output[()] return output @@ -3669,12 +3690,21 @@ cond1 = (q > 0) & (q < 1) cond2 = (q==1) & cond0 cond = cond0 & cond1 - output = valarray(shape(cond),value=self.b) + output = valarray(shape(cond),value=self.b,typecode='d') + #typecode 'd' to handle nin and inf place(output,(1-cond0)*(cond1==cond1), self.badvalue) place(output,cond2,self.a-1) - goodargs = argsreduce(cond, *((q,)+args+(loc,))) - loc, goodargs = goodargs[-1], goodargs[:-1] - place(output,cond,self._ppf(*goodargs) + loc) + + + #same problem as with ppf + + + # call place only if at least 1 valid argument + if any(cond): + goodargs = argsreduce(cond, *((q,)+args+(loc,))) + loc, goodargs = goodargs[-1], goodargs[:-1] + place(output,cond,self._isf(*goodargs) + loc) #PB same as ticket 766 + if output.ndim == 0: return output[()] return output @@ -3797,8 +3827,8 @@ if mu is None: return self._munp(1,*args) else: return mu elif (n==2): - if mu2 is None: return self._munp(2,*args) - else: return mu + if mu2 is None or mu is None: return self._munp(2,*args) + else: return mu2 + mu*mu elif (n==3): if g1 is None or mu2 is None: return self._munp(3,*args) else: return g1*(mu2**1.5) From scipy-svn at scipy.org Wed Nov 12 22:48:57 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 21:48:57 -0600 (CST) Subject: [Scipy-svn] r5078 - trunk/scipy/stats Message-ID: <20081113034857.BD5E239C05F@scipy.org> Author: josef Date: 2008-11-12 21:48:56 -0600 (Wed, 12 Nov 2008) New Revision: 5078 Modified: trunk/scipy/stats/distributions.py Log: corrections in discrete distributions randint, and dlaplace, skip partially broken dlaplace._stats Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 03:37:39 UTC (rev 5077) +++ trunk/scipy/stats/distributions.py 2008-11-13 03:48:56 UTC (rev 5078) @@ -4080,6 +4080,8 @@ # FIXME: Fails _cdfvec class logser_gen(rv_discrete): def _rvs(self, pr): + # looks wrong for pr>0.5, too few k=1 + # trying to use generic is worse, no k=1 at all return mtrand.logseries(pr,size=self._size) def _argcheck(self, pr): return (pr > 0) & (pr < 1) @@ -4238,7 +4240,7 @@ k = floor(x) return (k-min+1)*1.0/(max-min) def _ppf(self, q, min, max): - val = ceil(q*(max-min)+min) + val = ceil(q*(max-min)+min)-1 return val def _stats(self, min, max): m2, m1 = arr(max), arr(min) @@ -4324,8 +4326,13 @@ const = 1.0/(1+exp(-a)) cons2 = 1+exp(a) ind = q < const - return ceil(1.0/a*where(ind, log(q*cons2)-1, -log((1-q)*cons2))) - def _stats(self, a): + return ceil(where(ind, log(q*cons2)/a-1, -log((1-q)*cons2)/a)) + + def _stats_skip(self, a): + # variance mu2 does not aggree with sample variance, + # nor with direct calculation using pmf + # remove for now because generic calculation works + # except it does not show nice zeros for mean and skew(?) ea = exp(-a) e2a = exp(-2*a) e3a = exp(-3*a) From scipy-svn at scipy.org Wed Nov 12 22:51:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 21:51:09 -0600 (CST) Subject: [Scipy-svn] r5079 - trunk/scipy/stats/tests Message-ID: <20081113035109.2BC7339C05F@scipy.org> Author: josef Date: 2008-11-12 21:51:07 -0600 (Wed, 12 Nov 2008) New Revision: 5079 Added: trunk/scipy/stats/tests/test_discrete_basic.py Log: add test for basic methods of discrete distributions Added: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-13 03:48:56 UTC (rev 5078) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-13 03:51:07 UTC (rev 5079) @@ -0,0 +1,116 @@ +import numpy.testing as npt +import numpy as np +import nose + +from scipy import stats + +distdiscrete = [ + ['bernoulli',(0.3,)], + ['binom', (5, 0.4)], + ['boltzmann',(1.4, 19)], + ['dlaplace', (0.8,)], #0.5 + ['geom', (0.5,)], + ['hypergeom',(30, 12, 6)], + ['logser', (0.6,)], + ['nbinom', (5, 0.5)], + ['planck', (0.51,)], #4.1 + ['poisson', (0.6,)], + ['randint', (7, 31)], + ['zipf', (4,)] ] # arg=4 is ok, + # Zipf broken for arg = 2, e.g. weird .stats + +def test_discrete_basic(): + for distname, arg in distdiscrete: + distfn = getattr(stats,distname) + #assert stats.dlaplace.rvs(0.8) != None + rvs = distfn.rvs(size=10000,*arg) + m,v = distfn.stats(*arg) + #yield npt.assert_almost_equal(rvs.mean(), m, decimal=4,err_msg='mean') + #yield npt.assert_almost_equal, rvs.mean(), m, 2, 'mean' # does not work + yield check_sample_mean, rvs.mean(), m, distname + 'sample mean test' + yield check_sample_mean, rvs.var(), v, distname + 'sample var test' + yield check_cdf_ppf, distfn, arg + yield check_pmf_cdf, distfn, arg + yield check_oth, distfn, arg + +def test_discrete_private(): + #testing private methods mostly for debugging + # some tests might fail by design, + # e.g. incorrect definition of distfn.a and distfn.b + for distname, arg in distdiscrete: + distfn = getattr(stats,distname) + rvs = distfn.rvs(size=10000,*arg) + m,v = distfn.stats(*arg) + + yield check_ppf_ppf, distfn, arg + yield check_cdf_ppf_private, distfn, arg + yield check_generic_moment, distfn, arg, m, 1, 3 # last is decimal + yield check_generic_moment, distfn, arg, v+m*m, 2, 3 # last is decimal + yield check_moment_frozen, distfn, arg, m, 1, 3 # last is decimal + yield check_moment_frozen, distfn, arg, v+m*m, 2, 3 # last is decimal + + +def check_sample_mean(sm,m,msg): + if m < np.inf: + npt.assert_almost_equal(sm, m, decimal=0, err_msg=msg + \ + ' - finite moment') + else: + assert sm > 10000, 'infinite moment, sm = ' + str(sm) + +def check_sample_var(sm,m): + npt.assert_almost_equal(sm, m, decimal=0, err_msg= 'var') + +def check_cdf_ppf(distfn,arg): + ppf05 = distfn.ppf(0.5,*arg) + cdf05 = distfn.cdf(ppf05,*arg) + npt.assert_almost_equal(distfn.ppf(cdf05-1e-6,*arg),ppf05, + err_msg=str(distfn) + 'ppf-cdf-median') + assert (distfn.ppf(cdf05+1e-4,*arg)>ppf05), str(distfn) + 'ppf-cdf-next' + +def check_cdf_ppf_private(distfn,arg): + ppf05 = distfn._ppf(0.5,*arg) + cdf05 = distfn.cdf(ppf05,*arg) + npt.assert_almost_equal(distfn._ppf(cdf05-1e-6,*arg),ppf05, + err_msg=str(distfn) + 'ppf-cdf-median') + assert (distfn._ppf(cdf05+1e-4,*arg)>ppf05), str(distfn) + 'ppf-cdf-next' + +def check_ppf_ppf(distfn, arg): + assert distfn.ppf(0.5,*arg) < np.inf + ppfs = distfn.ppf([0.5,0.9],*arg) + ppf_s = [distfn._ppf(0.5,*arg), distfn._ppf(0.9,*arg)] + assert np.all(ppfs < np.inf) + assert ppf_s[0] == distfn.ppf(0.5,*arg) + assert ppf_s[1] == distfn.ppf(0.9,*arg) + assert ppf_s[0] == ppfs[0] + assert ppf_s[1] == ppfs[1] + +def check_pmf_cdf(distfn, arg): + startind = np.int(distfn._ppf(0.01,*arg)-1) + index = range(startind,startind+10) + cdfs = distfn.cdf(index,*arg) + npt.assert_almost_equal(cdfs, distfn.pmf(index, *arg).cumsum() + \ + cdfs[0] - distfn.pmf(index[0],*arg), + decimal=4, err_msg='pmf-cdf') + +def check_generic_moment(distfn, arg, m, k, decim): + npt.assert_almost_equal(distfn.generic_moment(k,*arg), m, decimal=decim, + err_msg= str(distfn) + ' generic moment test') + +def check_moment_frozen(distfn, arg, m, k, decim): + npt.assert_almost_equal(distfn(*arg).moment(k), m, decimal=decim, + err_msg= str(distfn) + ' frozen moment test') + +def check_oth(distfn, arg): + #checking other methods of distfn + meanint = round(distfn.stats(*arg)[0]) # closest integer to mean + npt.assert_almost_equal(distfn.sf(meanint, *arg), 1 - \ + distfn.cdf(meanint, *arg), decimal=8) + median_sf = distfn.isf(0.5, *arg) + + assert distfn.sf(median_sf - 1, *arg) > 0.5 + assert distfn.cdf(median_sf + 1, *arg) > 0.5 + npt.assert_equal(distfn.isf(0.5, *arg), distfn.ppf(0.5, *arg)) + + +if __name__ == "__main__": + nose.run(argv=['', __file__]) From scipy-svn at scipy.org Wed Nov 12 23:00:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:00:27 -0600 (CST) Subject: [Scipy-svn] r5080 - trunk/scipy/stats Message-ID: <20081113040027.BBEE739C05F@scipy.org> Author: josef Date: 2008-11-12 22:00:24 -0600 (Wed, 12 Nov 2008) New Revision: 5080 Modified: trunk/scipy/stats/distributions.py Log: corrections to broken generic methods for rv_continuous Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 03:51:07 UTC (rev 5079) +++ trunk/scipy/stats/distributions.py 2008-11-13 04:00:24 UTC (rev 5080) @@ -385,15 +385,23 @@ self._size = 1 self.m = 0.0 self.moment_type = momtype + + self.expandarr = 1 + + if not hasattr(self,'numargs'): + #allows more general subclassing with *args + cdf_signature = inspect.getargspec(self._cdf.im_func) + numargs1 = len(cdf_signature[0]) - 2 + pdf_signature = inspect.getargspec(self._pdf.im_func) + numargs2 = len(pdf_signature[0]) - 2 + self.numargs = max(numargs1, numargs2) + #nin correction self.vecfunc = sgf(self._ppf_single_call,otypes='d') + self.vecfunc.nin = self.numargs + 1 self.vecentropy = sgf(self._entropy,otypes='d') + self.vecentropy.nin = self.numargs + 1 self.veccdf = sgf(self._cdf_single_call,otypes='d') - self.expandarr = 1 - cdf_signature = inspect.getargspec(self._cdf.im_func) - numargs1 = len(cdf_signature[0]) - 2 - pdf_signature = inspect.getargspec(self._pdf.im_func) - numargs2 = len(pdf_signature[0]) - 2 - self.numargs = max(numargs1, numargs2) + self.veccdf.nin = self.numargs+1 self.shapes = shapes self.extradoc = extradoc if momtype == 0: @@ -410,7 +418,8 @@ if self.__doc__ is None: self.__doc__ = rv_continuous.__doc__ if self.__doc__ is not None: - self.__doc__ = self.__doc__.replace("A Generic",longname) + if longname is not None: + self.__doc__ = self.__doc__.replace("A Generic",longname) if name is not None: self.__doc__ = self.__doc__.replace("generic",name) if shapes is None: @@ -471,7 +480,7 @@ return self.vecfunc(q,*args) def _isf(self, q, *args): - return self.vecfunc(1.0-q,*args) + return self._ppf(1.0-q,*args) #use correct _ppf for subclasses # The actual cacluation functions (no basic checking need be done) # If these are defined, the others won't be looked at. @@ -539,8 +548,9 @@ output = zeros(shape(cond),'d') place(output,(1-cond0)*(cond1==cond1),self.badvalue) place(output,cond2,1.0) - goodargs = argsreduce(cond, *((x,)+args)) - place(output,cond,self._cdf(*goodargs)) + if any(cond): #call only if at least 1 entry + goodargs = argsreduce(cond, *((x,)+args)) + place(output,cond,self._cdf(*goodargs)) if output.ndim == 0: return output[()] return output @@ -600,9 +610,10 @@ output = valarray(shape(cond),value=self.a*scale + loc) place(output,(1-cond0)+(1-cond1)*(q!=0.0), self.badvalue) place(output,cond2,self.b*scale + loc) - goodargs = argsreduce(cond, *((q,)+args+(scale,loc))) - scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] - place(output,cond,self._ppf(*goodargs)*scale + loc) + if any(cond): #call only if at least 1 entry + goodargs = argsreduce(cond, *((q,)+args+(scale,loc))) + scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] + place(output,cond,self._ppf(*goodargs)*scale + loc) if output.ndim == 0: return output[()] return output @@ -631,9 +642,9 @@ output = valarray(shape(cond),value=self.b) place(output,(1-cond0)*(cond1==cond1), self.badvalue) place(output,cond2,self.a) - goodargs = argsreduce(cond, *((1.0-q,)+args+(scale,loc))) + goodargs = argsreduce(cond, *((q,)+args+(scale,loc))) #PB replace 1-q by q scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] - place(output,cond,self._ppf(*goodargs)*scale + loc) + place(output,cond,self._isf(*goodargs)*scale + loc) #PB use _isf instead of _ppf if output.ndim == 0: return output[()] return output @@ -687,7 +698,7 @@ if g1 is None: mu3 = None else: - mu3 = g1*(mu2**1.5) + mu3 = g1*np.power(mu2,1.5) #(mu2**1.5) breaks down for nan and nin default = valarray(shape(cond), self.badvalue) output = [] @@ -763,8 +774,8 @@ if mu is None: return self._munp(1,*args) else: return mu elif (n==2): - if mu2 is None: return self._munp(2,*args) - else: return mu + if mu2 is None or mu is None: return self._munp(2,*args) + else: return mu2 + mu*mu elif (n==3): if g1 is None or mu2 is None: return self._munp(3,*args) else: return g1*(mu2**1.5) From scipy-svn at scipy.org Wed Nov 12 23:03:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:03:58 -0600 (CST) Subject: [Scipy-svn] r5081 - in trunk/scipy/cluster: . tests Message-ID: <20081113040358.774A839C05F@scipy.org> Author: damian.eads Date: 2008-11-12 22:03:56 -0600 (Wed, 12 Nov 2008) New Revision: 5081 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for correspond and numobs_linkage. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-13 04:00:24 UTC (rev 5080) +++ trunk/scipy/cluster/hierarchy.py 2008-11-13 04:03:56 UTC (rev 5081) @@ -96,8 +96,8 @@ +------------------+-------------------------------------------------+ |is_monotonic |checks if a linkage is monotonic. | +------------------+-------------------------------------------------+ -|Z_y_correspond |checks for validity of distance matrix given a | -| |linkage. | +|correspond |checks whether a condensed distance matrix | +| |corresponds with a linkage | +------------------+-------------------------------------------------+ |numobs_linkage |the number of observations corresponding to a | | |linkage matrix. | @@ -590,7 +590,7 @@ s = y.shape if len(s) == 1: distance.is_valid_y(y, throw=True, name='y') - d = np.ceil(np.sqrt(s[0] * 2)) + d = distance.numobs_y(y) if method not in _cpy_non_euclid_methods.keys(): raise ValueError("Valid methods when the raw observations are omitted are 'single', 'complete', 'weighted', and 'average'.") # Since the C code does not support striding using strides. @@ -1205,6 +1205,8 @@ raise ValueError('Linkage matrix \'%s\' must have 4 columns.' % name) else: raise ValueError('Linkage matrix must have 4 columns.') + if Z.shape[0] == 0: + raise ValueError('Linkage must be over at least one observation.') n = Z.shape[0] if n > 1: if ((Z[:,0] < 0).any() or @@ -1238,7 +1240,7 @@ is_valid_linkage(Z, throw=True, name='Z') return (Z.shape[0] + 1) -def Z_y_correspond(Z, Y): +def correspond(Z, Y): """ Checks if a linkage matrix Z and condensed distance matrix Y could possibly correspond to one another. @@ -1262,6 +1264,8 @@ A boolean indicating whether the linkage matrix and distance matrix could possibly correspond to one another. """ + is_valid_linkage(Z, throw=True) + distance.is_valid_y(Y, throw=True) Z = np.asarray(Z, order='c') Y = np.asarray(Y, order='c') return distance.numobs_y(Y) == numobs_linkage(Z) Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 04:00:24 UTC (rev 5080) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 04:03:56 UTC (rev 5081) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, numobs_linkage, correspond from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -135,6 +135,11 @@ class TestLinkage(TestCase): + def test_linkage_empty_distance_matrix(self): + "Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected." + y = np.zeros((0,)) + self.failUnlessRaises(ValueError, linkage, y) + ################### linkage def test_linkage_single_tdist(self): "Tests linkage(Y, 'single') on the tdist data set." @@ -537,7 +542,6 @@ for k in xrange(0, 3): self.help_is_isomorphic_randperm(1000, 5) - def test_is_isomorphic_6A(self): "Tests is_isomorphic on test case #5A (1000 observations, 2 random clusters, random permutation of the labeling, slightly nonisomorphic.) Run 3 times." for k in xrange(0, 3): @@ -567,6 +571,61 @@ self.failUnless(is_isomorphic(a, b) == (not noniso)) self.failUnless(is_isomorphic(b, a) == (not noniso)) +class TestNumObsLinkage(TestCase): + + def test_numobs_linkage_empty(self): + "Tests numobs_linkage(Z) with empty linkage." + Z = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, numobs_linkage, Z) + + + def test_numobs_linkage_1x4(self): + "Tests numobs_linkage(Z) on linkage over 2 observations." + Z = np.asarray([[0, 1, 3.0, 2]], dtype=np.double) + self.failUnless(numobs_linkage(Z) == 2) + + def test_numobs_linkage_2x4(self): + "Tests numobs_linkage(Z) on linkage over 3 observations." + Z = np.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=np.double) + self.failUnless(numobs_linkage(Z) == 3) + + def test_numobs_linkage_4_and_up(self): + "Tests numobs_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3)." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + self.failUnless(numobs_linkage(Z) == i) + +class TestCorrespond(TestCase): + + def test_correspond_empty(self): + "Tests correspond(Z, y) with empty linkage and condensed distance matrix." + y = np.zeros((0,)) + Z = np.zeros((0,4)) + self.failUnlessRaises(ValueError, correspond, Z, y) + + def test_correspond_2_and_up(self): + "Tests correspond(Z, y) on linkage and CDMs over observation sets of different sizes." + for i in xrange(2, 4): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + self.failUnless(correspond(Z, y)) + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + self.failUnless(correspond(Z, y)) + + def test_correspond_4_and_up(self): + "Tests correspond(Z, y) on linkage and CDMs over observation sets between sizes 4 and 15 (step size 3)." + for (i, j) in zip(range(2, 4), range(3, 5)) + zip(range(3, 5), range(2, 4)): + y = np.random.rand(i*(i-1)/2) + y2 = np.random.rand(j*(j-1)/2) + Z = linkage(y) + Z2 = linkage(y2) + self.failUnless(correspond(Z, y2) == False) + self.failUnless(correspond(Z2, y) == False) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Wed Nov 12 23:04:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:04:25 -0600 (CST) Subject: [Scipy-svn] r5082 - tags Message-ID: <20081113040425.7717339C05F@scipy.org> Author: cdavid Date: 2008-11-12 22:04:05 -0600 (Wed, 12 Nov 2008) New Revision: 5082 Added: tags/scipy-with-arpack/ Log: Tag the trunk just before the removing of ARPACK until license clarification. Copied: tags/scipy-with-arpack (from rev 5081, trunk) From scipy-svn at scipy.org Wed Nov 12 23:06:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:06:11 -0600 (CST) Subject: [Scipy-svn] r5083 - trunk/scipy/stats Message-ID: <20081113040611.C5CAF39C05F@scipy.org> Author: josef Date: 2008-11-12 22:06:09 -0600 (Wed, 12 Nov 2008) New Revision: 5083 Modified: trunk/scipy/stats/distributions.py Log: corrections for continuous distributions: alpha, foldcauchy, powerlognorm, recipinvgauss Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 04:04:05 UTC (rev 5082) +++ trunk/scipy/stats/distributions.py 2008-11-13 04:06:09 UTC (rev 5083) @@ -925,7 +925,7 @@ return special.ndtr(a-1.0/x) / special.ndtr(a) def _ppf(self, q, a): return 1.0/arr(a-special.ndtri(q*special.ndtr(a))) - def _stats(self): + def _stats(self, a): return [inf]*2 + [nan]*2 alpha = alpha_gen(a=0.0,name='alpha',shapes='a',extradoc=""" @@ -1461,7 +1461,7 @@ return 1.0/pi*(1.0/(1+(x-c)**2) + 1.0/(1+(x+c)**2)) def _cdf(self, x, c): return 1.0/pi*(arctan(x-c) + arctan(x+c)) - def _stats(self, x, c): + def _stats(self, c): return inf, inf, nan, nan foldcauchy = foldcauchy_gen(a=0.0, name='foldcauchy', longname = "A folded Cauchy", @@ -2769,7 +2769,8 @@ class powerlognorm_gen(rv_continuous): def _pdf(self, x, c, s): - return c/(x*s)*norm.pdf(log(x)/s) + return c/(x*s)*norm.pdf(log(x)/s)*pow(norm.cdf(-log(x)/s),c*1.0-1.0) + def _cdf(self, x, c, s): return 1.0 - pow(norm.cdf(-log(x)/s),c*1.0) def _ppf(self, q, c, s): @@ -2911,6 +2912,8 @@ # FIXME: PPF does not work. class recipinvgauss_gen(rv_continuous): + def _rvs(self, mu): #added, taken from invnorm + return 1.0/mtrand.wald(mu, 1.0, size=self._size) def _pdf(self, x, mu): return 1.0/sqrt(2*pi*x)*exp(-(1-mu*x)**2.0 / (2*x*mu**2.0)) def _cdf(self, x, mu): @@ -2918,7 +2921,8 @@ trm2 = 1.0/mu + x isqx = 1.0/sqrt(x) return 1.0-norm.cdf(isqx*trm1)-exp(2.0/mu)*norm.cdf(-isqx*trm2) -recipinvgauss = recipinvgauss_gen(a=0.0, name='recipinvgauss', + # xb=50 or something large is necessary for stats to converge without exception +recipinvgauss = recipinvgauss_gen(a=0.0, xb=50, name='recipinvgauss', longname="A reciprocal inverse Gaussian", shapes="mu", extradoc=""" From scipy-svn at scipy.org Wed Nov 12 23:09:22 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:09:22 -0600 (CST) Subject: [Scipy-svn] r5084 - in trunk/scipy: cluster cluster/tests spatial/tests Message-ID: <20081113040922.D535139C05F@scipy.org> Author: damian.eads Date: 2008-11-12 22:09:20 -0600 (Wed, 12 Nov 2008) New Revision: 5084 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py trunk/scipy/spatial/tests/test_distance.py Log: Renamed numobs_linkage to num_obs_linkage. Moved some distance tests from test_hierarchy to test_distance. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-13 04:06:09 UTC (rev 5083) +++ trunk/scipy/cluster/hierarchy.py 2008-11-13 04:09:20 UTC (rev 5084) @@ -99,7 +99,7 @@ |correspond |checks whether a condensed distance matrix | | |corresponds with a linkage | +------------------+-------------------------------------------------+ -|numobs_linkage |the number of observations corresponding to a | +|num_obs_linkage |the number of observations corresponding to a | | |linkage matrix. | +------------------+-------------------------------------------------+ @@ -1223,7 +1223,7 @@ valid = False return valid -def numobs_linkage(Z): +def num_obs_linkage(Z): """ Returns the number of original observations of the linkage matrix passed. @@ -1268,7 +1268,7 @@ distance.is_valid_y(Y, throw=True) Z = np.asarray(Z, order='c') Y = np.asarray(Y, order='c') - return distance.numobs_y(Y) == numobs_linkage(Z) + return distance.numobs_y(Y) == num_obs_linkage(Z) def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None): """ Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 04:06:09 UTC (rev 5083) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 04:09:20 UTC (rev 5084) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, numobs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, numobs_linkage, correspond +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -104,34 +104,15 @@ class TestNumObs(TestCase): - ############## numobs_dm - def test_numobs_dm_multi_matrix(self): - "Tests numobs_dm with observation matrices of multiple sizes." - for n in xrange(1, 10): - X = np.random.rand(n, 4) - Y = pdist(X) - A = squareform(Y) - if verbose >= 3: - print A.shape, Y.shape - self.failUnless(numobs_dm(A) == n) - - def test_numobs_y_multi_matrix(self): - "Tests numobs_y with observation matrices of multiple sizes." + def test_num_obs_linkage_multi_matrix(self): + "Tests num_obs_linkage with observation matrices of multiple sizes." for n in xrange(2, 10): X = np.random.rand(n, 4) Y = pdist(X) - #print A.shape, Y.shape, Yr.shape - self.failUnless(numobs_y(Y) == n) - - def test_numobs_linkage_multi_matrix(self): - "Tests numobs_linkage with observation matrices of multiple sizes." - for n in xrange(2, 10): - X = np.random.rand(n, 4) - Y = pdist(X) Z = linkage(Y) #print Z #print A.shape, Y.shape, Yr.shape - self.failUnless(numobs_linkage(Z) == n) + self.failUnless(num_obs_linkage(Z) == n) class TestLinkage(TestCase): @@ -573,29 +554,29 @@ class TestNumObsLinkage(TestCase): - def test_numobs_linkage_empty(self): - "Tests numobs_linkage(Z) with empty linkage." + def test_num_obs_linkage_empty(self): + "Tests num_obs_linkage(Z) with empty linkage." Z = np.zeros((0, 4), dtype=np.double) - self.failUnlessRaises(ValueError, numobs_linkage, Z) + self.failUnlessRaises(ValueError, num_obs_linkage, Z) - def test_numobs_linkage_1x4(self): - "Tests numobs_linkage(Z) on linkage over 2 observations." + def test_num_obs_linkage_1x4(self): + "Tests num_obs_linkage(Z) on linkage over 2 observations." Z = np.asarray([[0, 1, 3.0, 2]], dtype=np.double) - self.failUnless(numobs_linkage(Z) == 2) + self.failUnless(num_obs_linkage(Z) == 2) - def test_numobs_linkage_2x4(self): - "Tests numobs_linkage(Z) on linkage over 3 observations." + def test_num_obs_linkage_2x4(self): + "Tests num_obs_linkage(Z) on linkage over 3 observations." Z = np.asarray([[0, 1, 3.0, 2], [3, 2, 4.0, 3]], dtype=np.double) - self.failUnless(numobs_linkage(Z) == 3) + self.failUnless(num_obs_linkage(Z) == 3) - def test_numobs_linkage_4_and_up(self): - "Tests numobs_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3)." + def test_num_obs_linkage_4_and_up(self): + "Tests num_obs_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3)." for i in xrange(4, 15, 3): y = np.random.rand(i*(i-1)/2) Z = linkage(y) - self.failUnless(numobs_linkage(Z) == i) + self.failUnless(num_obs_linkage(Z) == i) class TestCorrespond(TestCase): Modified: trunk/scipy/spatial/tests/test_distance.py =================================================================== --- trunk/scipy/spatial/tests/test_distance.py 2008-11-13 04:06:09 UTC (rev 5083) +++ trunk/scipy/spatial/tests/test_distance.py 2008-11-13 04:09:20 UTC (rev 5084) @@ -1433,6 +1433,14 @@ class TestNumObsY(TestCase): + def test_numobs_y_multi_matrix(self): + "Tests numobs_y with observation matrices of multiple sizes." + for n in xrange(2, 10): + X = np.random.rand(n, 4) + Y = pdist(X) + #print A.shape, Y.shape, Yr.shape + self.failUnless(numobs_y(Y) == n) + def test_numobs_y_1(self): "Tests numobs_y(y) on a condensed distance matrix over 1 observations. Expecting exception." self.failUnlessRaises(ValueError, self.check_y, 1) @@ -1479,6 +1487,17 @@ class TestNumObsDM(TestCase): + ############## numobs_dm + def test_numobs_dm_multi_matrix(self): + "Tests numobs_dm with observation matrices of multiple sizes." + for n in xrange(1, 10): + X = np.random.rand(n, 4) + Y = pdist(X) + A = squareform(Y) + if verbose >= 3: + print A.shape, Y.shape + self.failUnless(numobs_dm(A) == n) + def test_numobs_dm_0(self): "Tests numobs_dm(D) on a 0x0 distance matrix. Expecting exception." self.failUnless(self.check_D(0)) From scipy-svn at scipy.org Wed Nov 12 23:12:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:12:50 -0600 (CST) Subject: [Scipy-svn] r5085 - trunk/scipy/stats Message-ID: <20081113041250.0E78839C05F@scipy.org> Author: josef Date: 2008-11-12 22:12:47 -0600 (Wed, 12 Nov 2008) New Revision: 5085 Modified: trunk/scipy/stats/distributions.py Log: skip some (partially) broken methods when generic method works correctly. undo when methods are fixed Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 04:09:20 UTC (rev 5084) +++ trunk/scipy/stats/distributions.py 2008-11-13 04:12:47 UTC (rev 5085) @@ -1019,7 +1019,8 @@ return (u1 / u2) def _pdf(self, x, a, b): return 1.0/special.beta(a,b)*x**(a-1.0)/(1+x)**(a+b) - def _cdf(self, x, a, b): + def _cdf_skip(self, x, a, b): + # remove for now: special.hyp2f1 is incorrect for large a x = where(x==1.0, 1.0-1e-6,x) return pow(x,a)*special.hyp2f1(a+b,a,1+a,-x)/a/special.beta(a,b) def _munp(self, n, a, b): @@ -2528,7 +2529,7 @@ class ncf_gen(rv_continuous): def _rvs(self, dfn, dfd, nc): return mtrand.noncentral_f(dfn,dfd,nc,self._size) - def _pdf(self, x, dfn, dfd, nc): + def _pdf_skip(self, x, dfn, dfd, nc): n1,n2 = dfn, dfd term = -nc/2+nc*n1*x/(2*(n2+n1*x)) + gamln(n1/2.)+gamln(1+n2/2.) term -= gamln((n1+n2)/2.0) @@ -2537,6 +2538,8 @@ Px *= (n2+n1*x)**(-(n1+n2)/2) Px *= special.assoc_laguerre(-nc*n1*x/(2.0*(n2+n1*x)),n2/2,n1/2-1) Px /= special.beta(n1/2,n2/2) + #this function does not have a return + # drop it for now, the generic function seems to work ok def _cdf(self, x, dfn, dfd, nc): return special.ncfdtr(dfn,dfd,nc,x) def _ppf(self, q, dfn, dfd, nc): @@ -2813,7 +2816,8 @@ class rdist_gen(rv_continuous): def _pdf(self, x, c): return pow((1.0-x*x),c/2.0-1) / special.beta(0.5,c/2.0) - def _cdf(self, x, c): + def _cdf_skip(self, x, c): + #error inspecial.hyp2f1 for some values see tickets 758, 759 return 0.5 + x/special.beta(0.5,c/2.0)* \ special.hyp2f1(0.5,1.0-c/2.0,1.5,x*x) def _munp(self, n, c): From scipy-svn at scipy.org Wed Nov 12 23:14:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:14:40 -0600 (CST) Subject: [Scipy-svn] r5086 - trunk/scipy/cluster/tests Message-ID: <20081113041440.8154D39C05F@scipy.org> Author: damian.eads Date: 2008-11-12 22:14:38 -0600 (Wed, 12 Nov 2008) New Revision: 5086 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote more tests for hierarchy.correspond. Removed some unnecessary imports from test_hierarchy. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 04:12:47 UTC (rev 5085) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 04:14:38 UTC (rev 5086) @@ -39,7 +39,7 @@ from numpy.testing import * from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond -from scipy.spatial.distance import squareform, pdist, numobs_dm, numobs_y +from scipy.spatial.distance import squareform, pdist _tdist = np.array([[0, 662, 877, 255, 412, 996], [662, 0, 295, 468, 268, 400], @@ -102,18 +102,6 @@ load_testing_files() -class TestNumObs(TestCase): - - def test_num_obs_linkage_multi_matrix(self): - "Tests num_obs_linkage with observation matrices of multiple sizes." - for n in xrange(2, 10): - X = np.random.rand(n, 4) - Y = pdist(X) - Z = linkage(Y) - #print Z - #print A.shape, Y.shape, Yr.shape - self.failUnless(num_obs_linkage(Z) == n) - class TestLinkage(TestCase): def test_linkage_empty_distance_matrix(self): @@ -598,7 +586,7 @@ self.failUnless(correspond(Z, y)) def test_correspond_4_and_up(self): - "Tests correspond(Z, y) on linkage and CDMs over observation sets between sizes 4 and 15 (step size 3)." + "Tests correspond(Z, y) on linkage and CDMs over observation sets of different sizes. Correspondance should be false." for (i, j) in zip(range(2, 4), range(3, 5)) + zip(range(3, 5), range(2, 4)): y = np.random.rand(i*(i-1)/2) y2 = np.random.rand(j*(j-1)/2) @@ -607,6 +595,26 @@ self.failUnless(correspond(Z, y2) == False) self.failUnless(correspond(Z2, y) == False) + def test_correspond_4_and_up_2(self): + "Tests correspond(Z, y) on linkage and CDMs over observation sets of different sizes. Correspondance should be false." + for (i, j) in zip(range(2, 7), range(16, 21)) + zip(range(2, 7), range(16, 21)): + y = np.random.rand(i*(i-1)/2) + y2 = np.random.rand(j*(j-1)/2) + Z = linkage(y) + Z2 = linkage(y2) + self.failUnless(correspond(Z, y2) == False) + self.failUnless(correspond(Z2, y) == False) + + def test_num_obs_linkage_multi_matrix(self): + "Tests num_obs_linkage with observation matrices of multiple sizes." + for n in xrange(2, 10): + X = np.random.rand(n, 4) + Y = pdist(X) + Z = linkage(Y) + #print Z + #print A.shape, Y.shape, Yr.shape + self.failUnless(num_obs_linkage(Z) == n) + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Wed Nov 12 23:23:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:23:29 -0600 (CST) Subject: [Scipy-svn] r5087 - in trunk/scipy: cluster spatial spatial/tests Message-ID: <20081113042329.2734639C05F@scipy.org> Author: damian.eads Date: 2008-11-12 22:23:27 -0600 (Wed, 12 Nov 2008) New Revision: 5087 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/spatial/distance.py trunk/scipy/spatial/tests/test_distance.py Log: Renamed numobs_* to num_obs_* to be more consistent with Python naming standards. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-13 04:14:38 UTC (rev 5086) +++ trunk/scipy/cluster/hierarchy.py 2008-11-13 04:23:27 UTC (rev 5087) @@ -590,7 +590,7 @@ s = y.shape if len(s) == 1: distance.is_valid_y(y, throw=True, name='y') - d = distance.numobs_y(y) + d = distance.num_obs_y(y) if method not in _cpy_non_euclid_methods.keys(): raise ValueError("Valid methods when the raw observations are omitted are 'single', 'complete', 'weighted', and 'average'.") # Since the C code does not support striding using strides. @@ -1268,7 +1268,7 @@ distance.is_valid_y(Y, throw=True) Z = np.asarray(Z, order='c') Y = np.asarray(Y, order='c') - return distance.numobs_y(Y) == num_obs_linkage(Z) + return distance.num_obs_y(Y) == num_obs_linkage(Z) def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None): """ Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-13 04:14:38 UTC (rev 5086) +++ trunk/scipy/spatial/distance.py 2008-11-13 04:23:27 UTC (rev 5087) @@ -1,5 +1,4 @@ """ - Function Reference ------------------ @@ -30,9 +29,9 @@ +------------------+-------------------------------------------------+ |is_valid_y | checks for a valid condensed distance matrix. | +------------------+-------------------------------------------------+ -|numobs_dm | # of observations in a distance matrix. | +|num_obs_dm | # of observations in a distance matrix. | +------------------+-------------------------------------------------+ -|numobs_y | # of observations in a condensed distance | +|num_obs_y | # of observations in a condensed distance | | | matrix. | +------------------+-------------------------------------------------+ @@ -1515,7 +1514,7 @@ valid = False return valid -def numobs_dm(d): +def num_obs_dm(d): """ Returns the number of original observations that correspond to a square, redudant distance matrix ``D``. @@ -1531,7 +1530,7 @@ is_valid_dm(d, tol=np.inf, throw=True, name='d') return d.shape[0] -def numobs_y(Y): +def num_obs_y(Y): """ Returns the number of original observations that correspond to a condensed distance matrix ``Y``. Modified: trunk/scipy/spatial/tests/test_distance.py =================================================================== --- trunk/scipy/spatial/tests/test_distance.py 2008-11-13 04:14:38 UTC (rev 5086) +++ trunk/scipy/spatial/tests/test_distance.py 2008-11-13 04:23:27 UTC (rev 5087) @@ -40,7 +40,7 @@ from numpy.testing import * from scipy.spatial.distance import squareform, pdist, cdist, matching, \ jaccard, dice, sokalsneath, rogerstanimoto, \ - russellrao, yule, numobs_y, numobs_dm, \ + russellrao, yule, num_obs_y, num_obs_dm, \ is_valid_dm, is_valid_y _filenames = ["iris.txt", @@ -1433,37 +1433,37 @@ class TestNumObsY(TestCase): - def test_numobs_y_multi_matrix(self): - "Tests numobs_y with observation matrices of multiple sizes." + def test_num_obs_y_multi_matrix(self): + "Tests num_obs_y with observation matrices of multiple sizes." for n in xrange(2, 10): X = np.random.rand(n, 4) Y = pdist(X) #print A.shape, Y.shape, Yr.shape - self.failUnless(numobs_y(Y) == n) + self.failUnless(num_obs_y(Y) == n) - def test_numobs_y_1(self): - "Tests numobs_y(y) on a condensed distance matrix over 1 observations. Expecting exception." + def test_num_obs_y_1(self): + "Tests num_obs_y(y) on a condensed distance matrix over 1 observations. Expecting exception." self.failUnlessRaises(ValueError, self.check_y, 1) - def test_numobs_y_2(self): - "Tests numobs_y(y) on a condensed distance matrix over 2 observations." + def test_num_obs_y_2(self): + "Tests num_obs_y(y) on a condensed distance matrix over 2 observations." self.failUnless(self.check_y(2)) - def test_numobs_y_3(self): - "Tests numobs_y(y) on a condensed distance matrix over 3 observations." + def test_num_obs_y_3(self): + "Tests num_obs_y(y) on a condensed distance matrix over 3 observations." self.failUnless(self.check_y(3)) - def test_numobs_y_4(self): - "Tests numobs_y(y) on a condensed distance matrix over 4 observations." + def test_num_obs_y_4(self): + "Tests num_obs_y(y) on a condensed distance matrix over 4 observations." self.failUnless(self.check_y(4)) - def test_numobs_y_5_10(self): - "Tests numobs_y(y) on a condensed distance matrix between 5 and 15 observations." + def test_num_obs_y_5_10(self): + "Tests num_obs_y(y) on a condensed distance matrix between 5 and 15 observations." for i in xrange(5, 16): self.minit(i) - def test_numobs_y_2_100(self): - "Tests numobs_y(y) on 100 improper condensed distance matrices. Expecting exception." + def test_num_obs_y_2_100(self): + "Tests num_obs_y(y) on 100 improper condensed distance matrices. Expecting exception." a = set([]) for n in xrange(2, 16): a.add(n*(n-1)/2) @@ -1477,49 +1477,49 @@ def bad_y(self, n): y = np.random.rand(n) - return numobs_y(y) + return num_obs_y(y) def check_y(self, n): - return numobs_y(self.make_y(n)) == n + return num_obs_y(self.make_y(n)) == n def make_y(self, n): return np.random.rand((n*(n-1)/2)) class TestNumObsDM(TestCase): - ############## numobs_dm - def test_numobs_dm_multi_matrix(self): - "Tests numobs_dm with observation matrices of multiple sizes." + ############## num_obs_dm + def test_num_obs_dm_multi_matrix(self): + "Tests num_obs_dm with observation matrices of multiple sizes." for n in xrange(1, 10): X = np.random.rand(n, 4) Y = pdist(X) A = squareform(Y) if verbose >= 3: print A.shape, Y.shape - self.failUnless(numobs_dm(A) == n) + self.failUnless(num_obs_dm(A) == n) - def test_numobs_dm_0(self): - "Tests numobs_dm(D) on a 0x0 distance matrix. Expecting exception." + def test_num_obs_dm_0(self): + "Tests num_obs_dm(D) on a 0x0 distance matrix. Expecting exception." self.failUnless(self.check_D(0)) - def test_numobs_dm_1(self): - "Tests numobs_dm(D) on a 1x1 distance matrix." + def test_num_obs_dm_1(self): + "Tests num_obs_dm(D) on a 1x1 distance matrix." self.failUnless(self.check_D(1)) - def test_numobs_dm_2(self): - "Tests numobs_dm(D) on a 2x2 distance matrix." + def test_num_obs_dm_2(self): + "Tests num_obs_dm(D) on a 2x2 distance matrix." self.failUnless(self.check_D(2)) - def test_numobs_dm_3(self): - "Tests numobs_dm(D) on a 3x3 distance matrix." + def test_num_obs_dm_3(self): + "Tests num_obs_dm(D) on a 3x3 distance matrix." self.failUnless(self.check_D(2)) - def test_numobs_dm_4(self): - "Tests numobs_dm(D) on a 4x4 distance matrix." + def test_num_obs_dm_4(self): + "Tests num_obs_dm(D) on a 4x4 distance matrix." self.failUnless(self.check_D(4)) def check_D(self, n): - return numobs_dm(self.make_D(n)) == n + return num_obs_dm(self.make_D(n)) == n def make_D(self, n): return np.random.rand(n, n) From scipy-svn at scipy.org Wed Nov 12 23:32:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 22:32:21 -0600 (CST) Subject: [Scipy-svn] r5088 - trunk/scipy/sparse/linalg/eigen Message-ID: <20081113043221.8D99839C05F@scipy.org> Author: cdavid Date: 2008-11-12 22:32:10 -0600 (Wed, 12 Nov 2008) New Revision: 5088 Removed: trunk/scipy/sparse/linalg/eigen/arpack/ Modified: trunk/scipy/sparse/linalg/eigen/__init__.py trunk/scipy/sparse/linalg/eigen/info.py trunk/scipy/sparse/linalg/eigen/setup.py trunk/scipy/sparse/linalg/eigen/setupscons.py Log: Remove ARPACK wrapper until the license issues are cleared. Modified: trunk/scipy/sparse/linalg/eigen/__init__.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/__init__.py 2008-11-13 04:23:27 UTC (rev 5087) +++ trunk/scipy/sparse/linalg/eigen/__init__.py 2008-11-13 04:32:10 UTC (rev 5088) @@ -2,7 +2,6 @@ from info import __doc__ -from arpack import * from lobpcg import * __all__ = filter(lambda s:not s.startswith('_'),dir()) Modified: trunk/scipy/sparse/linalg/eigen/info.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/info.py 2008-11-13 04:23:27 UTC (rev 5087) +++ trunk/scipy/sparse/linalg/eigen/info.py 2008-11-13 04:32:10 UTC (rev 5088) @@ -3,8 +3,7 @@ ------------------------- The submodules of sparse.linalg.eigen: - 1. arpack: spare eigenvalue solver using iterative methods - 2. lobpcg: Locally Optimal Block Preconditioned Conjugate Gradient Method + 1. lobpcg: Locally Optimal Block Preconditioned Conjugate Gradient Method Examples Modified: trunk/scipy/sparse/linalg/eigen/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/setup.py 2008-11-13 04:23:27 UTC (rev 5087) +++ trunk/scipy/sparse/linalg/eigen/setup.py 2008-11-13 04:32:10 UTC (rev 5088) @@ -5,7 +5,6 @@ config = Configuration('eigen',parent_package,top_path) - config.add_subpackage(('arpack')) config.add_subpackage(('lobpcg')) return config Modified: trunk/scipy/sparse/linalg/eigen/setupscons.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/setupscons.py 2008-11-13 04:23:27 UTC (rev 5087) +++ trunk/scipy/sparse/linalg/eigen/setupscons.py 2008-11-13 04:32:10 UTC (rev 5088) @@ -5,7 +5,6 @@ config = Configuration('eigen',parent_package,top_path, setup_name = 'setupscons.py') - config.add_subpackage(('arpack')) config.add_subpackage(('lobpcg')) return config From scipy-svn at scipy.org Thu Nov 13 00:54:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 23:54:28 -0600 (CST) Subject: [Scipy-svn] r5089 - trunk/scipy/stats/tests Message-ID: <20081113055428.C06C339C05F@scipy.org> Author: josef Date: 2008-11-12 23:54:26 -0600 (Wed, 12 Nov 2008) New Revision: 5089 Added: trunk/scipy/stats/tests/test_continuous_basic.py Log: add test for basic methods of continuous distributions Added: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-13 04:32:10 UTC (rev 5088) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-13 05:54:26 UTC (rev 5089) @@ -0,0 +1,191 @@ +import numpy.testing as npt +import numpy as np +import nose + +from scipy import stats + +""" +Test all continuous distributions. + +Parameters were chosen for those distributions that pass the +Kolmogorov-Smirnov test. This provides safe parameters for each +distributions so that we can perform further testing of class methods. + +These tests currently check only/mostly for serious errors and exceptions, +not for numerically exact results. +""" + +DECIMAL = 2 # specify the precision of the tests + +distcont = [ + ['alpha', (3.5704770516650459,)], + ['anglit', ()], + ['arcsine', ()], + ['beta', (2.3098496451481823, 0.62687954300963677)], + ['betaprime', (100, 86)], + ['bradford', (0.29891359763170633,)], + ['burr', (0.94839838075366045, 4.3820284068855795)], + ['cauchy', ()], + ['chi', (78,)], + ['chi2', (55,)], + ['cosine', ()], + ['dgamma', (1.1023326088288166,)], + ['dweibull', (2.0685080649914673,)], + ['erlang', (4, 0.7341136511570574, 0.047510038926818488)], + ['expon', ()], + ['exponpow', (2.697119160358469,)], + ['exponweib', (2.8923945291034436, 1.9505288745913174)], + ['f', (29, 18)], + ['fatiguelife', (29, 18)], + ['fisk', (3.0857548622253179,)], + ['foldcauchy', (4.7164673455831894,)], + ['foldnorm', (1.9521253373555869,)], + ['frechet_l', (3.6279911255583239,)], + ['frechet_r', (1.8928171603534227,)], + ['gamma', (1.9932305483800778,)], + ['gausshyper', (13.763771604130699, 3.1189636648681431, + 2.5145980350183019, 5.1811649903971615)], + ['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)], + ['genextreme', (3.3184017469423535,)], + ['gengamma', (4.4162385429431925, 3.1193091679242761)], + ['genhalflogistic', (0.77274727809929322,)], + ['genlogistic', (0.41192440799679475,)], + ['genpareto', (4.4566867037959144,)], + ['gilbrat', ()], + ['gompertz', (0.94743713075105251,)], + ['gumbel_l', ()], + ['gumbel_r', ()], + ['halfcauchy', ()], + ['halflogistic', ()], + ['halfnorm', ()], + ['hypsecant', ()], + ['invgamma', (2.0668996136993067,)], + ['invnorm', (0.14546264555347513,)], + ['invweibull', (0.58847112119264788,)], + ['johnsonsb', (4.3172675099141058, 3.1837781130785063)], + ['johnsonsu', (2.554395574161155, 2.2482281679651965)], + ['kstwobign', ()], + ['laplace', ()], + ['levy', ()], + ['levy_l', ()], +# ['levy_stable', (0.35667405469844993, +# -0.67450531578494011)], #NotImplementedError + ['loggamma', (0.41411931826052117,)], + ['logistic', ()], + ['loglaplace', (3.2505926592051435,)], + ['lognorm', (0.95368226960575331,)], + ['lomax', (1.8771398388773268,)], + ['maxwell', ()], + ['mielke', (4.6420495492121487, 0.59707419545516938)], + ['nakagami', (4.9673794866666237,)], + ['ncf', (27, 27, 0.41578441799226107)], + ['nct', (14, 0.24045031331198066)], + ['ncx2', (21, 1.0560465975116415)], + ['norm', ()], + ['pareto', (2.621716532144454,)], + ['powerlaw', (1.6591133289905851,)], + ['powerlognorm', (2.1413923530064087, 0.44639540782048337)], + ['powernorm', (4.4453652254590779,)], + ['rayleigh', ()], + ['rdist', (3.8266985793976525,)], + ['recipinvgauss', (0.63004267809369119,)], + ['reciprocal', (0.0062309367010521255, 1.0062309367010522)], + ['rice', (0.7749725210111873,)], + ['semicircular', ()], + ['t', (2.7433514990818093,)], + ['triang', (0.15785029824528218,)], + ['truncexpon', (4.6907725456810478,)], + ['truncnorm', (-1.0978730080013919, 2.7306754109031979)], + ['tukeylambda', (3.1321477856738267,)], + ['uniform', ()], + ['vonmises', (3.9939042581071398,)], + ['wald', ()], + ['weibull_max', (2.8687961709100187,)], + ['weibull_min', (1.7866166930421596,)], + ['wrapcauchy', (0.031071279018614728,)]] + + +def test_cont_basic(): + for distname, arg in distcont[:]: + distfn = getattr(stats, distname) + rvs = distfn.rvs(size=1000,*arg) + sm = rvs.mean() + sv = rvs.var() + skurt = stats.kurtosis(rvs) + sskew = stats.skew(rvs) + yield check_sample_meanvar_, distfn, arg, sm, sv, distname + \ + 'sample mean test' + yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + yield check_cdf_ppf, distfn, arg, distname + yield check_sf_isf, distfn, arg, distname + yield check_pdf, distfn, arg, distname + #yield check_oth, distfn, arg # is still missing + + +def check_sample_meanvar_(distfn, arg, sm, sv, msg): + m,v = distfn.stats(*arg) + check_sample_meanvar, sm, m, msg + 'sample mean test' + check_sample_meanvar, sv, v, msg + 'sample var test' + +def check_sample_skew_kurt(distfn, arg, sk, ss, msg): + k,s = distfn.stats(moment='ks',*arg) + check_sample_meanvar, sk, k, msg + 'sample skew test' + check_sample_meanvar, ss, s, msg + 'sample kurtosis test' + +def check_sample_meanvar(sm,m,msg): + + if m < np.inf: + npt.assert_almost_equal(sm, m, decimal=DECIMAL, err_msg= msg + \ + ' - finite moment') + else: + assert sm > 10000, 'infinite moment, sm = ' + str(sm) + +def check_cdf_ppf(distfn,arg,msg): + npt.assert_almost_equal(distfn.cdf(distfn.ppf([0.1,0.5,0.9], *arg), *arg), + [0.1,0.5,0.9], decimal=DECIMAL, err_msg= msg + \ + ' - cdf-ppf roundtrip') + +def check_sf_isf(distfn,arg,msg): + npt.assert_almost_equal(distfn.sf(distfn.isf([0.1,0.5,0.9], *arg), *arg), + [0.1,0.5,0.9], decimal=DECIMAL, err_msg= msg + \ + ' - sf-isf roundtrip') + npt.assert_almost_equal(distfn.cdf([0.1,0.9], *arg), + 1.0-distfn.sf([0.1,0.9], *arg), + decimal=DECIMAL, err_msg= msg + \ + ' - cdf-sf relationship') + +def check_pdf(distfn, arg, msg): + median = distfn.ppf(0.5, *arg) + eps = 1e-6 + pdfv = distfn.pdf(median, *arg) + if (pdfv < 1e-4) or (pdfv > 1e4): + # avoid checking a case where pdf is close to zero or huge (singularity) + median = median + 0.1 + pdfv = distfn.pdf(median, *arg) + cdfdiff = (distfn.cdf(median + eps, *arg) - + distfn.cdf(median - eps, *arg))/eps/2.0 + #replace with better diff and better test (more points) + npt.assert_almost_equal(pdfv, cdfdiff, + decimal=DECIMAL, err_msg= msg + ' - cdf-pdf relationship') + + + +def _est_all_distributions(): + #test from scipy.stats.tests + for dist, args in distcont: + distfunc = getattr(stats, dist) + alpha = 0.01 + yield check_distribution, dist, args, alpha + + +def check_distribution(dist, args, alpha): + #test from scipy.stats.tests + D,pval = stats.kstest(dist,'', args=args, N=1000) + if (pval < alpha): + D,pval = stats.kstest(dist,'',args=args, N=1000) + assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ + "; alpha = " + str(alpha) + "\nargs = " + str(args) + +if __name__ == "__main__": + nose.run(argv=['', __file__]) + From scipy-svn at scipy.org Thu Nov 13 00:58:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 12 Nov 2008 23:58:18 -0600 (CST) Subject: [Scipy-svn] r5090 - trunk/scipy/stats Message-ID: <20081113055818.3FE4439C05F@scipy.org> Author: josef Date: 2008-11-12 23:58:16 -0600 (Wed, 12 Nov 2008) New Revision: 5090 Modified: trunk/scipy/stats/distributions.py Log: corrections to continuous distributions: dweibul, invweibul, levy, levy_l and skip vonmises._stats,all tests pass but needs review Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-13 05:54:26 UTC (rev 5089) +++ trunk/scipy/stats/distributions.py 2008-11-13 05:58:16 UTC (rev 5090) @@ -1271,7 +1271,8 @@ return where(x>0,0.5+fac,0.5-fac) def _sf(self, x, a): fac = 0.5*special.gammainc(a,abs(x)) - return where(x>0,0.5-0.5*fac,0.5+0.5*fac) + #return where(x>0,0.5-0.5*fac,0.5+0.5*fac) + return where(x>0,0.5-fac,0.5+fac) def _ppf(self, q, a): fac = special.gammainccinv(a,1-abs(2*q-1)) return where(q>0.5, fac, -fac) @@ -1301,7 +1302,7 @@ def _cdf(self, x, c): Cx1 = 0.5*exp(-abs(x)**c) return where(x > 0, 1-Cx1, Cx1) - def _ppf(self, q, c): + def _ppf_skip(self, q, c): fac = where(q<=0.5,2*q,2*q-1) fac = pow(arr(log(1.0/fac)),1.0/c) return where(q>0.5,fac,-fac) @@ -2103,7 +2104,9 @@ class invweibull_gen(rv_continuous): def _pdf(self, x, c): xc1 = x**(-c-1.0) - xc2 = xc1*x + #xc2 = xc1*x + xc2 = x**(-c) + xc2 = exp(-xc2) return c*xc1*xc2 def _cdf(self, x, c): xc1 = x**(-c) @@ -2198,7 +2201,7 @@ class levy_gen(rv_continuous): def _pdf(self, x): - return 1/sqrt(2*x)/x*exp(-1/(2*x)) + return 1/sqrt(2*pi*x)/x*exp(-1/(2*x)) def _cdf(self, x): return 2*(1-norm._cdf(1/sqrt(x))) def _ppf(self, q): @@ -2222,7 +2225,7 @@ class levy_l_gen(rv_continuous): def _pdf(self, x): ax = abs(x) - return 1/sqrt(2*ax)/ax*exp(-1/(2*ax)) + return 1/sqrt(2*pi*ax)/ax*exp(-1/(2*ax)) def _cdf(self, x): ax = abs(x) return 2*norm._cdf(1/sqrt(ax))-1 @@ -3145,7 +3148,7 @@ return exp(b*cos(x)) / (2*pi*special.i0(b)) def _cdf(self, x, b): return vonmises_cython.von_mises_cdf(b,x) - def _stats(self, b): + def _stats_skip(self, b): return 0, None, 0, None vonmises = vonmises_gen(name='vonmises', longname="A Von Mises", shapes="b", extradoc=""" From scipy-svn at scipy.org Thu Nov 13 14:40:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 13:40:03 -0600 (CST) Subject: [Scipy-svn] r5091 - trunk/scipy/stats/tests Message-ID: <20081113194003.0D74639C088@scipy.org> Author: josef Date: 2008-11-13 13:40:00 -0600 (Thu, 13 Nov 2008) New Revision: 5091 Modified: trunk/scipy/stats/tests/test_discrete_chisquare.py Log: add random seed to test, drop known failing test (logser) temporarily Modified: trunk/scipy/stats/tests/test_discrete_chisquare.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-13 05:58:16 UTC (rev 5090) +++ trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-13 19:40:00 UTC (rev 5091) @@ -1,6 +1,7 @@ import numpy as np from scipy import stats +from numpy.testing import dec debug = False @@ -31,6 +32,7 @@ wsupp = 1.0/nsupp distfn = getattr(stats, distname) + np.random.seed(9765456) rvs = distfn.rvs(size=n,*arg) # construct intervals with minimum mass 1/nsupp @@ -74,9 +76,8 @@ print 'n*pmf', n*distfn.pmf(list(distsupport)[:10],*arg) assert (pval > alpha), 'chisquare - test for %s' \ - 'at arg = %s' % (distname,str(arg)) + 'at arg = %s with pval = %s' % (distname,str(arg),str(pval)) - def test_discrete_rvs_cdf(): distdiscrete = [ ['bernoulli',(0.3,)], @@ -91,12 +92,32 @@ ['poisson', (0.6,)], ['randint', (7, 31)], ['zipf', (2,)] ] + + distknownfail = ['logser'] - for distname, arg in distdiscrete: + for distname, arg in distdiscrete: #[['nbinom', (5, 0.5)]]: #distdiscrete: + if distname in distknownfail: + continue if debug: print distname yield check_discrete_chisquare, distname, arg + +# decorator does not seem to work correctly with yield ???? +# I get error instead of yield +# drop failing test for now + at dec.knownfailureif(True, "This test is known to fail") +def _est_discrete_rvs_cdf_fail(): + distknownfail = [ ['logser', (0.6,)]] + for distname, arg in distknownfail: + if debug: + print distname + yield check_discrete_chisquare, distname, arg + + + + + if __name__ == '__main__': import nose nose.run(argv=['', __file__]) From scipy-svn at scipy.org Thu Nov 13 16:03:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 15:03:47 -0600 (CST) Subject: [Scipy-svn] r5092 - in trunk/scipy/cluster: . tests Message-ID: <20081113210347.D63A739C05F@scipy.org> Author: damian.eads Date: 2008-11-13 15:03:45 -0600 (Thu, 13 Nov 2008) New Revision: 5092 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Added tests for scipy.cluster.hierarchy.is_isomorphic. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-13 19:40:00 UTC (rev 5091) +++ trunk/scipy/cluster/hierarchy.py 2008-11-13 21:03:45 UTC (rev 5092) @@ -1086,7 +1086,7 @@ is_valid_linkage(Z, throw=True, name='Z') # We expect the i'th value to be greater than its successor. - return (Z[:-1,2]>=Z[1:,2]).all() + return (Z[1:,2]>=Z[:-1,2]).all() def is_valid_im(R, warning=False, throw=False, name=None): """ Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 19:40:00 UTC (rev 5091) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-13 21:03:45 UTC (rev 5092) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic from scipy.spatial.distance import squareform, pdist _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -615,6 +615,77 @@ #print A.shape, Y.shape, Yr.shape self.failUnless(num_obs_linkage(Z) == n) +class TestIsMonotonic(TestCase): + + def test_is_monotonic_empty(self): + "Tests is_monotonic(Z) on an empty linkage." + Z = np.zeros((0, 4)) + self.failUnlessRaises(ValueError, is_monotonic, Z) + + def test_is_monotonic_1x4(self): + "Tests is_monotonic(Z) on 1x4 linkage. Expecting True." + Z = np.asarray([[0, 1, 0.3, 2]], dtype=np.double); + self.failUnless(is_monotonic(Z) == True) + + def test_is_monotonic_2x4_T(self): + "Tests is_monotonic(Z) on 2x4 linkage. Expecting True." + Z = np.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 3]], dtype=np.double) + self.failUnless(is_monotonic(Z) == True) + + def test_is_monotonic_2x4_F(self): + "Tests is_monotonic(Z) on 2x4 linkage. Expecting False." + Z = np.asarray([[0, 1, 0.4, 2], + [2, 3, 0.3, 3]], dtype=np.double) + self.failUnless(is_monotonic(Z) == False) + + def test_is_monotonic_3x4_T(self): + "Tests is_monotonic(Z) on 3x4 linkage. Expecting True." + Z = np.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 2], + [3, 4, 0.6, 4]], dtype=np.double) + self.failUnless(is_monotonic(Z) == True) + + def test_is_monotonic_3x4_F1(self): + "Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False." + Z = np.asarray([[0, 1, 0.3, 2], + [2, 3, 0.2, 2], + [3, 4, 0.6, 4]], dtype=np.double) + self.failUnless(is_monotonic(Z) == False) + + def test_is_monotonic_3x4_F2(self): + "Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False." + Z = np.asarray([[0, 1, 0.8, 2], + [2, 3, 0.4, 2], + [3, 4, 0.6, 4]], dtype=np.double) + self.failUnless(is_monotonic(Z) == False) + + def test_is_monotonic_3x4_F3(self): + "Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False" + Z = np.asarray([[0, 1, 0.3, 2], + [2, 3, 0.4, 2], + [3, 4, 0.2, 4]], dtype=np.double) + self.failUnless(is_monotonic(Z) == False) + + def test_is_monotonic_tdist_linkage(self): + "Tests is_monotonic(Z) on clustering generated by single linkage on tdist data set. Expecting True." + Z = linkage(_ytdist, 'single') + self.failUnless(is_monotonic(Z) == True) + + def test_is_monotonic_tdist_linkage(self): + "Tests is_monotonic(Z) on clustering generated by single linkage on tdist data set. Perturbing. Expecting False." + Z = linkage(_ytdist, 'single') + Z[2,2]=0.0 + self.failUnless(is_monotonic(Z) == False) + + def test_is_monotonic_iris_linkage(self): + "Tests is_monotonic(Z) on clustering generated by single linkage on Iris data set. Expecting True." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'single') + self.failUnless(is_monotonic(Z) == True) + + def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') From scipy-svn at scipy.org Thu Nov 13 16:21:05 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 15:21:05 -0600 (CST) Subject: [Scipy-svn] r5093 - in trunk/scipy/interpolate: . tests Message-ID: <20081113212105.2A90D39C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 15:20:50 -0600 (Thu, 13 Nov 2008) New Revision: 5093 Modified: trunk/scipy/interpolate/fitpack2.py trunk/scipy/interpolate/tests/test_fitpack.py Log: interpolate: don't change the __class__ of a live UnivariateSpline object, if the object is an instance of user-defined subclass. (Fixes #660) Modified: trunk/scipy/interpolate/fitpack2.py =================================================================== --- trunk/scipy/interpolate/fitpack2.py 2008-11-13 21:03:45 UTC (rev 5092) +++ trunk/scipy/interpolate/fitpack2.py 2008-11-13 21:20:50 UTC (rev 5093) @@ -103,19 +103,28 @@ pass elif ier==-1: # the spline returned is an interpolating spline - self.__class__ = InterpolatedUnivariateSpline + self._set_class(InterpolatedUnivariateSpline) elif ier==-2: # the spline returned is the weighted least-squares # polynomial of degree k. In this extreme case fp gives # the upper bound fp0 for the smoothing factor s. - self.__class__ = LSQUnivariateSpline + self._set_class(LSQUnivariateSpline) else: # error if ier==1: - self.__class__ = LSQUnivariateSpline + self._set_class(LSQUnivariateSpline) message = _curfit_messages.get(ier,'ier=%s' % (ier)) warnings.warn(message) + def _set_class(self, cls): + self._spline_class = cls + if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline, + LSQUnivariateSpline): + self.__class__ = cls + else: + # It's an unknown subclass -- don't change class. cf. #660 + pass + def _reset_nest(self, data, nest=None): n = data[10] if nest is None: Modified: trunk/scipy/interpolate/tests/test_fitpack.py =================================================================== --- trunk/scipy/interpolate/tests/test_fitpack.py 2008-11-13 21:03:45 UTC (rev 5092) +++ trunk/scipy/interpolate/tests/test_fitpack.py 2008-11-13 21:20:50 UTC (rev 5093) @@ -36,6 +36,15 @@ assert_almost_equal(lut.get_residual(),0.0) assert_array_almost_equal(lut([1,1.5,2]),[0,1,2]) + def test_subclassing(self): + + class ZeroSpline(UnivariateSpline): + def __call__(self, x): + return 0*array(x) + + sp = ZeroSpline([1,2,3,4,5], [3,2,3,2,3], k=2) + assert_array_equal(sp([1.5, 2.5]), [0., 0.]) + class TestLSQBivariateSpline(TestCase): def test_linear_constant(self): x = [1,1,1,2,2,2,3,3,3] From scipy-svn at scipy.org Thu Nov 13 16:23:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 15:23:36 -0600 (CST) Subject: [Scipy-svn] r5094 - in trunk/scipy/interpolate: . tests Message-ID: <20081113212336.5021B39C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 15:23:23 -0600 (Thu, 13 Nov 2008) New Revision: 5094 Modified: trunk/scipy/interpolate/fitpack2.py trunk/scipy/interpolate/tests/test_fitpack.py Log: interpolate: correction -- the bugfix in 5093 was for #731, not for #660 Modified: trunk/scipy/interpolate/fitpack2.py =================================================================== --- trunk/scipy/interpolate/fitpack2.py 2008-11-13 21:20:50 UTC (rev 5093) +++ trunk/scipy/interpolate/fitpack2.py 2008-11-13 21:23:23 UTC (rev 5094) @@ -122,7 +122,7 @@ LSQUnivariateSpline): self.__class__ = cls else: - # It's an unknown subclass -- don't change class. cf. #660 + # It's an unknown subclass -- don't change class. cf. #731 pass def _reset_nest(self, data, nest=None): Modified: trunk/scipy/interpolate/tests/test_fitpack.py =================================================================== --- trunk/scipy/interpolate/tests/test_fitpack.py 2008-11-13 21:20:50 UTC (rev 5093) +++ trunk/scipy/interpolate/tests/test_fitpack.py 2008-11-13 21:23:23 UTC (rev 5094) @@ -37,6 +37,7 @@ assert_array_almost_equal(lut([1,1.5,2]),[0,1,2]) def test_subclassing(self): + # See #731 class ZeroSpline(UnivariateSpline): def __call__(self, x): From scipy-svn at scipy.org Thu Nov 13 16:47:37 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 15:47:37 -0600 (CST) Subject: [Scipy-svn] r5095 - trunk/scipy/stats/tests Message-ID: <20081113214737.5CA3F39C05F@scipy.org> Author: josef Date: 2008-11-13 15:47:30 -0600 (Thu, 13 Nov 2008) New Revision: 5095 Modified: trunk/scipy/stats/tests/test_continuous_basic.py Log: add missing kstests for continuous rvs Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-13 21:23:23 UTC (rev 5094) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-13 21:47:30 UTC (rev 5095) @@ -64,6 +64,7 @@ ['invweibull', (0.58847112119264788,)], ['johnsonsb', (4.3172675099141058, 3.1837781130785063)], ['johnsonsu', (2.554395574161155, 2.2482281679651965)], + ['ksone', (22,)], # new added ['kstwobign', ()], ['laplace', ()], ['levy', ()], @@ -168,9 +169,14 @@ npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg= msg + ' - cdf-pdf relationship') +distmissing = ['wald', 'gausshyper', 'genexpon', 'rv_continuous', + 'loglaplace', 'rdist', 'semicircular', 'invweibull', 'ksone', + 'cosine', 'kstwobign', 'truncnorm', 'mielke', 'recipinvgauss', 'levy', + 'johnsonsu', 'levy_l', 'powernorm', 'wrapcauchy', + 'johnsonsb', 'truncexpon', 'rice', 'invnorm', 'invgamma', + 'powerlognorm'] - -def _est_all_distributions(): +def test_missing_distributions(): #test from scipy.stats.tests for dist, args in distcont: distfunc = getattr(stats, dist) From scipy-svn at scipy.org Thu Nov 13 17:23:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 16:23:16 -0600 (CST) Subject: [Scipy-svn] r5096 - in trunk/scipy: cluster odr optimize spatial Message-ID: <20081113222316.6AE2039C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 16:22:59 -0600 (Thu, 13 Nov 2008) New Revision: 5096 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/odr/odrpack.py trunk/scipy/optimize/optimize.py trunk/scipy/spatial/distance.py Log: Fix docstrings that made Sphinx to fail Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-13 21:47:30 UTC (rev 5095) +++ trunk/scipy/cluster/hierarchy.py 2008-11-13 22:22:59 UTC (rev 5096) @@ -435,46 +435,46 @@ def linkage(y, method='single', metric='euclidean'): - """ + r""" Performs hierarchical/agglomerative clustering on the - condensed distance matrix y. y must be a {n \choose 2} sized + condensed distance matrix y. y must be a :math:`{n \choose 2}` sized vector where n is the number of original observations paired in the distance matrix. The behavior of this function is very similar to the MATLAB(TM) linkage function. - A 4 by :math:`$(n-1)$` matrix ``Z`` is returned. At the - :math:`$i$`th iteration, clusters with indices ``Z[i, 0]`` and - ``Z[i, 1]`` are combined to form cluster :math:`$n + i$`. A - cluster with an index less than :math:`$n$` corresponds to one of - the :math:`$n$` original observations. The distance between + A 4 by :math:`(n-1)` matrix ``Z`` is returned. At the + :math:`i`-th iteration, clusters with indices ``Z[i, 0]`` and + ``Z[i, 1]`` are combined to form cluster :math:`n + i`. A + cluster with an index less than :math:`n` corresponds to one of + the :math:`n` original observations. The distance between clusters ``Z[i, 0]`` and ``Z[i, 1]`` is given by ``Z[i, 2]``. The fourth value ``Z[i, 3]`` represents the number of original observations in the newly formed cluster. The following linkage methods are used to compute the distance - :math:`$d(s, t)$` between two clusters :math:`$s$` and - :math:`$t$`. The algorithm begins with a forest of clusters that + :math:`d(s, t)` between two clusters :math:`s` and + :math:`t`. The algorithm begins with a forest of clusters that have yet to be used in the hierarchy being formed. When two - clusters :math:`$s$` and :math:`$t$` from this forest are combined - into a single cluster :math:`$u$`, :math:`$s$` and :math:`$t$` are - removed from the forest, and :math:`$u$` is added to the + clusters :math:`s` and :math:`t` from this forest are combined + into a single cluster :math:`u`, :math:`s` and :math:`t` are + removed from the forest, and :math:`u` is added to the forest. When only one cluster remains in the forest, the algorithm stops, and this cluster becomes the root. A distance matrix is maintained at each iteration. The ``d[i,j]`` - entry corresponds to the distance between cluster :math:`$i$` and - :math:`$j$` in the original forest. + entry corresponds to the distance between cluster :math:`i` and + :math:`j` in the original forest. At each iteration, the algorithm must update the distance matrix to reflect the distance of the newly formed cluster u with the remaining clusters in the forest. - Suppose there are :math:`$|u|$` original observations - :math:`$u[0], \ldots, u[|u|-1]$` in cluster :math:`$u$` and - :math:`$|v|$` original objects :math:`$v[0], \ldots, v[|v|-1]$` in - cluster :math:`$v$`. Recall :math:`$s$` and :math:`$t$` are - combined to form cluster :math:`$u$`. Let :math:`$v$` be any - remaining cluster in the forest that is not :math:`$u$`. + Suppose there are :math:`|u|` original observations + :math:`u[0], \ldots, u[|u|-1]` in cluster :math:`u` and + :math:`|v|` original objects :math:`v[0], \ldots, v[|v|-1]` in + cluster :math:`v`. Recall :math:`s` and :math:`t` are + combined to form cluster :math:`u`. Let :math:`v` be any + remaining cluster in the forest that is not :math:`u`. :Parameters: Q : ndarray @@ -482,8 +482,8 @@ distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that ``pdist`` returns. Alternatively, a collection of - :math:`$m$` observation vectors in n dimensions may be passed as - a :math:`$m$` by :math:`$n$` array. + :math:`m` observation vectors in n dimensions may be passed as + a :math:`m` by :math:`n` array. method : string The linkage algorithm to use. See the ``Linkage Methods`` section below for full descriptions. @@ -495,15 +495,15 @@ --------------- The following are methods for calculating the distance between the - newly formed cluster :math:`$u$` and each :math:`$v$`. + newly formed cluster :math:`u` and each :math:`v`. * method=``single`` assigns .. math: d(u,v) = \min(dist(u[i],v[j])) - for all points :math:`$i$` in cluster :math:`$u$` and - :math:`$j$` in cluster :math:`$v$`. This is also known as the + for all points :math:`i` in cluster :math:`u` and + :math:`j` in cluster :math:`v`. This is also known as the Nearest Point Algorithm. * method=``complete`` assigns @@ -511,8 +511,8 @@ .. math: d(u, v) = \max(dist(u[i],v[j])) - for all points :math:`$i$` in cluster u and :math:`$j$` in - cluster :math:`$v$`. This is also known by the Farthest Point + for all points :math:`i` in cluster u and :math:`j` in + cluster :math:`v`. This is also known by the Farthest Point Algorithm or Voor Hees Algorithm. * method=``average`` assigns @@ -521,9 +521,9 @@ d(u,v) = \sum_{ij} \frac{d(u[i], v[j])} {(|u|*|v|) - for all points :math:`$i$` and :math:`$j$` where :math:`$|u|$` - and :math:`$|v|$` are the cardinalities of clusters :math:`$u$` - and :math:`$v$`, respectively. This is also called the UPGMA + for all points :math:`i` and :math:`j` where :math:`|u|` + and :math:`|v|` are the cardinalities of clusters :math:`u` + and :math:`v`, respectively. This is also called the UPGMA algorithm. This is called UPGMA. * method='weighted' assigns @@ -540,24 +540,24 @@ .. math: dist(s,t) = euclid(c_s, c_t) - where :math:`$c_s$` and :math:`$c_t$` are the centroids of - clusters :math:`$s$` and :math:`$t$`, respectively. When two - clusters :math:`$s$` and :math:`$t$` are combined into a new - cluster :math:`$u$`, the new centroid is computed over all the - original objects in clusters :math:`$s$` and :math:`$t$`. The + where :math:`c_s` and :math:`c_t` are the centroids of + clusters :math:`s` and :math:`t`, respectively. When two + clusters :math:`s` and :math:`t` are combined into a new + cluster :math:`u`, the new centroid is computed over all the + original objects in clusters :math:`s` and :math:`t`. The distance then becomes the Euclidean distance between the - centroid of :math:`$u$` and the centroid of a remaining cluster - :math:`$v$` in the forest. This is also known as the UPGMC + centroid of :math:`u` and the centroid of a remaining cluster + :math:`v` in the forest. This is also known as the UPGMC algorithm. * method='median' assigns math:`$d(s,t)$` like the ``centroid`` method. When two clusters s and t are combined into a new - cluster :math:`$u$`, the average of centroids s and t give the - new centroid :math:`$u$`. This is also known as the WPGMC + cluster :math:`u`, the average of centroids s and t give the + new centroid :math:`u`. This is also known as the WPGMC algorithm. * method='ward' uses the Ward variance minimization algorithm. - The new entry :math:`$d(u,v)$` is computed as follows, + The new entry :math:`d(u,v)` is computed as follows, .. math: @@ -568,10 +568,10 @@ + \frac{|v|} {T}d(s,t)^2} - where :math:`$u$` is the newly joined cluster consisting of - clusters :math:`$s$` and :math:`$t$`, :math:`$v$` is an unused - cluster in the forest, :math:`$T=|v|+|s|+|t|$`, and - :math:`$|*|$` is the cardinality of its argument. This is also + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also known as the incremental algorithm. Warning @@ -653,12 +653,12 @@ self.count = left.count + right.count def get_id(self): - """ - The identifier of the target node. For :math:`$0 leq i < n$`, - :math:`$i$` corresponds to original observation - :math:`$i$`. For :math:`$n \leq i$` < :math:`$2n-1$`, - :math:`$i$` corresponds to non-singleton cluster formed at - iteration :math:`$i-n$`. + r""" + The identifier of the target node. For :math:`0 \leq i < n`, + :math:`i` corresponds to original observation + :math:`i`. For :math:`n \leq i` < :math:`2n-1`, + :math:`i` corresponds to non-singleton cluster formed at + iteration :math:`i-n`. :Returns: @@ -896,7 +896,7 @@ - Y : ndarray (optional) Calculates the cophenetic correlation coefficient ``c`` of a hierarchical clustering defined by the linkage matrix ``Z`` - of a set of :math:`$n$` observations in :math:`$m$` + of a set of :math:`n` observations in :math:`m` dimensions. ``Y`` is the condensed distance matrix from which ``Z`` was generated. @@ -906,8 +906,8 @@ - d : ndarray The cophenetic distance matrix in condensed form. The - :math:`$ij$` th entry is the cophenetic distance between - original observations :math:`$i$` and :math:`$j$`. + :math:`ij` th entry is the cophenetic distance between + original observations :math:`i` and :math:`j`. """ @@ -942,7 +942,7 @@ return (c, zz) def inconsistent(Z, d=2): - """ + r""" Calculates inconsistency statistics on a linkage. :Parameters: @@ -951,17 +951,17 @@ non-singleton cluster - Z : ndarray - The :math:`$(n-1)$` by 4 matrix encoding the linkage + The :math:`(n-1)` by 4 matrix encoding the linkage (hierarchical clustering). See ``linkage`` documentation for more information on its form. :Returns: - R : ndarray - A :math:`$(n-1)$` by 5 matrix where the ``i``'th row + A :math:`(n-1)` by 5 matrix where the ``i``'th row contains the link statistics for the non-singleton cluster ``i``. The link statistics are computed over the link - heights for links :math:`$d$` levels below the cluster + heights for links :math:`d` levels below the cluster ``i``. ``R[i,0]`` and ``R[i,1]`` are the mean and standard deviation of the link heights, respectively; ``R[i,2]`` is the number of links included in the calculation; and @@ -1070,7 +1070,7 @@ def is_monotonic(Z): """ Returns ``True`` if the linkage passed is monotonic. The linkage - is monotonic if for every cluster :math:`$s$` and :math:`$t$` + is monotonic if for every cluster :math:`s` and :math:`t` joined, the distance between them is no less than the distance between any previously joined clusters. @@ -1092,9 +1092,9 @@ """ Returns True if the inconsistency matrix passed is valid. It must - be a :math:`$n$` by 4 numpy array of doubles. The standard + be a :math:`n` by 4 numpy array of doubles. The standard deviations ``R[:,1]`` must be nonnegative. The link counts - ``R[:,2]`` must be positive and no greater than :math:`$n-1$`. + ``R[:,2]`` must be positive and no greater than :math:`n-1`. :Arguments: - R : ndarray @@ -1153,13 +1153,13 @@ return valid def is_valid_linkage(Z, warning=False, throw=False, name=None): - """ + r""" Checks the validity of a linkage matrix. A linkage matrix is valid - if it is a two dimensional nd-array (type double) with :math:`$n$` + if it is a two dimensional nd-array (type double) with :math:`n` rows and 4 columns. The first two columns must contain indices - between 0 and :math:`$2n-1$`. For a given row ``i``, - :math:`$0 \leq \mathtt{Z[i,0]} \leq i+n-1$` and - :math:`$0 \leq Z[i,1] \leq i+n-1$` (i.e. a cluster + between 0 and :math:`2n-1`. For a given row ``i``, + :math:`0 \leq \mathtt{Z[i,0]} \leq i+n-1` and + :math:`0 \leq Z[i,1] \leq i+n-1` (i.e. a cluster cannot join another cluster unless the cluster being joined has been generated.) Modified: trunk/scipy/odr/odrpack.py =================================================================== --- trunk/scipy/odr/odrpack.py 2008-11-13 21:47:30 UTC (rev 5095) +++ trunk/scipy/odr/odrpack.py 2008-11-13 22:22:59 UTC (rev 5096) @@ -873,9 +873,9 @@ default value from class initialization is for all of these options set to 0. - _______________________________________________________________________ + ========= ===== ===================================================== Parameter Value Meaning - --------- ----- ------- + ========= ===== ===================================================== fit_type 0 explicit ODR 1 implicit ODR 2 ordinary least-squares @@ -898,7 +898,7 @@ restart 0 fit is not a restart 1 fit is a restart - _______________________________________________________________________ + ========= ===== ===================================================== The permissible values are different from those given on pg. 31 of the ODRPACK User's Guide only in that one cannot specify numbers greater than the Modified: trunk/scipy/optimize/optimize.py =================================================================== --- trunk/scipy/optimize/optimize.py 2008-11-13 21:47:30 UTC (rev 5095) +++ trunk/scipy/optimize/optimize.py 2008-11-13 22:22:59 UTC (rev 5096) @@ -1457,9 +1457,8 @@ Number of objective function evaluations made. Notes + ----- - ---------------------------- - Uses inverse parabolic interpolation when possible to speed up convergence of golden section method. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-13 21:47:30 UTC (rev 5095) +++ trunk/scipy/spatial/distance.py 2008-11-13 22:22:59 UTC (rev 5096) @@ -175,7 +175,7 @@ return X def minkowski(u, v, p): - """ + r""" Computes the Minkowski distance between two vectors ``u`` and ``v``, defined as @@ -189,7 +189,7 @@ v : ndarray An n-dimensional vector. p : ndarray - The norm of the difference :math:`${||u-v||}_p$`. + The norm of the difference :math:`{||u-v||}_p`. :Returns: d : double @@ -202,7 +202,7 @@ return (abs(u-v)**p).sum() ** (1.0 / p) def wminkowski(u, v, p, w): - """ + r""" Computes the weighted Minkowski distance between two vectors ``u`` and ``v``, defined as @@ -216,7 +216,7 @@ v : ndarray An :math:`n`-dimensional vector. p : ndarray - The norm of the difference :math:`${||u-v||}_p$`. + The norm of the difference :math:`{||u-v||}_p`. w : ndarray The weight vector. @@ -279,7 +279,7 @@ return ((u-v)*(u-v).T).sum() def cosine(u, v): - """ + r""" Computes the Cosine distance between two n-vectors u and v, which is defined as @@ -303,7 +303,7 @@ (np.sqrt(np.dot(u, u.T)) * np.sqrt(np.dot(v, v.T))))) def correlation(u, v): - """ + r""" Computes the correlation distance between two n-vectors ``u`` and ``v``, which is defined as @@ -312,7 +312,7 @@ \frac{1 - (u - n{|u|}_1){(v - n{|v|}_1)}^T} {{|(u - n{|u|}_1)|}_2 {|(v - n{|v|}_1)|}^T} - where :math:`$|*|_1$` is the Manhattan norm and ``n`` is the + where :math:`|*|_1` is the Manhattan norm and ``n`` is the common dimensionality of the vectors. :Parameters: @@ -334,7 +334,7 @@ * np.sqrt(np.dot(vm, vm)))) def hamming(u, v): - """ + r""" Computes the Hamming distance between two n-vectors ``u`` and ``v``, which is simply the proportion of disagreeing components in ``u`` and ``v``. If ``u`` and ``v`` are boolean vectors, the Hamming @@ -344,9 +344,9 @@ \frac{c_{01} + c_{10}}{n} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`. :Parameters: u : ndarray @@ -372,9 +372,9 @@ \frac{c_{TF} + c_{FT}} {c_{TT} + c_{FT} + c_{TF}} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`. :Parameters: u : ndarray @@ -402,9 +402,9 @@ \frac{c_{TF} + c_{FT} - c_{TT} + n} {c_{FT} + c_{TF} + n} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`. :Parameters: u : ndarray @@ -478,7 +478,7 @@ .. math: (u-v)V^{-1}(u-v)^T - where ``VI`` is the inverse covariance matrix :math:`$V^{-1}$`. + where ``VI`` is the inverse covariance matrix :math:`V^{-1}`. :Parameters: u : ndarray @@ -614,9 +614,9 @@ \frac{R} \frac{c_{TT} + c_{FF} + \frac{R}{2}} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$` and :math:`$R = 2.0 * (c_{TF} + c_{FT})$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n` and :math:`R = 2.0 * (c_{TF} + c_{FT})`. :Parameters: u : ndarray @@ -642,9 +642,9 @@ \frac{c_{TF} + c_{FT}}{n} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`. :Parameters: u : ndarray @@ -671,9 +671,9 @@ \frac{c_{TF} + c_{FT} {2c_{TT} + c_{FT} + c_{TF}} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`. :Parameters: u : ndarray @@ -703,9 +703,9 @@ \frac{R} {c_{TT} + c_{FF} + R} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$` and :math:`$R = 2(c_{TF} + c_{FT})$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`. :Parameters: u : ndarray @@ -733,9 +733,9 @@ \frac{n - c_{TT}} {n} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`. :Parameters: u : ndarray @@ -765,10 +765,10 @@ \frac{2R} {S + 2R} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$`, :math:`$R = 2 * (c_{TF} + c{FT})$` and - :math:`$S = c_{FF} + c_{TT}$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n`, :math:`R = 2 * (c_{TF} + c{FT})` and + :math:`S = c_{FF} + c_{TT}`. :Parameters: u : ndarray @@ -801,9 +801,9 @@ \frac{2R} {c_{TT} + 2R} - where :math:`$c_{ij}$` is the number of occurrences of - :math:`$\mathtt{u[k]}` = i$ and :math:`$\mathtt{v[k]} = j$` for - :math:`$k < n$` and :math:`$R = 2(c_{TF} + c{FT})$`. + where :math:`c_{ij}` is the number of occurrences of + :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for + :math:`k < n` and :math:`R = 2(c_{TF} + c{FT})`. :Parameters: u : ndarray @@ -829,7 +829,7 @@ """ Computes the pairwise distances between m original observations in n-dimensional space. Returns a condensed distance matrix Y. For - each :math:`$i$` and :math:`$j$` (where :math:`$i Author: ptvirtan Date: 2008-11-13 18:34:38 -0600 (Thu, 13 Nov 2008) New Revision: 5097 Modified: scipy-docs/trunk/source/odr.rst scipy-docs/trunk/source/optimize.rst Log: Add some functions back, now that the docstrings are fixed Modified: scipy-docs/trunk/source/odr.rst =================================================================== --- scipy-docs/trunk/source/odr.rst 2008-11-13 22:22:59 UTC (rev 5096) +++ scipy-docs/trunk/source/odr.rst 2008-11-14 00:34:38 UTC (rev 5097) @@ -20,8 +20,7 @@ .. automethod:: set_iprint - .. note:: XXX: Sphinx doesn't like "set_job" docstring; after it's fixed, - add "set_job" here. + .. automethod:: set_job .. autoclass:: Output Modified: scipy-docs/trunk/source/optimize.rst =================================================================== --- scipy-docs/trunk/source/optimize.rst 2008-11-13 22:22:59 UTC (rev 5096) +++ scipy-docs/trunk/source/optimize.rst 2008-11-14 00:34:38 UTC (rev 5097) @@ -48,13 +48,9 @@ fminbound golden - bracket + bracket + brent -.. note:: - - XXX: Sphinx didn't like "brent" docstring; add it to the list after - it's fixed. - Root finding ============ From scipy-svn at scipy.org Thu Nov 13 19:35:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 18:35:33 -0600 (CST) Subject: [Scipy-svn] r5098 - in scipy-docs/trunk/source: . tutorial tutorial/examples Message-ID: <20081114003533.4BA8D39C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 18:35:03 -0600 (Thu, 13 Nov 2008) New Revision: 5098 Added: scipy-docs/trunk/source/tutorial/ scipy-docs/trunk/source/tutorial/examples/ scipy-docs/trunk/source/tutorial/examples/1.1 scipy-docs/trunk/source/tutorial/examples/10.2.1 scipy-docs/trunk/source/tutorial/examples/10.2.2 scipy-docs/trunk/source/tutorial/examples/10.2.3 scipy-docs/trunk/source/tutorial/examples/10.2.5 scipy-docs/trunk/source/tutorial/examples/10.3.1 scipy-docs/trunk/source/tutorial/examples/10.3.2 scipy-docs/trunk/source/tutorial/examples/10.3.6 scipy-docs/trunk/source/tutorial/examples/10.4.4 scipy-docs/trunk/source/tutorial/examples/2.1 scipy-docs/trunk/source/tutorial/examples/2.2 scipy-docs/trunk/source/tutorial/examples/2.3 scipy-docs/trunk/source/tutorial/examples/3.1 scipy-docs/trunk/source/tutorial/examples/3.2 scipy-docs/trunk/source/tutorial/examples/4.1 scipy-docs/trunk/source/tutorial/examples/4.2 scipy-docs/trunk/source/tutorial/examples/4.3 scipy-docs/trunk/source/tutorial/examples/4.4 scipy-docs/trunk/source/tutorial/examples/4.5 scipy-docs/trunk/source/tutorial/examples/4.6 scipy-docs/trunk/source/tutorial/examples/5.1 scipy-docs/trunk/source/tutorial/examples/5.2 scipy-docs/trunk/source/tutorial/examples/5.3 scipy-docs/trunk/source/tutorial/examples/5.4 scipy-docs/trunk/source/tutorial/examples/5.5 scipy-docs/trunk/source/tutorial/examples/5.6 scipy-docs/trunk/source/tutorial/examples/5.7 scipy-docs/trunk/source/tutorial/examples/5.8 scipy-docs/trunk/source/tutorial/examples/5.9 scipy-docs/trunk/source/tutorial/examples/6.1 scipy-docs/trunk/source/tutorial/examples/6.2 scipy-docs/trunk/source/tutorial/examples/6.3 scipy-docs/trunk/source/tutorial/examples/6.4 scipy-docs/trunk/source/tutorial/index.rst Modified: scipy-docs/trunk/source/conf.py scipy-docs/trunk/source/index.rst Log: Add the old Scipy tutorial (needs updating) Modified: scipy-docs/trunk/source/conf.py =================================================================== --- scipy-docs/trunk/source/conf.py 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/conf.py 2008-11-14 00:35:03 UTC (rev 5098) @@ -21,7 +21,7 @@ # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'numpydoc', 'phantom_import', 'autosummary', 'sphinx.ext.intersphinx', - 'sphinx.ext.coverage'] + 'sphinx.ext.coverage', 'only_directives', 'plot_directive'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] Modified: scipy-docs/trunk/source/index.rst =================================================================== --- scipy-docs/trunk/source/index.rst 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/index.rst 2008-11-14 00:35:03 UTC (rev 5098) @@ -5,9 +5,18 @@ SciPy (pronounced "Sigh Pie") is open-source software for mathematics, science, and engineering. + .. toctree:: :maxdepth: 1 + tutorial/index + +Reference +--------- + +.. toctree:: + :maxdepth: 1 + cluster constants fftpack Added: scipy-docs/trunk/source/tutorial/examples/1.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/1.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/1.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,37 @@ +>>> info(optimize.fmin) + fmin(func, x0, args=(), xtol=0.0001, ftol=0.0001, maxiter=None, maxfun=None, + full_output=0, printmessg=1) + +Minimize a function using the simplex algorithm. + +Description: + + Uses a Nelder-Mead simplex algorithm to find the minimum of function + of one or more variables. + +Inputs: + + func -- the Python function or method to be minimized. + x0 -- the initial guess. + args -- extra arguments for func. + xtol -- relative tolerance + +Outputs: (xopt, {fopt, warnflag}) + + xopt -- minimizer of function + + fopt -- value of function at minimum: fopt = func(xopt) + warnflag -- Integer warning flag: + 1 : 'Maximum number of function evaluations.' + 2 : 'Maximum number of iterations.' + +Additional Inputs: + + xtol -- acceptable relative error in xopt for convergence. + ftol -- acceptable relative error in func(xopt) for convergence. + maxiter -- the maximum number of iterations to perform. + maxfun -- the maximum number of function evaluations. + full_output -- non-zero if fval and warnflag outputs are desired. + printmessg -- non-zero to print convergence messages. + + Added: scipy-docs/trunk/source/tutorial/examples/10.2.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.2.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,13 @@ +>>> A = mat('[1 3 5; 2 5 1; 2 3 8]') +>>> A +Matrix([[1, 3, 5], + [2, 5, 1], + [2, 3, 8]]) +>>> A.I +Matrix([[-1.48, 0.36, 0.88], + [ 0.56, 0.08, -0.36], + [ 0.16, -0.12, 0.04]]) +>>> linalg.inv(A) +array([[-1.48, 0.36, 0.88], + [ 0.56, 0.08, -0.36], + [ 0.16, -0.12, 0.04]]) Added: scipy-docs/trunk/source/tutorial/examples/10.2.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.2.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,10 @@ +>>> A = mat('[1 3 5; 2 5 1; 2 3 8]') +>>> b = mat('[10;8;3]') +>>> A.I*b +Matrix([[-9.28], + [ 5.16], + [ 0.76]]) +>>> linalg.solve(A,b) +array([[-9.28], + [ 5.16], + [ 0.76]]) Added: scipy-docs/trunk/source/tutorial/examples/10.2.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.3 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.2.3 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,4 @@ +>>> A = mat('[1 3 5; 2 5 1; 2 3 8]') +>>> linalg.det(A) +-25.000000000000004 + Added: scipy-docs/trunk/source/tutorial/examples/10.2.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,17 @@ +c1,c2= 5.0,2.0 +i = r_[1:11] +xi = 0.1*i +yi = c1*exp(-xi)+c2*xi +zi = yi + 0.05*max(yi)*randn(len(yi)) + +A = c_[exp(-xi)[:,NewAxis],xi[:,NewAxis]] +c,resid,rank,sigma = linalg.lstsq(A,zi) + +xi2 = r_[0.1:1.0:100j] +yi2 = c[0]*exp(-xi2) + c[1]*xi2 + +xplt.plot(xi,zi,'x',xi2,yi2) +xplt.limits(0,1.1,3.0,5.5) +xplt.xlabel('x_i') +xplt.title('Data fitting with linalg.lstsq') +xplt.eps('lstsq_fit') Added: scipy-docs/trunk/source/tutorial/examples/10.3.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.3.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,18 @@ +>>> A = mat('[1 5 2; 2 4 1; 3 6 2]') +>>> la,v = linalg.eig(A) +>>> l1,l2,l3 = la +>>> print l1, l2, l3 +(7.95791620491+0j) (-1.25766470568+0j) (0.299748500767+0j) + +>>> print v[:,0] +array([-0.5297, -0.4494, -0.7193]) +>>> print v[:,1] +[-0.9073 0.2866 0.3076] +>>> print v[:,2] +[ 0.2838 -0.3901 0.8759] +>>> print sum(abs(v**2),axis=0) +[ 1. 1. 1.] + +>>> v1 = mat(v[:,0]).T +>>> print max(ravel(abs(A*v1-l1*v1))) +4.4408920985e-16 Added: scipy-docs/trunk/source/tutorial/examples/10.3.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.3.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,22 @@ +>>> A = mat('[1 3 2; 1 2 3]') +>>> M,N = A.shape +>>> U,s,Vh = linalg.svd(A) +>>> Sig = mat(diagsvd(s,M,N)) +>>> U, Vh = mat(U), mat(Vh) +>>> print U +Matrix([[-0.7071, -0.7071], + [-0.7071, 0.7071]]) +>>> print Sig +Matrix([[ 5.1962, 0. , 0. ], + [ 0. , 1. , 0. ]]) +>>> print Vh +Matrix([[-0.2722, -0.6804, -0.6804], + [-0. , -0.7071, 0.7071], + [-0.9623, 0.1925, 0.1925]]) + +>>> print A +Matrix([[1, 3, 2], + [1, 2, 3]]) +>>> print U*Sig*Vh +Matrix([[ 1., 3., 2.], + [ 1., 2., 3.]]) Added: scipy-docs/trunk/source/tutorial/examples/10.3.6 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.6 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.3.6 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,36 @@ +>>> A = mat('[1 3 2; 1 4 5; 2 3 6]') +>>> T,Z = linalg.schur(A) +>>> T1,Z1 = linalg.schur(A,'complex') +>>> T2,Z2 = linalg.rsf2csf(T,Z) +>>> print T +Matrix([[ 9.9001, 1.7895, -0.655 ], + [ 0. , 0.5499, -1.5775], + [ 0. , 0.5126, 0.5499]]) +>>> print T2 +Matrix([[ 9.9001+0.j , -0.3244+1.5546j, -0.8862+0.569j ], + [ 0. +0.j , 0.5499+0.8993j, 1.0649-0.j ], + [ 0. +0.j , 0. +0.j , 0.5499-0.8993j]]) +>>> print abs(T1-T2) # different +[[ 0. 2.1184 0.1949] + [ 0. 0. 1.2676] + [ 0. 0. 0. ]] +>>> print abs(Z1-Z2) # different +[[ 0.0683 1.1175 0.1973] + [ 0.1186 0.5644 0.247 ] + [ 0.1262 0.7645 0.1916]] +>>> T,Z,T1,Z1,T2,Z2 = map(mat,(T,Z,T1,Z1,T2,Z2)) +>>> print abs(A-Z*T*Z.H) +Matrix([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +>>> print abs(A-Z1*T1*Z1.H) +Matrix([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +>>> print abs(A-Z2*T2*Z2.H) +Matrix([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + + + Added: scipy-docs/trunk/source/tutorial/examples/10.4.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.4.4 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/10.4.4 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,10 @@ +>>> A = rand(3,3) +>>> B = linalg.funm(A,lambda x: special.jv(0,real(x))) +>>> print A +[[ 0.0593 0.5612 0.4403] + [ 0.8797 0.2556 0.1452] + [ 0.964 0.9666 0.1243]] +>>> print B +[[ 0.8206 -0.1212 -0.0612] + [-0.1323 0.8256 -0.0627] + [-0.2073 -0.1946 0.8516]] Added: scipy-docs/trunk/source/tutorial/examples/2.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/2.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,20 @@ +>>> mgrid[0:5,0:5] +array([[[0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4]], + [[0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4]]]) +>>> mgrid[0:5:4j,0:5:4j] +array([[[ 0. , 0. , 0. , 0. ], + [ 1.6667, 1.6667, 1.6667, 1.6667], + [ 3.3333, 3.3333, 3.3333, 3.3333], + [ 5. , 5. , 5. , 5. ]], + [[ 0. , 1.6667, 3.3333, 5. ], + [ 0. , 1.6667, 3.3333, 5. ], + [ 0. , 1.6667, 3.3333, 5. ], + [ 0. , 1.6667, 3.3333, 5. ]]]) Added: scipy-docs/trunk/source/tutorial/examples/2.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/2.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,14 @@ +>>> p = poly1d([3,4,5]) +>>> print p + 2 +3 x + 4 x + 5 +>>> print p*p + 4 3 2 +9 x + 24 x + 46 x + 40 x + 25 +>>> print p.integ(k=6) + 3 2 +x + 2 x + 5 x + 6 +>>> print p.deriv() +6 x + 4 +>>> p([4,5]) +array([ 69, 100]) \ No newline at end of file Added: scipy-docs/trunk/source/tutorial/examples/2.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.3 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/2.3 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,6 @@ +>>> x = r_[-2:3] +>>> x +array([-2, -1, 0, 1, 2]) +>>> select([x > 3, x >= 0],[0,x+2]) +array([0, 0, 2, 3, 4]) + Added: scipy-docs/trunk/source/tutorial/examples/3.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/3.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/3.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,5 @@ +>>> def addsubtract(a,b): + if a > b: + return a - b + else: + return a + b Added: scipy-docs/trunk/source/tutorial/examples/3.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/3.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/3.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,2 @@ +>>> vec_addsubtract([0,3,6,9],[1,3,5,7]) +array([1, 6, 1, 2]) Added: scipy-docs/trunk/source/tutorial/examples/4.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/4.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,13 @@ +>>> help(integrate) +Methods for Integrating Functions + + odeint -- Integrate ordinary differential equations. + quad -- General purpose integration. + dblquad -- General purpose double integration. + tplquad -- General purpose triple integration. + gauss_quad -- Integrate func(x) using Gaussian quadrature of order n. + gauss_quadtol -- Integrate with given tolerance using Gaussian quadrature. + + See the orthogonal module (integrate.orthogonal) for Gaussian + quadrature roots and weights. + Added: scipy-docs/trunk/source/tutorial/examples/4.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/4.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,11 @@ +>>> result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5) +>>> print result +(1.1178179380783249, 7.8663172481899801e-09) + +>>> I = sqrt(2/pi)*(18.0/27*sqrt(2)*cos(4.5)-4.0/27*sqrt(2)*sin(4.5)+ + sqrt(2*pi)*special.fresnl(3/sqrt(pi))[0]) +>>> print I +1.117817938088701 + +>>> print abs(result[0]-I) +1.03761443881e-11 Added: scipy-docs/trunk/source/tutorial/examples/4.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.3 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/4.3 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,13 @@ +>>> from integrate import quad, Inf +>>> def integrand(t,n,x): + return exp(-x*t) / t**n + +>>> def expint(n,x): + return quad(integrand, 1, Inf, args=(n, x))[0] + +>>> vec_expint = vectorize(expint) + +>>> vec_expint(3,arange(1.0,4.0,0.5)) +array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) +>>> special.expn(3,arange(1.0,4.0,0.5)) +array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) Added: scipy-docs/trunk/source/tutorial/examples/4.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.4 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/4.4 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,10 @@ +>>> result = quad(lambda x: expint(3, x), 0, Inf) +>>> print result +(0.33333333324560266, 2.8548934485373678e-09) + +>>> I3 = 1.0/3.0 +>>> print I3 +0.333333333333 + +>>> print I3 - result[0] +8.77306560731e-11 Added: scipy-docs/trunk/source/tutorial/examples/4.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.5 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/4.5 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,11 @@ +>>> from __future__ import nested_scopes +>>> from integrate import quad, dblquad, Inf +>>> def I(n): + return dblquad(lambda t, x: exp(-x*t)/t**n, 0, Inf, lambda x: 1, lambda x: Inf) + +>>> print I(4) +(0.25000000000435768, 1.0518245707751597e-09) +>>> print I(3) +(0.33333333325010883, 2.8604069919261191e-09) +>>> print I(2) +(0.49999999999857514, 1.8855523253868967e-09) Added: scipy-docs/trunk/source/tutorial/examples/4.6 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.6 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/4.6 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,27 @@ +>>> from integrate import odeint +>>> from special import gamma, airy +>>> y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0) +>>> y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0) +>>> y0 = [y0_0, y1_0] +>>> def func(y, t): + return [t*y[1],y[0]] + +>>> def gradient(y,t): + return [[0,t],[1,0]] + +>>> x = arange(0,4.0, 0.01) +>>> t = x +>>> ychk = airy(x)[0] +>>> y = odeint(func, y0, t) +>>> y2 = odeint(func, y0, t, Dfun=gradient) + +>>> import sys +>>> sys.float_output_precision = 6 +>>> print ychk[:36:6] +[ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806] + +>>> print y[:36:6,1] +[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] + +>>> print y2[:36:6,1] +[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] Added: scipy-docs/trunk/source/tutorial/examples/5.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,37 @@ +>>> info(optimize) + Optimization Tools + +A collection of general-purpose optimization routines. + + fmin -- Nelder-Mead Simplex algorithm + (uses only function calls) + fmin_powell -- Powell's (modified) level set method (uses only + function calls) + fmin_bfgs -- Quasi-Newton method (can use function and gradient) + fmin_ncg -- Line-search Newton Conjugate Gradient (can use + function, gradient and hessian). + leastsq -- Minimize the sum of squares of M equations in + N unknowns given a starting estimate. + + Scalar function minimizers + + fminbound -- Bounded minimization of a scalar function. + brent -- 1-D function minimization using Brent method. + golden -- 1-D function minimization using Golden Section method + bracket -- Bracket a minimum (given two starting points) + +Also a collection of general_purpose root-finding routines. + + fsolve -- Non-linear multi-variable equation solver. + + Scalar function solvers + + brentq -- quadratic interpolation Brent method + brenth -- Brent method (modified by Harris with + hyperbolic extrapolation) + ridder -- Ridder's method + bisect -- Bisection method + newton -- Secant method or Newton's method + + fixed_point -- Single-variable fixed-point solver. + Added: scipy-docs/trunk/source/tutorial/examples/5.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,13 @@ +>>> from scipy.optimize import fmin +>>> def rosen(x): # The Rosenbrock function + return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin(rosen, x0) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 516 + Function evaluations: 825 + +>>> print xopt +[ 1. 1. 1. 1. 1.] Added: scipy-docs/trunk/source/tutorial/examples/5.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.3 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.3 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,10 @@ +>>> def rosen_der(x): + xm = x[1:-1] + xm_m1 = x[:-2] + xm_p1 = x[2:] + der = zeros(x.shape,x.typecode()) + der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm) + der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0]) + der[-1] = 200*(x[-1]-x[-2]**2) + return der + Added: scipy-docs/trunk/source/tutorial/examples/5.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.4 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.4 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,11 @@ +>>> from scipy.optimize import fmin_bfgs + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin_bfgs(rosen, x0, fprime=rosen_der) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 109 + Function evaluations: 262 + Gradient evaluations: 110 +>>> print xopt +[ 1. 1. 1. 1. 1.] Added: scipy-docs/trunk/source/tutorial/examples/5.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.5 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.5 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,21 @@ +>>> from scipy.optimize import fmin_ncg +>>> def rosen_hess(x): + x = asarray(x) + H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1) + diagonal = zeros(len(x),x.typecode()) + diagonal[0] = 1200*x[0]-400*x[1]+2 + diagonal[-1] = 200 + diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:] + H = H + diag(diagonal) + return H + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess=rosen_hess) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 19 + Function evaluations: 40 + Gradient evaluations: 19 + Hessian evaluations: 19 +>>> print xopt +[ 0.9999 0.9999 0.9998 0.9996 0.9991] Added: scipy-docs/trunk/source/tutorial/examples/5.6 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.6 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.6 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,20 @@ +>>> from scipy.optimize import fmin_ncg +>>> def rosen_hess_p(x,p): + x = asarray(x) + Hp = zeros(len(x),x.typecode()) + Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1] + Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \ + -400*x[1:-1]*p[2:] + Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1] + return Hp + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess_p=rosen_hess_p) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 20 + Function evaluations: 42 + Gradient evaluations: 20 + Hessian evaluations: 44 +>>> print xopt +[ 1. 1. 1. 0.9999 0.9999] Added: scipy-docs/trunk/source/tutorial/examples/5.7 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.7 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.7 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,31 @@ +>>> from numpy import * +>>> x = arange(0,6e-2,6e-2/30) +>>> A,k,theta = 10, 1.0/3e-2, pi/6 +>>> y_true = A*sin(2*pi*k*x+theta) +>>> y_meas = y_true + 2*random.randn(len(x)) + +>>> def residuals(p, y, x): +... A,k,theta = p +... err = y-A*sin(2*pi*k*x+theta) +... return err + +>>> def peval(x, p): +... return p[0]*sin(2*pi*p[1]*x+p[2]) + +>>> p0 = [8, 1/2.3e-2, pi/3] +>>> print array(p0) +[ 8. 43.4783 1.0472] + +>>> from scipy.optimize import leastsq +>>> plsq = leastsq(residuals, p0, args=(y_meas, x)) +>>> print plsq[0] +[ 10.9437 33.3605 0.5834] + +>>> print array([A, k, theta]) +[ 10. 33.3333 0.5236] + +>>> import matplotlib.pyplot as plt +>>> plt.plot(x,peval(x,plsq[0]),x,y_meas,'o',x,y_true) +>>> plt.title('Least-squares fit to noisy data') +>>> plt.legend(['Fit', 'Noisy', 'True']) +>>> plt.show() Added: scipy-docs/trunk/source/tutorial/examples/5.8 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.8 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.8 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,7 @@ +>>> from scipy.special import j1 + +>>> from scipy.optimize import fminbound +>>> xmin = fminbound(j1, 4, 7) +>>> print xmin +5.33144184241 + Added: scipy-docs/trunk/source/tutorial/examples/5.9 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.9 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/5.9 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,16 @@ +>>> def func(x): + return x + 2*cos(x) + +>>> def func2(x): + out = [x[0]*cos(x[1]) - 4] + out.append(x[1]*x[0] - x[1] - 5) + return out + +>>> from optimize import fsolve +>>> x0 = fsolve(func, 0.3) +>>> print x0 +-1.02986652932 + +>>> x02 = fsolve(func2, [1, 1]) +>>> print x02 +[ 6.5041 0.9084] Added: scipy-docs/trunk/source/tutorial/examples/6.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,18 @@ +>>> x = arange(0,10) +>>> y = exp(-x/3.0) +>>> f = interpolate.linear_1d(x,y) +>>> help(f) +Instance of class: linear_1d + + (x_new) + +Find linearly interpolated y_new = (x_new). + +Inputs: + x_new -- New independent variables. + +Outputs: + y_new -- Linearly interpolated values corresponding to x_new. + +>>> xnew = arange(0,9,0.1) +>>> xplt.plot(x,y,'x',xnew,f(xnew),'.') Added: scipy-docs/trunk/source/tutorial/examples/6.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,56 @@ +>>> from numpy import * +>>> import matplotlib.pyplot as plt +>>> from scipy import interpolate + +>>> # Cubic-spline +>>> x = arange(0,2*pi+pi/4,2*pi/8) +>>> y = sin(x) +>>> tck = interpolate.splrep(x,y,s=0) +>>> xnew = arange(0,2*pi,pi/50) +>>> ynew = interpolate.splev(xnew,tck,der=0) +>>> plt.plot(x,y,'x',xnew,ynew,xnew,sin(xnew),x,y,'b') +>>> #plt.legend(['Linear','Cubic Spline', 'True']) +>>> plt.axis([-0.05,6.33,-1.05,1.05]) +>>> plt.title('Cubic-spline interpolation') +>>> plt.show() + +>>> # Derivative of spline +>>> yder = interpolate.splev(xnew,tck,der=1) +>>> plt.plot(xnew,yder,xnew,cos(xnew),'|') +>>> #plt.legend(['Cubic Spline', 'True']) +>>> plt.axis([-0.05,6.33,-1.05,1.05]) +>>> plt.title('Derivative estimation from spline') +>>> plt.show() + +>>> # Integral of spline +>>> def integ(x,tck,constant=-1): +>>> x = atleast_1d(x) +>>> out = zeros(x.shape, dtype=x.dtype) +>>> for n in xrange(len(out)): +>>> out[n] = interpolate.splint(0,x[n],tck) +>>> out += constant +>>> return out +>>> +>>> yint = integ(xnew,tck) +>>> plt.plot(xnew,yint,xnew,-cos(xnew),'|') +>>> #plt.legend(['Cubic Spline', 'True']) +>>> plt.axis([-0.05,6.33,-1.05,1.05]) +>>> plt.title('Integral estimation from spline') +>>> plt.show() + +>>> # Roots of spline +>>> print interpolate.sproot(tck) +[ 0. 3.1416] + +>>> # Parametric spline +>>> t = arange(0,1.1,.1) +>>> x = sin(2*pi*t) +>>> y = cos(2*pi*t) +>>> tck,u = interpolate.splprep([x,y],s=0) +>>> unew = arange(0,1.01,0.01) +>>> out = interpolate.splev(unew,tck) +>>> plt.plot(x,y,'x',out[0],out[1],sin(2*pi*unew),cos(2*pi*unew),x,y,'b') +>>> #plt.legend(['Linear','Cubic Spline', 'True'],['b-x','m','r']) +>>> plt.axis([-1.05,1.05,-1.05,1.05]) +>>> plt.title('Spline of parametrically-defined curve') +>>> plt.show() Added: scipy-docs/trunk/source/tutorial/examples/6.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,14 @@ +>>> # Define function over sparse 20x20 grid +>>> x,y = mgrid[-1:1:20j,-1:1:20j] +>>> z = (x+y)*exp(-6.0*(x*x+y*y)) +>>> xplt.surf(z,x,y,shade=1,palette='rainbow') +>>> xplt.title3("Sparsely sampled function.") +>>> xplt.eps("2d_func") + +>>> # Interpolate function over new 70x70 grid +>>> xnew,ynew = mgrid[-1:1:70j,-1:1:70j] +>>> tck = interpolate.bisplrep(x,y,z,s=0) +>>> znew = interpolate.bisplev(xnew[:,0],ynew[0,:],tck) +>>> xplt.surf(znew,xnew,ynew,shade=1,palette='rainbow') +>>> xplt.title3("Interpolated function.") +>>> xplt.eps("2d_interp") Added: scipy-docs/trunk/source/tutorial/examples/6.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,16 @@ +>>> image = lena().astype(Float32) +>>> derfilt = array([1.0,-2,1.0],Float32) +>>> ck = signal.cspline2d(image,8.0) +>>> deriv = signal.sepfir2d(ck, derfilt, [1]) + \ +>>> signal.sepfir2d(ck, [1], derfilt) +>>> +>>> ## Alternatively we could have done: +>>> ## laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],Float32) +>>> ## deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm') +>>> +>>> xplt.imagesc(image[::-1]) # flip image so it looks right-side up. +>>> xplt.title('Original image') +>>> xplt.eps('lena_image') +>>> xplt.imagesc(deriv[::-1]) +>>> xplt.title('Output of spline edge filter') +>>> xplt.eps('lena_edge') Added: scipy-docs/trunk/source/tutorial/index.rst =================================================================== --- scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:34:38 UTC (rev 5097) +++ scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:35:03 UTC (rev 5098) @@ -0,0 +1,2237 @@ +############## +SciPy Tutorial +############## + +.. sectionauthor:: Travis E. Oliphant, Pauli Virtanen + +.. currentmodule:: scipy + +.. warning:: + + This is adapted from the old Scipy tutorial, and it is being revised. + Parts of it are still out-of-date. + + +Introduction +============ + +SciPy is a collection of mathematical algorithms and convenience +functions built on the Numpy extension for Python. It adds +significant power to the interactive Python session by exposing the +user to high-level commands and classes for the manipulation and +visualization of data. With SciPy, an interactive Python session +becomes a data-processing and system-prototyping environment rivaling +sytems such as Matlab, IDL, Octave, R-Lab, and SciLab. + +The additional power of using SciPy within Python, however, is that a +powerful programming language is also available for use in developing +sophisticated programs and specialized applications. Scientific +applications written in SciPy benefit from the development of +additional modules in numerous niche's of the software landscape by +developers across the world. Everything from parallel programming to +web and data-base subroutines and classes have been made available to +the Python programmer. All of this power is available in addition to +the mathematical libraries in SciPy. + +This document provides a tutorial for the first-time user of SciPy to +help get started with some of the features available in this powerful +package. It is assumed that the user has already installed the +package. Some general Python facility is also assumed such as could be +acquired by working through the Tutorial in the Python distribution. +For further introductory help the user is directed to the Numpy +documentation. Throughout this tutorial it is assumed that the user +has imported all of the names defined in the SciPy namespace using the +command + + >>> from scipy import * + +General Help +------------ + +Python provides the facility of documentation strings. The functions +and classes available in SciPy use this method for on-line +documentation. There are two methods for reading these messages and +getting help. Python provides the command :func:`help` in the pydoc +module. Entering this command with no arguments (i.e. ``>>> help`` ) +launches an interactive help session that allows searching through the +keywords and modules available to all of Python. Running the command +help with an object as the argument displays the calling signature, +and the documentation string of the object. + +The pydoc method of help is sophisticated but uses a pager to display +the text. Sometimes this can interfere with the terminal you are +running the interactive session within. A scipy-specific help system +is also available under the command scipy.info. The signature and +documentation string for the object passed to the help command are +printed to standard output (or to a writeable object passed as the +third argument). The second keyword argument of "scipy.info "defines the maximum width of the line for printing. If a module is +passed as the argument to help than a list of the functions and +classes defined in that module is printed. For example: + +.. literalinclude:: examples/1.1 + +Another useful command is :func:`source`. When given a function +written in Python as an argument, it prints out a listing of the +source code for that function. This can be helpful in learning about +an algorithm or understanding exactly what a function is doing with +its arguments. Also don't forget about the Python command ``dir`` +which can be used to look at the namespace of a module or package. + + +SciPy Organization +------------------ + +SciPy is organized into subpackages covering different scientific +computing domains. Many common functions which several subpackages +rely are in :mod:`numpy`. This allows for the possibility of +separately distributing the subpackages of scipy as long as Numpy is +provided as well. + +Two other packages are installed at the higher-level: scipy_distutils +and weave. These two packages while distributed with main scipy +package could see use independently of scipy and so are treated as +separate packages and described elsewhere. + +The remaining subpackages are summarized in the following table (a * +denotes an optional sub-package that requires additional libraries to +function or is not available on all platforms). + + +=========== ===================================================================== +Subpackage Description +=========== ===================================================================== +cluster Clustering algorithms +cow Cluster of Workstations code for parallel programming +fftpack FFT based on fftpack -- default +fftw* FFT based on fftw --- requires FFTW libraries (is this still needed?) +ga Genetic algorithms +gplt* Plotting --- requires gnuplot +integrate Integration +interpolate Interpolation +io Input and Output +linalg Linear algebra +optimize Optimization and root-finding routines +plt* Plotting --- requires wxPython +signal Signal processing +special Special functions +stats Statistical distributions and functions +xplt Plotting with gist +=========== ===================================================================== + + + +Because of their ubiquitousness, some of the functions in these +subpackages are also made available in the scipy namespace to ease +their use in interactive sessions and programs. In addition, many +convenience functions are located in :mod:`numpy` and the in the +top-level of the :mod:`scipy` package. Before looking at the +sub-packages individually, we will first look at some of these common +functions. + + +Basic functions in Numpy and top-level scipy +============================================ + +Interaction with Numpy +------------------------ + +To begin with, all of the Numpy functions have been subsumed into +the scipy namespace so that all of those functions are available +without additionally importing Numpy. In addition, the universal +functions (addition, subtraction, division) have been altered to not +raise exceptions if floating-point errors are encountered, +instead NaN's and Inf's are returned in the arrays. To assist in +detection of these events new universal functions (isnan, isfinite, +isinf) have been added. + +In addition, the comparision operators have been changed to allow +comparisons and logical operations of complex numbers (only the real +part is compared). Also, with the new universal functions in SciPy, +the logical operations (except logical_XXX functions) all return +arrays of unsigned bytes (8-bits per element instead of the old +32-bits, or even 64-bits) per element [#]_ . + +In an effort to get a consistency for default arguments, some of the +default arguments have changed from Numpy. The idea is for you to use +scipy as a base package instead of Numpy anyway. + +Finally, some of the basic functions like log, sqrt, and inverse trig +functions have been modified to return complex numbers instead of +NaN's where appropriate (*i.e.* ``scipy.sqrt(-1)`` returns ``1j``). + +.. [#] Be careful when treating logical expressions as integers as the 8-bit + integers may silently overflow at 256. + + + +Top-level scipy routines +------------------------ + +The purpose of the top level of scipy is to collect general-purpose +routines that the other sub-packages can use and to provide a simple +replacement for Numpy. Anytime you might think to import Numpy, +you can import scipy_base instead and remove yourself from direct +dependence on Numpy. These routines are divided into several files +for organizational purposes, but they are all available under the +scipy_base namespace (and the scipy namespace). There are routines for +type handling and type checking, shape and matrix manipulation, +polynomial processing, and other useful functions. Rather than giving +a detailed description of each of these functions (which is available +using the :func:`help`, :func:`info` and :func:`source` commands), +this tutorial will discuss some of the more useful commands which +require a little introduction to use to their full potential. + + +Type handling +^^^^^^^^^^^^^ + +Note the difference between :func:`iscomplex` ( :func:`isreal` ) and :func:`iscomplexobj` ( :func:`isrealobj` ). The former command is array based and returns byte arrays of ones +and zeros providing the result of the element-wise test. The latter +command is object based and returns a scalar describing the result of +the test on the entire object. + +Often it is required to get just the real and/or imaginary part of a +complex number. While complex numbers and arrays have attributes that +return those values, if one is not sure whether or not the object will +be complex-valued, it is better to use the functional forms +:func:`real` and :func:`imag` . These functions succeed for anything +that can be turned into a Numpy array. Consider also the function +:func:`real_if_close` which transforms a complex-valued number with +tiny imaginary part into a real number. + +Occasionally the need to check whether or not a number is a scalar +(Python (long)int, Python float, Python complex, or rank-0 array) +occurs in coding. This functionality is provided in the convenient +function :func:`isscalar` which returns a 1 or a 0. + +Finally, ensuring that objects are a certain Numpy type occurs often +enough that it has been given a convenient interface in SciPy through +the use of the :obj:`cast` dictionary. The dictionary is keyed by the +type it is desired to cast to and the dictionary stores functions to +perform the casting. Thus, ``>>> a = cast['f'](d)`` returns an array +of float32 from d. This function is also useful as an easy way to get +a scalar of a certain type: ``>>> fpi = cast['f'](pi)`` although this +should not be needed if you use alter_numeric(). + + +Index Tricks +^^^^^^^^^^^^ + +Thre are some class instances that make special use of the slicing +functionality to provide efficient means for array construction. This +part will discuss the operation of :obj:`mgrid` , :obj:`ogrid` , :obj:`r_` , and :obj:`c_` for quickly constructing arrays. + +One familiar with Matlab may complain that it is difficult to +construct arrays from the interactive session with Python. Suppose, +for example that one wants to construct an array that begins with 3 +followed by 5 zeros and then contains 10 numbers spanning the range -1 +to 1 (inclusive on both ends). Before SciPy, you would need to enter +something like the following ``>>> concatenate(([3],[0]*5,arange(-1,1.002,2/9.0))`` . With the :obj:`r_` command one can enter this as ``>>> r_[3,[0]*5,-1:1:10j]`` which can ease typing and make for more readable code. Notice how +objects are concatenated, and the slicing syntax is (ab)used to +construct ranges. The other term that deserves a little explanation is +the use of the complex number 10j as the step size in the slicing +syntax. This non-standard use allows the number to be interpreted as +the number of points to produce in the range rather than as a step +size (note we would have used the long integer notation, 10L, but this +notation may go away in Python as the integers become unified). This +non-standard usage may be unsightly to some, but it gives the user the +ability to quickly construct complicated vectors in a very readable +fashion. When the number of points is specified in this way, the end- +point is inclusive. + +The "r "stands for row concatenation because if the objects between commas are +2 dimensional arrays, they are stacked by rows (and thus must have +commensurate columns). There is an equivalent command :obj:`c_` that stacks 2d arrays by columns but works identically to :obj:`r_` for 1d arrays. + +Another very useful class instance which makes use of extended slicing +notation is the function :obj:`mgrid` . In the simplest case, this function can be used to construct 1d +ranges as a convenient substitute for arange. It also allows the use +of complex-numbers in the step-size to indicate the number of points +to place between the (inclusive) end-points. The real purpose of this +function however is to produce N, N-d arrays which provide coordinate +arrays for an N-dimensional volume. The easiest way to understand this +is with an example of its usage: + +.. literalinclude:: examples/2.1 + +Having meshed arrays like this is sometimes very useful. However, it +is not always needed just to evaluate some N-dimensional function over +a grid due to the array-broadcasting rules of Numpy and SciPy. If +this is the only purpose for generating a meshgrid, you should instead +use the function :obj:`ogrid` which generates an "open "grid using NewAxis judiciously to create N, N-d arrays where only one- +dimension in each array has length greater than 1. This will save +memory and create the same result if the only purpose for the meshgrid +is to generate sample points for evaluation of an N-d function. + + +Shape manipulation +^^^^^^^^^^^^^^^^^^ + +In this category of functions are routines for squeezing out length- +one dimensions from N-dimensional arrays, ensuring that an array is at +least 1-, 2-, or 3-dimensional, and stacking (concatenating) arrays by +rows, columns, and "pages "(in the third dimension). Routines for splitting arrays (roughly the +opposite of stacking arrays) are also available. + + +Matrix manipulations +^^^^^^^^^^^^^^^^^^^^ + +These are functions specifically suited for 2-dimensional arrays that +were part of MLab in the Numpy distribution, but have been placed in +scipy_base for completeness so that users are not importing Numpy. + + +Polynomials +^^^^^^^^^^^ + +There are two (interchangeable) ways to deal with 1-d polynomials in +SciPy. The first is to use the :class:`poly1d` class in Numpy. This +class accepts coefficients or polynomial roots to initialize a +polynomial. The polynomial object can then be manipulated in algebraic +expressions, integrated, differentiated, and evaluated. It even prints +like a polynomial: + +.. literalinclude:: examples/2.2 + +The other way to handle polynomials is as an array of coefficients +with the first element of the array giving the coefficient of the +highest power. There are explicit functions to add, subtract, +multiply, divide, integrate, differentiate, and evaluate polynomials +represented as sequences of coefficients. + + +Vectorizing functions (vectorize) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +One of the features that SciPy provides is a class :obj:`vectorize` to +convert an ordinary Python function which accepts scalars and returns +scalars into a "vectorized-function "with the same broadcasting rules +as other Numpy functions (*i.e.* the Universal functions, or +ufuncs). For example, suppose you have a Python function named +:obj:`addsubtract` defined as: + +.. literalinclude:: examples/3.1 + +which defines a function of two scalar variables and returns a scalar +result. The class vectorize can be used to "vectorize "this function so that :: + + >>> vec_addsubtract = vectorize(addsubtract) + +returns a function which takes array arguments and returns an array +result: + +.. literalinclude:: examples/3.2 + +This particular function could have been written in vector form +without the use of :obj:`vectorize` . But, what if the function you have written is the result of some +optimization or integration routine. Such functions can likely only be +vectorized using ``vectorize.`` + + +Other useful functions +^^^^^^^^^^^^^^^^^^^^^^ + +There are several other functions in the scipy_base package including +most of the other functions that are also in MLab that comes with the +Numpy package. The reason for duplicating these functions is to +allow SciPy to potentially alter their original interface and make it +easier for users to know how to get access to functions +``>>> from scipy import \*.`` + +New functions which should be mentioned are :obj:`mod(x,y)` which can +replace ``x % y`` when it is desired that the result take the sign of +*y* instead of *x* . Also included is :obj:`fix` which always rounds +to the nearest integer towards zero. For doing phase processing, the +functions :func:`angle`, and :obj:`unwrap` are also useful. Also, the +:obj:`linspace` and :obj:`logspace` functions return equally spaced samples +in a linear or log scale. Finally, mention should be made of the new +function :obj:`select` which extends the functionality of :obj:`where` to +include multiple conditions and multiple choices. The calling +convention is ``select(condlist,choicelist,default=0).`` :obj:`select` is +a vectorized form of the multiple if-statement. It allows rapid +construction of a function which returns an array of results based on +a list of conditions. Each element of the return array is taken from +the array in a ``choicelist`` corresponding to the first condition in +``condlist`` that is true. For example + +.. literalinclude:: examples/2.3 + + +Common functions +---------------- + +Some functions depend on sub-packages of SciPy but should be available +from the top-level of SciPy due to their common use. These are +functions that might have been placed in scipy_base except for their +dependence on other sub-packages of SciPy. For example the +:obj:`factorial` and :obj:`comb` functions compute :math:`n!` and +:math:`n!/k!(n-k)!` using either exact integer arithmetic (thanks to +Python's Long integer object), or by using floating-point precision +and the gamma function. The functions :obj:`rand` and :obj:`randn` +are used so often that they warranted a place at the top level. There +are convenience functions for the interactive use: :obj:`disp` +(similar to print), and :obj:`who` (returns a list of defined +variables and memory consumption--upper bounded). Another function +returns a common image used in image processing: :obj:`lena`. + +Finally, two functions are provided that are useful for approximating +derivatives of functions using discrete-differences. The function :obj:`central_diff_weights` returns weighting coefficients for an equally-spaced :math:`N` -point approximation to the derivative of order :math:`o.` These weights must be multiplied by the function corresponding to +these points and the results added to obtain the derivative +approximation. This function is intended for use when only samples of +the function are avaiable. When the function is an object that can be +handed to a routine and evaluated, the function :obj:`derivative` can be used to automatically evaluate the object at the correct points +to obtain an N-point approximation to the :math:`o^{\textrm{th}}` -derivative at a given point. + + +Special functions (special) +=========================== + +.. currentmodule:: scipy.special + +The main feature of the :mod:`scipy.special` package is the definition of +numerous special functions of mathematical physics. Available +functions include airy, elliptic, bessel, gamma, beta, hypergeometric, +parabolic cylinder, mathieu, spheroidal wave, struve, and +kelvin. There are also some low-level stats functions that are not +intended for general use as an easier interface to these functions is +provided by the ``stats`` module. Most of these functions can take +array arguments and return array results following the same +broadcasting rules as other math functions in Numerical Python. Many +of these functions also accept complex-numbers as input. For a +complete list of the available functions with a one-line description +type ``>>>info(special).`` Each function also has it's own +documentation accessible using help. If you don't see a function you +need, consider writing it and contributing it to the library. You can +write the function in either C, Fortran, or Python. Look in the source +code of the library for examples of each of these kind of functions. + + +Integration (integrate) +======================= + +.. currentmodule:: scipy.integrate + +The :mod:`scipy.integrate` sub-package provides several integration +techniques including an ordinary differential equation integrator. An +overview of the module is provided by the help command: + +.. literalinclude:: examples/4.1 + + +General integration (integrate.quad) +------------------------------------ + +The function :obj:`quad` is provided to integrate a function of one +variable between two points. The points can be :math:`\pm\infty` +(:math:`\pm` ``inf``) to indicate infinite limits. For example, +suppose you wish to integrate a bessel function ``jv(2.5,x)`` along +the interval :math:`[0,4.5].` + +.. math:: + :nowrap: + + \[ I=\int_{0}^{4.5}J_{2.5}\left(x\right)\, dx.\] + +This could be computed using :obj:`quad`: + +.. literalinclude:: examples/4.2 + +The first argument to quad is a "callable "Python object ( *i.e* a function, method, or class instance). Notice the use of a lambda- +function in this case as the argument. The next two arguments are the +limits of integration. The return value is a tuple, with the first +element holding the estimated value of the integral and the second +element holding an upper bound on the error. Notice, that in this +case, the true value of this integral is + +.. math:: + :nowrap: + + \[ I=\sqrt{\frac{2}{\pi}}\left(\frac{18}{27}\sqrt{2}\cos\left(4.5\right)-\frac{4}{27}\sqrt{2}\sin\left(4.5\right)+\sqrt{2\pi}\textrm{Si}\left(\frac{3}{\sqrt{\pi}}\right)\right),\] + +where + +.. math:: + :nowrap: + + \[ \textrm{Si}\left(x\right)=\int_{0}^{x}\sin\left(\frac{\pi}{2}t^{2}\right)\, dt.\] + +is the Fresnel sine integral. Note that the numerically-computed +integral is within :math:`1.04\times10^{-11}` of the exact result --- well below the reported error bound. + +Infinite inputs are also allowed in :obj:`quad` by using :math:`\pm` +``inf`` as one of the arguments. For example, suppose that a numerical +value for the exponential integral: + +.. math:: + :nowrap: + + \[ E_{n}\left(x\right)=\int_{1}^{\infty}\frac{e^{-xt}}{t^{n}}\, dt.\] + +is desired (and the fact that this integral can be computed as +``special.expn(n,x)`` is forgotten). The functionality of the function +:obj:`special.expn` can be replicated by defining a new function +:obj:`vec_expint` based on the routine :obj:`quad`: + +.. literalinclude:: examples/4.3 + +The function which is integrated can even use the quad argument +(though the error bound may underestimate the error due to possible +numerical error in the integrand from the use of :obj:`quad` ). The integral in this case is + +.. math:: + :nowrap: + + \[ I_{n}=\int_{0}^{\infty}\int_{1}^{\infty}\frac{e^{-xt}}{t^{n}}\, dt\, dx=\frac{1}{n}.\] + +.. literalinclude:: examples/4.4 + +This last example shows that multiple integration can be handled using +repeated calls to :func:`quad`. The mechanics of this for double and +triple integration have been wrapped up into the functions +:obj:`dblquad` and :obj:`tplquad`. The function, :obj:`dblquad` +performs double integration. Use the help function to be sure that the +arguments are defined in the correct order. In addition, the limits on +all inner integrals are actually functions which can be constant +functions. An example of using double integration to compute several +values of :math:`I_{n}` is shown below: + +.. literalinclude:: examples/4.5 + + +Gaussian quadrature (integrate.gauss_quadtol) +--------------------------------------------- + +A few functions are also provided in order to perform simple Gaussian +quadrature over a fixed interval. The first is :obj:`fixed_quad` which +performs fixed-order Gaussian quadrature. The second function is +:obj:`quadrature` which performs Gaussian quadrature of multiple +orders until the difference in the integral estimate is beneath some +tolerance supplied by the user. These functions both use the module +:mod:`special.orthogonal` which can calculate the roots and quadrature +weights of a large variety of orthogonal polynomials (the polynomials +themselves are available as special functions returning instances of +the polynomial class --- e.g. ``special.legendre`` ). + + +Integrating using samples +------------------------- + +There are three functions for computing integrals given only samples: :obj:`trapz` , :obj:`simps` , and :obj:`romb` . The first two functions use Newton-Coates formulas of order 1 and 2 +respectively to perform integration. These two functions can handle, +non-equally-spaced samples. The trapezoidal rule approximates the +function as a straight line between adjacent points, while Simpson's +rule approximates the function between three adjacent points as a +parabola. + +If the samples are equally-spaced and the number of samples available +is :math:`2^{k}+1` for some integer :math:`k` , then Romberg integration can be used to obtain high-precision +estimates of the integral using the available samples. Romberg +integration uses the trapezoid rule at step-sizes related by a power +of two and then performs Richardson extrapolation on these estimates +to approximate the integral with a higher-degree of accuracy. (A +different interface to Romberg integration useful when the function +can be provided is also available as :func:`integrate.romberg`). + + +Ordinary differential equations (integrate.odeint) +-------------------------------------------------- + +Integrating a set of ordinary differential equations (ODEs) given +initial conditions is another useful example. The function :obj:`odeint` is available in SciPy for integrating a first-order vector +differential equation: + +.. math:: + :nowrap: + + \[ \frac{d\mathbf{y}}{dt}=\mathbf{f}\left(\mathbf{y},t\right),\] + +given initial conditions :math:`\mathbf{y}\left(0\right)=y_{0},` where :math:`\mathbf{y}` is a length :math:`N` vector and :math:`\mathbf{f}` is a mapping from :math:`\mathcal{R}^{N}` to :math:`\mathcal{R}^{N}.` A higher-order ordinary differential equation can always be reduced to +a differential equation of this type by introducing intermediate +derivatives into the :math:`\mathbf{y}` vector. + +For example suppose it is desired to find the solution to the +following second-order differential equation: + +.. math:: + :nowrap: + + \[ \frac{d^{2}w}{dz^{2}}-zw(z)=0\] + +with initial conditions :math:`w\left(0\right)=\frac{1}{\sqrt[3]{3^{2}}\Gamma\left(\frac{2}{3}\right)}` and :math:`\left.\frac{dw}{dz}\right|_{z=0}=-\frac{1}{\sqrt[3]{3}\Gamma\left(\frac{1}{3}\right)}.` It is known that the solution to this differential equation with these +boundary conditions is the Airy function + +.. math:: + :nowrap: + + \[ w=\textrm{Ai}\left(z\right),\] + +which gives a means to check the integrator using :func:`special.airy`. + +First, convert this ODE into standard form by setting :math:`\mathbf{y}=\left[\frac{dw}{dz},w\right]` and :math:`t=z.` Thus, the differential equation becomes + +.. math:: + :nowrap: + + \[ \frac{d\mathbf{y}}{dt}=\left[\begin{array}{c} ty_{1}\\ y_{0}\end{array}\right]=\left[\begin{array}{cc} 0 & t\\ 1 & 0\end{array}\right]\left[\begin{array}{c} y_{0}\\ y_{1}\end{array}\right]=\left[\begin{array}{cc} 0 & t\\ 1 & 0\end{array}\right]\mathbf{y}.\] + +In other words, + +.. math:: + :nowrap: + + \[ \mathbf{f}\left(\mathbf{y},t\right)=\mathbf{A}\left(t\right)\mathbf{y}.\] + + + +As an interesting reminder, if :math:`\mathbf{A}\left(t\right)` commutes with :math:`\int_{0}^{t}\mathbf{A}\left(\tau\right)\, d\tau` under matrix multiplication, then this linear differential equation +has an exact solution using the matrix exponential: + +.. math:: + :nowrap: + + \[ \mathbf{y}\left(t\right)=\exp\left(\int_{0}^{t}\mathbf{A}\left(\tau\right)d\tau\right)\mathbf{y}\left(0\right),\] + +However, in this case, :math:`\mathbf{A}\left(t\right)` and its integral do not commute. + +There are many optional inputs and outputs available when using odeint +which can help tune the solver. These additional inputs and outputs +are not needed much of the time, however, and the three required input +arguments and the output solution suffice. The required inputs are the +function defining the derivative, *fprime*, the initial conditions +vector, *y0*, and the time points to obtain a solution, *t*, (with +the initial value point as the first element of this sequence). The +output to :obj:`odeint` is a matrix where each row contains the +solution vector at each requested time point (thus, the initial +conditions are given in the first output row). + +The following example illustrates the use of odeint including the +usage of the *Dfun* option which allows the user to specify a gradient +(with respect to :math:`\mathbf{y}` ) of the function, +:math:`\mathbf{f}\left(\mathbf{y},t\right)`. + +.. literalinclude:: examples/4.6 + + +Optimization (optimize) +======================= + +There are several classical optimization algorithms provided by SciPy +in the :mod:`scipy.optimize` package. An overview of the module is +available using :func:`help` (or :func:`pydoc.help`): + +.. literalinclude:: examples/5.1 + +The first four algorithms are unconstrained minimization algorithms +(fmin: Nelder-Mead simplex, fmin_bfgs: BFGS, fmin_ncg: Newton +Conjugate Gradient, and leastsq: Levenburg-Marquardt). The fourth +algorithm only works for functions of a single variable but allows +minimization over a specified interval. The last algorithm actually +finds the roots of a general function of possibly many variables. It +is included in the optimization package because at the (non-boundary) +extreme points of a function, the gradient is equal to zero. + + +Nelder-Mead Simplex algorithm (optimize.fmin) +--------------------------------------------- + +The simplex algorithm is probably the simplest way to minimize a +fairly well-behaved function. The simplex algorithm requires only +function evaluations and is a good choice for simple minimization +problems. However, because it does not use any gradient evaluations, +it may take longer to find the minimum. To demonstrate the +minimization function consider the problem of minimizing the +Rosenbrock function of :math:`N` variables: + +.. math:: + :nowrap: + + \[ f\left(\mathbf{x}\right)=\sum_{i=1}^{N-1}100\left(x_{i}-x_{i-1}^{2}\right)^{2}+\left(1-x_{i-1}\right)^{2}.\] + +The minimum value of this function is 0 which is achieved when :math:`x_{i}=1.` This minimum can be found using the :obj:`fmin` routine as shown in the example below: + +.. literalinclude:: examples/5.2 + +Another optimization algorithm that needs only function calls to find +the minimum is Powell's method available as :func:`optimize.fmin_powell`. + + +Broyden-Fletcher-Goldfarb-Shanno algorithm (optimize.fmin_bfgs) +--------------------------------------------------------------- + +In order to converge more quickly to the solution, this routine uses +the gradient of the objective function. If the gradient is not given +by the user, then it is estimated using first-differences. The +Broyden-Fletcher-Goldfarb-Shanno (BFGS) method typically requires +fewer function calls than the simplex algorithm even when the gradient +must be estimated. + +To demonstrate this algorithm, the Rosenbrock function is again used. +The gradient of the Rosenbrock function is the vector: + +.. math:: + :nowrap: + + \begin{eqnarray*} \frac{\partial f}{\partial x_{j}} & = & \sum_{i=1}^{N}200\left(x_{i}-x_{i-1}^{2}\right)\left(\delta_{i,j}-2x_{i-1}\delta_{i-1,j}\right)-2\left(1-x_{i-1}\right)\delta_{i-1,j}.\\ & = & 200\left(x_{j}-x_{j-1}^{2}\right)-400x_{j}\left(x_{j+1}-x_{j}^{2}\right)-2\left(1-x_{j}\right).\end{eqnarray*} + +This expression is valid for the interior derivatives. Special cases +are + +.. math:: + :nowrap: + + \begin{eqnarray*} \frac{\partial f}{\partial x_{0}} & = & -400x_{0}\left(x_{1}-x_{0}^{2}\right)-2\left(1-x_{0}\right),\\ \frac{\partial f}{\partial x_{N-1}} & = & 200\left(x_{N-1}-x_{N-2}^{2}\right).\end{eqnarray*} + +A Python function which computes this gradient is constructed by the +code-segment: + +.. literalinclude:: examples/5.3 + +The calling signature for the BFGS minimization algorithm is similar +to :obj:`fmin` with the addition of the *fprime* argument. An example +usage of :obj:`fmin_bfgs` is shown in the following example which +minimizes the Rosenbrock function. + +.. literalinclude:: examples/5.4 + + +Newton-Conjugate-Gradient (optimize.fmin_ncg) +--------------------------------------------- + +The method which requires the fewest function calls and is therefore +often the fastest method to minimize functions of many variables is +:obj:`fmin_ncg`. This method is a modified Newton's method and uses a +conjugate gradient algorithm to (approximately) invert the local +Hessian. Newton's method is based on fitting the function locally to +a quadratic form: + +.. math:: + :nowrap: + + \[ f\left(\mathbf{x}\right)\approx f\left(\mathbf{x}_{0}\right)+\nabla f\left(\mathbf{x}_{0}\right)\cdot\left(\mathbf{x}-\mathbf{x}_{0}\right)+\frac{1}{2}\left(\mathbf{x}-\mathbf{x}_{0}\right)^{T}\mathbf{H}\left(\mathbf{x}_{0}\right)\left(\mathbf{x}-\mathbf{x}_{0}\right).\] + +where :math:`\mathbf{H}\left(\mathbf{x}_{0}\right)` is a matrix of second-derivatives (the Hessian). If the Hessian is +positive definite then the local minimum of this function can be found +by setting the gradient of the quadratic form to zero, resulting in + +.. math:: + :nowrap: + + \[ \mathbf{x}_{\textrm{opt}}=\mathbf{x}_{0}-\mathbf{H}^{-1}\nabla f.\] + +The inverse of the Hessian is evaluted using the conjugate-gradient +method. An example of employing this method to minimizing the +Rosenbrock function is given below. To take full advantage of the +NewtonCG method, a function which computes the Hessian must be +provided. The Hessian matrix itself does not need to be constructed, +only a vector which is the product of the Hessian with an arbitrary +vector needs to be available to the minimization routine. As a result, +the user can provide either a function to compute the Hessian matrix, +or a function to compute the product of the Hessian with an arbitrary +vector. + + +Full Hessian example: +^^^^^^^^^^^^^^^^^^^^^ + +The Hessian of the Rosenbrock function is + +.. math:: + :nowrap: + + \begin{eqnarray*} H_{ij}=\frac{\partial^{2}f}{\partial x_{i}\partial x_{j}} & = & 200\left(\delta_{i,j}-2x_{i-1}\delta_{i-1,j}\right)-400x_{i}\left(\delta_{i+1,j}-2x_{i}\delta_{i,j}\right)-400\delta_{i,j}\left(x_{i+1}-x_{i}^{2}\right)+2\delta_{i,j},\\ & = & \left(202+1200x_{i}^{2}-400x_{i+1}\right)\delta_{i,j}-400x_{i}\delta_{i+1,j}-400x_{i-1}\delta_{i-1,j},\end{eqnarray*} + +if :math:`i,j\in\left[1,N-2\right]` with :math:`i,j\in\left[0,N-1\right]` defining the :math:`N\times N` matrix. Other non-zero entries of the matrix are + +.. math:: + :nowrap: + + \begin{eqnarray*} \frac{\partial^{2}f}{\partial x_{0}^{2}} & = & 1200x_{0}^{2}-400x_{1}+2,\\ \frac{\partial^{2}f}{\partial x_{0}\partial x_{1}}=\frac{\partial^{2}f}{\partial x_{1}\partial x_{0}} & = & -400x_{0},\\ \frac{\partial^{2}f}{\partial x_{N-1}\partial x_{N-2}}=\frac{\partial^{2}f}{\partial x_{N-2}\partial x_{N-1}} & = & -400x_{N-2},\\ \frac{\partial^{2}f}{\partial x_{N-1}^{2}} & = & 200.\end{eqnarray*} + +For example, the Hessian when :math:`N=5` is + +.. math:: + :nowrap: + + \[ \mathbf{H}=\left[\begin{array}{ccccc} 1200x_{0}^{2}-400x_{1}+2 & -400x_{0} & 0 & 0 & 0\\ -400x_{0} & 202+1200x_{1}^{2}-400x_{2} & -400x_{1} & 0 & 0\\ 0 & -400x_{1} & 202+1200x_{2}^{2}-400x_{3} & -400x_{2} & 0\\ 0 & & -400x_{2} & 202+1200x_{3}^{2}-400x_{4} & -400x_{3}\\ 0 & 0 & 0 & -400x_{3} & 200\end{array}\right].\] + +The code which computes this Hessian along with the code to minimize +the function using :obj:`fmin_ncg` is shown in the following example: + +.. literalinclude:: examples/5.5 + + + +Hessian product example: +^^^^^^^^^^^^^^^^^^^^^^^^ + +For larger minimization problems, storing the entire Hessian matrix +can consume considerable time and memory. The Newton-CG algorithm only +needs the product of the Hessian times an arbitrary vector. As a +result, the user can supply code to compute this product rather than +the full Hessian by setting the *fhess_p* keyword to the desired +function. The *fhess_p* function should take the minimization vector as +the first argument and the arbitrary vector as the second +argument. Any extra arguments passed to the function to be minimized +will also be passed to this function. If possible, using Newton-CG +with the hessian product option is probably the fastest way to +minimize the function. + +In this case, the product of the Rosenbrock Hessian with an arbitrary +vector is not difficult to compute. If :math:`\mathbf{p}` is the arbitrary vector, then :math:`\mathbf{H}\left(\mathbf{x}\right)\mathbf{p}` has elements: + +.. math:: + :nowrap: + + \[ \mathbf{H}\left(\mathbf{x}\right)\mathbf{p}=\left[\begin{array}{c} \left(1200x_{0}^{2}-400x_{1}+2\right)p_{0}-400x_{0}p_{1}\\ \vdots\\ -400x_{i-1}p_{i-1}+\left(202+1200x_{i}^{2}-400x_{i+1}\right)p_{i}-400x_{i}p_{i+1}\\ \vdots\\ -400x_{N-2}p_{N-2}+200p_{N-1}\end{array}\right].\] + +Code which makes use of the *fhess_p* keyword to minimize the Rosenbrock function using :obj:`fmin_ncg` follows: + +.. literalinclude:: examples/5.6 + + +Least-square fitting (minimize.leastsq) +--------------------------------------- + +All of the previously-explained minimization procedures can be used to +solve a least-squares problem provided the appropriate objective +function is constructed. For example, suppose it is desired to fit a +set of data :math:`\left\{ \mathbf{x}_{i},\mathbf{y}_{i}\right\} ` to a known model, :math:`\mathbf{y}=\mathbf{f}\left(\mathbf{x},\mathbf{p}\right)` where :math:`\mathbf{p}` is a vector of parameters for the model that need to be found. A +common method for determining which parameter vector gives the best +fit to the data is to minimize the sum of squares of the residuals. +The residual is usually defined for each observed data-point as + +.. math:: + :nowrap: + + \[ e_{i}\left(\mathbf{p},\mathbf{y}_{i},\mathbf{x}_{i}\right)=\left\Vert \mathbf{y}_{i}-\mathbf{f}\left(\mathbf{x}_{i},\mathbf{p}\right)\right\Vert .\] + +An objective function to pass to any of the previous minization +algorithms to obtain a least-squares fit is. + +.. math:: + :nowrap: + + \[ J\left(\mathbf{p}\right)=\sum_{i=0}^{N-1}e_{i}^{2}\left(\mathbf{p}\right).\] + + + +The :obj:`leastsq` algorithm performs this squaring and summing of the residuals +automatically. It takes as an input argument the vector function :math:`\mathbf{e}\left(\mathbf{p}\right)` and returns the value of :math:`\mathbf{p}` which minimizes :math:`J\left(\mathbf{p}\right)=\mathbf{e}^{T}\mathbf{e}` directly. The user is also encouraged to provide the Jacobian matrix +of the function (with derivatives down the columns or across the +rows). If the Jacobian is not provided, it is estimated. + +An example should clarify the usage. Suppose it is believed some +measured data follow a sinusoidal pattern + +.. math:: + :nowrap: + + \[ y_{i}=A\sin\left(2\pi kx_{i}+\theta\right)\] + +where the parameters :math:`A,` :math:`k` , and :math:`\theta` are unknown. The residual vector is + +.. math:: + :nowrap: + + \[ e_{i}=\left|y_{i}-A\sin\left(2\pi kx_{i}+\theta\right)\right|.\] + +By defining a function to compute the residuals and (selecting an +appropriate starting position), the least-squares fit routine can be +used to find the best-fit parameters :math:`\hat{A},\,\hat{k},\,\hat{\theta}` . This is shown in the following example and a plot of the results is +shown in Figure `1 <#fig-least-squares-fit>`__ . + +.. plot:: source/tutorial/examples/5.7 + :include-source: + :doctest-format: + :align: center + +.. **Figure 1** Least-square fitting to noisy data using +.. :obj:`scipy.optimize.leastsq` +.. +.. .. _`fig:least_squares_fit`: + + +Scalar function minimizers +-------------------------- + +Often only the minimum of a scalar function is needed (a scalar +function is one that takes a scalar as input and returns a scalar +output). In these circumstances, other optimization techniques have +been developed that can work faster. + + +Unconstrained minimization (optimize.brent) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +There are actually two methods that can be used to minimize a scalar +function (:obj:`brent` and :func:`golden`), but :obj:`golden` is +included only for academic purposes and should rarely be used. The +brent method uses Brent's algorithm for locating a minimum. Optimally +a bracket should be given which contains the minimum desired. A +bracket is a triple :math:`\left(a,b,c\right)` such that +:math:`f\left(a\right)>f\left(b\right)`__ ). + +.. plot:: source/tutorial/examples/6.2 + :include-source: + :doctest-format: + + +.. figure:: interp_cubic.epsi + :align: center + + **Figure 3** .. image: interp_cubic_der.epsi + + + + + .. image: interp_cubic_int.epsi + + + .. image: interp_cubic_param.epsi + + + + Examples of using cubic-spline interpolation. + + .. _`fig:spline-1d`: + + + + +.. literalinclude:: examples/6.2 + + + +Two-dimensionsal spline representation (interpolate.bisplrep) +------------------------------------------------------------- + +For (smooth) spline-fitting to a two dimensional surface, the function +:obj:`interpolate.bisplrep` is available. This function takes as +required inputs the **1-D** arrays *x*, *y*, and *z* which represent +points on the surface :math:`z=f\left(x,y\right).` The default output +is a list :math:`\left[tx,ty,c,kx,ky\right]` whose entries represent +respectively, the components of the knot positions, the coefficients +of the spline, and the order of the spline in each coordinate. It is +convenient to hold this list in a single object, *tck,* so that it can +be passed easily to the function :obj:`interpolate.bisplev`. The +keyword, *s* , can be used to change the amount of smoothing performed +on the data while determining the appropriate spline. The default +value is :math:`s=m-\sqrt{2m}` where :math:`m` is the number of data +points in the *x, y,* and *z* vectors. As a result, if no smoothing is +desired, then :math:`s=0` should be passed to +:obj:`interpolate.bisplrep` . + +To evaluate the two-dimensional spline and it's partial derivatives +(up to the order of the spline), the function +:obj:`interpolate.bisplev` is required. This function takes as the +first two arguments **two 1-D arrays** whose cross-product specifies +the domain over which to evaluate the spline. The third argument is +the *tck* list returned from :obj:`interpolate.bisplrep`. If desired, +the fourth and fifth arguments provide the orders of the partial +derivative in the :math:`x` and :math:`y` direction respectively. + +It is important to note that two dimensional interpolation should not +be used to find the spline representation of images. The algorithm +used is not amenable to large numbers of input points. The signal +processing toolbox contains more appropriate algorithms for finding +the spline representation of an image. The two dimensional +interpolation commands are intended for use when interpolating a two +dimensional function as shown in the example that follows (See also +Figure `4 <#fig-2d-interp>`__ ). This example uses the :obj:`mgrid` command in SciPy which is useful for defining a "mesh-grid "in many dimensions. (See also the :obj:`ogrid` command if the full-mesh is not needed). The number of output +arguments and the number of dimensions of each argument is determined +by the number of indexing objects passed in :obj:`mgrid`[]. +.. literalinclude:: examples/6.3 + + + + + + +.. figure:: 2d_func.epsi + :align: center + + **Figure 4** .. image: 2d_interp.epsi + + + + Example of two-dimensional spline interpolation. + + .. _`fig:2d_interp`: + + + + + + +Signal Processing (signal) +========================== + +The signal processing toolbox currently contains some filtering +functions, a limited set of filter design tools, and a few B-spline +interpolation algorithms for one- and two-dimensional data. While the +B-spline algorithms could technically be placed under the +interpolation category, they are included here because they only work +with equally-spaced data and make heavy use of filter-theory and +transfer-function formalism to provide a fast B-spline transform. To +understand this section you will need to understand that a signal in +SciPy is an array of real or complex numbers. + + +B-splines +--------- + +A B-spline is an approximation of a continuous function over a finite- +domain in terms of B-spline coefficients and knot points. If the knot- +points are equally spaced with spacing :math:`\Delta x` , then the B-spline approximation to a 1-dimensional function is the +finite-basis expansion. + +.. math:: + :nowrap: + + \[ y\left(x\right)\approx\sum_{j}c_{j}\beta^{o}\left(\frac{x}{\Delta x}-j\right).\] + +In two dimensions with knot-spacing :math:`\Delta x` and :math:`\Delta y` , the function representation is + +.. math:: + :nowrap: + + \[ z\left(x,y\right)\approx\sum_{j}\sum_{k}c_{jk}\beta^{o}\left(\frac{x}{\Delta x}-j\right)\beta^{o}\left(\frac{y}{\Delta y}-k\right).\] + +In these expressions, :math:`\beta^{o}\left(\cdot\right)` is the space-limited B-spline basis function of order, :math:`o` . The requirement of equally-spaced knot-points and equally-spaced +data points, allows the development of fast (inverse-filtering) +algorithms for determining the coefficients, :math:`c_{j}` , from sample-values, :math:`y_{n}` . Unlike the general spline interpolation algorithms, these algorithms +can quickly find the spline coefficients for large images. + +The advantage of representing a set of samples via B-spline basis +functions is that continuous-domain operators (derivatives, re- +sampling, integral, etc.) which assume that the data samples are drawn +from an underlying continuous function can be computed with relative +ease from the spline coefficients. For example, the second-derivative +of a spline is + +.. math:: + :nowrap: + + \[ y{}^{\prime\prime}\left(x\right)=\frac{1}{\Delta x^{2}}\sum_{j}c_{j}\beta^{o\prime\prime}\left(\frac{x}{\Delta x}-j\right).\] + +Using the property of B-splines that + +.. math:: + :nowrap: + + \[ \frac{d^{2}\beta^{o}\left(w\right)}{dw^{2}}=\beta^{o-2}\left(w+1\right)-2\beta^{o-2}\left(w\right)+\beta^{o-2}\left(w-1\right)\] + +it can be seen that + +.. math:: + :nowrap: + + \[ y^{\prime\prime}\left(x\right)=\frac{1}{\Delta x^{2}}\sum_{j}c_{j}\left[\beta^{o-2}\left(\frac{x}{\Delta x}-j+1\right)-2\beta^{o-2}\left(\frac{x}{\Delta x}-j\right)+\beta^{o-2}\left(\frac{x}{\Delta x}-j-1\right)\right].\] + +If :math:`o=3` , then at the sample points, + +.. math:: + :nowrap: + + \begin{eqnarray*} \Delta x^{2}\left.y^{\prime}\left(x\right)\right|_{x=n\Delta x} & = & \sum_{j}c_{j}\delta_{n-j+1}-2c_{j}\delta_{n-j}+c_{j}\delta_{n-j-1},\\ & = & c_{n+1}-2c_{n}+c_{n-1}.\end{eqnarray*} + +Thus, the second-derivative signal can be easily calculated from the +spline fit. if desired, smoothing splines can be found to make the +second-derivative less sensitive to random-errors. + +The savvy reader will have already noticed that the data samples are +related to the knot coefficients via a convolution operator, so that +simple convolution with the sampled B-spline function recovers the +original data from the spline coefficients. The output of convolutions +can change depending on how boundaries are handled (this becomes +increasingly more important as the number of dimensions in the data- +set increases). The algorithms relating to B-splines in the signal- +processing sub package assume mirror-symmetric boundary conditions. +Thus, spline coefficients are computed based on that assumption, and +data-samples can be recovered exactly from the spline coefficients by +assuming them to be mirror-symmetric also. + +Currently the package provides functions for determining second- and +third-order cubic spline coefficients from equally spaced samples in +one- and two-dimensions (:func:`signal.qspline1d`, +:func:`signal.qspline2d`, :func:`signal.cspline1d`, +:func:`signal.cspline2d`). The package also supplies a function ( +:obj:`signal.bspline` ) for evaluating the bspline basis function, +:math:`\beta^{o}\left(x\right)` for arbitrary order and :math:`x.` For +large :math:`o` , the B-spline basis function can be approximated well +by a zero-mean Gaussian function with standard-deviation equal to +:math:`\sigma_{o}=\left(o+1\right)/12` : + +.. math:: + :nowrap: + + \[ \beta^{o}\left(x\right)\approx\frac{1}{\sqrt{2\pi\sigma_{o}^{2}}}\exp\left(-\frac{x^{2}}{2\sigma_{o}}\right).\] + +A function to compute this Gaussian for arbitrary :math:`x` and +:math:`o` is also available ( :obj:`signal.gauss_spline` ). The +following code and Figure uses spline-filtering to compute an +edge-image (the second-derivative of a smoothed spline) of Lena's face +which is an array returned by the command :func:`lena`. The command +:obj:`signal.sepfir2d` was used to apply a separable two-dimensional +FIR filter with mirror- symmetric boundary conditions to the spline +coefficients. This function is ideally suited for reconstructing +samples from spline coefficients and is faster than +:obj:`signal.convolve2d` which convolves arbitrary two-dimensional +filters and allows for choosing mirror-symmetric boundary conditions. + + +.. literalinclude:: examples/6.4 + + + + +.. figure:: lena_image.epsi + :align: center + + **Figure 5** .. image: lena_edge.epsi + + + + Example of using smoothing splines to filter images. + + .. _`fig:lena_edge_spline`: + + + + +Filtering +--------- + +Filtering is a generic name for any system that modifies an input +signal in some way. In SciPy a signal can be thought of as a Numpy +array. There are different kinds of filters for different kinds of +operations. There are two broad kinds of filtering operations: linear +and non-linear. Linear filters can always be reduced to multiplication +of the flattened Numpy array by an appropriate matrix resulting in +another flattened Numpy array. Of course, this is not usually the +best way to compute the filter as the matrices and vectors involved +may be huge. For example filtering a :math:`512\times512` image with this method would require multiplication of a :math:`512^{2}x512^{2}` matrix with a :math:`512^{2}` vector. Just trying to store the :math:`512^{2}\times512^{2}` matrix using a standard Numpy array would require :math:`68,719,476,736` elements. At 4 bytes per element this would require :math:`256\textrm{GB}` of memory. In most applications most of the elements of this matrix +are zero and a different method for computing the output of the filter +is employed. + + +Convolution/Correlation +^^^^^^^^^^^^^^^^^^^^^^^ + +Many linear filters also have the property of shift-invariance. This +means that the filtering operation is the same at different locations +in the signal and it implies that the filtering matrix can be +constructed from knowledge of one row (or column) of the matrix alone. +In this case, the matrix multiplication can be accomplished using +Fourier transforms. + +Let :math:`x\left[n\right]` define a one-dimensional signal indexed by the integer :math:`n.` Full convolution of two one-dimensional signals can be expressed as + +.. math:: + :nowrap: + + \[ y\left[n\right]=\sum_{k=-\infty}^{\infty}x\left[k\right]h\left[n-k\right].\] + +This equation can only be implemented directly if we limit the +sequences to finite support sequences that can be stored in a +computer, choose :math:`n=0` to be the starting point of both sequences, let :math:`K+1` be that value for which :math:`y\left[n\right]=0` for all :math:`n>K+1` and :math:`M+1` be that value for which :math:`x\left[n\right]=0` for all :math:`n>M+1` , then the discrete convolution expression is + +.. math:: + :nowrap: + + \[ y\left[n\right]=\sum_{k=\max\left(n-M,0\right)}^{\min\left(n,K\right)}x\left[k\right]h\left[n-k\right].\] + +For convenience assume :math:`K\geq M.` Then, more explicitly the output of this operation is + +.. math:: + :nowrap: + + \begin{eqnarray*} y\left[0\right] & = & x\left[0\right]h\left[0\right]\\ y\left[1\right] & = & x\left[0\right]h\left[1\right]+x\left[1\right]h\left[0\right]\\ y\left[2\right] & = & x\left[0\right]h\left[2\right]+x\left[1\right]h\left[1\right]+x\left[2\right]h\left[0\right]\\ \vdots & \vdots & \vdots\\ y\left[M\right] & = & x\left[0\right]h\left[M\right]+x\left[1\right]h\left[M-1\right]+\cdots+x\left[M\right]h\left[0\right]\\ y\left[M+1\right] & = & x\left[1\right]h\left[M\right]+x\left[2\right]h\left[M-1\right]+\cdots+x\left[M+1\right]h\left[0\right]\\ \vdots & \vdots & \vdots\\ y\left[K\right] & = & x\left[K-M\right]h\left[M\right]+\cdots+x\left[K\right]h\left[0\right]\\ y\left[K+1\right] & = & x\left[K+1-M\right]h\left[M\right]+\cdots+x\left[K\right]h\left[1\right]\\ \vdots & \vdots & \vdots\\ y\left[K+M-1\right] & = & x\left[K-1\right]h\left[M\right]+x\left[K\right]h\left[M-1\right]\\ y\left[K+M\right] & = & x\left[K\right]h\left[M\right].\end{eqnarray*} + +Thus, the full discrete convolution of two finite sequences of lengths :math:`K+1` and :math:`M+1` respectively results in a finite sequence of length :math:`K+M+1=\left(K+1\right)+\left(M+1\right)-1.` + +One dimensional convolution is implemented in SciPy with the function ``signal.convolve`` . This function takes as inputs the signals :math:`x,` :math:`h` , and an optional flag and returns the signal :math:`y.` The optional flag allows for specification of which part of the output +signal to return. The default value of 'full' returns the entire +signal. If the flag has a value of 'same' then only the middle :math:`K` values are returned starting at :math:`y\left[\left\lfloor \frac{M-1}{2}\right\rfloor \right]` so that the output has the same length as the largest input. If the +flag has a value of 'valid' then only the middle :math:`K-M+1=\left(K+1\right)-\left(M+1\right)+1` output values are returned where :math:`z` depends on all of the values of the smallest input from :math:`h\left[0\right]` to :math:`h\left[M\right].` In other words only the values :math:`y\left[M\right]` to :math:`y\left[K\right]` inclusive are returned. + +This same function ``signal.convolve`` can actually take :math:`N` -dimensional arrays as inputs and will return the :math:`N` -dimensional convolution of the two arrays. The same input flags are +available for that case as well. + +Correlation is very similar to convolution except for the minus sign +becomes a plus sign. Thus + +.. math:: + :nowrap: + + \[ w\left[n\right]=\sum_{k=-\infty}^{\infty}y\left[k\right]x\left[n+k\right]\] + +is the (cross) correlation of the signals :math:`y` and :math:`x.` For finite-length signals with :math:`y\left[n\right]=0` outside of the range :math:`\left[0,K\right]` and :math:`x\left[n\right]=0` outside of the range :math:`\left[0,M\right],` the summation can simplify to + +.. math:: + :nowrap: + + \[ w\left[n\right]=\sum_{k=\max\left(0,-n\right)}^{\min\left(K,M-n\right)}y\left[k\right]x\left[n+k\right].\] + +Assuming again that :math:`K\geq M` this is + +.. math:: + :nowrap: + + \begin{eqnarray*} w\left[-K\right] & = & y\left[K\right]x\left[0\right]\\ w\left[-K+1\right] & = & y\left[K-1\right]x\left[0\right]+y\left[K\right]x\left[1\right]\\ \vdots & \vdots & \vdots\\ w\left[M-K\right] & = & y\left[K-M\right]x\left[0\right]+y\left[K-M+1\right]x\left[1\right]+\cdots+y\left[K\right]x\left[M\right]\\ w\left[M-K+1\right] & = & y\left[K-M-1\right]x\left[0\right]+\cdots+y\left[K-1\right]x\left[M\right]\\ \vdots & \vdots & \vdots\\ w\left[-1\right] & = & y\left[1\right]x\left[0\right]+y\left[2\right]x\left[1\right]+\cdots+y\left[M+1\right]x\left[M\right]\\ w\left[0\right] & = & y\left[0\right]x\left[0\right]+y\left[1\right]x\left[1\right]+\cdots+y\left[M\right]x\left[M\right]\\ w\left[1\right] & = & y\left[0\right]x\left[1\right]+y\left[1\right]x\left[2\right]+\cdots+y\left[M-1\right]x\left[M\right]\\ w\left[2\right] & = & y\left[0\right]x\left[2\right]+y\left[1\right]x\left[3\right]+\cdots+y\left[M-2\right]x\left[M\right]\\ \vdots & \vdots & \vdots\\ w\left[M-1\right] & = & y\left[0\right]x\left[M-1\right]+y\left[1\right]x\left[M\right]\\ w\left[M\right] & = & y\left[0\right]x\left[M\right].\end{eqnarray*} + + + +The SciPy function ``signal.correlate`` implements this operation. Equivalent flags are available for this +operation to return the full :math:`K+M+1` length sequence ('full') or a sequence with the same size as the +largest sequence starting at :math:`w\left[-K+\left\lfloor \frac{M-1}{2}\right\rfloor \right]` ('same') or a sequence where the values depend on all the values of +the smallest sequence ('valid'). This final option returns the :math:`K-M+1` values :math:`w\left[M-K\right]` to :math:`w\left[0\right]` inclusive. + +The function :obj:`signal.correlate` can also take arbitrary :math:`N` -dimensional arrays as input and return the :math:`N` -dimensional convolution of the two arrays on output. + +When :math:`N=2,` :obj:`signal.correlate` and/or :obj:`signal.convolve` can be used to construct arbitrary image filters to perform actions +such as blurring, enhancing, and edge-detection for an image. + +Convolution is mainly used for filtering when one of the signals is +much smaller than the other ( :math:`K\gg M` ), otherwise linear filtering is more easily accomplished in the +frequency domain (see Fourier Transforms). + + +Difference-equation filtering +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A general class of linear one-dimensional filters (that includes +convolution filters) are filters described by the difference equation + +.. math:: + :nowrap: + + \[ \sum_{k=0}^{N}a_{k}y\left[n-k\right]=\sum_{k=0}^{M}b_{k}x\left[n-k\right]\] + +where :math:`x\left[n\right]` is the input sequence and :math:`y\left[n\right]` is the output sequence. If we assume initial rest so that :math:`y\left[n\right]=0` for :math:`n<0` , then this kind of filter can be implemented using convolution. +However, the convolution filter sequence :math:`h\left[n\right]` could be infinite if :math:`a_{k}\neq0` for :math:`k\geq1.` In addition, this general class of linear filter allows initial +conditions to be placed on :math:`y\left[n\right]` for :math:`n<0` resulting in a filter that cannot be expressed using convolution. + +The difference equation filter can be thought of as finding :math:`y\left[n\right]` recursively in terms of it's previous values + +.. math:: + :nowrap: + + \[ a_{0}y\left[n\right]=-a_{1}y\left[n-1\right]-\cdots-a_{N}y\left[n-N\right]+\cdots+b_{0}x\left[n\right]+\cdots+b_{M}x\left[n-M\right].\] + +Often :math:`a_{0}=1` is chosen for normalization. The implementation in SciPy of this +general difference equation filter is a little more complicated then +would be implied by the previous equation. It is implemented so that +only one signal needs to be delayed. The actual implementation +equations are (assuming :math:`a_{0}=1` ). + +.. math:: + :nowrap: + + \begin{eqnarray*} y\left[n\right] & = & b_{0}x\left[n\right]+z_{0}\left[n-1\right]\\ z_{0}\left[n\right] & = & b_{1}x\left[n\right]+z_{1}\left[n-1\right]-a_{1}y\left[n\right]\\ z_{1}\left[n\right] & = & b_{2}x\left[n\right]+z_{2}\left[n-1\right]-a_{2}y\left[n\right]\\ \vdots & \vdots & \vdots\\ z_{K-2}\left[n\right] & = & b_{K-1}x\left[n\right]+z_{K-1}\left[n-1\right]-a_{K-1}y\left[n\right]\\ z_{K-1}\left[n\right] & = & b_{K}x\left[n\right]-a_{K}y\left[n\right],\end{eqnarray*} + +where :math:`K=\max\left(N,M\right).` Note that :math:`b_{K}=0` if :math:`K>M` and :math:`a_{K}=0` if :math:`K>N.` In this way, the output at time :math:`n` depends only on the input at time :math:`n` and the value of :math:`z_{0}` at the previous time. This can always be calculated as long as the :math:`K` values :math:`z_{0}\left[n-1\right]\ldots z_{K-1}\left[n-1\right]` are computed and stored at each time step. + +The difference-equation filter is called using the command :obj:`signal.lfilter` in SciPy. This command takes as inputs the vector :math:`b,` the vector, :math:`a,` a signal :math:`x` and returns the vector :math:`y` (the same length as :math:`x` ) computed using the equation given above. If :math:`x` is :math:`N` -dimensional, then the filter is computed along the axis provided. If, +desired, initial conditions providing the values of :math:`z_{0}\left[-1\right]` to :math:`z_{K-1}\left[-1\right]` can be provided or else it will be assumed that they are all zero. If +initial conditions are provided, then the final conditions on the +intermediate variables are also returned. These could be used, for +example, to restart the calculation in the same state. + +Sometimes it is more convenient to express the initial conditions in +terms of the signals :math:`x\left[n\right]` and :math:`y\left[n\right].` In other words, perhaps you have the values of :math:`x\left[-M\right]` to :math:`x\left[-1\right]` and the values of :math:`y\left[-N\right]` to :math:`y\left[-1\right]` and would like to determine what values of :math:`z_{m}\left[-1\right]` should be delivered as initial conditions to the difference-equation +filter. It is not difficult to show that for :math:`0\leq mN` the generalized inverse is + +.. math:: + :nowrap: + + \[ \mathbf{A}^{\dagger}=\left(\mathbf{A}^{H}\mathbf{A}\right)^{-1}\mathbf{A}^{H}\] + +while if :math:`M Author: ptvirtan Date: 2008-11-13 18:35:43 -0600 (Thu, 13 Nov 2008) New Revision: 5099 Added: scipy-docs/trunk/source/spatial.rst Modified: scipy-docs/trunk/source/cluster.hierarchy.rst scipy-docs/trunk/source/index.rst scipy-docs/trunk/source/misc.rst scipy-docs/trunk/source/sparse.linalg.rst scipy-docs/trunk/source/weave.rst Log: Add TODO warnings for unorganized parts of the documentation Modified: scipy-docs/trunk/source/cluster.hierarchy.rst =================================================================== --- scipy-docs/trunk/source/cluster.hierarchy.rst 2008-11-14 00:35:03 UTC (rev 5098) +++ scipy-docs/trunk/source/cluster.hierarchy.rst 2008-11-14 00:35:43 UTC (rev 5099) @@ -2,5 +2,9 @@ Hierarchical clustering (:mod:`scipy.cluster.hierarchy`) ======================================================== +.. warning:: + + This documentation is work-in-progress and unorganized. + .. automodule:: scipy.cluster.hierarchy :members: Modified: scipy-docs/trunk/source/index.rst =================================================================== --- scipy-docs/trunk/source/index.rst 2008-11-14 00:35:03 UTC (rev 5098) +++ scipy-docs/trunk/source/index.rst 2008-11-14 00:35:43 UTC (rev 5099) @@ -1,11 +1,10 @@ -############### -SciPy reference -############### +##### +SciPy +##### SciPy (pronounced "Sigh Pie") is open-source software for mathematics, science, and engineering. - .. toctree:: :maxdepth: 1 Modified: scipy-docs/trunk/source/misc.rst =================================================================== --- scipy-docs/trunk/source/misc.rst 2008-11-14 00:35:03 UTC (rev 5098) +++ scipy-docs/trunk/source/misc.rst 2008-11-14 00:35:43 UTC (rev 5099) @@ -2,5 +2,9 @@ Miscellaneous routines (:mod:`scipy.misc`) ========================================== +.. warning:: + + This documentation is work-in-progress and unorganized. + .. automodule:: scipy.misc :members: Modified: scipy-docs/trunk/source/sparse.linalg.rst =================================================================== --- scipy-docs/trunk/source/sparse.linalg.rst 2008-11-14 00:35:03 UTC (rev 5098) +++ scipy-docs/trunk/source/sparse.linalg.rst 2008-11-14 00:35:43 UTC (rev 5099) @@ -2,5 +2,9 @@ Sparse linear algebra (:mod:`scipy.sparse.linalg`) ================================================== +.. warning:: + + This documentation is work-in-progress and unorganized. + .. automodule:: scipy.sparse.linalg :members: Added: scipy-docs/trunk/source/spatial.rst =================================================================== --- scipy-docs/trunk/source/spatial.rst 2008-11-14 00:35:03 UTC (rev 5098) +++ scipy-docs/trunk/source/spatial.rst 2008-11-14 00:35:43 UTC (rev 5099) @@ -0,0 +1,10 @@ +============================================ +Distance computations (:mod:`scipy.spatial`) +============================================ + +.. warning:: + + This documentation is work-in-progress and unorganized. + +.. automodule:: scipy.spatial + :members: Modified: scipy-docs/trunk/source/weave.rst =================================================================== --- scipy-docs/trunk/source/weave.rst 2008-11-14 00:35:03 UTC (rev 5098) +++ scipy-docs/trunk/source/weave.rst 2008-11-14 00:35:43 UTC (rev 5099) @@ -2,5 +2,9 @@ C/C++ integration (:mod:`scipy.weave`) ====================================== +.. warning:: + + This documentation is work-in-progress and unorganized. + .. automodule:: scipy.weave :members: From scipy-svn at scipy.org Thu Nov 13 19:36:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 18:36:45 -0600 (CST) Subject: [Scipy-svn] r5100 - scipy-docs/trunk Message-ID: <20081114003645.50E5339C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 18:36:33 -0600 (Thu, 13 Nov 2008) New Revision: 5100 Modified: scipy-docs/trunk/Makefile Log: Mark targets as phony in makefile Modified: scipy-docs/trunk/Makefile =================================================================== --- scipy-docs/trunk/Makefile 2008-11-14 00:35:43 UTC (rev 5099) +++ scipy-docs/trunk/Makefile 2008-11-14 00:36:33 UTC (rev 5100) @@ -107,3 +107,6 @@ @echo @echo "Link check complete; look for any errors in the above output " \ "or in build/linkcheck/output.txt." + +.PHONY: help clean upload dist generate ext html pickle web htmlhelp latex \ + coverage changes linkcheck From scipy-svn at scipy.org Thu Nov 13 19:37:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 18:37:27 -0600 (CST) Subject: [Scipy-svn] r5101 - in scipy-docs/trunk: . source source/tutorial source/tutorial/examples Message-ID: <20081114003727.A475E39C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 18:36:56 -0600 (Thu, 13 Nov 2008) New Revision: 5101 Modified: scipy-docs/trunk/Makefile scipy-docs/trunk/source/conf.py scipy-docs/trunk/source/spatial.rst scipy-docs/trunk/source/tutorial/examples/10.2.5 scipy-docs/trunk/source/tutorial/examples/6.1 scipy-docs/trunk/source/tutorial/examples/6.2 scipy-docs/trunk/source/tutorial/examples/6.3 scipy-docs/trunk/source/tutorial/examples/6.4 scipy-docs/trunk/source/tutorial/index.rst Log: Fix plots in tutorial: generate all figures from the source code, using matplotlib. Modified: scipy-docs/trunk/Makefile =================================================================== --- scipy-docs/trunk/Makefile 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/Makefile 2008-11-14 00:36:56 UTC (rev 5101) @@ -108,5 +108,5 @@ @echo "Link check complete; look for any errors in the above output " \ "or in build/linkcheck/output.txt." -.PHONY: help clean upload dist generate ext html pickle web htmlhelp latex \ +.PHONY: help clean upload dist generate html pickle web htmlhelp latex \ coverage changes linkcheck Modified: scipy-docs/trunk/source/conf.py =================================================================== --- scipy-docs/trunk/source/conf.py 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/conf.py 2008-11-14 00:36:56 UTC (rev 5101) @@ -69,7 +69,7 @@ # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +show_authors = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' @@ -231,3 +231,11 @@ coverage_ignore_c_items = {} +#------------------------------------------------------------------------------ +# Plot +#------------------------------------------------------------------------------ +plot_pre_code = """ +import numpy +numpy.random.seed(123) +""" +plot_output_dir = '_static/plot_directive' Modified: scipy-docs/trunk/source/spatial.rst =================================================================== --- scipy-docs/trunk/source/spatial.rst 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/spatial.rst 2008-11-14 00:36:56 UTC (rev 5101) @@ -6,5 +6,9 @@ This documentation is work-in-progress and unorganized. +.. toctree:: + + spatial.distance + .. automodule:: scipy.spatial :members: Modified: scipy-docs/trunk/source/tutorial/examples/10.2.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:36:56 UTC (rev 5101) @@ -1,3 +1,7 @@ +from numpy import * +from scipy import linalg +import matplotlib.pyplot as plt + c1,c2= 5.0,2.0 i = r_[1:11] xi = 0.1*i @@ -2,5 +6,5 @@ yi = c1*exp(-xi)+c2*xi -zi = yi + 0.05*max(yi)*randn(len(yi)) +zi = yi + 0.05*max(yi)*random.randn(len(yi)) -A = c_[exp(-xi)[:,NewAxis],xi[:,NewAxis]] +A = c_[exp(-xi)[:,newaxis],xi[:,newaxis]] c,resid,rank,sigma = linalg.lstsq(A,zi) @@ -10,8 +14,8 @@ xi2 = r_[0.1:1.0:100j] yi2 = c[0]*exp(-xi2) + c[1]*xi2 -xplt.plot(xi,zi,'x',xi2,yi2) -xplt.limits(0,1.1,3.0,5.5) -xplt.xlabel('x_i') -xplt.title('Data fitting with linalg.lstsq') -xplt.eps('lstsq_fit') +plt.plot(xi,zi,'x',xi2,yi2) +plt.axis([0,1.1,3.0,5.5]) +plt.xlabel('$x_i$') +plt.title('Data fitting with linalg.lstsq') +plt.show() Modified: scipy-docs/trunk/source/tutorial/examples/6.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:36:56 UTC (rev 5101) @@ -1,18 +1,10 @@ +>>> from numpy import * +>>> from scipy import interpolate + >>> x = arange(0,10) >>> y = exp(-x/3.0) ->>> f = interpolate.linear_1d(x,y) ->>> help(f) -Instance of class: linear_1d +>>> f = interpolate.interp1d(x, y) - (x_new) - -Find linearly interpolated y_new = (x_new). - -Inputs: - x_new -- New independent variables. - -Outputs: - y_new -- Linearly interpolated values corresponding to x_new. - >>> xnew = arange(0,9,0.1) ->>> xplt.plot(x,y,'x',xnew,f(xnew),'.') +>>> import matplotlib.pyplot as plt +>>> plt.plot(x,y,'o',xnew,f(xnew),'-') Modified: scipy-docs/trunk/source/tutorial/examples/6.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:36:56 UTC (rev 5101) @@ -8,16 +8,19 @@ >>> tck = interpolate.splrep(x,y,s=0) >>> xnew = arange(0,2*pi,pi/50) >>> ynew = interpolate.splev(xnew,tck,der=0) + +>>> plt.figure() >>> plt.plot(x,y,'x',xnew,ynew,xnew,sin(xnew),x,y,'b') ->>> #plt.legend(['Linear','Cubic Spline', 'True']) +>>> plt.legend(['Linear','Cubic Spline', 'True']) >>> plt.axis([-0.05,6.33,-1.05,1.05]) >>> plt.title('Cubic-spline interpolation') >>> plt.show() >>> # Derivative of spline >>> yder = interpolate.splev(xnew,tck,der=1) ->>> plt.plot(xnew,yder,xnew,cos(xnew),'|') ->>> #plt.legend(['Cubic Spline', 'True']) +>>> plt.figure() +>>> plt.plot(xnew,yder,xnew,cos(xnew),'--') +>>> plt.legend(['Cubic Spline', 'True']) >>> plt.axis([-0.05,6.33,-1.05,1.05]) >>> plt.title('Derivative estimation from spline') >>> plt.show() @@ -32,8 +35,9 @@ >>> return out >>> >>> yint = integ(xnew,tck) ->>> plt.plot(xnew,yint,xnew,-cos(xnew),'|') ->>> #plt.legend(['Cubic Spline', 'True']) +>>> plt.figure() +>>> plt.plot(xnew,yint,xnew,-cos(xnew),'--') +>>> plt.legend(['Cubic Spline', 'True']) >>> plt.axis([-0.05,6.33,-1.05,1.05]) >>> plt.title('Integral estimation from spline') >>> plt.show() @@ -49,8 +53,9 @@ >>> tck,u = interpolate.splprep([x,y],s=0) >>> unew = arange(0,1.01,0.01) >>> out = interpolate.splev(unew,tck) +>>> plt.figure() >>> plt.plot(x,y,'x',out[0],out[1],sin(2*pi*unew),cos(2*pi*unew),x,y,'b') ->>> #plt.legend(['Linear','Cubic Spline', 'True'],['b-x','m','r']) +>>> plt.legend(['Linear','Cubic Spline', 'True']) >>> plt.axis([-1.05,1.05,-1.05,1.05]) >>> plt.title('Spline of parametrically-defined curve') >>> plt.show() Modified: scipy-docs/trunk/source/tutorial/examples/6.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:36:56 UTC (rev 5101) @@ -1,14 +1,24 @@ +>>> from numpy import * +>>> from scipy import interpolate +>>> import matplotlib.pyplot as plt + >>> # Define function over sparse 20x20 grid >>> x,y = mgrid[-1:1:20j,-1:1:20j] >>> z = (x+y)*exp(-6.0*(x*x+y*y)) ->>> xplt.surf(z,x,y,shade=1,palette='rainbow') ->>> xplt.title3("Sparsely sampled function.") ->>> xplt.eps("2d_func") +>>> plt.figure() +>>> plt.pcolor(x,y,z) +>>> plt.colorbar() +>>> plt.title("Sparsely sampled function.") +>>> plt.show() + >>> # Interpolate function over new 70x70 grid >>> xnew,ynew = mgrid[-1:1:70j,-1:1:70j] >>> tck = interpolate.bisplrep(x,y,z,s=0) >>> znew = interpolate.bisplev(xnew[:,0],ynew[0,:],tck) ->>> xplt.surf(znew,xnew,ynew,shade=1,palette='rainbow') ->>> xplt.title3("Interpolated function.") ->>> xplt.eps("2d_interp") + +>>> plt.figure() +>>> plt.pcolor(xnew,ynew,znew) +>>> plt.colorbar() +>>> plt.title("Interpolated function.") +>>> plt.show() Modified: scipy-docs/trunk/source/tutorial/examples/6.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:36:56 UTC (rev 5101) @@ -1,16 +1,25 @@ ->>> image = lena().astype(Float32) ->>> derfilt = array([1.0,-2,1.0],Float32) +>>> from numpy import * +>>> from scipy import signal, misc +>>> import matplotlib.pyplot as plt + +>>> image = misc.lena().astype(float32) +>>> derfilt = array([1.0,-2,1.0],float32) >>> ck = signal.cspline2d(image,8.0) >>> deriv = signal.sepfir2d(ck, derfilt, [1]) + \ >>> signal.sepfir2d(ck, [1], derfilt) >>> >>> ## Alternatively we could have done: ->>> ## laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],Float32) +>>> ## laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],float32) >>> ## deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm') ->>> ->>> xplt.imagesc(image[::-1]) # flip image so it looks right-side up. ->>> xplt.title('Original image') ->>> xplt.eps('lena_image') ->>> xplt.imagesc(deriv[::-1]) ->>> xplt.title('Output of spline edge filter') ->>> xplt.eps('lena_edge') + +>>> plt.figure() +>>> plt.imshow(image) +>>> plt.gray() +>>> plt.title('Original image') +>>> plt.show() + +>>> plt.figure() +>>> plt.imshow(deriv) +>>> plt.gray() +>>> plt.title('Output of spline edge filter') +>>> plt.show() Modified: scipy-docs/trunk/source/tutorial/index.rst =================================================================== --- scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:36:33 UTC (rev 5100) +++ scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:36:56 UTC (rev 5101) @@ -841,15 +841,15 @@ used to find the best-fit parameters :math:`\hat{A},\,\hat{k},\,\hat{\theta}` . This is shown in the following example and a plot of the results is shown in Figure `1 <#fig-least-squares-fit>`__ . +.. _`fig:least_squares_fit`: + .. plot:: source/tutorial/examples/5.7 :include-source: :doctest-format: :align: center -.. **Figure 1** Least-square fitting to noisy data using -.. :obj:`scipy.optimize.leastsq` -.. -.. .. _`fig:least_squares_fit`: +.. XXX: **Figure 1** Least-square fitting to noisy data using +.. XXX: :obj:`scipy.optimize.leastsq` Scalar function minimizers @@ -963,25 +963,24 @@ create a function based on fixed data points which can be evaluated anywhere within the domain defined by the given data using linear interpolation. An instance of this class is created by passing the 1-d -vectors comprising the data. The instance of this class defines a *__call__* method and can therefore by treated like a function which interpolates -between known data values to obtain unknown values (it even has a -docstring for help). Behavior at the boundary can be specified at -instantiation time. The following example demonstrates it's use. +vectors comprising the data. The instance of this class defines a +*__call__* method and can therefore by treated like a function which +interpolates between known data values to obtain unknown values (it +even has a docstring for help). Behavior at the boundary can be +specified at instantiation time. The following example demonstrates +it's use. +.. _`fig:inter_1d`: -.. literalinclude:: examples/6.1 -Figure shows the result: - -.. figure:: inter_1d.epsi +.. plot:: source/tutorial/examples/6.1 + :doctest-format: + :include-source: :align: center - **Figure 2** One-dimensional interpolation using the class :obj:`interpolate.linear_1d` - - .. _`fig:inter_1d`: +.. **Figure 2** One-dimensional interpolation using the + class :obj:`interpolate.linear_1d` - - Spline interpolation in 1-d (interpolate.splXXX) ------------------------------------------------ @@ -1016,34 +1015,9 @@ .. plot:: source/tutorial/examples/6.2 :include-source: :doctest-format: - - -.. figure:: interp_cubic.epsi :align: center - **Figure 3** .. image: interp_cubic_der.epsi - - - - - .. image: interp_cubic_int.epsi - - - .. image: interp_cubic_param.epsi - - - - Examples of using cubic-spline interpolation. - - .. _`fig:spline-1d`: - - - -.. literalinclude:: examples/6.2 - - - Two-dimensionsal spline representation (interpolate.bisplrep) ------------------------------------------------------------- @@ -1082,29 +1056,18 @@ Figure `4 <#fig-2d-interp>`__ ). This example uses the :obj:`mgrid` command in SciPy which is useful for defining a "mesh-grid "in many dimensions. (See also the :obj:`ogrid` command if the full-mesh is not needed). The number of output arguments and the number of dimensions of each argument is determined by the number of indexing objects passed in :obj:`mgrid`[]. -.. literalinclude:: examples/6.3 +.. _`fig:2d_interp`: - - - - -.. figure:: 2d_func.epsi +.. plot:: source/tutorial/examples/6.3 + :doctest-format: + :include-source: :align: center - **Figure 4** .. image: 2d_interp.epsi - - - - Example of two-dimensional spline interpolation. - - .. _`fig:2d_interp`: +.. XXX: **Figure 4** +.. XXX: Example of two-dimensional spline interpolation. - - - - Signal Processing (signal) ========================== @@ -1221,26 +1184,18 @@ :obj:`signal.convolve2d` which convolves arbitrary two-dimensional filters and allows for choosing mirror-symmetric boundary conditions. +.. _`fig:lena_edge_spline`: -.. literalinclude:: examples/6.4 - - - - -.. figure:: lena_image.epsi +.. plot:: source/tutorial/examples/6.4 + :doctest-format: + :include-source: :align: center - **Figure 5** .. image: lena_edge.epsi - - - - Example of using smoothing splines to filter images. - - .. _`fig:lena_edge_spline`: +.. **Figure 5** +.. .. image: figs/lena_edge.pdf +.. Example of using smoothing splines to filter images. - - Filtering --------- @@ -1250,11 +1205,16 @@ operations. There are two broad kinds of filtering operations: linear and non-linear. Linear filters can always be reduced to multiplication of the flattened Numpy array by an appropriate matrix resulting in -another flattened Numpy array. Of course, this is not usually the -best way to compute the filter as the matrices and vectors involved -may be huge. For example filtering a :math:`512\times512` image with this method would require multiplication of a :math:`512^{2}x512^{2}` matrix with a :math:`512^{2}` vector. Just trying to store the :math:`512^{2}\times512^{2}` matrix using a standard Numpy array would require :math:`68,719,476,736` elements. At 4 bytes per element this would require :math:`256\textrm{GB}` of memory. In most applications most of the elements of this matrix -are zero and a different method for computing the output of the filter -is employed. +another flattened Numpy array. Of course, this is not usually the best +way to compute the filter as the matrices and vectors involved may be +huge. For example filtering a :math:`512\times512` image with this +method would require multiplication of a :math:`512^{2}x512^{2}` +matrix with a :math:`512^{2}` vector. Just trying to store the +:math:`512^{2}\times512^{2}` matrix using a standard Numpy array would +require :math:`68,719,476,736` elements. At 4 bytes per element this +would require :math:`256\textrm{GB}` of memory. In most applications +most of the elements of this matrix are zero and a different method +for computing the output of the filter is employed. Convolution/Correlation @@ -1628,10 +1588,9 @@ \[ \mathbf{A^{-1}=\frac{1}{25}\left[\begin{array}{ccc} -37 & 9 & 22\\ 14 & 2 & -9\\ 4 & -3 & 1\end{array}\right]=\left[\begin{array}{ccc} -1.48 & 0.36 & 0.88\\ 0.56 & 0.08 & -0.36\\ 0.16 & -0.12 & 0.04\end{array}\right].}\] The following example demonstrates this computation in SciPy + .. literalinclude:: examples/10.2.1 - - Solving linear system ^^^^^^^^^^^^^^^^^^^^^ @@ -1657,10 +1616,9 @@ However, it is better to use the linalg.solve command which can be faster and more numerically stable. In this case it gives the same answer as shown in the following example: + .. literalinclude:: examples/10.2.2 - - Finding Determinant ^^^^^^^^^^^^^^^^^^^ @@ -1689,11 +1647,8 @@ In SciPy this is computed as shown in this example: - .. literalinclude:: examples/10.2.3 - - Computing norms ^^^^^^^^^^^^^^^ @@ -1794,13 +1749,11 @@ where :math:`x_{i}=0.1i` for :math:`i=1\ldots10` , :math:`c_{1}=5` , and :math:`c_{2}=4.` Noise is added to :math:`y_{i}` and the coefficients :math:`c_{1}` and :math:`c_{2}` are estimated using linear least squares. +.. plot:: source/tutorial/examples/10.2.5 + :include-source: + :align: center -XXX: Unknown inset Box Frameless -XXX: Unknown inset Box Frameless - - - Generalized inverse ^^^^^^^^^^^^^^^^^^^ @@ -1924,11 +1877,8 @@ the original equation. The eigenvectors associated with these eigenvalues can then be found. - .. literalinclude:: examples/10.3.1 - - Singular value decomposition ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1944,21 +1894,11 @@ is the singular-value decomposition of :math:`\mathbf{A}.` Every matrix has a singular value decomposition. Sometimes, the singular values are called the spectrum of :math:`\mathbf{A}.` The command :obj:`linalg.svd` will return :math:`\mathbf{U}` , :math:`\mathbf{V}^{H}` , and :math:`\sigma_{i}` as an array of the singular values. To obtain the matrix :math:`\mathbf{\Sigma}` use :obj:`linalg.diagsvd`. The following example illustrates the use of :obj:`linalg.svd` . - .. literalinclude:: examples/10.3.2 - - - .. [#] A hermition matrix :math:`\mathbf{D}` satisfies :math:`\mathbf{D}^{H}=\mathbf{D}.` - - - - .. [#] A unitary matrix :math:`\mathbf{D}` satisfies :math:`\mathbf{D}^{H}\mathbf{D}=\mathbf{I}=\mathbf{D}\mathbf{D}^{H}` so that :math:`\mathbf{D}^{-1}=\mathbf{D}^{H}.` - - LU decomposition @@ -2052,11 +1992,8 @@ The following example illustrates the schur decomposition: - .. literalinclude:: examples/10.3.6 - - Matrix Functions ---------------- @@ -2180,10 +2117,8 @@ algorithm. For example the following code computes the zeroth-order Bessel function applied to a matrix. - .. literalinclude:: examples/10.4.4 - Statistics ========== From scipy-svn at scipy.org Thu Nov 13 19:37:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 18:37:58 -0600 (CST) Subject: [Scipy-svn] r5102 - scipy-docs/trunk/source/tutorial Message-ID: <20081114003758.40E3439C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 18:37:38 -0600 (Thu, 13 Nov 2008) New Revision: 5102 Modified: scipy-docs/trunk/source/tutorial/index.rst Log: Fix sectionauthor Modified: scipy-docs/trunk/source/tutorial/index.rst =================================================================== --- scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:36:56 UTC (rev 5101) +++ scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:37:38 UTC (rev 5102) @@ -2,7 +2,7 @@ SciPy Tutorial ############## -.. sectionauthor:: Travis E. Oliphant, Pauli Virtanen +.. sectionauthor:: Travis E. Oliphant .. currentmodule:: scipy From scipy-svn at scipy.org Thu Nov 13 20:02:15 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 19:02:15 -0600 (CST) Subject: [Scipy-svn] r5103 - in scipy-docs/trunk/source/tutorial: . examples Message-ID: <20081114010215.4BE8539C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 18:56:39 -0600 (Thu, 13 Nov 2008) New Revision: 5103 Added: scipy-docs/trunk/source/tutorial/examples/1-1 scipy-docs/trunk/source/tutorial/examples/10-2-1 scipy-docs/trunk/source/tutorial/examples/10-2-2 scipy-docs/trunk/source/tutorial/examples/10-2-3 scipy-docs/trunk/source/tutorial/examples/10-2-5 scipy-docs/trunk/source/tutorial/examples/10-3-1 scipy-docs/trunk/source/tutorial/examples/10-3-2 scipy-docs/trunk/source/tutorial/examples/10-3-6 scipy-docs/trunk/source/tutorial/examples/10-4-4 scipy-docs/trunk/source/tutorial/examples/2-1 scipy-docs/trunk/source/tutorial/examples/2-2 scipy-docs/trunk/source/tutorial/examples/2-3 scipy-docs/trunk/source/tutorial/examples/3-1 scipy-docs/trunk/source/tutorial/examples/3-2 scipy-docs/trunk/source/tutorial/examples/4-1 scipy-docs/trunk/source/tutorial/examples/4-2 scipy-docs/trunk/source/tutorial/examples/4-3 scipy-docs/trunk/source/tutorial/examples/4-4 scipy-docs/trunk/source/tutorial/examples/4-5 scipy-docs/trunk/source/tutorial/examples/4-6 scipy-docs/trunk/source/tutorial/examples/5-1 scipy-docs/trunk/source/tutorial/examples/5-2 scipy-docs/trunk/source/tutorial/examples/5-3 scipy-docs/trunk/source/tutorial/examples/5-4 scipy-docs/trunk/source/tutorial/examples/5-5 scipy-docs/trunk/source/tutorial/examples/5-6 scipy-docs/trunk/source/tutorial/examples/5-7 scipy-docs/trunk/source/tutorial/examples/5-8 scipy-docs/trunk/source/tutorial/examples/5-9 scipy-docs/trunk/source/tutorial/examples/6-1 scipy-docs/trunk/source/tutorial/examples/6-2 scipy-docs/trunk/source/tutorial/examples/6-3 scipy-docs/trunk/source/tutorial/examples/6-4 Removed: scipy-docs/trunk/source/tutorial/examples/1.1 scipy-docs/trunk/source/tutorial/examples/10.2.1 scipy-docs/trunk/source/tutorial/examples/10.2.2 scipy-docs/trunk/source/tutorial/examples/10.2.3 scipy-docs/trunk/source/tutorial/examples/10.2.5 scipy-docs/trunk/source/tutorial/examples/10.3.1 scipy-docs/trunk/source/tutorial/examples/10.3.2 scipy-docs/trunk/source/tutorial/examples/10.3.6 scipy-docs/trunk/source/tutorial/examples/10.4.4 scipy-docs/trunk/source/tutorial/examples/2.1 scipy-docs/trunk/source/tutorial/examples/2.2 scipy-docs/trunk/source/tutorial/examples/2.3 scipy-docs/trunk/source/tutorial/examples/3.1 scipy-docs/trunk/source/tutorial/examples/3.2 scipy-docs/trunk/source/tutorial/examples/4.1 scipy-docs/trunk/source/tutorial/examples/4.2 scipy-docs/trunk/source/tutorial/examples/4.3 scipy-docs/trunk/source/tutorial/examples/4.4 scipy-docs/trunk/source/tutorial/examples/4.5 scipy-docs/trunk/source/tutorial/examples/4.6 scipy-docs/trunk/source/tutorial/examples/5.1 scipy-docs/trunk/source/tutorial/examples/5.2 scipy-docs/trunk/source/tutorial/examples/5.3 scipy-docs/trunk/source/tutorial/examples/5.4 scipy-docs/trunk/source/tutorial/examples/5.5 scipy-docs/trunk/source/tutorial/examples/5.6 scipy-docs/trunk/source/tutorial/examples/5.7 scipy-docs/trunk/source/tutorial/examples/5.8 scipy-docs/trunk/source/tutorial/examples/5.9 scipy-docs/trunk/source/tutorial/examples/6.1 scipy-docs/trunk/source/tutorial/examples/6.2 scipy-docs/trunk/source/tutorial/examples/6.3 scipy-docs/trunk/source/tutorial/examples/6.4 Modified: scipy-docs/trunk/source/tutorial/index.rst Log: docs: Rename files so that the generated images get names that Latex approves of Copied: scipy-docs/trunk/source/tutorial/examples/1-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/1.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/1.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/1-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,37 @@ +>>> info(optimize.fmin) + fmin(func, x0, args=(), xtol=0.0001, ftol=0.0001, maxiter=None, maxfun=None, + full_output=0, printmessg=1) + +Minimize a function using the simplex algorithm. + +Description: + + Uses a Nelder-Mead simplex algorithm to find the minimum of function + of one or more variables. + +Inputs: + + func -- the Python function or method to be minimized. + x0 -- the initial guess. + args -- extra arguments for func. + xtol -- relative tolerance + +Outputs: (xopt, {fopt, warnflag}) + + xopt -- minimizer of function + + fopt -- value of function at minimum: fopt = func(xopt) + warnflag -- Integer warning flag: + 1 : 'Maximum number of function evaluations.' + 2 : 'Maximum number of iterations.' + +Additional Inputs: + + xtol -- acceptable relative error in xopt for convergence. + ftol -- acceptable relative error in func(xopt) for convergence. + maxiter -- the maximum number of iterations to perform. + maxfun -- the maximum number of function evaluations. + full_output -- non-zero if fval and warnflag outputs are desired. + printmessg -- non-zero to print convergence messages. + + Deleted: scipy-docs/trunk/source/tutorial/examples/1.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/1.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/1.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,37 +0,0 @@ ->>> info(optimize.fmin) - fmin(func, x0, args=(), xtol=0.0001, ftol=0.0001, maxiter=None, maxfun=None, - full_output=0, printmessg=1) - -Minimize a function using the simplex algorithm. - -Description: - - Uses a Nelder-Mead simplex algorithm to find the minimum of function - of one or more variables. - -Inputs: - - func -- the Python function or method to be minimized. - x0 -- the initial guess. - args -- extra arguments for func. - xtol -- relative tolerance - -Outputs: (xopt, {fopt, warnflag}) - - xopt -- minimizer of function - - fopt -- value of function at minimum: fopt = func(xopt) - warnflag -- Integer warning flag: - 1 : 'Maximum number of function evaluations.' - 2 : 'Maximum number of iterations.' - -Additional Inputs: - - xtol -- acceptable relative error in xopt for convergence. - ftol -- acceptable relative error in func(xopt) for convergence. - maxiter -- the maximum number of iterations to perform. - maxfun -- the maximum number of function evaluations. - full_output -- non-zero if fval and warnflag outputs are desired. - printmessg -- non-zero to print convergence messages. - - Copied: scipy-docs/trunk/source/tutorial/examples/10-2-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.2.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-2-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,13 @@ +>>> A = mat('[1 3 5; 2 5 1; 2 3 8]') +>>> A +Matrix([[1, 3, 5], + [2, 5, 1], + [2, 3, 8]]) +>>> A.I +Matrix([[-1.48, 0.36, 0.88], + [ 0.56, 0.08, -0.36], + [ 0.16, -0.12, 0.04]]) +>>> linalg.inv(A) +array([[-1.48, 0.36, 0.88], + [ 0.56, 0.08, -0.36], + [ 0.16, -0.12, 0.04]]) Copied: scipy-docs/trunk/source/tutorial/examples/10-2-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.2.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-2-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,10 @@ +>>> A = mat('[1 3 5; 2 5 1; 2 3 8]') +>>> b = mat('[10;8;3]') +>>> A.I*b +Matrix([[-9.28], + [ 5.16], + [ 0.76]]) +>>> linalg.solve(A,b) +array([[-9.28], + [ 5.16], + [ 0.76]]) Copied: scipy-docs/trunk/source/tutorial/examples/10-2-3 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.2.3) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-2-3 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,4 @@ +>>> A = mat('[1 3 5; 2 5 1; 2 3 8]') +>>> linalg.det(A) +-25.000000000000004 + Copied: scipy-docs/trunk/source/tutorial/examples/10-2-5 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.2.5) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-2-5 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,21 @@ +from numpy import * +from scipy import linalg +import matplotlib.pyplot as plt + +c1,c2= 5.0,2.0 +i = r_[1:11] +xi = 0.1*i +yi = c1*exp(-xi)+c2*xi +zi = yi + 0.05*max(yi)*random.randn(len(yi)) + +A = c_[exp(-xi)[:,newaxis],xi[:,newaxis]] +c,resid,rank,sigma = linalg.lstsq(A,zi) + +xi2 = r_[0.1:1.0:100j] +yi2 = c[0]*exp(-xi2) + c[1]*xi2 + +plt.plot(xi,zi,'x',xi2,yi2) +plt.axis([0,1.1,3.0,5.5]) +plt.xlabel('$x_i$') +plt.title('Data fitting with linalg.lstsq') +plt.show() Copied: scipy-docs/trunk/source/tutorial/examples/10-3-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.3.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-3-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,18 @@ +>>> A = mat('[1 5 2; 2 4 1; 3 6 2]') +>>> la,v = linalg.eig(A) +>>> l1,l2,l3 = la +>>> print l1, l2, l3 +(7.95791620491+0j) (-1.25766470568+0j) (0.299748500767+0j) + +>>> print v[:,0] +array([-0.5297, -0.4494, -0.7193]) +>>> print v[:,1] +[-0.9073 0.2866 0.3076] +>>> print v[:,2] +[ 0.2838 -0.3901 0.8759] +>>> print sum(abs(v**2),axis=0) +[ 1. 1. 1.] + +>>> v1 = mat(v[:,0]).T +>>> print max(ravel(abs(A*v1-l1*v1))) +4.4408920985e-16 Copied: scipy-docs/trunk/source/tutorial/examples/10-3-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.3.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-3-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,22 @@ +>>> A = mat('[1 3 2; 1 2 3]') +>>> M,N = A.shape +>>> U,s,Vh = linalg.svd(A) +>>> Sig = mat(diagsvd(s,M,N)) +>>> U, Vh = mat(U), mat(Vh) +>>> print U +Matrix([[-0.7071, -0.7071], + [-0.7071, 0.7071]]) +>>> print Sig +Matrix([[ 5.1962, 0. , 0. ], + [ 0. , 1. , 0. ]]) +>>> print Vh +Matrix([[-0.2722, -0.6804, -0.6804], + [-0. , -0.7071, 0.7071], + [-0.9623, 0.1925, 0.1925]]) + +>>> print A +Matrix([[1, 3, 2], + [1, 2, 3]]) +>>> print U*Sig*Vh +Matrix([[ 1., 3., 2.], + [ 1., 2., 3.]]) Copied: scipy-docs/trunk/source/tutorial/examples/10-3-6 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.3.6) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.6 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-3-6 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,36 @@ +>>> A = mat('[1 3 2; 1 4 5; 2 3 6]') +>>> T,Z = linalg.schur(A) +>>> T1,Z1 = linalg.schur(A,'complex') +>>> T2,Z2 = linalg.rsf2csf(T,Z) +>>> print T +Matrix([[ 9.9001, 1.7895, -0.655 ], + [ 0. , 0.5499, -1.5775], + [ 0. , 0.5126, 0.5499]]) +>>> print T2 +Matrix([[ 9.9001+0.j , -0.3244+1.5546j, -0.8862+0.569j ], + [ 0. +0.j , 0.5499+0.8993j, 1.0649-0.j ], + [ 0. +0.j , 0. +0.j , 0.5499-0.8993j]]) +>>> print abs(T1-T2) # different +[[ 0. 2.1184 0.1949] + [ 0. 0. 1.2676] + [ 0. 0. 0. ]] +>>> print abs(Z1-Z2) # different +[[ 0.0683 1.1175 0.1973] + [ 0.1186 0.5644 0.247 ] + [ 0.1262 0.7645 0.1916]] +>>> T,Z,T1,Z1,T2,Z2 = map(mat,(T,Z,T1,Z1,T2,Z2)) +>>> print abs(A-Z*T*Z.H) +Matrix([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +>>> print abs(A-Z1*T1*Z1.H) +Matrix([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) +>>> print abs(A-Z2*T2*Z2.H) +Matrix([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + + + Copied: scipy-docs/trunk/source/tutorial/examples/10-4-4 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/10.4.4) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.4.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10-4-4 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,10 @@ +>>> A = rand(3,3) +>>> B = linalg.funm(A,lambda x: special.jv(0,real(x))) +>>> print A +[[ 0.0593 0.5612 0.4403] + [ 0.8797 0.2556 0.1452] + [ 0.964 0.9666 0.1243]] +>>> print B +[[ 0.8206 -0.1212 -0.0612] + [-0.1323 0.8256 -0.0627] + [-0.2073 -0.1946 0.8516]] Deleted: scipy-docs/trunk/source/tutorial/examples/10.2.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.2.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,13 +0,0 @@ ->>> A = mat('[1 3 5; 2 5 1; 2 3 8]') ->>> A -Matrix([[1, 3, 5], - [2, 5, 1], - [2, 3, 8]]) ->>> A.I -Matrix([[-1.48, 0.36, 0.88], - [ 0.56, 0.08, -0.36], - [ 0.16, -0.12, 0.04]]) ->>> linalg.inv(A) -array([[-1.48, 0.36, 0.88], - [ 0.56, 0.08, -0.36], - [ 0.16, -0.12, 0.04]]) Deleted: scipy-docs/trunk/source/tutorial/examples/10.2.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.2.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,10 +0,0 @@ ->>> A = mat('[1 3 5; 2 5 1; 2 3 8]') ->>> b = mat('[10;8;3]') ->>> A.I*b -Matrix([[-9.28], - [ 5.16], - [ 0.76]]) ->>> linalg.solve(A,b) -array([[-9.28], - [ 5.16], - [ 0.76]]) Deleted: scipy-docs/trunk/source/tutorial/examples/10.2.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.2.3 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,4 +0,0 @@ ->>> A = mat('[1 3 5; 2 5 1; 2 3 8]') ->>> linalg.det(A) --25.000000000000004 - Deleted: scipy-docs/trunk/source/tutorial/examples/10.2.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.2.5 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,21 +0,0 @@ -from numpy import * -from scipy import linalg -import matplotlib.pyplot as plt - -c1,c2= 5.0,2.0 -i = r_[1:11] -xi = 0.1*i -yi = c1*exp(-xi)+c2*xi -zi = yi + 0.05*max(yi)*random.randn(len(yi)) - -A = c_[exp(-xi)[:,newaxis],xi[:,newaxis]] -c,resid,rank,sigma = linalg.lstsq(A,zi) - -xi2 = r_[0.1:1.0:100j] -yi2 = c[0]*exp(-xi2) + c[1]*xi2 - -plt.plot(xi,zi,'x',xi2,yi2) -plt.axis([0,1.1,3.0,5.5]) -plt.xlabel('$x_i$') -plt.title('Data fitting with linalg.lstsq') -plt.show() Deleted: scipy-docs/trunk/source/tutorial/examples/10.3.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.3.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,18 +0,0 @@ ->>> A = mat('[1 5 2; 2 4 1; 3 6 2]') ->>> la,v = linalg.eig(A) ->>> l1,l2,l3 = la ->>> print l1, l2, l3 -(7.95791620491+0j) (-1.25766470568+0j) (0.299748500767+0j) - ->>> print v[:,0] -array([-0.5297, -0.4494, -0.7193]) ->>> print v[:,1] -[-0.9073 0.2866 0.3076] ->>> print v[:,2] -[ 0.2838 -0.3901 0.8759] ->>> print sum(abs(v**2),axis=0) -[ 1. 1. 1.] - ->>> v1 = mat(v[:,0]).T ->>> print max(ravel(abs(A*v1-l1*v1))) -4.4408920985e-16 Deleted: scipy-docs/trunk/source/tutorial/examples/10.3.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.3.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,22 +0,0 @@ ->>> A = mat('[1 3 2; 1 2 3]') ->>> M,N = A.shape ->>> U,s,Vh = linalg.svd(A) ->>> Sig = mat(diagsvd(s,M,N)) ->>> U, Vh = mat(U), mat(Vh) ->>> print U -Matrix([[-0.7071, -0.7071], - [-0.7071, 0.7071]]) ->>> print Sig -Matrix([[ 5.1962, 0. , 0. ], - [ 0. , 1. , 0. ]]) ->>> print Vh -Matrix([[-0.2722, -0.6804, -0.6804], - [-0. , -0.7071, 0.7071], - [-0.9623, 0.1925, 0.1925]]) - ->>> print A -Matrix([[1, 3, 2], - [1, 2, 3]]) ->>> print U*Sig*Vh -Matrix([[ 1., 3., 2.], - [ 1., 2., 3.]]) Deleted: scipy-docs/trunk/source/tutorial/examples/10.3.6 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.3.6 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.3.6 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,36 +0,0 @@ ->>> A = mat('[1 3 2; 1 4 5; 2 3 6]') ->>> T,Z = linalg.schur(A) ->>> T1,Z1 = linalg.schur(A,'complex') ->>> T2,Z2 = linalg.rsf2csf(T,Z) ->>> print T -Matrix([[ 9.9001, 1.7895, -0.655 ], - [ 0. , 0.5499, -1.5775], - [ 0. , 0.5126, 0.5499]]) ->>> print T2 -Matrix([[ 9.9001+0.j , -0.3244+1.5546j, -0.8862+0.569j ], - [ 0. +0.j , 0.5499+0.8993j, 1.0649-0.j ], - [ 0. +0.j , 0. +0.j , 0.5499-0.8993j]]) ->>> print abs(T1-T2) # different -[[ 0. 2.1184 0.1949] - [ 0. 0. 1.2676] - [ 0. 0. 0. ]] ->>> print abs(Z1-Z2) # different -[[ 0.0683 1.1175 0.1973] - [ 0.1186 0.5644 0.247 ] - [ 0.1262 0.7645 0.1916]] ->>> T,Z,T1,Z1,T2,Z2 = map(mat,(T,Z,T1,Z1,T2,Z2)) ->>> print abs(A-Z*T*Z.H) -Matrix([[ 0., 0., 0.], - [ 0., 0., 0.], - [ 0., 0., 0.]]) ->>> print abs(A-Z1*T1*Z1.H) -Matrix([[ 0., 0., 0.], - [ 0., 0., 0.], - [ 0., 0., 0.]]) ->>> print abs(A-Z2*T2*Z2.H) -Matrix([[ 0., 0., 0.], - [ 0., 0., 0.], - [ 0., 0., 0.]]) - - - Deleted: scipy-docs/trunk/source/tutorial/examples/10.4.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/10.4.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/10.4.4 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,10 +0,0 @@ ->>> A = rand(3,3) ->>> B = linalg.funm(A,lambda x: special.jv(0,real(x))) ->>> print A -[[ 0.0593 0.5612 0.4403] - [ 0.8797 0.2556 0.1452] - [ 0.964 0.9666 0.1243]] ->>> print B -[[ 0.8206 -0.1212 -0.0612] - [-0.1323 0.8256 -0.0627] - [-0.2073 -0.1946 0.8516]] Copied: scipy-docs/trunk/source/tutorial/examples/2-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/2.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/2-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,20 @@ +>>> mgrid[0:5,0:5] +array([[[0, 0, 0, 0, 0], + [1, 1, 1, 1, 1], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 3], + [4, 4, 4, 4, 4]], + [[0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4], + [0, 1, 2, 3, 4]]]) +>>> mgrid[0:5:4j,0:5:4j] +array([[[ 0. , 0. , 0. , 0. ], + [ 1.6667, 1.6667, 1.6667, 1.6667], + [ 3.3333, 3.3333, 3.3333, 3.3333], + [ 5. , 5. , 5. , 5. ]], + [[ 0. , 1.6667, 3.3333, 5. ], + [ 0. , 1.6667, 3.3333, 5. ], + [ 0. , 1.6667, 3.3333, 5. ], + [ 0. , 1.6667, 3.3333, 5. ]]]) Copied: scipy-docs/trunk/source/tutorial/examples/2-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/2.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/2-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,14 @@ +>>> p = poly1d([3,4,5]) +>>> print p + 2 +3 x + 4 x + 5 +>>> print p*p + 4 3 2 +9 x + 24 x + 46 x + 40 x + 25 +>>> print p.integ(k=6) + 3 2 +x + 2 x + 5 x + 6 +>>> print p.deriv() +6 x + 4 +>>> p([4,5]) +array([ 69, 100]) \ No newline at end of file Copied: scipy-docs/trunk/source/tutorial/examples/2-3 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/2.3) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/2-3 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,6 @@ +>>> x = r_[-2:3] +>>> x +array([-2, -1, 0, 1, 2]) +>>> select([x > 3, x >= 0],[0,x+2]) +array([0, 0, 2, 3, 4]) + Deleted: scipy-docs/trunk/source/tutorial/examples/2.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/2.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,20 +0,0 @@ ->>> mgrid[0:5,0:5] -array([[[0, 0, 0, 0, 0], - [1, 1, 1, 1, 1], - [2, 2, 2, 2, 2], - [3, 3, 3, 3, 3], - [4, 4, 4, 4, 4]], - [[0, 1, 2, 3, 4], - [0, 1, 2, 3, 4], - [0, 1, 2, 3, 4], - [0, 1, 2, 3, 4], - [0, 1, 2, 3, 4]]]) ->>> mgrid[0:5:4j,0:5:4j] -array([[[ 0. , 0. , 0. , 0. ], - [ 1.6667, 1.6667, 1.6667, 1.6667], - [ 3.3333, 3.3333, 3.3333, 3.3333], - [ 5. , 5. , 5. , 5. ]], - [[ 0. , 1.6667, 3.3333, 5. ], - [ 0. , 1.6667, 3.3333, 5. ], - [ 0. , 1.6667, 3.3333, 5. ], - [ 0. , 1.6667, 3.3333, 5. ]]]) Deleted: scipy-docs/trunk/source/tutorial/examples/2.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/2.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,14 +0,0 @@ ->>> p = poly1d([3,4,5]) ->>> print p - 2 -3 x + 4 x + 5 ->>> print p*p - 4 3 2 -9 x + 24 x + 46 x + 40 x + 25 ->>> print p.integ(k=6) - 3 2 -x + 2 x + 5 x + 6 ->>> print p.deriv() -6 x + 4 ->>> p([4,5]) -array([ 69, 100]) \ No newline at end of file Deleted: scipy-docs/trunk/source/tutorial/examples/2.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/2.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/2.3 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,6 +0,0 @@ ->>> x = r_[-2:3] ->>> x -array([-2, -1, 0, 1, 2]) ->>> select([x > 3, x >= 0],[0,x+2]) -array([0, 0, 2, 3, 4]) - Copied: scipy-docs/trunk/source/tutorial/examples/3-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/3.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/3.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/3-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,5 @@ +>>> def addsubtract(a,b): + if a > b: + return a - b + else: + return a + b Copied: scipy-docs/trunk/source/tutorial/examples/3-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/3.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/3.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/3-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,2 @@ +>>> vec_addsubtract([0,3,6,9],[1,3,5,7]) +array([1, 6, 1, 2]) Deleted: scipy-docs/trunk/source/tutorial/examples/3.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/3.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/3.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,5 +0,0 @@ ->>> def addsubtract(a,b): - if a > b: - return a - b - else: - return a + b Deleted: scipy-docs/trunk/source/tutorial/examples/3.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/3.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/3.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,2 +0,0 @@ ->>> vec_addsubtract([0,3,6,9],[1,3,5,7]) -array([1, 6, 1, 2]) Copied: scipy-docs/trunk/source/tutorial/examples/4-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/4.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,13 @@ +>>> help(integrate) +Methods for Integrating Functions + + odeint -- Integrate ordinary differential equations. + quad -- General purpose integration. + dblquad -- General purpose double integration. + tplquad -- General purpose triple integration. + gauss_quad -- Integrate func(x) using Gaussian quadrature of order n. + gauss_quadtol -- Integrate with given tolerance using Gaussian quadrature. + + See the orthogonal module (integrate.orthogonal) for Gaussian + quadrature roots and weights. + Copied: scipy-docs/trunk/source/tutorial/examples/4-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/4.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,11 @@ +>>> result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5) +>>> print result +(1.1178179380783249, 7.8663172481899801e-09) + +>>> I = sqrt(2/pi)*(18.0/27*sqrt(2)*cos(4.5)-4.0/27*sqrt(2)*sin(4.5)+ + sqrt(2*pi)*special.fresnl(3/sqrt(pi))[0]) +>>> print I +1.117817938088701 + +>>> print abs(result[0]-I) +1.03761443881e-11 Copied: scipy-docs/trunk/source/tutorial/examples/4-3 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/4.3) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4-3 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,13 @@ +>>> from integrate import quad, Inf +>>> def integrand(t,n,x): + return exp(-x*t) / t**n + +>>> def expint(n,x): + return quad(integrand, 1, Inf, args=(n, x))[0] + +>>> vec_expint = vectorize(expint) + +>>> vec_expint(3,arange(1.0,4.0,0.5)) +array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) +>>> special.expn(3,arange(1.0,4.0,0.5)) +array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) Copied: scipy-docs/trunk/source/tutorial/examples/4-4 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/4.4) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4-4 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,10 @@ +>>> result = quad(lambda x: expint(3, x), 0, Inf) +>>> print result +(0.33333333324560266, 2.8548934485373678e-09) + +>>> I3 = 1.0/3.0 +>>> print I3 +0.333333333333 + +>>> print I3 - result[0] +8.77306560731e-11 Copied: scipy-docs/trunk/source/tutorial/examples/4-5 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/4.5) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.5 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4-5 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,11 @@ +>>> from __future__ import nested_scopes +>>> from integrate import quad, dblquad, Inf +>>> def I(n): + return dblquad(lambda t, x: exp(-x*t)/t**n, 0, Inf, lambda x: 1, lambda x: Inf) + +>>> print I(4) +(0.25000000000435768, 1.0518245707751597e-09) +>>> print I(3) +(0.33333333325010883, 2.8604069919261191e-09) +>>> print I(2) +(0.49999999999857514, 1.8855523253868967e-09) Copied: scipy-docs/trunk/source/tutorial/examples/4-6 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/4.6) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.6 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4-6 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,27 @@ +>>> from integrate import odeint +>>> from special import gamma, airy +>>> y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0) +>>> y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0) +>>> y0 = [y0_0, y1_0] +>>> def func(y, t): + return [t*y[1],y[0]] + +>>> def gradient(y,t): + return [[0,t],[1,0]] + +>>> x = arange(0,4.0, 0.01) +>>> t = x +>>> ychk = airy(x)[0] +>>> y = odeint(func, y0, t) +>>> y2 = odeint(func, y0, t, Dfun=gradient) + +>>> import sys +>>> sys.float_output_precision = 6 +>>> print ychk[:36:6] +[ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806] + +>>> print y[:36:6,1] +[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] + +>>> print y2[:36:6,1] +[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] Deleted: scipy-docs/trunk/source/tutorial/examples/4.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,13 +0,0 @@ ->>> help(integrate) -Methods for Integrating Functions - - odeint -- Integrate ordinary differential equations. - quad -- General purpose integration. - dblquad -- General purpose double integration. - tplquad -- General purpose triple integration. - gauss_quad -- Integrate func(x) using Gaussian quadrature of order n. - gauss_quadtol -- Integrate with given tolerance using Gaussian quadrature. - - See the orthogonal module (integrate.orthogonal) for Gaussian - quadrature roots and weights. - Deleted: scipy-docs/trunk/source/tutorial/examples/4.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,11 +0,0 @@ ->>> result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5) ->>> print result -(1.1178179380783249, 7.8663172481899801e-09) - ->>> I = sqrt(2/pi)*(18.0/27*sqrt(2)*cos(4.5)-4.0/27*sqrt(2)*sin(4.5)+ - sqrt(2*pi)*special.fresnl(3/sqrt(pi))[0]) ->>> print I -1.117817938088701 - ->>> print abs(result[0]-I) -1.03761443881e-11 Deleted: scipy-docs/trunk/source/tutorial/examples/4.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4.3 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,13 +0,0 @@ ->>> from integrate import quad, Inf ->>> def integrand(t,n,x): - return exp(-x*t) / t**n - ->>> def expint(n,x): - return quad(integrand, 1, Inf, args=(n, x))[0] - ->>> vec_expint = vectorize(expint) - ->>> vec_expint(3,arange(1.0,4.0,0.5)) -array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) ->>> special.expn(3,arange(1.0,4.0,0.5)) -array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) Deleted: scipy-docs/trunk/source/tutorial/examples/4.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4.4 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,10 +0,0 @@ ->>> result = quad(lambda x: expint(3, x), 0, Inf) ->>> print result -(0.33333333324560266, 2.8548934485373678e-09) - ->>> I3 = 1.0/3.0 ->>> print I3 -0.333333333333 - ->>> print I3 - result[0] -8.77306560731e-11 Deleted: scipy-docs/trunk/source/tutorial/examples/4.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.5 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4.5 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,11 +0,0 @@ ->>> from __future__ import nested_scopes ->>> from integrate import quad, dblquad, Inf ->>> def I(n): - return dblquad(lambda t, x: exp(-x*t)/t**n, 0, Inf, lambda x: 1, lambda x: Inf) - ->>> print I(4) -(0.25000000000435768, 1.0518245707751597e-09) ->>> print I(3) -(0.33333333325010883, 2.8604069919261191e-09) ->>> print I(2) -(0.49999999999857514, 1.8855523253868967e-09) Deleted: scipy-docs/trunk/source/tutorial/examples/4.6 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/4.6 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/4.6 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,27 +0,0 @@ ->>> from integrate import odeint ->>> from special import gamma, airy ->>> y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0) ->>> y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0) ->>> y0 = [y0_0, y1_0] ->>> def func(y, t): - return [t*y[1],y[0]] - ->>> def gradient(y,t): - return [[0,t],[1,0]] - ->>> x = arange(0,4.0, 0.01) ->>> t = x ->>> ychk = airy(x)[0] ->>> y = odeint(func, y0, t) ->>> y2 = odeint(func, y0, t, Dfun=gradient) - ->>> import sys ->>> sys.float_output_precision = 6 ->>> print ychk[:36:6] -[ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806] - ->>> print y[:36:6,1] -[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] - ->>> print y2[:36:6,1] -[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806] Copied: scipy-docs/trunk/source/tutorial/examples/5-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,37 @@ +>>> info(optimize) + Optimization Tools + +A collection of general-purpose optimization routines. + + fmin -- Nelder-Mead Simplex algorithm + (uses only function calls) + fmin_powell -- Powell's (modified) level set method (uses only + function calls) + fmin_bfgs -- Quasi-Newton method (can use function and gradient) + fmin_ncg -- Line-search Newton Conjugate Gradient (can use + function, gradient and hessian). + leastsq -- Minimize the sum of squares of M equations in + N unknowns given a starting estimate. + + Scalar function minimizers + + fminbound -- Bounded minimization of a scalar function. + brent -- 1-D function minimization using Brent method. + golden -- 1-D function minimization using Golden Section method + bracket -- Bracket a minimum (given two starting points) + +Also a collection of general_purpose root-finding routines. + + fsolve -- Non-linear multi-variable equation solver. + + Scalar function solvers + + brentq -- quadratic interpolation Brent method + brenth -- Brent method (modified by Harris with + hyperbolic extrapolation) + ridder -- Ridder's method + bisect -- Bisection method + newton -- Secant method or Newton's method + + fixed_point -- Single-variable fixed-point solver. + Copied: scipy-docs/trunk/source/tutorial/examples/5-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,13 @@ +>>> from scipy.optimize import fmin +>>> def rosen(x): # The Rosenbrock function + return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin(rosen, x0) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 516 + Function evaluations: 825 + +>>> print xopt +[ 1. 1. 1. 1. 1.] Copied: scipy-docs/trunk/source/tutorial/examples/5-3 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.3) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-3 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,10 @@ +>>> def rosen_der(x): + xm = x[1:-1] + xm_m1 = x[:-2] + xm_p1 = x[2:] + der = zeros(x.shape,x.typecode()) + der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm) + der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0]) + der[-1] = 200*(x[-1]-x[-2]**2) + return der + Copied: scipy-docs/trunk/source/tutorial/examples/5-4 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.4) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-4 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,11 @@ +>>> from scipy.optimize import fmin_bfgs + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin_bfgs(rosen, x0, fprime=rosen_der) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 109 + Function evaluations: 262 + Gradient evaluations: 110 +>>> print xopt +[ 1. 1. 1. 1. 1.] Copied: scipy-docs/trunk/source/tutorial/examples/5-5 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.5) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.5 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-5 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,21 @@ +>>> from scipy.optimize import fmin_ncg +>>> def rosen_hess(x): + x = asarray(x) + H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1) + diagonal = zeros(len(x),x.typecode()) + diagonal[0] = 1200*x[0]-400*x[1]+2 + diagonal[-1] = 200 + diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:] + H = H + diag(diagonal) + return H + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess=rosen_hess) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 19 + Function evaluations: 40 + Gradient evaluations: 19 + Hessian evaluations: 19 +>>> print xopt +[ 0.9999 0.9999 0.9998 0.9996 0.9991] Copied: scipy-docs/trunk/source/tutorial/examples/5-6 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.6) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.6 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-6 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,20 @@ +>>> from scipy.optimize import fmin_ncg +>>> def rosen_hess_p(x,p): + x = asarray(x) + Hp = zeros(len(x),x.typecode()) + Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1] + Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \ + -400*x[1:-1]*p[2:] + Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1] + return Hp + +>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] +>>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess_p=rosen_hess_p) +Optimization terminated successfully. + Current function value: 0.000000 + Iterations: 20 + Function evaluations: 42 + Gradient evaluations: 20 + Hessian evaluations: 44 +>>> print xopt +[ 1. 1. 1. 0.9999 0.9999] Copied: scipy-docs/trunk/source/tutorial/examples/5-7 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.7) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.7 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-7 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,31 @@ +>>> from numpy import * +>>> x = arange(0,6e-2,6e-2/30) +>>> A,k,theta = 10, 1.0/3e-2, pi/6 +>>> y_true = A*sin(2*pi*k*x+theta) +>>> y_meas = y_true + 2*random.randn(len(x)) + +>>> def residuals(p, y, x): +... A,k,theta = p +... err = y-A*sin(2*pi*k*x+theta) +... return err + +>>> def peval(x, p): +... return p[0]*sin(2*pi*p[1]*x+p[2]) + +>>> p0 = [8, 1/2.3e-2, pi/3] +>>> print array(p0) +[ 8. 43.4783 1.0472] + +>>> from scipy.optimize import leastsq +>>> plsq = leastsq(residuals, p0, args=(y_meas, x)) +>>> print plsq[0] +[ 10.9437 33.3605 0.5834] + +>>> print array([A, k, theta]) +[ 10. 33.3333 0.5236] + +>>> import matplotlib.pyplot as plt +>>> plt.plot(x,peval(x,plsq[0]),x,y_meas,'o',x,y_true) +>>> plt.title('Least-squares fit to noisy data') +>>> plt.legend(['Fit', 'Noisy', 'True']) +>>> plt.show() Copied: scipy-docs/trunk/source/tutorial/examples/5-8 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.8) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.8 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-8 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,7 @@ +>>> from scipy.special import j1 + +>>> from scipy.optimize import fminbound +>>> xmin = fminbound(j1, 4, 7) +>>> print xmin +5.33144184241 + Copied: scipy-docs/trunk/source/tutorial/examples/5-9 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/5.9) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.9 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5-9 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,16 @@ +>>> def func(x): + return x + 2*cos(x) + +>>> def func2(x): + out = [x[0]*cos(x[1]) - 4] + out.append(x[1]*x[0] - x[1] - 5) + return out + +>>> from optimize import fsolve +>>> x0 = fsolve(func, 0.3) +>>> print x0 +-1.02986652932 + +>>> x02 = fsolve(func2, [1, 1]) +>>> print x02 +[ 6.5041 0.9084] Deleted: scipy-docs/trunk/source/tutorial/examples/5.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,37 +0,0 @@ ->>> info(optimize) - Optimization Tools - -A collection of general-purpose optimization routines. - - fmin -- Nelder-Mead Simplex algorithm - (uses only function calls) - fmin_powell -- Powell's (modified) level set method (uses only - function calls) - fmin_bfgs -- Quasi-Newton method (can use function and gradient) - fmin_ncg -- Line-search Newton Conjugate Gradient (can use - function, gradient and hessian). - leastsq -- Minimize the sum of squares of M equations in - N unknowns given a starting estimate. - - Scalar function minimizers - - fminbound -- Bounded minimization of a scalar function. - brent -- 1-D function minimization using Brent method. - golden -- 1-D function minimization using Golden Section method - bracket -- Bracket a minimum (given two starting points) - -Also a collection of general_purpose root-finding routines. - - fsolve -- Non-linear multi-variable equation solver. - - Scalar function solvers - - brentq -- quadratic interpolation Brent method - brenth -- Brent method (modified by Harris with - hyperbolic extrapolation) - ridder -- Ridder's method - bisect -- Bisection method - newton -- Secant method or Newton's method - - fixed_point -- Single-variable fixed-point solver. - Deleted: scipy-docs/trunk/source/tutorial/examples/5.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,13 +0,0 @@ ->>> from scipy.optimize import fmin ->>> def rosen(x): # The Rosenbrock function - return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) - ->>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin(rosen, x0) -Optimization terminated successfully. - Current function value: 0.000000 - Iterations: 516 - Function evaluations: 825 - ->>> print xopt -[ 1. 1. 1. 1. 1.] Deleted: scipy-docs/trunk/source/tutorial/examples/5.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.3 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,10 +0,0 @@ ->>> def rosen_der(x): - xm = x[1:-1] - xm_m1 = x[:-2] - xm_p1 = x[2:] - der = zeros(x.shape,x.typecode()) - der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm) - der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0]) - der[-1] = 200*(x[-1]-x[-2]**2) - return der - Deleted: scipy-docs/trunk/source/tutorial/examples/5.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.4 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,11 +0,0 @@ ->>> from scipy.optimize import fmin_bfgs - ->>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin_bfgs(rosen, x0, fprime=rosen_der) -Optimization terminated successfully. - Current function value: 0.000000 - Iterations: 109 - Function evaluations: 262 - Gradient evaluations: 110 ->>> print xopt -[ 1. 1. 1. 1. 1.] Deleted: scipy-docs/trunk/source/tutorial/examples/5.5 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.5 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.5 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,21 +0,0 @@ ->>> from scipy.optimize import fmin_ncg ->>> def rosen_hess(x): - x = asarray(x) - H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1) - diagonal = zeros(len(x),x.typecode()) - diagonal[0] = 1200*x[0]-400*x[1]+2 - diagonal[-1] = 200 - diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:] - H = H + diag(diagonal) - return H - ->>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess=rosen_hess) -Optimization terminated successfully. - Current function value: 0.000000 - Iterations: 19 - Function evaluations: 40 - Gradient evaluations: 19 - Hessian evaluations: 19 ->>> print xopt -[ 0.9999 0.9999 0.9998 0.9996 0.9991] Deleted: scipy-docs/trunk/source/tutorial/examples/5.6 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.6 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.6 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,20 +0,0 @@ ->>> from scipy.optimize import fmin_ncg ->>> def rosen_hess_p(x,p): - x = asarray(x) - Hp = zeros(len(x),x.typecode()) - Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1] - Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \ - -400*x[1:-1]*p[2:] - Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1] - return Hp - ->>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess_p=rosen_hess_p) -Optimization terminated successfully. - Current function value: 0.000000 - Iterations: 20 - Function evaluations: 42 - Gradient evaluations: 20 - Hessian evaluations: 44 ->>> print xopt -[ 1. 1. 1. 0.9999 0.9999] Deleted: scipy-docs/trunk/source/tutorial/examples/5.7 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.7 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.7 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,31 +0,0 @@ ->>> from numpy import * ->>> x = arange(0,6e-2,6e-2/30) ->>> A,k,theta = 10, 1.0/3e-2, pi/6 ->>> y_true = A*sin(2*pi*k*x+theta) ->>> y_meas = y_true + 2*random.randn(len(x)) - ->>> def residuals(p, y, x): -... A,k,theta = p -... err = y-A*sin(2*pi*k*x+theta) -... return err - ->>> def peval(x, p): -... return p[0]*sin(2*pi*p[1]*x+p[2]) - ->>> p0 = [8, 1/2.3e-2, pi/3] ->>> print array(p0) -[ 8. 43.4783 1.0472] - ->>> from scipy.optimize import leastsq ->>> plsq = leastsq(residuals, p0, args=(y_meas, x)) ->>> print plsq[0] -[ 10.9437 33.3605 0.5834] - ->>> print array([A, k, theta]) -[ 10. 33.3333 0.5236] - ->>> import matplotlib.pyplot as plt ->>> plt.plot(x,peval(x,plsq[0]),x,y_meas,'o',x,y_true) ->>> plt.title('Least-squares fit to noisy data') ->>> plt.legend(['Fit', 'Noisy', 'True']) ->>> plt.show() Deleted: scipy-docs/trunk/source/tutorial/examples/5.8 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.8 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.8 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,7 +0,0 @@ ->>> from scipy.special import j1 - ->>> from scipy.optimize import fminbound ->>> xmin = fminbound(j1, 4, 7) ->>> print xmin -5.33144184241 - Deleted: scipy-docs/trunk/source/tutorial/examples/5.9 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/5.9 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/5.9 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,16 +0,0 @@ ->>> def func(x): - return x + 2*cos(x) - ->>> def func2(x): - out = [x[0]*cos(x[1]) - 4] - out.append(x[1]*x[0] - x[1] - 5) - return out - ->>> from optimize import fsolve ->>> x0 = fsolve(func, 0.3) ->>> print x0 --1.02986652932 - ->>> x02 = fsolve(func2, [1, 1]) ->>> print x02 -[ 6.5041 0.9084] Copied: scipy-docs/trunk/source/tutorial/examples/6-1 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/6.1) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6-1 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,10 @@ +>>> from numpy import * +>>> from scipy import interpolate + +>>> x = arange(0,10) +>>> y = exp(-x/3.0) +>>> f = interpolate.interp1d(x, y) + +>>> xnew = arange(0,9,0.1) +>>> import matplotlib.pyplot as plt +>>> plt.plot(x,y,'o',xnew,f(xnew),'-') Copied: scipy-docs/trunk/source/tutorial/examples/6-2 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/6.2) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6-2 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,61 @@ +>>> from numpy import * +>>> import matplotlib.pyplot as plt +>>> from scipy import interpolate + +>>> # Cubic-spline +>>> x = arange(0,2*pi+pi/4,2*pi/8) +>>> y = sin(x) +>>> tck = interpolate.splrep(x,y,s=0) +>>> xnew = arange(0,2*pi,pi/50) +>>> ynew = interpolate.splev(xnew,tck,der=0) + +>>> plt.figure() +>>> plt.plot(x,y,'x',xnew,ynew,xnew,sin(xnew),x,y,'b') +>>> plt.legend(['Linear','Cubic Spline', 'True']) +>>> plt.axis([-0.05,6.33,-1.05,1.05]) +>>> plt.title('Cubic-spline interpolation') +>>> plt.show() + +>>> # Derivative of spline +>>> yder = interpolate.splev(xnew,tck,der=1) +>>> plt.figure() +>>> plt.plot(xnew,yder,xnew,cos(xnew),'--') +>>> plt.legend(['Cubic Spline', 'True']) +>>> plt.axis([-0.05,6.33,-1.05,1.05]) +>>> plt.title('Derivative estimation from spline') +>>> plt.show() + +>>> # Integral of spline +>>> def integ(x,tck,constant=-1): +>>> x = atleast_1d(x) +>>> out = zeros(x.shape, dtype=x.dtype) +>>> for n in xrange(len(out)): +>>> out[n] = interpolate.splint(0,x[n],tck) +>>> out += constant +>>> return out +>>> +>>> yint = integ(xnew,tck) +>>> plt.figure() +>>> plt.plot(xnew,yint,xnew,-cos(xnew),'--') +>>> plt.legend(['Cubic Spline', 'True']) +>>> plt.axis([-0.05,6.33,-1.05,1.05]) +>>> plt.title('Integral estimation from spline') +>>> plt.show() + +>>> # Roots of spline +>>> print interpolate.sproot(tck) +[ 0. 3.1416] + +>>> # Parametric spline +>>> t = arange(0,1.1,.1) +>>> x = sin(2*pi*t) +>>> y = cos(2*pi*t) +>>> tck,u = interpolate.splprep([x,y],s=0) +>>> unew = arange(0,1.01,0.01) +>>> out = interpolate.splev(unew,tck) +>>> plt.figure() +>>> plt.plot(x,y,'x',out[0],out[1],sin(2*pi*unew),cos(2*pi*unew),x,y,'b') +>>> plt.legend(['Linear','Cubic Spline', 'True']) +>>> plt.axis([-1.05,1.05,-1.05,1.05]) +>>> plt.title('Spline of parametrically-defined curve') +>>> plt.show() Copied: scipy-docs/trunk/source/tutorial/examples/6-3 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/6.3) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6-3 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,24 @@ +>>> from numpy import * +>>> from scipy import interpolate +>>> import matplotlib.pyplot as plt + +>>> # Define function over sparse 20x20 grid +>>> x,y = mgrid[-1:1:20j,-1:1:20j] +>>> z = (x+y)*exp(-6.0*(x*x+y*y)) + +>>> plt.figure() +>>> plt.pcolor(x,y,z) +>>> plt.colorbar() +>>> plt.title("Sparsely sampled function.") +>>> plt.show() + +>>> # Interpolate function over new 70x70 grid +>>> xnew,ynew = mgrid[-1:1:70j,-1:1:70j] +>>> tck = interpolate.bisplrep(x,y,z,s=0) +>>> znew = interpolate.bisplev(xnew[:,0],ynew[0,:],tck) + +>>> plt.figure() +>>> plt.pcolor(xnew,ynew,znew) +>>> plt.colorbar() +>>> plt.title("Interpolated function.") +>>> plt.show() Copied: scipy-docs/trunk/source/tutorial/examples/6-4 (from rev 5102, scipy-docs/trunk/source/tutorial/examples/6.4) =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6-4 2008-11-14 00:56:39 UTC (rev 5103) @@ -0,0 +1,25 @@ +>>> from numpy import * +>>> from scipy import signal, misc +>>> import matplotlib.pyplot as plt + +>>> image = misc.lena().astype(float32) +>>> derfilt = array([1.0,-2,1.0],float32) +>>> ck = signal.cspline2d(image,8.0) +>>> deriv = signal.sepfir2d(ck, derfilt, [1]) + \ +>>> signal.sepfir2d(ck, [1], derfilt) +>>> +>>> ## Alternatively we could have done: +>>> ## laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],float32) +>>> ## deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm') + +>>> plt.figure() +>>> plt.imshow(image) +>>> plt.gray() +>>> plt.title('Original image') +>>> plt.show() + +>>> plt.figure() +>>> plt.imshow(deriv) +>>> plt.gray() +>>> plt.title('Output of spline edge filter') +>>> plt.show() Deleted: scipy-docs/trunk/source/tutorial/examples/6.1 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6.1 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,10 +0,0 @@ ->>> from numpy import * ->>> from scipy import interpolate - ->>> x = arange(0,10) ->>> y = exp(-x/3.0) ->>> f = interpolate.interp1d(x, y) - ->>> xnew = arange(0,9,0.1) ->>> import matplotlib.pyplot as plt ->>> plt.plot(x,y,'o',xnew,f(xnew),'-') Deleted: scipy-docs/trunk/source/tutorial/examples/6.2 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6.2 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,61 +0,0 @@ ->>> from numpy import * ->>> import matplotlib.pyplot as plt ->>> from scipy import interpolate - ->>> # Cubic-spline ->>> x = arange(0,2*pi+pi/4,2*pi/8) ->>> y = sin(x) ->>> tck = interpolate.splrep(x,y,s=0) ->>> xnew = arange(0,2*pi,pi/50) ->>> ynew = interpolate.splev(xnew,tck,der=0) - ->>> plt.figure() ->>> plt.plot(x,y,'x',xnew,ynew,xnew,sin(xnew),x,y,'b') ->>> plt.legend(['Linear','Cubic Spline', 'True']) ->>> plt.axis([-0.05,6.33,-1.05,1.05]) ->>> plt.title('Cubic-spline interpolation') ->>> plt.show() - ->>> # Derivative of spline ->>> yder = interpolate.splev(xnew,tck,der=1) ->>> plt.figure() ->>> plt.plot(xnew,yder,xnew,cos(xnew),'--') ->>> plt.legend(['Cubic Spline', 'True']) ->>> plt.axis([-0.05,6.33,-1.05,1.05]) ->>> plt.title('Derivative estimation from spline') ->>> plt.show() - ->>> # Integral of spline ->>> def integ(x,tck,constant=-1): ->>> x = atleast_1d(x) ->>> out = zeros(x.shape, dtype=x.dtype) ->>> for n in xrange(len(out)): ->>> out[n] = interpolate.splint(0,x[n],tck) ->>> out += constant ->>> return out ->>> ->>> yint = integ(xnew,tck) ->>> plt.figure() ->>> plt.plot(xnew,yint,xnew,-cos(xnew),'--') ->>> plt.legend(['Cubic Spline', 'True']) ->>> plt.axis([-0.05,6.33,-1.05,1.05]) ->>> plt.title('Integral estimation from spline') ->>> plt.show() - ->>> # Roots of spline ->>> print interpolate.sproot(tck) -[ 0. 3.1416] - ->>> # Parametric spline ->>> t = arange(0,1.1,.1) ->>> x = sin(2*pi*t) ->>> y = cos(2*pi*t) ->>> tck,u = interpolate.splprep([x,y],s=0) ->>> unew = arange(0,1.01,0.01) ->>> out = interpolate.splev(unew,tck) ->>> plt.figure() ->>> plt.plot(x,y,'x',out[0],out[1],sin(2*pi*unew),cos(2*pi*unew),x,y,'b') ->>> plt.legend(['Linear','Cubic Spline', 'True']) ->>> plt.axis([-1.05,1.05,-1.05,1.05]) ->>> plt.title('Spline of parametrically-defined curve') ->>> plt.show() Deleted: scipy-docs/trunk/source/tutorial/examples/6.3 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6.3 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,24 +0,0 @@ ->>> from numpy import * ->>> from scipy import interpolate ->>> import matplotlib.pyplot as plt - ->>> # Define function over sparse 20x20 grid ->>> x,y = mgrid[-1:1:20j,-1:1:20j] ->>> z = (x+y)*exp(-6.0*(x*x+y*y)) - ->>> plt.figure() ->>> plt.pcolor(x,y,z) ->>> plt.colorbar() ->>> plt.title("Sparsely sampled function.") ->>> plt.show() - ->>> # Interpolate function over new 70x70 grid ->>> xnew,ynew = mgrid[-1:1:70j,-1:1:70j] ->>> tck = interpolate.bisplrep(x,y,z,s=0) ->>> znew = interpolate.bisplev(xnew[:,0],ynew[0,:],tck) - ->>> plt.figure() ->>> plt.pcolor(xnew,ynew,znew) ->>> plt.colorbar() ->>> plt.title("Interpolated function.") ->>> plt.show() Deleted: scipy-docs/trunk/source/tutorial/examples/6.4 =================================================================== --- scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/examples/6.4 2008-11-14 00:56:39 UTC (rev 5103) @@ -1,25 +0,0 @@ ->>> from numpy import * ->>> from scipy import signal, misc ->>> import matplotlib.pyplot as plt - ->>> image = misc.lena().astype(float32) ->>> derfilt = array([1.0,-2,1.0],float32) ->>> ck = signal.cspline2d(image,8.0) ->>> deriv = signal.sepfir2d(ck, derfilt, [1]) + \ ->>> signal.sepfir2d(ck, [1], derfilt) ->>> ->>> ## Alternatively we could have done: ->>> ## laplacian = array([[0,1,0],[1,-4,1],[0,1,0]],float32) ->>> ## deriv2 = signal.convolve2d(ck,laplacian,mode='same',boundary='symm') - ->>> plt.figure() ->>> plt.imshow(image) ->>> plt.gray() ->>> plt.title('Original image') ->>> plt.show() - ->>> plt.figure() ->>> plt.imshow(deriv) ->>> plt.gray() ->>> plt.title('Output of spline edge filter') ->>> plt.show() Modified: scipy-docs/trunk/source/tutorial/index.rst =================================================================== --- scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:37:38 UTC (rev 5102) +++ scipy-docs/trunk/source/tutorial/index.rst 2008-11-14 00:56:39 UTC (rev 5103) @@ -68,7 +68,7 @@ passed as the argument to help than a list of the functions and classes defined in that module is printed. For example: -.. literalinclude:: examples/1.1 +.. literalinclude:: examples/1-1 Another useful command is :func:`source`. When given a function written in Python as an argument, it prints out a listing of the @@ -252,7 +252,7 @@ arrays for an N-dimensional volume. The easiest way to understand this is with an example of its usage: -.. literalinclude:: examples/2.1 +.. literalinclude:: examples/2-1 Having meshed arrays like this is sometimes very useful. However, it is not always needed just to evaluate some N-dimensional function over @@ -292,7 +292,7 @@ expressions, integrated, differentiated, and evaluated. It even prints like a polynomial: -.. literalinclude:: examples/2.2 +.. literalinclude:: examples/2-2 The other way to handle polynomials is as an array of coefficients with the first element of the array giving the coefficient of the @@ -311,7 +311,7 @@ ufuncs). For example, suppose you have a Python function named :obj:`addsubtract` defined as: -.. literalinclude:: examples/3.1 +.. literalinclude:: examples/3-1 which defines a function of two scalar variables and returns a scalar result. The class vectorize can be used to "vectorize "this function so that :: @@ -321,7 +321,7 @@ returns a function which takes array arguments and returns an array result: -.. literalinclude:: examples/3.2 +.. literalinclude:: examples/3-2 This particular function could have been written in vector form without the use of :obj:`vectorize` . But, what if the function you have written is the result of some @@ -355,7 +355,7 @@ the array in a ``choicelist`` corresponding to the first condition in ``condlist`` that is true. For example -.. literalinclude:: examples/2.3 +.. literalinclude:: examples/2-3 Common functions @@ -416,7 +416,7 @@ techniques including an ordinary differential equation integrator. An overview of the module is provided by the help command: -.. literalinclude:: examples/4.1 +.. literalinclude:: examples/4-1 General integration (integrate.quad) @@ -435,7 +435,7 @@ This could be computed using :obj:`quad`: -.. literalinclude:: examples/4.2 +.. literalinclude:: examples/4-2 The first argument to quad is a "callable "Python object ( *i.e* a function, method, or class instance). Notice the use of a lambda- function in this case as the argument. The next two arguments are the @@ -473,7 +473,7 @@ :obj:`special.expn` can be replicated by defining a new function :obj:`vec_expint` based on the routine :obj:`quad`: -.. literalinclude:: examples/4.3 +.. literalinclude:: examples/4-3 The function which is integrated can even use the quad argument (though the error bound may underestimate the error due to possible @@ -484,7 +484,7 @@ \[ I_{n}=\int_{0}^{\infty}\int_{1}^{\infty}\frac{e^{-xt}}{t^{n}}\, dt\, dx=\frac{1}{n}.\] -.. literalinclude:: examples/4.4 +.. literalinclude:: examples/4-4 This last example shows that multiple integration can be handled using repeated calls to :func:`quad`. The mechanics of this for double and @@ -496,7 +496,7 @@ functions. An example of using double integration to compute several values of :math:`I_{n}` is shown below: -.. literalinclude:: examples/4.5 +.. literalinclude:: examples/4-5 Gaussian quadrature (integrate.gauss_quadtol) @@ -610,7 +610,7 @@ (with respect to :math:`\mathbf{y}` ) of the function, :math:`\mathbf{f}\left(\mathbf{y},t\right)`. -.. literalinclude:: examples/4.6 +.. literalinclude:: examples/4-6 Optimization (optimize) @@ -620,7 +620,7 @@ in the :mod:`scipy.optimize` package. An overview of the module is available using :func:`help` (or :func:`pydoc.help`): -.. literalinclude:: examples/5.1 +.. literalinclude:: examples/5-1 The first four algorithms are unconstrained minimization algorithms (fmin: Nelder-Mead simplex, fmin_bfgs: BFGS, fmin_ncg: Newton @@ -650,7 +650,7 @@ The minimum value of this function is 0 which is achieved when :math:`x_{i}=1.` This minimum can be found using the :obj:`fmin` routine as shown in the example below: -.. literalinclude:: examples/5.2 +.. literalinclude:: examples/5-2 Another optimization algorithm that needs only function calls to find the minimum is Powell's method available as :func:`optimize.fmin_powell`. @@ -685,14 +685,14 @@ A Python function which computes this gradient is constructed by the code-segment: -.. literalinclude:: examples/5.3 +.. literalinclude:: examples/5-3 The calling signature for the BFGS minimization algorithm is similar to :obj:`fmin` with the addition of the *fprime* argument. An example usage of :obj:`fmin_bfgs` is shown in the following example which minimizes the Rosenbrock function. -.. literalinclude:: examples/5.4 +.. literalinclude:: examples/5-4 Newton-Conjugate-Gradient (optimize.fmin_ncg) @@ -758,7 +758,7 @@ The code which computes this Hessian along with the code to minimize the function using :obj:`fmin_ncg` is shown in the following example: -.. literalinclude:: examples/5.5 +.. literalinclude:: examples/5-5 @@ -787,7 +787,7 @@ Code which makes use of the *fhess_p* keyword to minimize the Rosenbrock function using :obj:`fmin_ncg` follows: -.. literalinclude:: examples/5.6 +.. literalinclude:: examples/5-6 Least-square fitting (minimize.leastsq) @@ -843,7 +843,7 @@ .. _`fig:least_squares_fit`: -.. plot:: source/tutorial/examples/5.7 +.. plot:: source/tutorial/examples/5-7 :include-source: :doctest-format: :align: center @@ -892,7 +892,7 @@ For example, to find the minimum of :math:`J_{1}\left(x\right)` near :math:`x=5` , :obj:`fminbound` can be called using the interval :math:`\left[4,7\right]` as a constraint. The result is :math:`x_{\textrm{min}}=5.3314` : -.. literalinclude:: examples/5.8 +.. literalinclude:: examples/5-8 @@ -922,7 +922,7 @@ The results are :math:`x=-1.0299` and :math:`x_{0}=6.5041,\, x_{1}=0.9084` . -.. literalinclude:: examples/5.9 +.. literalinclude:: examples/5-9 @@ -972,7 +972,7 @@ .. _`fig:inter_1d`: -.. plot:: source/tutorial/examples/6.1 +.. plot:: source/tutorial/examples/6-1 :doctest-format: :include-source: :align: center @@ -1012,7 +1012,7 @@ :func:`interpolate.sproot`). These functions are demonstrated in the example that follows (see also Figure `3 <#fig-spline-1d>`__ ). -.. plot:: source/tutorial/examples/6.2 +.. plot:: source/tutorial/examples/6-2 :include-source: :doctest-format: :align: center @@ -1059,7 +1059,7 @@ .. _`fig:2d_interp`: -.. plot:: source/tutorial/examples/6.3 +.. plot:: source/tutorial/examples/6-3 :doctest-format: :include-source: :align: center @@ -1186,7 +1186,7 @@ .. _`fig:lena_edge_spline`: -.. plot:: source/tutorial/examples/6.4 +.. plot:: source/tutorial/examples/6-4 :doctest-format: :include-source: :align: center @@ -1589,7 +1589,7 @@ The following example demonstrates this computation in SciPy -.. literalinclude:: examples/10.2.1 +.. literalinclude:: examples/10-2-1 Solving linear system ^^^^^^^^^^^^^^^^^^^^^ @@ -1617,7 +1617,7 @@ faster and more numerically stable. In this case it gives the same answer as shown in the following example: -.. literalinclude:: examples/10.2.2 +.. literalinclude:: examples/10-2-2 Finding Determinant ^^^^^^^^^^^^^^^^^^^ @@ -1647,7 +1647,7 @@ In SciPy this is computed as shown in this example: -.. literalinclude:: examples/10.2.3 +.. literalinclude:: examples/10-2-3 Computing norms ^^^^^^^^^^^^^^^ @@ -1749,7 +1749,7 @@ where :math:`x_{i}=0.1i` for :math:`i=1\ldots10` , :math:`c_{1}=5` , and :math:`c_{2}=4.` Noise is added to :math:`y_{i}` and the coefficients :math:`c_{1}` and :math:`c_{2}` are estimated using linear least squares. -.. plot:: source/tutorial/examples/10.2.5 +.. plot:: source/tutorial/examples/10-2-5 :include-source: :align: center @@ -1877,7 +1877,7 @@ the original equation. The eigenvectors associated with these eigenvalues can then be found. -.. literalinclude:: examples/10.3.1 +.. literalinclude:: examples/10-3-1 Singular value decomposition ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -1894,7 +1894,7 @@ is the singular-value decomposition of :math:`\mathbf{A}.` Every matrix has a singular value decomposition. Sometimes, the singular values are called the spectrum of :math:`\mathbf{A}.` The command :obj:`linalg.svd` will return :math:`\mathbf{U}` , :math:`\mathbf{V}^{H}` , and :math:`\sigma_{i}` as an array of the singular values. To obtain the matrix :math:`\mathbf{\Sigma}` use :obj:`linalg.diagsvd`. The following example illustrates the use of :obj:`linalg.svd` . -.. literalinclude:: examples/10.3.2 +.. literalinclude:: examples/10-3-2 .. [#] A hermition matrix :math:`\mathbf{D}` satisfies :math:`\mathbf{D}^{H}=\mathbf{D}.` @@ -1992,7 +1992,7 @@ The following example illustrates the schur decomposition: -.. literalinclude:: examples/10.3.6 +.. literalinclude:: examples/10-3-6 Matrix Functions ---------------- @@ -2117,7 +2117,7 @@ algorithm. For example the following code computes the zeroth-order Bessel function applied to a matrix. -.. literalinclude:: examples/10.4.4 +.. literalinclude:: examples/10-4-4 Statistics ========== From scipy-svn at scipy.org Thu Nov 13 20:03:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 19:03:21 -0600 (CST) Subject: [Scipy-svn] r5104 - scipy-docs/trunk Message-ID: <20081114010321.E55B039C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 19:03:11 -0600 (Thu, 13 Nov 2008) New Revision: 5104 Modified: scipy-docs/trunk/Makefile Log: docs: rsync -z in upload Modified: scipy-docs/trunk/Makefile =================================================================== --- scipy-docs/trunk/Makefile 2008-11-14 00:56:39 UTC (rev 5103) +++ scipy-docs/trunk/Makefile 2008-11-14 01:03:11 UTC (rev 5104) @@ -31,7 +31,7 @@ @test -e build/dist || { echo "make dist is required first"; exit 1; } @test output-is-fine -nt build/dist || { \ echo "Review the output in build/dist, and do 'touch output-is-fine' before uploading."; exit 1; } - rsync -r --delete-after -p build/dist/ $(USER)@docs.scipy.org:/home/docserver/www-root/doc/scipy/ + rsync -r -z --delete-after -p build/dist/ $(USER)@docs.scipy.org:/home/docserver/www-root/doc/scipy/ dist: html test -d build/latex || make latex From scipy-svn at scipy.org Thu Nov 13 20:16:45 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 19:16:45 -0600 (CST) Subject: [Scipy-svn] r5105 - scipy-docs/trunk/frontpage/_templates Message-ID: <20081114011645.7AC5939C05F@scipy.org> Author: ptvirtan Date: 2008-11-13 19:16:35 -0600 (Thu, 13 Nov 2008) New Revision: 5105 Modified: scipy-docs/trunk/frontpage/_templates/indexcontent.html Log: docs/frontpage: update Modified: scipy-docs/trunk/frontpage/_templates/indexcontent.html =================================================================== --- scipy-docs/trunk/frontpage/_templates/indexcontent.html 2008-11-14 01:03:11 UTC (rev 5104) +++ scipy-docs/trunk/frontpage/_templates/indexcontent.html 2008-11-14 01:16:35 UTC (rev 5105) @@ -4,7 +4,6 @@
    @@ -18,17 +17,14 @@

    Snapshots of work in progress:

    -
    From scipy-svn at scipy.org Thu Nov 13 23:16:31 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 13 Nov 2008 22:16:31 -0600 (CST) Subject: [Scipy-svn] r5106 - trunk/scipy/stats/tests Message-ID: <20081114041631.0552C39C05F@scipy.org> Author: josef Date: 2008-11-13 22:16:29 -0600 (Thu, 13 Nov 2008) New Revision: 5106 Modified: trunk/scipy/stats/tests/test_continuous_basic.py Log: correction to test parameters, add moment test Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-14 01:16:35 UTC (rev 5105) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-14 04:16:29 UTC (rev 5106) @@ -31,12 +31,12 @@ ['cosine', ()], ['dgamma', (1.1023326088288166,)], ['dweibull', (2.0685080649914673,)], - ['erlang', (4, 0.7341136511570574, 0.047510038926818488)], + ['erlang', (20,)], #correction numargs = 1 ['expon', ()], ['exponpow', (2.697119160358469,)], ['exponweib', (2.8923945291034436, 1.9505288745913174)], ['f', (29, 18)], - ['fatiguelife', (29, 18)], + ['fatiguelife', (29,)], #correction numargs = 1 ['fisk', (3.0857548622253179,)], ['foldcauchy', (4.7164673455831894,)], ['foldnorm', (1.9521253373555869,)], @@ -105,7 +105,13 @@ ['weibull_min', (1.7866166930421596,)], ['wrapcauchy', (0.031071279018614728,)]] +# for testing only specific functions +##distcont = [ +## ['erlang', (20,)], #correction numargs = 1 +## ['fatiguelife', (29,)], #correction numargs = 1 +## ['loggamma', (0.41411931826052117,)]] + def test_cont_basic(): for distname, arg in distcont[:]: distfn = getattr(stats, distname) @@ -117,12 +123,33 @@ yield check_sample_meanvar_, distfn, arg, sm, sv, distname + \ 'sample mean test' yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + yield check_moment, distfn, arg, distname yield check_cdf_ppf, distfn, arg, distname yield check_sf_isf, distfn, arg, distname yield check_pdf, distfn, arg, distname #yield check_oth, distfn, arg # is still missing + +def check_moment(distfn, arg, msg): + m,v = distfn.stats(*arg) + m1 = distfn.moment(1,*arg) + m2 = distfn.moment(2,*arg) + if m < np.inf: + npt.assert_almost_equal(m1, m, decimal=10, err_msg= msg + \ + ' - 1st moment') + else: + assert np.isinf(m1) or np.isnan(m1), \ + msg + ' - 1st moment -infinite, m1=%s' % str(m1) + #np.isnan(m1) temporary special treatment for loggamma + if v < np.inf: + npt.assert_almost_equal(m2-m1*m1, v, decimal=10, err_msg= msg + \ + ' - 2ndt moment') + else: + assert np.isinf(m2) or np.isnan(m2), \ + msg + ' - 2nd moment -infinite, m2=%s' % str(m2) + #np.isnan(m2) temporary special treatment for loggamma + def check_sample_meanvar_(distfn, arg, sm, sv, msg): m,v = distfn.stats(*arg) check_sample_meanvar, sm, m, msg + 'sample mean test' From scipy-svn at scipy.org Fri Nov 14 01:24:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 00:24:28 -0600 (CST) Subject: [Scipy-svn] r5107 - in trunk/scipy: cluster/tests spatial Message-ID: <20081114062428.6E46139C05F@scipy.org> Author: damian.eads Date: 2008-11-14 00:24:24 -0600 (Fri, 14 Nov 2008) New Revision: 5107 Modified: trunk/scipy/cluster/tests/test_hierarchy.py trunk/scipy/spatial/distance.py Log: Polishing scipy.spatial.distance docs. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-14 04:16:29 UTC (rev 5106) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-14 06:24:24 UTC (rev 5107) @@ -685,7 +685,6 @@ Z = linkage(X, 'single') self.failUnless(is_monotonic(Z) == True) - def help_single_inconsistent_depth(self, i): Y = squareform(_tdist) Z = linkage(Y, 'single') Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-14 04:16:29 UTC (rev 5106) +++ trunk/scipy/spatial/distance.py 2008-11-14 06:24:24 UTC (rev 5107) @@ -1571,24 +1571,24 @@ The following are common calling conventions: - 1. ``Y = cdist(X, 'euclidean')`` + 1. ``Y = cdist(XA, XB, 'euclidean')`` Computes the distance between :math:`m` points using Euclidean distance (2-norm) as the distance metric between the points. The points are arranged as :math:`m` :math:`n`-dimensional row vectors in the matrix X. - 2. ``Y = cdist(X, 'minkowski', p)`` + 2. ``Y = cdist(XA, XB, 'minkowski', p)`` Computes the distances using the Minkowski distance :math:`||u-v||_p` (:math:`p`-norm) where :math:`p \geq 1`. - 3. ``Y = cdist(X, 'cityblock')`` + 3. ``Y = cdist(XA, XB, 'cityblock')`` Computes the city block or Manhattan distance between the points. - 4. ``Y = cdist(X, 'seuclidean', V=None)`` + 4. ``Y = cdist(XA, XB, 'seuclidean', V=None)`` Computes the standardized Euclidean distance. The standardized Euclidean distance between two n-vectors ``u`` and ``v`` is @@ -1601,12 +1601,12 @@ the i'th components of the points. If not passed, it is automatically computed. - 5. ``Y = cdist(X, 'sqeuclidean')`` + 5. ``Y = cdist(XA, XB, 'sqeuclidean')`` Computes the squared Euclidean distance ||u-v||_2^2 between the vectors. - 6. ``Y = cdist(X, 'cosine')`` + 6. ``Y = cdist(XA, XB, 'cosine')`` Computes the cosine distance between vectors u and v, @@ -1617,7 +1617,7 @@ where |*|_2 is the 2 norm of its argument *. - 7. ``Y = cdist(X, 'correlation')`` + 7. ``Y = cdist(XA, XB, 'correlation')`` Computes the correlation distance between vectors u and v. This is @@ -1630,21 +1630,21 @@ argument, and :math:`n` is the common dimensionality of the vectors. - 8. ``Y = cdist(X, 'hamming')`` + 8. ``Y = cdist(XA, XB, 'hamming')`` Computes the normalized Hamming distance, or the proportion of those vector elements between two n-vectors ``u`` and ``v`` which disagree. To save memory, the matrix ``X`` can be of type boolean. - 9. ``Y = cdist(X, 'jaccard')`` + 9. ``Y = cdist(XA, XB, 'jaccard')`` Computes the Jaccard distance between the points. Given two vectors, ``u`` and ``v``, the Jaccard distance is the proportion of those elements ``u[i]`` and ``v[i]`` that disagree where at least one of them is non-zero. - 10. ``Y = cdist(X, 'chebyshev')`` + 10. ``Y = cdist(XA, XB, 'chebyshev')`` Computes the Chebyshev distance between the points. The Chebyshev distance between two n-vectors ``u`` and ``v`` is the @@ -1655,7 +1655,7 @@ d(u,v) = max_i {|u_i-v_i|}. - 11. ``Y = cdist(X, 'canberra')`` + 11. ``Y = cdist(XA, XB, 'canberra')`` Computes the Canberra distance between the points. The Canberra distance between two points ``u`` and ``v`` is @@ -1666,7 +1666,7 @@ {|u_i|+|v_i|} - 12. ``Y = cdist(X, 'braycurtis')`` + 12. ``Y = cdist(XA, XB, 'braycurtis')`` Computes the Bray-Curtis distance between the points. The Bray-Curtis distance between two points ``u`` and ``v`` is @@ -1677,7 +1677,7 @@ d(u,v) = \frac{\sum_i {u_i-v_i}} {\sum_i {u_i+v_i}} - 13. ``Y = cdist(X, 'mahalanobis', VI=None)`` + 13. ``Y = cdist(XA, XB, 'mahalanobis', VI=None)`` Computes the Mahalanobis distance between the points. The Mahalanobis distance between two points ``u`` and ``v`` is @@ -1685,65 +1685,65 @@ variable) is the inverse covariance. If ``VI`` is not None, ``VI`` will be used as the inverse covariance matrix. - 14. ``Y = cdist(X, 'yule')`` + 14. ``Y = cdist(XA, XB, 'yule')`` Computes the Yule distance between each pair of boolean vectors. (see yule function documentation) - 15. ``Y = cdist(X, 'matching')`` + 15. ``Y = cdist(XA, 'matching')`` Computes the matching distance between each pair of boolean vectors. (see matching function documentation) - 16. ``Y = cdist(X, 'dice')`` + 16. ``Y = cdist(XA, 'dice')`` Computes the Dice distance between each pair of boolean vectors. (see dice function documentation) - 17. ``Y = cdist(X, 'kulsinski')`` + 17. ``Y = cdist(XA, XB, 'kulsinski')`` Computes the Kulsinski distance between each pair of boolean vectors. (see kulsinski function documentation) - 18. ``Y = cdist(X, 'rogerstanimoto')`` + 18. ``Y = cdist(XA, XB, 'rogerstanimoto')`` Computes the Rogers-Tanimoto distance between each pair of boolean vectors. (see rogerstanimoto function documentation) - 19. ``Y = cdist(X, 'russellrao')`` + 19. ``Y = cdist(XA, XB, 'russellrao')`` Computes the Russell-Rao distance between each pair of boolean vectors. (see russellrao function documentation) - 20. ``Y = cdist(X, 'sokalmichener')`` + 20. ``Y = cdist(XA, XB, 'sokalmichener')`` Computes the Sokal-Michener distance between each pair of boolean vectors. (see sokalmichener function documentation) - 21. ``Y = cdist(X, 'sokalsneath')`` + 21. ``Y = cdist(XA, XB, 'sokalsneath')`` Computes the Sokal-Sneath distance between the vectors. (see sokalsneath function documentation) - 22. ``Y = cdist(X, 'wminkowski')`` + 22. ``Y = cdist(XA, XB, 'wminkowski')`` Computes the weighted Minkowski distance between the vectors. (see sokalsneath function documentation) - 23. ``Y = cdist(X, f)`` + 23. ``Y = cdist(XA, XB, f)`` Computes the distance between all pairs of vectors in X using the user supplied 2-arity function f. For example, Euclidean distance between the vectors could be computed as follows:: - dm = cdist(X, (lambda u, v: np.sqrt(((u-v)*(u-v).T).sum()))) + dm = cdist(XA, XB, (lambda u, v: np.sqrt(((u-v)*(u-v).T).sum()))) Note that you should avoid passing a reference to one of the distance functions defined in this library. For example,:: - dm = cdist(X, sokalsneath) + dm = cdist(XA, XB, sokalsneath) would calculate the pair-wise distances between the vectors in X using the Python function sokalsneath. This would result in @@ -1751,7 +1751,7 @@ is inefficient. Instead, the optimized C version is more efficient, and we call it using the following syntax.:: - dm = cdist(X, 'sokalsneath') + dm = cdist(XA, XB, 'sokalsneath') :Parameters: XA : ndarray @@ -1784,7 +1784,7 @@ """ -# 21. Y = cdist(X, 'test_Y') +# 21. Y = cdist(XA, XB, 'test_Y') # # Computes the distance between all pairs of vectors in X # using the distance metric Y but with a more succint, From scipy-svn at scipy.org Fri Nov 14 10:28:40 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 09:28:40 -0600 (CST) Subject: [Scipy-svn] r5108 - in trunk/scipy/stats: . tests Message-ID: <20081114152840.15EA439C05F@scipy.org> Author: josef Date: 2008-11-14 09:28:34 -0600 (Fri, 14 Nov 2008) New Revision: 5108 Added: trunk/scipy/stats/tests/test_continuous_extra.py Modified: trunk/scipy/stats/distributions.py Log: add test for bounds of ppf and isf of continuous rv, fix nan for out-of-bounds isf arguments Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-14 06:24:24 UTC (rev 5107) +++ trunk/scipy/stats/distributions.py 2008-11-14 15:28:34 UTC (rev 5108) @@ -640,11 +640,13 @@ cond2 = (q==1) & cond0 cond = cond0 & cond1 output = valarray(shape(cond),value=self.b) - place(output,(1-cond0)*(cond1==cond1), self.badvalue) + #place(output,(1-cond0)*(cond1==cond1), self.badvalue) + place(output,(1-cond0)*(cond1==cond1)+(1-cond1)*(q!=0.0), self.badvalue) place(output,cond2,self.a) - goodargs = argsreduce(cond, *((q,)+args+(scale,loc))) #PB replace 1-q by q - scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] - place(output,cond,self._isf(*goodargs)*scale + loc) #PB use _isf instead of _ppf + if any(cond): #call only if at least 1 entry + goodargs = argsreduce(cond, *((q,)+args+(scale,loc))) #PB replace 1-q by q + scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2] + place(output,cond,self._isf(*goodargs)*scale + loc) #PB use _isf instead of _ppf if output.ndim == 0: return output[()] return output @@ -766,10 +768,10 @@ if (n > 0) and (n < 5): signature = inspect.getargspec(self._stats.im_func) if (signature[2] is not None) or ('moments' in signature[0]): - dict = {'moments':{1:'m',2:'v',3:'vs',4:'vk'}[n]} + mdict = {'moments':{1:'m',2:'v',3:'vs',4:'vk'}[n]} else: - dict = {} - mu, mu2, g1, g2 = self._stats(*args,**dict) + mdict = {} + mu, mu2, g1, g2 = self._stats(*args,**mdict) if (n==1): if mu is None: return self._munp(1,*args) else: return mu Added: trunk/scipy/stats/tests/test_continuous_extra.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-14 06:24:24 UTC (rev 5107) +++ trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-14 15:28:34 UTC (rev 5108) @@ -0,0 +1,55 @@ +import numpy.testing as npt +import numpy as np +import nose + +from scipy import stats + +from test_continuous_basic import distcont + +DECIMAL = 5 + +def test_cont_extra(): + for distname, arg in distcont[:]: + distfn = getattr(stats, distname) +## rvs = distfn.rvs(size=1000,*arg) +## sm = rvs.mean() +## sv = rvs.var() +## skurt = stats.kurtosis(rvs) +## sskew = stats.skew(rvs) + yield check_ppf_limits, distfn, arg, distname + \ + ' ppf limit test' + +def check_ppf_limits(distfn,arg,msg): + below,low,upp,above = distfn.ppf([-1,0,1,2], *arg) + #print distfn.name, distfn.a, low, distfn.b, upp + print distfn.name,below,low,upp,above + assert_equal_inf_nan(distfn.a,low, msg + 'ppf lower bound') + assert_equal_inf_nan(distfn.b,upp, msg + 'ppf upper bound') + assert np.isnan(below), msg + 'ppf out of bounds - below' + assert np.isnan(above), msg + 'ppf out of bounds - above' + +def check_ppf_limits(distfn,arg,msg): + below,low,upp,above = distfn.isf([-1,0,1,2], *arg) + #print distfn.name, distfn.a, low, distfn.b, upp + print distfn.name,below,low,upp,above + assert_equal_inf_nan(distfn.a,upp, msg + 'ppf lower bound') + assert_equal_inf_nan(distfn.b,low, msg + 'ppf upper bound') + assert np.isnan(below), msg + 'ppf out of bounds - below' + assert np.isnan(above), msg + 'ppf out of bounds - above' + + +def assert_equal_inf_nan(v1,v2,msg): + if not np.isinf(v1): + npt.assert_almost_equal(v1, v2, decimal=DECIMAL, err_msg= msg + \ + ' - finite') + else: + assert np.isinf(v2) or np.isnan(v2), \ + msg + ' - infinite, v2=%s' % str(v2) + +if __name__ == "__main__": + import nose + #nose.run(argv=['', __file__]) + print distcont[:5] + test_cont_extra() + nose.runmodule(argv=[__file__,'-s'], exit=False) + From scipy-svn at scipy.org Fri Nov 14 13:42:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 12:42:39 -0600 (CST) Subject: [Scipy-svn] r5109 - trunk/scipy/stats Message-ID: <20081114184239.7D95939C088@scipy.org> Author: josef Date: 2008-11-14 12:42:37 -0600 (Fri, 14 Nov 2008) New Revision: 5109 Modified: trunk/scipy/stats/distributions.py Log: fix (non-convergent) moment calculation of loggamma; force var to be inf if mean is inf, instead of nan Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-14 15:28:34 UTC (rev 5108) +++ trunk/scipy/stats/distributions.py 2008-11-14 18:42:37 UTC (rev 5109) @@ -720,6 +720,9 @@ if mu is None: mu = self._munp(1.0,*goodargs) mu2 = mu2p - mu*mu + if np.isinf(mu): + #if mean is inf then var is also inf + mu2 = np.inf out0 = default.copy() place(out0,cond,mu2*scale*scale) output.append(out0) @@ -2324,6 +2327,9 @@ return special.gammainc(c, exp(x)) def _ppf(self, q, c): return log(special.gammaincinv(c,q)) + def _munp(self,n,*args): + # use generic moment calculation using ppf + return self._mom0_sc(n,*args) loggamma = loggamma_gen(name='loggamma', longname="A log gamma", extradoc=""" From scipy-svn at scipy.org Fri Nov 14 22:45:27 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 21:45:27 -0600 (CST) Subject: [Scipy-svn] r5110 - in trunk/scipy/sparse: . tests Message-ID: <20081115034527.C528239C088@scipy.org> Author: wnbell Date: 2008-11-14 21:45:23 -0600 (Fri, 14 Nov 2008) New Revision: 5110 Modified: trunk/scipy/sparse/compressed.py trunk/scipy/sparse/dok.py trunk/scipy/sparse/lil.py trunk/scipy/sparse/tests/test_base.py Log: added more rigorous checking of __getitem__ and __setitem__ Modified: trunk/scipy/sparse/compressed.py =================================================================== --- trunk/scipy/sparse/compressed.py 2008-11-14 18:42:37 UTC (rev 5109) +++ trunk/scipy/sparse/compressed.py 2008-11-15 03:45:23 UTC (rev 5110) @@ -371,7 +371,7 @@ if (col < 0): col += N if not (0<=row= self.shape[0] or j < 0 or - j >= self.shape[1]) + assert not (i < 0 or i >= self.shape[0] or j < 0 or j >= self.shape[1]) except AssertionError: - raise IndexError, "index out of bounds" + raise IndexError('index out of bounds') return dict.get(self, key, default) def __getitem__(self, key): @@ -111,7 +110,7 @@ try: i, j = key except (ValueError, TypeError): - raise TypeError, "index must be a pair of integers or slices" + raise TypeError('index must be a pair of integers or slices') # Bounds checking @@ -119,16 +118,17 @@ if i < 0: i += self.shape[0] if i < 0 or i >= self.shape[0]: - raise IndexError, "index out of bounds" + raise IndexError('index out of bounds') + if isintlike(j): if j < 0: j += self.shape[1] if j < 0 or j >= self.shape[1]: - raise IndexError, "index out of bounds" + raise IndexError('index out of bounds') # First deal with the case where both i and j are integers if isintlike(i) and isintlike(j): - return dict.get(self, key, 0.) + return dict.get(self, (i,j), 0.) else: # Either i or j is a slice, sequence, or invalid. If i is a slice # or sequence, unfold it first and call __getitem__ recursively. @@ -141,7 +141,7 @@ else: # Make sure i is an integer. (But allow it to be a subclass of int). if not isintlike(i): - raise TypeError, "index must be a pair of integers or slices" + raise TypeError('index must be a pair of integers or slices') seq = None if seq is not None: # i is a seq @@ -151,7 +151,7 @@ last = seq[-1] if first < 0 or first >= self.shape[0] or last < 0 \ or last >= self.shape[0]: - raise IndexError, "index out of bounds" + raise IndexError('index out of bounds') newshape = (last-first+1, 1) new = dok_matrix(newshape) # ** This uses linear time in the size m of dimension 0: Modified: trunk/scipy/sparse/lil.py =================================================================== --- trunk/scipy/sparse/lil.py 2008-11-14 18:42:37 UTC (rev 5109) +++ trunk/scipy/sparse/lil.py 2008-11-15 03:45:23 UTC (rev 5110) @@ -155,14 +155,19 @@ return new def _get1(self, i, j): - row = self.rows[i] - data = self.data[i] + + if i < 0: + i += self.shape[0] + if i < 0 or i >= self.shape[0]: + raise IndexError('row index out of bounds') if j < 0: j += self.shape[1] - - if j < 0 or j > self.shape[1]: + if j < 0 or j >= self.shape[1]: raise IndexError('column index out of bounds') + + row = self.rows[i] + data = self.data[i] pos = bisect_left(row, j) if pos != len(data) and row[pos] == j: Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-11-14 18:42:37 UTC (rev 5109) +++ trunk/scipy/sparse/tests/test_base.py 2008-11-15 03:45:23 UTC (rev 5110) @@ -573,20 +573,34 @@ class _TestGetSet: def test_setelement(self): - a = self.spmatrix((3,4)) - a[1,2] = 4.0 - a[0,1] = 3 - a[2,0] = 2.0 - a[0,-1] = 8 - a[-1,-2] = 7 - assert_array_equal(a.todense(),[[0,3,0,8],[0,0,4,0],[2,0,7,0]]) + A = self.spmatrix((3,4)) + A[ 1, 2] = 4.0 + A[ 0, 1] = 3 + A[ 2, 0] = 2.0 + A[ 0,-1] = 8 + A[-1,-2] = 7 + A[ 0, 1] = 5 + assert_array_equal(A.todense(),[[0,5,0,8],[0,0,4,0],[2,0,7,0]]) + + for ij in [(0,4),(-1,4),(3,0),(3,4),(3,-1)]: + assert_raises(IndexError, A.__setitem__, ij, 123.0) def test_getelement(self): - assert_equal(self.datsp[0,0],1) - assert_equal(self.datsp[0,1],0) - assert_equal(self.datsp[1,0],3) - assert_equal(self.datsp[2,1],2) + D = array([[1,0,0], + [4,3,0], + [0,2,0], + [0,0,0]]) + A = self.spmatrix(D) + M,N = D.shape + + for i in range(-M, M): + for j in range(-N, N): + assert_equal(A[i,j], D[i,j]) + + for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1)]: + assert_raises(IndexError, A.__getitem__, ij) + class _TestSolve: def test_solve(self): """ Test whether the lu_solve command segfaults, as reported by Nils From scipy-svn at scipy.org Fri Nov 14 22:45:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 21:45:43 -0600 (CST) Subject: [Scipy-svn] r5111 - trunk/scipy/stats Message-ID: <20081115034543.65EAE39C089@scipy.org> Author: josef Date: 2008-11-14 21:45:41 -0600 (Fri, 14 Nov 2008) New Revision: 5111 Modified: trunk/scipy/stats/distributions.py Log: fix entropy for continuous rv with numargs==0 Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-15 03:45:23 UTC (rev 5110) +++ trunk/scipy/stats/distributions.py 2008-11-15 03:45:41 UTC (rev 5111) @@ -848,12 +848,16 @@ def entropy(self, *args, **kwds): loc,scale=map(kwds.get,['loc','scale']) args, loc, scale = self._fix_loc_scale(args, loc, scale) - args = map(arr,args) + args = tuple(map(arr,args)) cond0 = self._argcheck(*args) & (scale > 0) & (loc==loc) output = zeros(shape(cond0),'d') place(output,(1-cond0),self.badvalue) goodargs = argsreduce(cond0, *args) - place(output,cond0,self.vecentropy(*goodargs)+log(scale)) + #I don't know when or why vecentropy got broken when numargs == 0 + if self.numargs == 0: + place(output,cond0,self._entropy()+log(scale)) + else: + place(output,cond0,self.vecentropy(*goodargs)+log(scale)) return output _EULER = 0.577215664901532860606512090082402431042 # -special.psi(1) From scipy-svn at scipy.org Fri Nov 14 22:48:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 21:48:50 -0600 (CST) Subject: [Scipy-svn] r5112 - trunk/scipy/stats Message-ID: <20081115034850.F1E5F39C088@scipy.org> Author: josef Date: 2008-11-14 21:48:48 -0600 (Fri, 14 Nov 2008) New Revision: 5112 Modified: trunk/scipy/stats/distributions.py Log: improve generic entropy integration for continuous rv, when integration returns nan. 6 continuous distributions still return nan for entropy because of integration problems. Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-15 03:45:41 UTC (rev 5111) +++ trunk/scipy/stats/distributions.py 2008-11-15 03:48:48 UTC (rev 5112) @@ -843,7 +843,22 @@ def integ(x): val = self._pdf(x, *args) return val*log(val) - return -scipy.integrate.quad(integ,self.a,self.b)[0] + + entr = -scipy.integrate.quad(integ,self.a,self.b)[0] + if not np.isnan(entr): + return entr + else: # try with different limits if integration problems + low,upp = self.ppf([0.001,0.999],*args) + if np.isinf(self.b): + upper = upp + else: + upper = self.b + if np.isinf(self.a): + lower = low + else: + lower = self.a + return -scipy.integrate.quad(integ,lower,upper)[0] + def entropy(self, *args, **kwds): loc,scale=map(kwds.get,['loc','scale']) From scipy-svn at scipy.org Fri Nov 14 22:50:42 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 21:50:42 -0600 (CST) Subject: [Scipy-svn] r5113 - trunk/scipy/stats Message-ID: <20081115035042.3C7A239C088@scipy.org> Author: josef Date: 2008-11-14 21:50:40 -0600 (Fri, 14 Nov 2008) New Revision: 5113 Modified: trunk/scipy/stats/distributions.py Log: enable foldcauchy to calculate ppf for up to q=0.999 Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-15 03:48:48 UTC (rev 5112) +++ trunk/scipy/stats/distributions.py 2008-11-15 03:50:40 UTC (rev 5113) @@ -1489,7 +1489,8 @@ return 1.0/pi*(arctan(x-c) + arctan(x+c)) def _stats(self, c): return inf, inf, nan, nan -foldcauchy = foldcauchy_gen(a=0.0, name='foldcauchy', +# setting xb=1000 allows to calculate ppf for up to q=0.9993 +foldcauchy = foldcauchy_gen(a=0.0, name='foldcauchy',xb=1000, longname = "A folded Cauchy", shapes='c',extradoc=""" From scipy-svn at scipy.org Fri Nov 14 23:03:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 22:03:46 -0600 (CST) Subject: [Scipy-svn] r5114 - trunk/scipy/stats/tests Message-ID: <20081115040346.DBDE639C088@scipy.org> Author: josef Date: 2008-11-14 22:03:44 -0600 (Fri, 14 Nov 2008) New Revision: 5114 Modified: trunk/scipy/stats/tests/test_continuous_basic.py Log: small improvements to tests for continuous rv Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-15 03:50:40 UTC (rev 5113) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-15 04:03:44 UTC (rev 5114) @@ -22,7 +22,7 @@ ['anglit', ()], ['arcsine', ()], ['beta', (2.3098496451481823, 0.62687954300963677)], - ['betaprime', (100, 86)], + ['betaprime', (5, 6)], # avoid unbound error in entropy with (100, 86)], ['bradford', (0.29891359763170633,)], ['burr', (0.94839838075366045, 4.3820284068855795)], ['cauchy', ()], @@ -50,7 +50,7 @@ ['gengamma', (4.4162385429431925, 3.1193091679242761)], ['genhalflogistic', (0.77274727809929322,)], ['genlogistic', (0.41192440799679475,)], - ['genpareto', (4.4566867037959144,)], + ['genpareto', (0.1,)], # use case with finite moments ['gilbrat', ()], ['gompertz', (0.94743713075105251,)], ['gumbel_l', ()], @@ -135,14 +135,14 @@ m,v = distfn.stats(*arg) m1 = distfn.moment(1,*arg) m2 = distfn.moment(2,*arg) - if m < np.inf: + if not np.isinf(m): npt.assert_almost_equal(m1, m, decimal=10, err_msg= msg + \ ' - 1st moment') else: assert np.isinf(m1) or np.isnan(m1), \ msg + ' - 1st moment -infinite, m1=%s' % str(m1) #np.isnan(m1) temporary special treatment for loggamma - if v < np.inf: + if not np.isinf(v): npt.assert_almost_equal(m2-m1*m1, v, decimal=10, err_msg= msg + \ ' - 2ndt moment') else: @@ -161,16 +161,15 @@ check_sample_meanvar, ss, s, msg + 'sample kurtosis test' def check_sample_meanvar(sm,m,msg): - - if m < np.inf: + if not np.isinf(m): npt.assert_almost_equal(sm, m, decimal=DECIMAL, err_msg= msg + \ ' - finite moment') else: assert sm > 10000, 'infinite moment, sm = ' + str(sm) def check_cdf_ppf(distfn,arg,msg): - npt.assert_almost_equal(distfn.cdf(distfn.ppf([0.1,0.5,0.9], *arg), *arg), - [0.1,0.5,0.9], decimal=DECIMAL, err_msg= msg + \ + npt.assert_almost_equal(distfn.cdf(distfn.ppf([0.001,0.5,0.990], *arg), *arg), + [0.001,0.5,0.999], decimal=DECIMAL, err_msg= msg + \ ' - cdf-ppf roundtrip') def check_sf_isf(distfn,arg,msg): From scipy-svn at scipy.org Fri Nov 14 23:16:04 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 14 Nov 2008 22:16:04 -0600 (CST) Subject: [Scipy-svn] r5115 - trunk/scipy/stats/tests Message-ID: <20081115041604.5ADC439C05F@scipy.org> Author: josef Date: 2008-11-14 22:16:00 -0600 (Fri, 14 Nov 2008) New Revision: 5115 Modified: trunk/scipy/stats/tests/test_continuous_extra.py Log: corrections to tests, add loc and scale test for continuous rv stats Modified: trunk/scipy/stats/tests/test_continuous_extra.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-15 04:03:44 UTC (rev 5114) +++ trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-15 04:16:00 UTC (rev 5115) @@ -16,29 +16,52 @@ ## sv = rvs.var() ## skurt = stats.kurtosis(rvs) ## sskew = stats.skew(rvs) + yield check_ppf_limits, distfn, arg, distname + \ ' ppf limit test' + yield check_isf_limits, distfn, arg, distname + \ + ' isf limit test' + yield check_loc_scale, distfn, arg, distname + \ + ' loc, scale test' + #entropy test checks only for isnan, currently 6 isnan + # +## yield check_entropy, distfn, arg, distname + \ +## ' loc, scale test' + def check_ppf_limits(distfn,arg,msg): below,low,upp,above = distfn.ppf([-1,0,1,2], *arg) #print distfn.name, distfn.a, low, distfn.b, upp - print distfn.name,below,low,upp,above + #print distfn.name,below,low,upp,above assert_equal_inf_nan(distfn.a,low, msg + 'ppf lower bound') assert_equal_inf_nan(distfn.b,upp, msg + 'ppf upper bound') assert np.isnan(below), msg + 'ppf out of bounds - below' assert np.isnan(above), msg + 'ppf out of bounds - above' -def check_ppf_limits(distfn,arg,msg): +def check_isf_limits(distfn,arg,msg): below,low,upp,above = distfn.isf([-1,0,1,2], *arg) #print distfn.name, distfn.a, low, distfn.b, upp - print distfn.name,below,low,upp,above - assert_equal_inf_nan(distfn.a,upp, msg + 'ppf lower bound') - assert_equal_inf_nan(distfn.b,low, msg + 'ppf upper bound') - assert np.isnan(below), msg + 'ppf out of bounds - below' - assert np.isnan(above), msg + 'ppf out of bounds - above' + #print distfn.name,below,low,upp,above + assert_equal_inf_nan(distfn.a,upp, msg + 'isf lower bound') + assert_equal_inf_nan(distfn.b,low, msg + 'isf upper bound') + assert np.isnan(below), msg + 'isf out of bounds - below' + assert np.isnan(above), msg + 'isf out of bounds - above' +def check_loc_scale(distfn,arg,msg): + m,v = distfn.stats(*arg) + loc, scale = 10.0, 10.0 + mt,vt = distfn.stats(loc=loc, scale=scale, *arg) + assert_equal_inf_nan(m*scale+loc,mt,msg + 'mean') + assert_equal_inf_nan(v*scale*scale,vt,msg + 'var') + +def check_entropy(distfn,arg,msg): + ent = distfn.entropy(*arg) + #print 'Entropy =', ent + assert not np.isnan(ent), msg + 'test Entropy is nan'\ + def assert_equal_inf_nan(v1,v2,msg): + assert not np.isnan(v1) if not np.isinf(v1): npt.assert_almost_equal(v1, v2, decimal=DECIMAL, err_msg= msg + \ ' - finite') @@ -49,7 +72,7 @@ if __name__ == "__main__": import nose #nose.run(argv=['', __file__]) - print distcont[:5] - test_cont_extra() + #print distcont[:5] + #test_cont_extra() nose.runmodule(argv=[__file__,'-s'], exit=False) From scipy-svn at scipy.org Sat Nov 15 07:28:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 15 Nov 2008 06:28:46 -0600 (CST) Subject: [Scipy-svn] r5116 - scipy-docs/trunk/source Message-ID: <20081115122846.1E41239C05F@scipy.org> Author: ptvirtan Date: 2008-11-15 06:28:35 -0600 (Sat, 15 Nov 2008) New Revision: 5116 Modified: scipy-docs/trunk/source/stats.rst Log: docs: include base class for discrete distributions, as mentioned by josefpktd. Modified: scipy-docs/trunk/source/stats.rst =================================================================== --- scipy-docs/trunk/source/stats.rst 2008-11-15 04:16:00 UTC (rev 5115) +++ scipy-docs/trunk/source/stats.rst 2008-11-15 12:28:35 UTC (rev 5116) @@ -7,7 +7,7 @@ This module contains a large number of probability distributions as well as a growing library of statistical functions. -Each included distribution is an instance of the class rv_continous: +Each included continuous distribution is an instance of the class rv_continous: .. autosummary:: :toctree: generated/ @@ -20,7 +20,19 @@ rv_continuous.isf rv_continuous.stats +Each discrete distribution is an instance of the class rv_discrete: +.. autosummary:: + :toctree: generated/ + + rv_discrete + rv_discrete.pmf + rv_discrete.cdf + rv_discrete.sf + rv_discrete.ppf + rv_discrete.isf + rv_discrete.stats + Continuous distributions ======================== From scipy-svn at scipy.org Sat Nov 15 16:09:31 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 15 Nov 2008 15:09:31 -0600 (CST) Subject: [Scipy-svn] r5117 - in trunk/scipy/sparse/linalg: . tests Message-ID: <20081115210931.C8E9339C088@scipy.org> Author: wnbell Date: 2008-11-15 15:09:27 -0600 (Sat, 15 Nov 2008) New Revision: 5117 Modified: trunk/scipy/sparse/linalg/interface.py trunk/scipy/sparse/linalg/tests/test_interface.py Log: added __mul__ to LinearOperator Modified: trunk/scipy/sparse/linalg/interface.py =================================================================== --- trunk/scipy/sparse/linalg/interface.py 2008-11-15 12:28:35 UTC (rev 5116) +++ trunk/scipy/sparse/linalg/interface.py 2008-11-15 21:09:27 UTC (rev 5117) @@ -48,6 +48,8 @@ <2x2 LinearOperator with unspecified dtype> >>> A.matvec( ones(2) ) array([ 2., 3.]) + >>> A * ones(2) + array([ 2., 3.]) """ def __init__( self, shape, matvec, rmatvec=None, matmat=None, dtype=None ): @@ -79,6 +81,14 @@ if dtype is not None: self.dtype = numpy.dtype(dtype) + def __mul__(self,x): + x = numpy.asarray(x) + + if numpy.rank(x.squeeze()) == 1: + return self.matvec(x) + else: + return self.matmat(x) + def __repr__(self): M,N = self.shape if hasattr(self,'dtype'): Modified: trunk/scipy/sparse/linalg/tests/test_interface.py =================================================================== --- trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-15 12:28:35 UTC (rev 5116) +++ trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-15 21:09:27 UTC (rev 5117) @@ -44,12 +44,16 @@ assert_equal(A.matvec(array([1,2,3])), [14,32]) assert_equal(A.matvec(array([[1],[2],[3]])), [[14],[32]]) + + assert_equal(A * array([1,2,3]), [14,32]) + assert_equal(A * array([[1],[2],[3]]), [[14],[32]]) assert_equal(A.rmatvec(array([1,2])), [9,12,15]) assert_equal(A.rmatvec(array([[1],[2]])), [[9],[12],[15]]) - assert_equal(A.matmat(array([[1,4],[2,5],[3,6]])), \ - [[14,32],[32,77]] ) + assert_equal(A.matmat(array([[1,4],[2,5],[3,6]])), [[14,32],[32,77]] ) + + assert_equal(A * array([[1,4],[2,5],[3,6]]), [[14,32],[32,77]] ) if hasattr(M,'dtype'): assert_equal(A.dtype, M.dtype) From scipy-svn at scipy.org Sun Nov 16 01:41:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 00:41:11 -0600 (CST) Subject: [Scipy-svn] r5118 - trunk/doc Message-ID: <20081116064111.A6D8E39C1EC@scipy.org> Author: jarrod.millman Date: 2008-11-16 00:41:09 -0600 (Sun, 16 Nov 2008) New Revision: 5118 Added: trunk/doc/releases/ Log: directory for release notes From scipy-svn at scipy.org Sun Nov 16 01:42:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 00:42:12 -0600 (CST) Subject: [Scipy-svn] r5119 - trunk/doc/releases Message-ID: <20081116064212.7318F39C1EC@scipy.org> Author: jarrod.millman Date: 2008-11-16 00:42:07 -0600 (Sun, 16 Nov 2008) New Revision: 5119 Added: trunk/doc/releases/0.7.0-notes.rst Log: adding notes from Damian Eads Added: trunk/doc/releases/0.7.0-notes.rst =================================================================== --- trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:41:09 UTC (rev 5118) +++ trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:42:07 UTC (rev 5119) @@ -0,0 +1,40 @@ +Hierarchical Clustering +======================= + +This module adds new hierarchical clustering functionality to the +cluster package. Its interface is similar to the hierarchical +clustering functions provided in MATLAB(TM)'s Statistics Toolbox to +facilitate easier migration to the NumPy/SciPy framework. Linkage +methods implemented include single, complete, average, weighted, +centroid, median, and ward. Several functions are provided for +computing statistics on clusters including inconsistency statistics, +cophenetic distance, and maximum distance of descendants. The fcluster +and fclusterdata functions take hierarchical tree clusterings +generated by these algorithms, cuts the tree, and labels the flat +clusters. The leaders function finds the root of each flat cluster +given a hierarchical clustering and labellings of its leaves. Finally, a +matplotlib extension is provided for plotting dendrograms, which +may be outputted to postscript or any other supported format. + +Spatial Package +=============== + +The new scipy.spatial package provides routines for distance computation +and kd-tree manipulation. + +Distance Module +---------------- + +Provides a multitude of common distance functions useful for spatial +statistics, clustering, and kd-trees. Distance and dissimilarity +functions provided include Bray-Curtis, Canberra, Chebyshev, City +Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, +Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, +Squared Euclidean, Standardized Euclidean, Sokal-Michener, +Sokal-Sneath, and Yule. Two functions are provided for computing +distances between collections of vectors: pdist and cdist. pdist +is similar to the MATLAB(TM) function and computes pairwise distances +between a collection of vectors. cdist computes distances between +vectors in two sets of vectors. squareform is useful for converting +a square distance matrix to a condensed matrix and vice versa. + From scipy-svn at scipy.org Sun Nov 16 01:47:08 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 00:47:08 -0600 (CST) Subject: [Scipy-svn] r5120 - trunk/doc/releases Message-ID: <20081116064708.3FC3F39C1EC@scipy.org> Author: jarrod.millman Date: 2008-11-16 00:47:06 -0600 (Sun, 16 Nov 2008) New Revision: 5120 Modified: trunk/doc/releases/0.7.0-notes.rst Log: merge notes from wiki Modified: trunk/doc/releases/0.7.0-notes.rst =================================================================== --- trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:42:07 UTC (rev 5119) +++ trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:47:06 UTC (rev 5120) @@ -1,3 +1,14 @@ +This is a new stable release. Please note that unlike previous versions of !SciPy, this release requires Python 2.4 or greater. This release also requires !NumPy 1.2.0 or greater. + += Changes = + +== scipy.io == + +The IO code in both !NumPy and !SciPy is undergoing a major reworking. !NumPy will be where basic code for reading and writing !NumPy arrays is located, while !SciPy will house file readers and writers for various data formats (data, audio, video, images, matlab, excel, etc.). This will take place in stages. The first stage was completed with the release of !NumPy 1.1.0. As part of this phase: + * many of the functions in scipy.io have been deprecated + +mention specific improvements to io, e.g. MATLAB sparse support (TODO) + Hierarchical Clustering ======================= @@ -38,3 +49,73 @@ vectors in two sets of vectors. squareform is useful for converting a square distance matrix to a condensed matrix and vice versa. + +== scipy.fftpack == +FFTW2, FFTW3, MKL and DJBFFT wrappers have been removed. Only (NETLIB) fftpack remains. By focusing on one backend, we hope to add new features - like float32 support - more easily. + +=== scipy.io.matlab === + +The Matlab (TM) file readers/writers have a number of improvements: + * default version 5 + +== scipy.sparse == + * added support for integer dtypes such `int8`, `uint32`, etc. + * new class `dia_matrix` : the sparse DIAgonal format + * new class `bsr_matrix` : sparse Block CSR format + * new sparse matrix construction functions + * `sparse.kron` : sparse Kronecker product + * `sparse.bmat` : sparse version of `numpy.bmat` + * `sparse.vstack` : sparse version of `numpy.vstack` + * `sparse.hstack` : sparse version of `numpy.hstack` + * extraction of submatrices and nonzero values + * `sparse.tril` : extract lower triangle + * `sparse.kron` : extract upper triangle + * `sparse.find` : nonzero values and their indices + * `csr_matrix` and `csc_matrix` now support slicing and fancy indexing + * e.g. `A[1:3, 4:7]` and `A[[3,2,6,8],:]` + * conversions among all sparse formats are now possible + * all formats have member functions such as `.tocsr()` and `.tolil()` + * sparse constructors now accept dense matrices and other sparse formats + * e.g. `A = csr_matrix( rand(3,3) )` and `B = lil_matrix( [[1,2],[3,4]] )` + * efficiency improvements to: + * format conversions + * sparse matrix arithmetic + * numerous bugfixes + +== New Spatial package == +Collection of spatial algorithms and data structures useful for spatial statistics and clustering applications. Includes fast compiled code for computing exact and approximate nearest neighbors, as well as a pure-python kd-tree with the same interface but that supports annotation and a variety of other algorithms. The API for both modules may change somewhat as user requirements become clearer. Also includes a submodule "distance" containing fast code for many definitions of "distance" between vectors. Distance and dissimilarity functions are provided include Bray-Curtis, Canberra, Chebyshev, City Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, Squared Euclidean, Standardized Euclidean, Sokal-Michener, Sokal-Sneath, and Yule. Two functions are provided for computing distances between collections of vectors: pdist and cdist. pdist is similar to the MATLAB(TM) function and computes pairwise distances between a collection of vectors. cdist computes distances between vectors in two sets of vectors. squareform converts between square distance matrices and condensed distance matrices. + +== New Constants package == +Collection of physical constants and conversion factors: +http://scipy.org/scipy/scipy/browser/trunk/scipy/constants/ + +== New Hierarchical Clustering module == +This module adds new hierarchical clustering functionality to the +cluster package. Its interface is similar to the hierarchical +clustering functions provided in MATLAB(TM)'s Statistics Toolbox to +facilitate easier migration to the NumPy/SciPy framework. Linkage +methods implemented include single, complete, average, weighted, +centroid, median, and ward. Several functions are provided for +computing statistics on clusters including inconsistency statistics, +cophenetic distance, and maximum distance of descendants. The fcluster +and fclusterdata functions take hierarchical tree clusterings +generated by these algorithms, cuts the tree, and labels the flat +clusters. The leaders function finds the root of each flat cluster +given a hierarchical clustering and labellings of its leaves. Finally, a +matplotlib extension is provided for plotting dendrograms, which +may be outputted to postscript or any other supported format. + +http://scipy.org/scipy/scipy/browser/trunk/scipy/cluster/hierarchy.py + +== New Radial Basis Function module == +http://scipy.org/scipy/scipy/browser/trunk/scipy/interpolate/rbf.py + +== Improved documentation == + +TODO + +== Running Tests == +We are moving away from having our own testing framework and are adopting [http://code.google.com/p/python-nose/ nose]. + +== Building !SciPy == +Support for !NumScons has been added. numscons is a tentative new build system for numpy/scipy, using scons at its core. From scipy-svn at scipy.org Sun Nov 16 01:57:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 00:57:03 -0600 (CST) Subject: [Scipy-svn] r5121 - trunk/doc/releases Message-ID: <20081116065703.08FDA39C088@scipy.org> Author: jarrod.millman Date: 2008-11-16 00:57:02 -0600 (Sun, 16 Nov 2008) New Revision: 5121 Modified: trunk/doc/releases/0.7.0-notes.rst Log: rest clean-up Modified: trunk/doc/releases/0.7.0-notes.rst =================================================================== --- trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:47:06 UTC (rev 5120) +++ trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:57:02 UTC (rev 5121) @@ -1,13 +1,26 @@ -This is a new stable release. Please note that unlike previous versions of !SciPy, this release requires Python 2.4 or greater. This release also requires !NumPy 1.2.0 or greater. +========================= +SciPy 0.7.0 Release Notes +========================= -= Changes = +This is a new stable release. Please note that unlike previous versions +of SciPy, this release requires Python 2.4 or greater. This release also +requires NumPy 1.2.0 or greater. -== scipy.io == +Changes +------- -The IO code in both !NumPy and !SciPy is undergoing a major reworking. !NumPy will be where basic code for reading and writing !NumPy arrays is located, while !SciPy will house file readers and writers for various data formats (data, audio, video, images, matlab, excel, etc.). This will take place in stages. The first stage was completed with the release of !NumPy 1.1.0. As part of this phase: - * many of the functions in scipy.io have been deprecated +SciPy IO +~~~~~~~~ -mention specific improvements to io, e.g. MATLAB sparse support (TODO) +The IO code in both NumPy and SciPy is undergoing a major reworking. NumPy +will be where basic code for reading and writing NumPy arrays is located, +while SciPy will house file readers and writers for various data formats +(data, audio, video, images, matlab, excel, etc.). This reworking started +NumPy 1.1.0 and will take place over many release. SciPy 0.7.0 has several +changes including: +* many of the functions in scipy.io have been deprecated +* the Matlab (TM) file readers/writers have a number of improvements: + * default version 5 Hierarchical Clustering ======================= @@ -27,12 +40,34 @@ matplotlib extension is provided for plotting dendrograms, which may be outputted to postscript or any other supported format. +== New Hierarchical Clustering module == +This module adds new hierarchical clustering functionality to the +cluster package. Its interface is similar to the hierarchical +clustering functions provided in MATLAB(TM)'s Statistics Toolbox to +facilitate easier migration to the NumPy/SciPy framework. Linkage +methods implemented include single, complete, average, weighted, +centroid, median, and ward. Several functions are provided for +computing statistics on clusters including inconsistency statistics, +cophenetic distance, and maximum distance of descendants. The fcluster +and fclusterdata functions take hierarchical tree clusterings +generated by these algorithms, cuts the tree, and labels the flat +clusters. The leaders function finds the root of each flat cluster +given a hierarchical clustering and labellings of its leaves. Finally, a +matplotlib extension is provided for plotting dendrograms, which +may be outputted to postscript or any other supported format. + +http://scipy.org/scipy/scipy/browser/trunk/scipy/cluster/hierarchy.py + Spatial Package =============== The new scipy.spatial package provides routines for distance computation and kd-tree manipulation. +== New Spatial package == +Collection of spatial algorithms and data structures useful for spatial statistics and clustering applications. Includes fast compiled code for computing exact and approximate nearest neighbors, as well as a pure-python kd-tree with the same interface but that supports annotation and a variety of other algorithms. The API for both modules may change somewhat as user requirements become clearer. Also includes a submodule "distance" containing fast code for many definitions of "distance" between vectors. Distance and dissimilarity functions are provided include Bray-Curtis, Canberra, Chebyshev, City Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, Squared Euclidean, Standardized Euclidean, Sokal-Michener, Sokal-Sneath, and Yule. Two functions are provided for computing distances between collections of vectors: pdist and cdist. pdist is similar to the MATLAB(TM) function and computes pairwise distances between a collection of vectors. cdist computes distances between vectors in two sets of vectors. squareform converts between square distance matrices and condensed distance matrices. + + Distance Module ---------------- @@ -50,15 +85,16 @@ a square distance matrix to a condensed matrix and vice versa. -== scipy.fftpack == -FFTW2, FFTW3, MKL and DJBFFT wrappers have been removed. Only (NETLIB) fftpack remains. By focusing on one backend, we hope to add new features - like float32 support - more easily. +fftpack +~~~~~~~ -=== scipy.io.matlab === +FFTW2, FFTW3, MKL and DJBFFT wrappers have been removed. Only (NETLIB) +fftpack remains. By focusing on one backend, we hope to add new +features -- like float32 support -- more easily. -The Matlab (TM) file readers/writers have a number of improvements: - * default version 5 +Sparse Matrices +~~~~~~~~~~~~~~~ -== scipy.sparse == * added support for integer dtypes such `int8`, `uint32`, etc. * new class `dia_matrix` : the sparse DIAgonal format * new class `bsr_matrix` : sparse Block CSR format @@ -82,31 +118,11 @@ * sparse matrix arithmetic * numerous bugfixes -== New Spatial package == -Collection of spatial algorithms and data structures useful for spatial statistics and clustering applications. Includes fast compiled code for computing exact and approximate nearest neighbors, as well as a pure-python kd-tree with the same interface but that supports annotation and a variety of other algorithms. The API for both modules may change somewhat as user requirements become clearer. Also includes a submodule "distance" containing fast code for many definitions of "distance" between vectors. Distance and dissimilarity functions are provided include Bray-Curtis, Canberra, Chebyshev, City Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, Squared Euclidean, Standardized Euclidean, Sokal-Michener, Sokal-Sneath, and Yule. Two functions are provided for computing distances between collections of vectors: pdist and cdist. pdist is similar to the MATLAB(TM) function and computes pairwise distances between a collection of vectors. cdist computes distances between vectors in two sets of vectors. squareform converts between square distance matrices and condensed distance matrices. - == New Constants package == Collection of physical constants and conversion factors: http://scipy.org/scipy/scipy/browser/trunk/scipy/constants/ -== New Hierarchical Clustering module == -This module adds new hierarchical clustering functionality to the -cluster package. Its interface is similar to the hierarchical -clustering functions provided in MATLAB(TM)'s Statistics Toolbox to -facilitate easier migration to the NumPy/SciPy framework. Linkage -methods implemented include single, complete, average, weighted, -centroid, median, and ward. Several functions are provided for -computing statistics on clusters including inconsistency statistics, -cophenetic distance, and maximum distance of descendants. The fcluster -and fclusterdata functions take hierarchical tree clusterings -generated by these algorithms, cuts the tree, and labels the flat -clusters. The leaders function finds the root of each flat cluster -given a hierarchical clustering and labellings of its leaves. Finally, a -matplotlib extension is provided for plotting dendrograms, which -may be outputted to postscript or any other supported format. -http://scipy.org/scipy/scipy/browser/trunk/scipy/cluster/hierarchy.py - == New Radial Basis Function module == http://scipy.org/scipy/scipy/browser/trunk/scipy/interpolate/rbf.py @@ -114,8 +130,14 @@ TODO -== Running Tests == -We are moving away from having our own testing framework and are adopting [http://code.google.com/p/python-nose/ nose]. +Running Tests +~~~~~~~~~~~~~ -== Building !SciPy == -Support for !NumScons has been added. numscons is a tentative new build system for numpy/scipy, using scons at its core. +We are moving away from having our own testing framework and are +adopting `nose `. + +Building SciPy +~~~~~~~~~~~~~~ + +Support for !NumScons has been added. numscons is a tentative new +build system for numpy/scipy, using scons at its core. From scipy-svn at scipy.org Sun Nov 16 02:03:52 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 01:03:52 -0600 (CST) Subject: [Scipy-svn] r5122 - trunk/doc/releases Message-ID: <20081116070352.2E14439C088@scipy.org> Author: jarrod.millman Date: 2008-11-16 01:03:50 -0600 (Sun, 16 Nov 2008) New Revision: 5122 Modified: trunk/doc/releases/0.7.0-notes.rst Log: more rest clean-up Modified: trunk/doc/releases/0.7.0-notes.rst =================================================================== --- trunk/doc/releases/0.7.0-notes.rst 2008-11-16 06:57:02 UTC (rev 5121) +++ trunk/doc/releases/0.7.0-notes.rst 2008-11-16 07:03:50 UTC (rev 5122) @@ -9,6 +9,32 @@ Changes ------- +Sparse Matrices +~~~~~~~~~~~~~~~ + +* added support for integer dtypes such ``int8``, ``uint32``, etc. +* new class ``dia_matrix`` : the sparse DIAgonal format +* new class ``bsr_matrix`` : sparse Block CSR format +* new sparse matrix construction functions + * ``sparse.kron`` : sparse Kronecker product + * ``sparse.bmat`` : sparse version of ``numpy.bmat`` + * ``sparse.vstack`` : sparse version of ``numpy.vstack`` + * ``sparse.hstack`` : sparse version of ``numpy.hstack`` +* extraction of submatrices and nonzero values + * ``sparse.tril`` : extract lower triangle + * ``sparse.kron`` : extract upper triangle + * ``sparse.find`` : nonzero values and their indices +* ``csr_matrix`` and ``csc_matrix`` now support slicing and fancy indexing + * e.g. ``A[1:3, 4:7]`` and ``A[[3,2,6,8],:]`` +* conversions among all sparse formats are now possible + * all formats have member functions such as ``.tocsr()`` and ``.tolil()`` +* sparse constructors now accept dense matrices and other sparse formats + * e.g. ``A = csr_matrix( rand(3,3) )`` and ``B = lil_matrix( [[1,2],[3,4]] )`` +* efficiency improvements to: + * format conversions + * sparse matrix arithmetic +* numerous bugfixes + SciPy IO ~~~~~~~~ @@ -18,6 +44,7 @@ (data, audio, video, images, matlab, excel, etc.). This reworking started NumPy 1.1.0 and will take place over many release. SciPy 0.7.0 has several changes including: + * many of the functions in scipy.io have been deprecated * the Matlab (TM) file readers/writers have a number of improvements: * default version 5 @@ -92,32 +119,7 @@ fftpack remains. By focusing on one backend, we hope to add new features -- like float32 support -- more easily. -Sparse Matrices -~~~~~~~~~~~~~~~ - * added support for integer dtypes such `int8`, `uint32`, etc. - * new class `dia_matrix` : the sparse DIAgonal format - * new class `bsr_matrix` : sparse Block CSR format - * new sparse matrix construction functions - * `sparse.kron` : sparse Kronecker product - * `sparse.bmat` : sparse version of `numpy.bmat` - * `sparse.vstack` : sparse version of `numpy.vstack` - * `sparse.hstack` : sparse version of `numpy.hstack` - * extraction of submatrices and nonzero values - * `sparse.tril` : extract lower triangle - * `sparse.kron` : extract upper triangle - * `sparse.find` : nonzero values and their indices - * `csr_matrix` and `csc_matrix` now support slicing and fancy indexing - * e.g. `A[1:3, 4:7]` and `A[[3,2,6,8],:]` - * conversions among all sparse formats are now possible - * all formats have member functions such as `.tocsr()` and `.tolil()` - * sparse constructors now accept dense matrices and other sparse formats - * e.g. `A = csr_matrix( rand(3,3) )` and `B = lil_matrix( [[1,2],[3,4]] )` - * efficiency improvements to: - * format conversions - * sparse matrix arithmetic - * numerous bugfixes - == New Constants package == Collection of physical constants and conversion factors: http://scipy.org/scipy/scipy/browser/trunk/scipy/constants/ From scipy-svn at scipy.org Sun Nov 16 02:04:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 01:04:51 -0600 (CST) Subject: [Scipy-svn] r5123 - trunk/doc/releases Message-ID: <20081116070451.6E8A239C088@scipy.org> Author: jarrod.millman Date: 2008-11-16 01:04:50 -0600 (Sun, 16 Nov 2008) New Revision: 5123 Modified: trunk/doc/releases/0.7.0-notes.rst Log: rest whitespace fixes Modified: trunk/doc/releases/0.7.0-notes.rst =================================================================== --- trunk/doc/releases/0.7.0-notes.rst 2008-11-16 07:03:50 UTC (rev 5122) +++ trunk/doc/releases/0.7.0-notes.rst 2008-11-16 07:04:50 UTC (rev 5123) @@ -16,23 +16,35 @@ * new class ``dia_matrix`` : the sparse DIAgonal format * new class ``bsr_matrix`` : sparse Block CSR format * new sparse matrix construction functions + * ``sparse.kron`` : sparse Kronecker product * ``sparse.bmat`` : sparse version of ``numpy.bmat`` * ``sparse.vstack`` : sparse version of ``numpy.vstack`` * ``sparse.hstack`` : sparse version of ``numpy.hstack`` + * extraction of submatrices and nonzero values + * ``sparse.tril`` : extract lower triangle * ``sparse.kron`` : extract upper triangle * ``sparse.find`` : nonzero values and their indices + * ``csr_matrix`` and ``csc_matrix`` now support slicing and fancy indexing + * e.g. ``A[1:3, 4:7]`` and ``A[[3,2,6,8],:]`` + * conversions among all sparse formats are now possible + * all formats have member functions such as ``.tocsr()`` and ``.tolil()`` + * sparse constructors now accept dense matrices and other sparse formats + * e.g. ``A = csr_matrix( rand(3,3) )`` and ``B = lil_matrix( [[1,2],[3,4]] )`` + * efficiency improvements to: + * format conversions * sparse matrix arithmetic + * numerous bugfixes SciPy IO From scipy-svn at scipy.org Sun Nov 16 02:28:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 01:28:26 -0600 (CST) Subject: [Scipy-svn] r5124 - trunk/doc/releases Message-ID: <20081116072826.109D239C088@scipy.org> Author: jarrod.millman Date: 2008-11-16 01:28:23 -0600 (Sun, 16 Nov 2008) New Revision: 5124 Modified: trunk/doc/releases/0.7.0-notes.rst Log: more rest clean-up Modified: trunk/doc/releases/0.7.0-notes.rst =================================================================== --- trunk/doc/releases/0.7.0-notes.rst 2008-11-16 07:04:50 UTC (rev 5123) +++ trunk/doc/releases/0.7.0-notes.rst 2008-11-16 07:28:23 UTC (rev 5124) @@ -47,8 +47,8 @@ * numerous bugfixes -SciPy IO -~~~~~~~~ +Reworking of IO package +~~~~~~~~~~~~~~~~~~~~~~~ The IO code in both NumPy and SciPy is undergoing a major reworking. NumPy will be where basic code for reading and writing NumPy arrays is located, @@ -59,10 +59,11 @@ * many of the functions in scipy.io have been deprecated * the Matlab (TM) file readers/writers have a number of improvements: + * default version 5 -Hierarchical Clustering -======================= +New Hierarchical Clustering module +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module adds new hierarchical clustering functionality to the cluster package. Its interface is similar to the hierarchical @@ -79,68 +80,49 @@ matplotlib extension is provided for plotting dendrograms, which may be outputted to postscript or any other supported format. -== New Hierarchical Clustering module == -This module adds new hierarchical clustering functionality to the -cluster package. Its interface is similar to the hierarchical -clustering functions provided in MATLAB(TM)'s Statistics Toolbox to -facilitate easier migration to the NumPy/SciPy framework. Linkage -methods implemented include single, complete, average, weighted, -centroid, median, and ward. Several functions are provided for -computing statistics on clusters including inconsistency statistics, -cophenetic distance, and maximum distance of descendants. The fcluster -and fclusterdata functions take hierarchical tree clusterings -generated by these algorithms, cuts the tree, and labels the flat -clusters. The leaders function finds the root of each flat cluster -given a hierarchical clustering and labellings of its leaves. Finally, a -matplotlib extension is provided for plotting dendrograms, which -may be outputted to postscript or any other supported format. +New Spatial package +~~~~~~~~~~~~~~~~~~~ -http://scipy.org/scipy/scipy/browser/trunk/scipy/cluster/hierarchy.py +Collection of spatial algorithms and data structures useful for spatial +statistics and clustering applications. Includes fast compiled code for +computing exact and approximate nearest neighbors, as well as a pure-python +kd-tree with the same interface but that supports annotation and a variety +of other algorithms. The API for both modules may change somewhat as user +requirements become clearer. -Spatial Package -=============== - -The new scipy.spatial package provides routines for distance computation -and kd-tree manipulation. - -== New Spatial package == -Collection of spatial algorithms and data structures useful for spatial statistics and clustering applications. Includes fast compiled code for computing exact and approximate nearest neighbors, as well as a pure-python kd-tree with the same interface but that supports annotation and a variety of other algorithms. The API for both modules may change somewhat as user requirements become clearer. Also includes a submodule "distance" containing fast code for many definitions of "distance" between vectors. Distance and dissimilarity functions are provided include Bray-Curtis, Canberra, Chebyshev, City Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, Squared Euclidean, Standardized Euclidean, Sokal-Michener, Sokal-Sneath, and Yule. Two functions are provided for computing distances between collections of vectors: pdist and cdist. pdist is similar to the MATLAB(TM) function and computes pairwise distances between a collection of vectors. cdist computes distances between vectors in two sets of vectors. squareform converts between square distance matrices and condensed distance matrices. - - -Distance Module ----------------- - -Provides a multitude of common distance functions useful for spatial -statistics, clustering, and kd-trees. Distance and dissimilarity -functions provided include Bray-Curtis, Canberra, Chebyshev, City -Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, +Also includes a submodule ``distance`` containing fast code for many definitions +of *distance* between vectors. These common distance functions are useful for +for many agorthms including spatial statistics, clustering, and kd-trees. +Distance and dissimilarity functions provided include Bray-Curtis, Canberra, +Chebyshev, City Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, -Squared Euclidean, Standardized Euclidean, Sokal-Michener, -Sokal-Sneath, and Yule. Two functions are provided for computing -distances between collections of vectors: pdist and cdist. pdist -is similar to the MATLAB(TM) function and computes pairwise distances -between a collection of vectors. cdist computes distances between -vectors in two sets of vectors. squareform is useful for converting -a square distance matrix to a condensed matrix and vice versa. +Squared Euclidean, Standardized Euclidean, Sokal-Michener, Sokal-Sneath, +and Yule. Two functions are provided for computing distances between +collections of vectors: ``pdist`` and ``cdist``. ``pdist`` is similar to the +MATLAB(TM) function and computes pairwise distances between a collection of +vectors. ``cdist`` computes distances between vectors in two sets of vectors. +``squareform`` converts between square distance matrices and condensed +distance matrices. +Reworked fftpack package +~~~~~~~~~~~~~~~~~~~~~~~~ -fftpack -~~~~~~~ - FFTW2, FFTW3, MKL and DJBFFT wrappers have been removed. Only (NETLIB) fftpack remains. By focusing on one backend, we hope to add new features -- like float32 support -- more easily. +New Constants package +~~~~~~~~~~~~~~~~~~~~~ -== New Constants package == -Collection of physical constants and conversion factors: -http://scipy.org/scipy/scipy/browser/trunk/scipy/constants/ +Collection of physical constants and conversion factors. +New Radial Basis Function module +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -== New Radial Basis Function module == http://scipy.org/scipy/scipy/browser/trunk/scipy/interpolate/rbf.py -== Improved documentation == +Major documentation improvements +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TODO @@ -153,5 +135,5 @@ Building SciPy ~~~~~~~~~~~~~~ -Support for !NumScons has been added. numscons is a tentative new -build system for numpy/scipy, using scons at its core. +Support for NumScons has been added. NumScons is a tentative new +build system for NumPy/SciPy, using scons at its core. From scipy-svn at scipy.org Sun Nov 16 02:44:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 01:44:18 -0600 (CST) Subject: [Scipy-svn] r5125 - trunk/doc Message-ID: <20081116074418.7B14F39C088@scipy.org> Author: jarrod.millman Date: 2008-11-16 01:44:16 -0600 (Sun, 16 Nov 2008) New Revision: 5125 Added: trunk/doc/release/ Removed: trunk/doc/releases/ Log: remove unneeded 's' Copied: trunk/doc/release (from rev 5124, trunk/doc/releases) From scipy-svn at scipy.org Sun Nov 16 04:24:01 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 03:24:01 -0600 (CST) Subject: [Scipy-svn] r5126 - in trunk: scipy/cluster/tests scipy/interpolate scipy/interpolate/tests scipy/io/matlab scipy/io/matlab/tests scipy/lib/lapack/tests scipy/linalg/tests scipy/signal scipy/sparse scipy/sparse/linalg/isolve scipy/sparse/linalg/isolve/tests scipy/sparse/linalg/tests scipy/sparse/tests scipy/spatial scipy/spatial/tests scipy/stats scipy/stats/tests tools/win32/build_scripts Message-ID: <20081116092401.8F1DA39C088@scipy.org> Author: jarrod.millman Date: 2008-11-16 03:23:48 -0600 (Sun, 16 Nov 2008) New Revision: 5126 Modified: trunk/scipy/cluster/tests/test_hierarchy.py trunk/scipy/interpolate/interpolate.py trunk/scipy/interpolate/interpolate_wrapper.py trunk/scipy/interpolate/tests/test_fitpack.py trunk/scipy/interpolate/tests/test_interpolate.py trunk/scipy/io/matlab/mio.py trunk/scipy/io/matlab/mio4.py trunk/scipy/io/matlab/mio5.py trunk/scipy/io/matlab/miobase.py trunk/scipy/io/matlab/tests/test_mio.py trunk/scipy/lib/lapack/tests/common.py trunk/scipy/lib/lapack/tests/test_esv.py trunk/scipy/lib/lapack/tests/test_gesv.py trunk/scipy/lib/lapack/tests/test_lapack.py trunk/scipy/linalg/tests/test_decomp.py trunk/scipy/signal/signaltools.py trunk/scipy/sparse/data.py trunk/scipy/sparse/lil.py trunk/scipy/sparse/linalg/isolve/iterative.py trunk/scipy/sparse/linalg/isolve/minres.py trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py trunk/scipy/sparse/linalg/tests/test_interface.py trunk/scipy/sparse/sputils.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/spatial/distance.py trunk/scipy/spatial/kdtree.py trunk/scipy/spatial/tests/test_kdtree.py trunk/scipy/stats/distributions.py trunk/scipy/stats/tests/test_stats.py trunk/tools/win32/build_scripts/pavement.py Log: ran reindent for upcoming release Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -461,7 +461,7 @@ b = [2, 2, 2] self.failUnless(is_isomorphic(a, b) == True) self.failUnless(is_isomorphic(b, a) == True) - + def test_is_isomorphic_2(self): "Tests is_isomorphic on test case #2 (two flat clusters, different labelings)" a = [1, 7, 1] @@ -529,7 +529,7 @@ def help_is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0): a = np.int_(np.random.rand(nobs) * nclusters) b = np.zeros(a.size, dtype=np.int_) - q = {} + q = {} P = np.random.permutation(nclusters) for i in xrange(0, a.shape[0]): b[i] = P[a[i]] @@ -699,4 +699,3 @@ if __name__ == "__main__": run_module_suite() - Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/interpolate/interpolate.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -94,7 +94,7 @@ def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=np.nan): self.x, self.y, self.z = map(ravel, map(asarray, [x, y, z])) - + if len(self.z) == len(self.x) * len(self.y): self.x, self.y = meshgrid(x,y) self.x, self.y = map(ravel, [self.x, self.y]) @@ -130,7 +130,7 @@ ------- z : 2D array with shape (len(y), len(x)) The interpolated values. - + """ x = atleast_1d(x) Modified: trunk/scipy/interpolate/interpolate_wrapper.py =================================================================== --- trunk/scipy/interpolate/interpolate_wrapper.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/interpolate/interpolate_wrapper.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -14,19 +14,19 @@ and returns corresponding y. """ shifted_x = np.concatenate(( np.array([x[0]-1]) , x[0:-1] )) - + midpoints_of_x = atleast_1d_and_contiguous( .5*(x + shifted_x) ) new_x = atleast_1d_and_contiguous(new_x) - + TINY = 1e-10 indices = np.searchsorted(midpoints_of_x, new_x+TINY)-1 indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(np.int)) new_y = np.take(y, indices, axis=-1) - + return new_y - - + + def linear(x, y, new_x): """ Linearly interpolates values in new_x based on the values in x and y @@ -80,7 +80,7 @@ _interpolate.loginterp_dddd(x, y, new_x, new_y) return new_y - + def block_average_above(x, y, new_x): """ Linearly interpolates values in new_x based on the values in x and y @@ -102,10 +102,10 @@ if len(y.shape) == 2: new_y = np.zeros((y.shape[0], len(new_x)), np.float64) for i in range(len(new_y)): - bad_index = _interpolate.block_averave_above_dddd(x, y[i], + bad_index = _interpolate.block_averave_above_dddd(x, y[i], new_x, new_y[i]) if bad_index is not None: - break + break else: new_y = np.zeros(len(new_x), np.float64) bad_index = _interpolate.block_average_above_dddd(x, y, new_x, new_y) @@ -115,12 +115,12 @@ "is out of the x range (%f, %f)" % \ (bad_index, new_x[bad_index], x[0], x[-1]) raise ValueError, msg - + return new_y def block(x, y, new_x): """ Essentially a step function. - + For each new_x[i], finds largest j such that x[j] < new_x[j], and returns y[j]. """ Modified: trunk/scipy/interpolate/tests/test_fitpack.py =================================================================== --- trunk/scipy/interpolate/tests/test_fitpack.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/interpolate/tests/test_fitpack.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -38,11 +38,11 @@ def test_subclassing(self): # See #731 - + class ZeroSpline(UnivariateSpline): def __call__(self, x): return 0*array(x) - + sp = ZeroSpline([1,2,3,4,5], [3,2,3,2,3], k=2) assert_array_equal(sp([1.5, 2.5]), [0., 0.]) Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -14,7 +14,7 @@ v,u = ogrid[0:2:24j, 0:pi:25j] assert_almost_equal(I(u.ravel(), v.ravel()), sin(u+0.5*v), decimal=2) - + def test_interp2d_meshgrid_input(self): # Ticket #703 x = linspace(0, 2, 16) Modified: trunk/scipy/io/matlab/mio.py =================================================================== --- trunk/scipy/io/matlab/mio.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/io/matlab/mio.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -51,8 +51,8 @@ def mat_reader_factory(file_name, appendmat=True, **kwargs): """Create reader for matlab .mat format files - %(file_arg)s - %(append_arg)s + %(file_arg)s + %(append_arg)s %(basename_arg)s %(load_args)s %(struct_arg)s @@ -91,14 +91,14 @@ def loadmat(file_name, mdict=None, appendmat=True, **kwargs): ''' Load Matlab(tm) file - %(file_arg)s + %(file_arg)s m_dict : dict, optional dictionary in which to insert matfile variables - %(append_arg)s + %(append_arg)s %(basename_arg)s %(load_args)s %(struct_arg)s - + Notes ----- v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported. @@ -124,13 +124,13 @@ file_name : {string, file-like object} Name of the mat file (do not need .mat extension if - appendmat==True) Can also pass open file-like object + appendmat==True) Can also pass open file-like object m_dict : dict dictionary from which to save matfile variables %(append_arg)s format : {'5', '4'} string, optional '5' for matlab 5 (up to matlab 7.2) - '4' for matlab 4 mat files, + '4' for matlab 4 mat files, """ file_is_string = isinstance(file_name, basestring) if file_is_string: Modified: trunk/scipy/io/matlab/mio4.py =================================================================== --- trunk/scipy/io/matlab/mio4.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/io/matlab/mio4.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -190,7 +190,7 @@ @filldoc def __init__(self, mat_stream, *args, **kwargs): ''' Initialize matlab 4 file reader - + %(matstream_arg)s %(load_args)s ''' Modified: trunk/scipy/io/matlab/mio5.py =================================================================== --- trunk/scipy/io/matlab/mio5.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/io/matlab/mio5.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -196,8 +196,8 @@ ''' Subclass to signal this is a matlab function ''' def __new__(cls, input_array): obj = np.asarray(input_array).view(cls) - + class Mat5ArrayReader(MatArrayReader): ''' Class to get Mat5 arrays @@ -516,7 +516,7 @@ uint16_codec=None ): '''Initializer for matlab 5 file format reader - + %(matstream_arg)s %(load_args)s %(struct_arg)s @@ -527,7 +527,7 @@ # Deal with deprecations if struct_as_record is None: warnings.warn("Using struct_as_record default value (False)" + - " This will change to True in future versions", + " This will change to True in future versions", FutureWarning, stacklevel=2) struct_as_record = False self.codecs = {} @@ -629,7 +629,7 @@ super(Mat5MatrixWriter, self).__init__(file_stream, arr, name) self.is_global = is_global self.unicode_strings = unicode_strings - + def write_dtype(self, arr): self.file_stream.write(arr.tostring()) Modified: trunk/scipy/io/matlab/miobase.py =================================================================== --- trunk/scipy/io/matlab/miobase.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/io/matlab/miobase.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -14,14 +14,14 @@ {'file_arg': '''file_name : string Name of the mat file (do not need .mat extension if - appendmat==True) If name not a full path name, search for the - file on the sys.path list and use the first one found (the - current directory is searched first). Can also pass open - file-like object''', + appendmat==True) If name not a full path name, search for the + file on the sys.path list and use the first one found (the + current directory is searched first). Can also pass open + file-like object''', 'append_arg': '''appendmat : {True, False} optional True to append the .mat extension to the end of the given - filename, if not already present''', + filename, if not already present''', 'basename_arg': '''base_name : string, optional, unused base name for unnamed variables. The code no longer uses @@ -29,12 +29,12 @@ it in future versions''', 'load_args': '''byte_order : {None, string}, optional - None by default, implying byte order guessed from mat - file. Otherwise can be one of ('native', '=', 'little', '<', - 'BIG', '>') + None by default, implying byte order guessed from mat + file. Otherwise can be one of ('native', '=', 'little', '<', + 'BIG', '>') mat_dtype : {False, True} optional If True, return arrays in same dtype as would be loaded into - matlab (instead of the dtype with which they are saved) + matlab (instead of the dtype with which they are saved) squeeze_me : {False, True} optional whether to squeeze unit matrix dimensions or not chars_as_strings : {True, False} optional @@ -46,15 +46,15 @@ 'struct_arg': '''struct_as_record : {False, True} optional Whether to load matlab structs as numpy record arrays, or as - old-style numpy arrays with dtype=object. Setting this flag - to False replicates the behaviour of scipy version 0.6 - (returning numpy object arrays). The preferred setting is - True, because it allows easier round-trip load and save of - matlab files. In a future version of scipy, we will change - the default setting to True, and following versions may remove - this flag entirely. For now, we set the default to False, for - backwards compatibility, but issue a warning. - Note that non-record arrays cannot be exported via savemat.''', + old-style numpy arrays with dtype=object. Setting this flag + to False replicates the behaviour of scipy version 0.6 + (returning numpy object arrays). The preferred setting is + True, because it allows easier round-trip load and save of + matlab files. In a future version of scipy, we will change + the default setting to True, and following versions may remove + this flag entirely. For now, we set the default to False, for + backwards compatibility, but issue a warning. + Note that non-record arrays cannot be exported via savemat.''', 'matstream_arg': '''mat_stream : file-like object with file API, open for reading'''} @@ -191,7 +191,7 @@ ): ''' Initializer for mat file reader - + mat_stream : file-like object with file API, open for reading %(load_args)s Modified: trunk/scipy/io/matlab/tests/test_mio.py =================================================================== --- trunk/scipy/io/matlab/tests/test_mio.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/io/matlab/tests/test_mio.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -210,7 +210,7 @@ # A field in a record array may not be an ndarray # A scalar from a record array will be type np.void if not isinstance(expected, - (np.void, np.ndarray, MatlabObject)): + (np.void, np.ndarray, MatlabObject)): assert_equal(expected, actual) return # This is an ndarray-like thing @@ -328,8 +328,8 @@ # This too yield assert_raises, FutureWarning, find_mat_file, fname # we need kwargs for this one - yield (lambda a, k: assert_raises(*a, **k), - (DeprecationWarning, loadmat, fname), + yield (lambda a, k: assert_raises(*a, **k), + (DeprecationWarning, loadmat, fname), {'struct_as_record':True, 'basename':'raw'}) warnings.resetwarnings() @@ -337,4 +337,3 @@ def test_regression_653(): """Regression test for #653.""" assert_raises(TypeError, savemat, StringIO(), {'d':{1:2}}, format='5') - Modified: trunk/scipy/lib/lapack/tests/common.py =================================================================== --- trunk/scipy/lib/lapack/tests/common.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/lib/lapack/tests/common.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -2,11 +2,11 @@ from scipy.lib.lapack import flapack, clapack -FUNCS_TP = {'ssygv' : np.float32, +FUNCS_TP = {'ssygv' : np.float32, 'dsygv': np.float, 'ssygvd' : np.float32, 'dsygvd' : np.float, - 'ssyev' : np.float32, + 'ssyev' : np.float32, 'dsyev': np.float, 'ssyevr' : np.float32, 'dsyevr' : np.float, @@ -14,7 +14,7 @@ 'dsyevr' : np.float, 'sgehrd' : np.float32, 'dgehrd' : np.float, - 'sgebal' : np.float32, + 'sgebal' : np.float32, 'dgebal': np.float} # Test FLAPACK if not empty @@ -50,4 +50,3 @@ FUNCS_CLAPACK = None PREC = {np.float32: 5, np.float: 12} - Modified: trunk/scipy/lib/lapack/tests/test_esv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/lib/lapack/tests/test_esv.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -25,7 +25,7 @@ assert not info, `info` assert_array_almost_equal(w, SYEV_REF, decimal=PREC[tp]) for i in range(3): - assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], decimal=PREC[tp]) def _test_base_irange(self, func, irange, lang): @@ -47,7 +47,7 @@ assert_array_almost_equal(w, SYEV_REF[rslice], decimal=PREC[tp]) for i in range(m): - assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], decimal=PREC[tp]) def _test_base_vrange(self, func, vrange, lang): @@ -68,7 +68,7 @@ assert_array_almost_equal(w, ew, decimal=PREC[tp]) for i in range(len(w)): - assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], + assert_array_almost_equal(np.dot(a,v[:,i]), w[i]*v[:,i], decimal=PREC[tp]) def _test_syevr_ranges(self, func, lang): @@ -104,32 +104,32 @@ self._test_syevr_ranges('dsyevr', 'F') # Clapack tests - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyev"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyev"], "Clapack empty, skip clapack test") def test_clapack_ssyev(self): self._test_base('ssyev', 'C') - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyev"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyev"], "Clapack empty, skip clapack test") def test_clapack_dsyev(self): self._test_base('dsyev', 'C') - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyevr"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyevr"], "Clapack empty, skip clapack test") def test_clapack_ssyevr(self): self._test_base('ssyevr', 'C') - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyevr"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyevr"], "Clapack empty, skip clapack test") def test_clapack_dsyevr(self): self._test_base('dsyevr', 'C') - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyevr"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssyevr"], "Clapack empty, skip clapack test") def test_clapack_ssyevr_ranges(self): self._test_syevr_ranges('ssyevr', 'C') - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyevr"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsyevr"], "Clapack empty, skip clapack test") def test_clapack_dsyevr_ranges(self): self._test_syevr_ranges('dsyevr', 'C') Modified: trunk/scipy/lib/lapack/tests/test_gesv.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/lib/lapack/tests/test_gesv.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -31,7 +31,7 @@ assert_array_almost_equal(np.dot(a,np.dot(b,v[:,i])), w[i]*v[:,i], decimal=PREC[tp]) elif itype == 3: - assert_array_almost_equal(np.dot(b,np.dot(a,v[:,i])), + assert_array_almost_equal(np.dot(b,np.dot(a,v[:,i])), w[i]*v[:,i], decimal=PREC[tp] - 1) else: raise ValueError, `itype` @@ -60,32 +60,32 @@ def test_dsygv_3(self): self._test_base('dsygv', 'F', 3) - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], "Clapack empty, skip flapack test") def test_clapack_ssygv_1(self): self._test_base('ssygv', 'C', 1) - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], "Clapack empty, skip flapack test") def test_clapack_ssygv_2(self): self._test_base('ssygv', 'C', 2) - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["ssygv"], "Clapack empty, skip flapack test") def test_clapack_ssygv_3(self): self._test_base('ssygv', 'C', 3) - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], "Clapack empty, skip flapack test") def test_clapack_dsygv_1(self): self._test_base('dsygv', 'C', 1) - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], "Clapack empty, skip flapack test") def test_clapack_dsygv_2(self): self._test_base('dsygv', 'C', 2) - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dsygv"], "Clapack empty, skip flapack test") def test_clapack_dsygv_3(self): self._test_base('dsygv', 'C', 3) Modified: trunk/scipy/lib/lapack/tests/test_lapack.py =================================================================== --- trunk/scipy/lib/lapack/tests/test_lapack.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/lib/lapack/tests/test_lapack.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -40,7 +40,7 @@ a = np.array([[-149, -50,-154], [ 537, 180, 546], [ -27, -9, -25]]).astype(tp) - + if lang == 'C': f = FUNCS_CLAPACK[func] elif lang == 'F': @@ -54,35 +54,35 @@ @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") def test_sgebal(self): self._test_gebal_base('sgebal', 'F') - + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip flapack test") def test_dgebal(self): self._test_gebal_base('dgebal', 'F') - + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip clapack test") def test_sgehrd(self): self._test_gehrd_base('sgehrd', 'F') - + @dec.skipif(FLAPACK_IS_EMPTY, "Flapack empty, skip clapack test") def test_dgehrd(self): self._test_gehrd_base('dgehrd', 'F') - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["sgebal"], + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["sgebal"], "Clapack empty, skip flapack test") def test_clapack_sgebal(self): self._test_gebal_base('sgebal', 'C') - - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dgebal"], + + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dgebal"], "Clapack empty, skip flapack test") def test_clapack_dgebal(self): self._test_gebal_base('dgebal', 'C') - - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["sgehrd"], + + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["sgehrd"], "Clapack empty, skip flapack test") def test_clapack_sgehrd(self): self._test_gehrd_base('sgehrd', 'C') - - @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dgehrd"], + + @dec.skipif(CLAPACK_IS_EMPTY or not FUNCS_CLAPACK["dgehrd"], "Clapack empty, skip flapack test") def test_clapack_dgehrd(self): self._test_gehrd_base('dgehrd', 'C') Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -41,12 +41,12 @@ act = act.dtype else: act = dtype(act) - + if isinstance(des, ndarray): des = des.dtype else: des = dtype(des) - + assert act == des, 'dtype mismatch: "%s" (should be "%s") '%(act, des) # XXX: This function should not be defined here, but somewhere in @@ -59,10 +59,10 @@ # scipy.linalg namespace def symrand(dim_or_eigv, dtype="d"): """Return a random symmetric (Hermitian) matrix. - + If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues uniformly distributed on (0.1,1]. - + If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose eigenvalues are sort(a). """ @@ -75,7 +75,7 @@ d = dim_or_eigv else: raise TypeError("input type not supported.") - + v = random_rot(dim, dtype=dtype) h = dot(dot(hermitian(v), diag(d)), v) # to avoid roundoff errors, symmetrize the matrix (again) @@ -99,7 +99,7 @@ D[n-1] = sign(x[0]) x[0] -= D[n-1]*sqrt((x*x).sum()) # Householder transformation - + Hx = eye(dim-n+1, dtype=dtype) - 2.*outer(x, x)/(x*x).sum() mat = eye(dim, dtype=dtype) mat[n-1:,n-1:] = Hx @@ -514,7 +514,7 @@ self.eigenproblem_standard(DIM, 'f', False, False) self.eigenproblem_standard(DIM, 'f', False, True) self.eigenproblem_standard(DIM, 'f', True, True) - + def test_eigh_complex_standard(self): self.eigenproblem_standard(DIM, 'D', False, False) self.eigenproblem_standard(DIM, 'D', False, True) @@ -523,7 +523,7 @@ self.eigenproblem_standard(DIM, 'F', False, True) self.eigenproblem_standard(DIM, 'F', True, True) - + class TestLU(TestCase): def __init__(self, *args, **kw): Modified: trunk/scipy/signal/signaltools.py =================================================================== --- trunk/scipy/signal/signaltools.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/signal/signaltools.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -942,7 +942,7 @@ The analytic signal `x_a(t)` of `x(t)` is:: x_a = F^{-1}(F(x) 2U) = x + i y - + where ``F`` is the Fourier transform, ``U`` the unit step function, and ``y`` the Hilbert transform of ``x``. [1] Modified: trunk/scipy/sparse/data.py =================================================================== --- trunk/scipy/sparse/data.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/data.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -66,5 +66,3 @@ def _mul_scalar(self, other): return self._with_data(self.data * other) - - Modified: trunk/scipy/sparse/lil.py =================================================================== --- trunk/scipy/sparse/lil.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/lil.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -155,7 +155,7 @@ return new def _get1(self, i, j): - + if i < 0: i += self.shape[0] if i < 0 or i >= self.shape[0]: @@ -165,7 +165,7 @@ j += self.shape[1] if j < 0 or j >= self.shape[1]: raise IndexError('column index out of bounds') - + row = self.rows[i] data = self.data[i] Modified: trunk/scipy/sparse/linalg/isolve/iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/linalg/isolve/iterative.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -31,7 +31,7 @@ Maximum number of iterations. Iteration will stop after maxiter steps even if the specified tolerance has not been achieved. M : {sparse matrix, dense matrix, LinearOperator} - Preconditioner for A. The preconditioner should approximate the + Preconditioner for A. The preconditioner should approximate the inverse of A. Effective preconditioning dramatically improves the rate of convergence, which implies that fewer iterations are needed to reach a given error tolerance. @@ -53,9 +53,9 @@ ---------------------- xtype : {'f','d','F','D'} The type of the result. If None, then it will be determined from - A.dtype.char and b. If A does not have a typecode method then it - will compute A.matvec(x0) to get a typecode. To save the extra - computation when A does not have a typecode attribute use xtype=0 + A.dtype.char and b. If A does not have a typecode method then it + will compute A.matvec(x0) to get a typecode. To save the extra + computation when A does not have a typecode attribute use xtype=0 for the same type as b or use xtype='f','d','F',or 'D'. This parameter has been superceeded by LinearOperator. """ @@ -123,7 +123,7 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 - + if info > 0 and iter_ == maxiter and resid > tol: #info isn't set appropriately otherwise info = iter_ @@ -185,7 +185,7 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 - + if info > 0 and iter_ == maxiter and resid > tol: #info isn't set appropriately otherwise info = iter_ @@ -299,24 +299,24 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 - + if info > 0 and iter_ == maxiter and resid > tol: #info isn't set appropriately otherwise info = iter_ return postprocess(x), info - + def gmres(A, b, x0=None, tol=1e-5, restrt=20, maxiter=None, xtype=None, M=None, callback=None): """Use Generalized Minimal RESidual iteration to solve A x = b - + Parameters ---------- A : {sparse matrix, dense matrix, LinearOperator} The N-by-N matrix of the linear system. b : {array, matrix} Right hand side of the linear system. Has shape (N,) or (N,1). - + Optional Parameters ------------------- x0 : {array, matrix} @@ -330,14 +330,14 @@ Maximum number of iterations. Iteration will stop after maxiter steps even if the specified tolerance has not been achieved. M : {sparse matrix, dense matrix, LinearOperator} - Preconditioner for A. The preconditioner should approximate the + Preconditioner for A. The preconditioner should approximate the inverse of A. Effective preconditioning dramatically improves the rate of convergence, which implies that fewer iterations are needed to reach a given error tolerance. callback : function User-supplied function to call after each iteration. It is called as callback(rk), where rk is the current residual vector. - + Outputs ------- x : {array, matrix} @@ -347,21 +347,21 @@ 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown - + See Also -------- LinearOperator - + Deprecated Parameters --------------------- xtype : {'f','d','F','D'} The type of the result. If None, then it will be determined from - A.dtype.char and b. If A does not have a typecode method then it - will compute A.matvec(x0) to get a typecode. To save the extra - computation when A does not have a typecode attribute use xtype=0 + A.dtype.char and b. If A does not have a typecode method then it + will compute A.matvec(x0) to get a typecode. To save the extra + computation when A does not have a typecode attribute use xtype=0 for the same type as b or use xtype='f','d','F',or 'D'. This parameter has been superceeded by LinearOperator. - + """ A,M,x,b,postprocess = make_system(A,M,x0,b,xtype) @@ -369,7 +369,7 @@ if maxiter is None: maxiter = n*10 - restrt = min(restrt, n) + restrt = min(restrt, n) matvec = A.matvec psolve = M.matvec @@ -433,7 +433,7 @@ if iter_num > maxiter: break - + if info >= 0 and resid > tol: #info isn't set appropriately otherwise info = maxiter @@ -450,7 +450,7 @@ The N-by-N matrix of the linear system. b : {array, matrix} Right hand side of the linear system. Has shape (N,) or (N,1). - + Optional Parameters ------------------- x0 : {array, matrix} @@ -469,7 +469,7 @@ callback : function User-supplied function to call after each iteration. It is called as callback(xk), where xk is the current solution vector. - + Outputs ------- x : {array, matrix} @@ -479,21 +479,21 @@ 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown - + See Also -------- LinearOperator - + Deprecated Parameters --------------------- xtype : {'f','d','F','D'} The type of the result. If None, then it will be determined from - A.dtype.char and b. If A does not have a typecode method then it - will compute A.matvec(x0) to get a typecode. To save the extra - computation when A does not have a typecode attribute use xtype=0 + A.dtype.char and b. If A does not have a typecode method then it + will compute A.matvec(x0) to get a typecode. To save the extra + computation when A does not have a typecode attribute use xtype=0 for the same type as b or use xtype='f','d','F',or 'D'. This parameter has been superceeded by LinearOperator. - + """ A_ = A A,M,x,b,postprocess = make_system(A,None,x0,b,xtype) @@ -568,10 +568,9 @@ ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 - + if info > 0 and iter_ == maxiter and resid > tol: #info isn't set appropriately otherwise info = iter_ return postprocess(x), info - Modified: trunk/scipy/sparse/linalg/isolve/minres.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/minres.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/linalg/isolve/minres.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -6,7 +6,7 @@ __all__ = ['minres'] - + header = \ """Use MINimum RESidual iteration to solve Ax=b @@ -17,7 +17,7 @@ """ footer = \ -""" +""" Notes ----- THIS FUNCTION IS EXPERIMENTAL AND SUBJECT TO CHANGE! Modified: trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/linalg/isolve/tests/test_iterative.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -106,7 +106,7 @@ """test whether all methods accept a trivial preconditioner""" tol = 1e-8 - + def identity(b,which=None): """trivial preconditioner""" return b @@ -131,9 +131,9 @@ x, info = solver(A, b, M=precond, x0=x0, tol=tol) assert_equal(info,0) assert( norm(b - A*x) < tol*norm(b) ) - + A = A.copy() - A.psolve = identity + A.psolve = identity A.rpsolve = identity x, info = solver(A, b, x0=x0, tol=tol) Modified: trunk/scipy/sparse/linalg/tests/test_interface.py =================================================================== --- trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -44,7 +44,7 @@ assert_equal(A.matvec(array([1,2,3])), [14,32]) assert_equal(A.matvec(array([[1],[2],[3]])), [[14],[32]]) - + assert_equal(A * array([1,2,3]), [14,32]) assert_equal(A * array([[1],[2],[3]]), [[14],[32]]) @@ -52,7 +52,7 @@ assert_equal(A.rmatvec(array([[1],[2]])), [[9],[12],[15]]) assert_equal(A.matmat(array([[1,4],[2,5],[3,6]])), [[14,32],[32,77]] ) - + assert_equal(A * array([[1,4],[2,5],[3,6]]), [[14,32],[32,77]] ) if hasattr(M,'dtype'): Modified: trunk/scipy/sparse/sputils.py =================================================================== --- trunk/scipy/sparse/sputils.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/sputils.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -106,8 +106,8 @@ if np.rank(M) == 0 and np.rank(N) == 0: return True return False - + def issequence(t): return isinstance(t, (list, tuple))\ or (isinstance(t, np.ndarray) and (t.ndim == 1)) Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/sparse/tests/test_base.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -581,7 +581,7 @@ A[-1,-2] = 7 A[ 0, 1] = 5 assert_array_equal(A.todense(),[[0,5,0,8],[0,0,4,0],[2,0,7,0]]) - + for ij in [(0,4),(-1,4),(3,0),(3,4),(3,-1)]: assert_raises(IndexError, A.__setitem__, ij, 123.0) @@ -597,7 +597,7 @@ for i in range(-M, M): for j in range(-N, N): assert_equal(A[i,j], D[i,j]) - + for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1)]: assert_raises(IndexError, A.__getitem__, ij) Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/spatial/distance.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -1432,7 +1432,7 @@ raise ValueError('Distance matrix must be symmetric.') if not (D[xrange(0, s[0]), xrange(0, s[0])] == 0).all(): if name: - raise ValueError('Distance matrix \'%s\' diagonal must be zero.' % name) + raise ValueError('Distance matrix \'%s\' diagonal must be zero.' % name) else: raise ValueError('Distance matrix diagonal must be zero.') else: Modified: trunk/scipy/spatial/kdtree.py =================================================================== --- trunk/scipy/spatial/kdtree.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/spatial/kdtree.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -6,7 +6,7 @@ def minkowski_distance_p(x,y,p=2): """Compute the pth power of the L**p distance between x and y - + For efficiency, this function computes the L**p distance but does not extract the pth root. If p is 1 or infinity, this is equal to the actual L**p distance. @@ -45,10 +45,10 @@ def volume(self): """Total volume.""" return np.prod(self.maxes-self.mins) - + def split(self, d, split): """Produce two hyperrectangles by splitting along axis d. - + In general, if you need to compute maximum and minimum distances to the children, it can be done more efficiently by updating the maximum and minimum distances to the parent. @@ -83,24 +83,24 @@ This class provides an index into a set of k-dimensional points which can be used to rapidly look up the nearest neighbors of any - point. + point. - The algorithm used is described in Maneewongvatana and Mount 1999. + The algorithm used is described in Maneewongvatana and Mount 1999. The general idea is that the kd-tree is a binary trie, each of whose nodes represents an axis-aligned hyperrectangle. Each node specifies an axis and splits the set of points based on whether their coordinate - along that axis is greater than or less than a particular value. + along that axis is greater than or less than a particular value. - During construction, the axis and splitting point are chosen by the + During construction, the axis and splitting point are chosen by the "sliding midpoint" rule, which ensures that the cells do not all - become long and thin. + become long and thin. - The tree can be queried for the r closest neighbors of any given point - (optionally returning only those within some maximum distance of the - point). It can also be queried, with a substantial gain in efficiency, + The tree can be queried for the r closest neighbors of any given point + (optionally returning only those within some maximum distance of the + point). It can also be queried, with a substantial gain in efficiency, for the r approximate closest neighbors. - For large dimensions (20 is already large) do not expect this to run + For large dimensions (20 is already large) do not expect this to run significantly faster than brute force. High-dimensional nearest-neighbor queries are a substantial open problem in computer science. @@ -146,7 +146,7 @@ self.less = less self.greater = greater self.children = less.children+greater.children - + def __build(self, idx, maxes, mins): if len(idx)<=self.leafsize: return KDTree.leafnode(idx) @@ -186,12 +186,12 @@ lessmaxes[d] = split greatermins = np.copy(mins) greatermins[d] = split - return KDTree.innernode(d, split, + return KDTree.innernode(d, split, self.__build(idx[less_idx],lessmaxes,mins), self.__build(idx[greater_idx],maxes,greatermins)) def __query(self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf): - + side_distances = np.maximum(0,np.maximum(x-self.maxes,self.mins-x)) if p!=np.inf: side_distances**=p @@ -205,7 +205,7 @@ # distances between the nearest side of the cell and the target # the head node of the cell q = [(min_distance, - tuple(side_distances), + tuple(side_distances), self.tree)] # priority queue for the nearest neighbors # furthest known neighbor first @@ -237,7 +237,7 @@ distance_upper_bound = -neighbors[0][0] else: # we don't push cells that are too far onto the queue at all, - # but since the distance_upper_bound decreases, we might get + # but since the distance_upper_bound decreases, we might get # here even if the cell's too far if min_distance>distance_upper_bound*epsfac: # since this is the nearest cell, we're done, bail out @@ -283,11 +283,11 @@ k : integer The number of nearest neighbors to return. eps : nonnegative float - Return approximate nearest neighbors; the kth returned value - is guaranteed to be no further than (1+eps) times the + Return approximate nearest neighbors; the kth returned value + is guaranteed to be no further than (1+eps) times the distance to the real kth nearest neighbor. p : float, 1<=p<=infinity - Which Minkowski p-norm to use. + Which Minkowski p-norm to use. 1 is the sum-of-absolute-values "Manhattan" distance 2 is the usual Euclidean distance infinity is the maximum-coordinate-difference distance @@ -299,14 +299,14 @@ Returns: ======== - + d : array of floats - The distances to the nearest neighbors. - If x has shape tuple+(self.m,), then d has shape tuple if - k is one, or tuple+(k,) if k is larger than one. Missing - neighbors are indicated with infinite distances. If k is None, - then d is an object array of shape tuple, containing lists - of distances. In either case the hits are sorted by distance + The distances to the nearest neighbors. + If x has shape tuple+(self.m,), then d has shape tuple if + k is one, or tuple+(k,) if k is larger than one. Missing + neighbors are indicated with infinite distances. If k is None, + then d is an object array of shape tuple, containing lists + of distances. In either case the hits are sorted by distance (nearest first). i : array of integers The locations of the neighbors in self.data. i is the same @@ -386,7 +386,7 @@ return traverse_checking(node.less, less)+traverse_checking(node.greater, greater) def traverse_no_checking(node): if isinstance(node, KDTree.leafnode): - + return node.idx.tolist() else: return traverse_no_checking(node.less)+traverse_no_checking(node.greater) @@ -450,7 +450,7 @@ Approximate search. Branches of the tree are not explored if their nearest points are further than r/(1+eps), and branches are added in bulk if their furthest points are nearer than r*(1+eps). - + Returns ======= @@ -501,7 +501,7 @@ other.tree, Rectangle(other.maxes, other.mins)) return results - + def count_neighbors(self, other, r, p=2.): """Count how many nearby pairs can be formed. @@ -527,7 +527,7 @@ result : integer or one-dimensional array of integers The number of pairs. Note that this is internally stored in a numpy int, - and so may overflow if very large (two billion). + and so may overflow if very large (two billion). """ def traverse(node1, rect1, node2, rect2, idx): @@ -577,7 +577,7 @@ return result else: raise ValueError("r must be either a single value or a one-dimensional array of values") - + def sparse_distance_matrix(self, other, max_distance, p=2.): """Compute a sparse distance matrix Modified: trunk/scipy/spatial/tests/test_kdtree.py =================================================================== --- trunk/scipy/spatial/tests/test_kdtree.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/spatial/tests/test_kdtree.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -13,7 +13,7 @@ assert_almost_equal(d**2,np.sum((x-self.data[i])**2)) eps = 1e-8 assert np.all(np.sum((self.data-x[np.newaxis,:])**2,axis=1)>d**2-eps) - + def test_m_nearest(self): x = self.x m = self.m @@ -73,7 +73,7 @@ d, i = self.kdtree.query(x, k, eps=eps) assert np.all(d<=d_real*(1+eps)) - + class test_random(ConsistencyTests): def setUp(self): self.n = 100 @@ -279,7 +279,7 @@ n = 20 m = 5 T = KDTree(np.random.randn(n,m)) - + r = T.query_ball_point(np.random.randn(2,3,m),1) assert_equal(r.shape,(2,3)) assert isinstance(r[0,0],list) @@ -368,7 +368,7 @@ m = 2 self.T1 = KDTree(np.random.randn(n,m),leafsize=2) self.T2 = KDTree(np.random.randn(n,m),leafsize=2) - + def test_one_radius(self): r = 0.2 assert_equal(self.T1.count_neighbors(self.T2, r), Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/stats/distributions.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -19,7 +19,7 @@ any, argsort, argmax, vectorize, r_, asarray, nan, inf, pi, isnan, isinf, \ power import numpy -import numpy as np +import numpy as np import numpy.random as mtrand from numpy import flatnonzero as nonzero from scipy.special import gammaln as gamln @@ -385,9 +385,9 @@ self._size = 1 self.m = 0.0 self.moment_type = momtype - + self.expandarr = 1 - + if not hasattr(self,'numargs'): #allows more general subclassing with *args cdf_signature = inspect.getargspec(self._cdf.im_func) @@ -395,7 +395,7 @@ pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2) - #nin correction + #nin correction self.vecfunc = sgf(self._ppf_single_call,otypes='d') self.vecfunc.nin = self.numargs + 1 self.vecentropy = sgf(self._entropy,otypes='d') @@ -843,7 +843,7 @@ def integ(x): val = self._pdf(x, *args) return val*log(val) - + entr = -scipy.integrate.quad(integ,self.a,self.b)[0] if not np.isnan(entr): return entr @@ -858,8 +858,8 @@ else: lower = self.a return -scipy.integrate.quad(integ,lower,upper)[0] - + def entropy(self, *args, **kwds): loc,scale=map(kwds.get,['loc','scale']) args, loc, scale = self._fix_loc_scale(args, loc, scale) @@ -2804,7 +2804,7 @@ class powerlognorm_gen(rv_continuous): def _pdf(self, x, c, s): return c/(x*s)*norm.pdf(log(x)/s)*pow(norm.cdf(-log(x)/s),c*1.0-1.0) - + def _cdf(self, x, c, s): return 1.0 - pow(norm.cdf(-log(x)/s),c*1.0) def _ppf(self, q, c, s): @@ -2957,7 +2957,7 @@ isqx = 1.0/sqrt(x) return 1.0-norm.cdf(isqx*trm1)-exp(2.0/mu)*norm.cdf(-isqx*trm2) # xb=50 or something large is necessary for stats to converge without exception -recipinvgauss = recipinvgauss_gen(a=0.0, xb=50, name='recipinvgauss', +recipinvgauss = recipinvgauss_gen(a=0.0, xb=50, name='recipinvgauss', longname="A reciprocal inverse Gaussian", shapes="mu", extradoc=""" @@ -3329,19 +3329,19 @@ #pos = self.a pos = max(0, self.a) count = 0 - #handle cases with infinite support + #handle cases with infinite support ulimit = max(1000, (min(self.b,1000) + max(self.a,-1000))/2.0 ) llimit = min(-1000, (min(self.b,1000) + max(self.a,-1000))/2.0 ) - + while (pos <= self.b) and ((pos <= ulimit) or \ (diff > self.moment_tol)): - diff = pos**n * self.pmf(pos,*args) + diff = pos**n * self.pmf(pos,*args) # use pmf because _pmf does not check support in randint # and there might be problems ? with correct self.a, self.b at this stage tot += diff pos += self.inc count += 1 - + if self.a < 0: #handle case when self.a = -inf diff = 1e100 pos = -self.inc @@ -3384,11 +3384,11 @@ #testcase: return wrong number at lower index #python -c "from scipy.stats import zipf;print zipf.ppf(0.01,2)" wrong #python -c "from scipy.stats import zipf;print zipf.ppf([0.01,0.61,0.77,0.83],2)" - #python -c "from scipy.stats import logser;print logser.ppf([0.1,0.66, 0.86,0.93],0.6)" + #python -c "from scipy.stats import logser;print logser.ppf([0.1,0.66, 0.86,0.93],0.6)" if qa > q: return a else: - return b + return b c = int((a+b)/2.0) qc = self._cdf(c, *args) if (qc < q): @@ -3529,11 +3529,11 @@ self._vecppf = new.instancemethod(_vppf, self, rv_discrete) - + #now that self.numargs is defined, we can adjust nin self._cdfvec.nin = self.numargs + 1 - + if longname is None: if name[0] in ['aeiouAEIOU']: hstr = "An " else: hstr = "A " @@ -3714,7 +3714,7 @@ goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] place(output,cond,self._ppf(*goodargs) + loc) - + if output.ndim == 0: return output[()] return output @@ -3744,17 +3744,17 @@ #typecode 'd' to handle nin and inf place(output,(1-cond0)*(cond1==cond1), self.badvalue) place(output,cond2,self.a-1) - + #same problem as with ppf - + # call place only if at least 1 valid argument if any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) loc, goodargs = goodargs[-1], goodargs[:-1] place(output,cond,self._isf(*goodargs) + loc) #PB same as ticket 766 - + if output.ndim == 0: return output[()] return output @@ -4382,7 +4382,7 @@ # variance mu2 does not aggree with sample variance, # nor with direct calculation using pmf # remove for now because generic calculation works - # except it does not show nice zeros for mean and skew(?) + # except it does not show nice zeros for mean and skew(?) ea = exp(-a) e2a = exp(-2*a) e3a = exp(-3*a) Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -903,11 +903,11 @@ assert_array_almost_equal(p, self.P1_2) def test_scoreatpercentile(): - assert_equal(stats.scoreatpercentile(range(10),50),4.5) - assert_equal(stats.scoreatpercentile(range(10),50,(2,7)),4.5) - assert_equal(stats.scoreatpercentile(range(100),50,(1,8)),4.5) - assert_equal(stats.scoreatpercentile(np.array([1, 10 ,100]),50,(10,100)), 55) - assert_equal(stats.scoreatpercentile(np.array([1, 10 ,100]),50,(1,10)), 5.5) + assert_equal(stats.scoreatpercentile(range(10),50),4.5) + assert_equal(stats.scoreatpercentile(range(10),50,(2,7)),4.5) + assert_equal(stats.scoreatpercentile(range(100),50,(1,8)),4.5) + assert_equal(stats.scoreatpercentile(np.array([1, 10 ,100]),50,(10,100)), 55) + assert_equal(stats.scoreatpercentile(np.array([1, 10 ,100]),50,(1,10)), 5.5) if __name__ == "__main__": run_module_suite() Modified: trunk/tools/win32/build_scripts/pavement.py =================================================================== --- trunk/tools/win32/build_scripts/pavement.py 2008-11-16 07:44:16 UTC (rev 5125) +++ trunk/tools/win32/build_scripts/pavement.py 2008-11-16 09:23:48 UTC (rev 5126) @@ -191,7 +191,7 @@ def get_svn_version(chdir): out = subprocess.Popen(['svn', 'info'], - stdout = subprocess.PIPE, + stdout = subprocess.PIPE, cwd = chdir).communicate()[0] r = re.compile('Revision: ([0-9]+)') svnver = None @@ -321,7 +321,7 @@ def raw_build_nsis(pyver): bdir = bootstrap_dir(options.pyver) - st = subprocess.call(['makensis', 'scipy-superinstaller.nsi'], + st = subprocess.call(['makensis', 'scipy-superinstaller.nsi'], cwd=bdir) if st: raise RuntimeError("Error while executing makensis command") From scipy-svn at scipy.org Sun Nov 16 06:35:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 05:35:17 -0600 (CST) Subject: [Scipy-svn] r5127 - scipy-docs/trunk trunk/doc Message-ID: <20081116113517.544EE39C088@scipy.org> Author: ptvirtan Date: 2008-11-16 05:34:49 -0600 (Sun, 16 Nov 2008) New Revision: 5127 Added: trunk/doc/Makefile trunk/doc/README.txt trunk/doc/frontpage/ trunk/doc/postprocess.py trunk/doc/source/ Removed: scipy-docs/trunk/Makefile scipy-docs/trunk/README.txt scipy-docs/trunk/frontpage/ scipy-docs/trunk/postprocess.py scipy-docs/trunk/source/ Log: Moving scipy-docs under the main Scipy tree Deleted: scipy-docs/trunk/Makefile =================================================================== --- scipy-docs/trunk/Makefile 2008-11-16 09:23:48 UTC (rev 5126) +++ scipy-docs/trunk/Makefile 2008-11-16 11:34:49 UTC (rev 5127) @@ -1,112 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = LANG=C sphinx-build -PAPER = - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source - -.PHONY: help clean html web pickle htmlhelp latex changes linkcheck - -help: - @echo "Please use \`make ' where is one of" - @echo " dist to make a distribution-ready tree" - @echo " html to make standalone HTML files" - @echo " pickle to make pickle files (usable by e.g. sphinx-web)" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " changes to make an overview over all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " upload USER=... to upload results to docs.scipy.org" - -clean: - -rm -rf build/* source/generated - -upload: - @test -e build/dist || { echo "make dist is required first"; exit 1; } - @test output-is-fine -nt build/dist || { \ - echo "Review the output in build/dist, and do 'touch output-is-fine' before uploading."; exit 1; } - rsync -r -z --delete-after -p build/dist/ $(USER)@docs.scipy.org:/home/docserver/www-root/doc/scipy/ - -dist: html - test -d build/latex || make latex - -make -C build/latex all-pdf - -rm -rf build/dist - mkdir -p build/dist - cp -r build/html build/dist/reference - touch build/dist/index.html - perl -pi -e 's#^\s*(
  • SciPy.*?Reference Guide.*?»
  • )$$#
  • Numpy and Scipy Documentation »
  • $$1#;' build/dist/*.html build/dist/*/*.html build/dist/*/*/*.html - (cd build/html && zip -9qr ../dist/scipy-html.zip .) - cp build/latex/*.pdf build/dist - cd build/dist && tar czf ../dist.tar.gz * - chmod ug=rwX,o=rX -R build/dist - find build/dist -type d -print0 | xargs -0r chmod g+s - -generate: build/generate-stamp -build/generate-stamp: $(wildcard source/*.rst) ext - mkdir -p build - ./ext/autosummary_generate.py source/*.rst \ - -p dump.xml -o source/generated - touch build/generate-stamp - -ext: - svn co http://sphinx.googlecode.com/svn/contrib/trunk/numpyext ext - -html: generate - mkdir -p build/html build/doctrees - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html - 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 - @echo - @echo "Build finished; now you can process the pickle files or run" - @echo " sphinx-web build/pickle" - @echo "to start the sphinx-web server." - -web: pickle - -htmlhelp: generate - mkdir -p build/htmlhelp build/doctrees - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) build/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in build/htmlhelp." - -latex: generate - mkdir -p build/latex build/doctrees - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) build/latex - python postprocess.py tex build/latex/*.tex - @echo - @echo "Build finished; the LaTeX files are in build/latex." - @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ - "run these through (pdf)latex." - -coverage: build - mkdir -p build/coverage build/doctrees - $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) build/coverage - @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 - @echo - @echo "The overview file is in build/changes." - -linkcheck: generate - mkdir -p build/linkcheck build/doctrees - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) build/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in build/linkcheck/output.txt." - -.PHONY: help clean upload dist generate html pickle web htmlhelp latex \ - coverage changes linkcheck Deleted: scipy-docs/trunk/README.txt =================================================================== --- scipy-docs/trunk/README.txt 2008-11-16 09:23:48 UTC (rev 5126) +++ scipy-docs/trunk/README.txt 2008-11-16 11:34:49 UTC (rev 5127) @@ -1,12 +0,0 @@ -SciPy Reference Guide -===================== - -Instructions ------------- -1. Optionally download an XML dump of the newest docstrings from the doc wiki - at ``/pydocweb/dump`` and save it as ``dump.xml``. -2. Run ``make html`` or ``make dist`` - -You can also run ``summarize.py`` to see which parts of the Numpy -namespace are documented. - Deleted: scipy-docs/trunk/postprocess.py =================================================================== --- scipy-docs/trunk/postprocess.py 2008-11-16 09:23:48 UTC (rev 5126) +++ scipy-docs/trunk/postprocess.py 2008-11-16 11:34:49 UTC (rev 5127) @@ -1,54 +0,0 @@ -#!/usr/bin/env python -""" -%prog MODE FILES... - -Post-processes HTML and Latex files output by Sphinx. -MODE is either 'html' or 'tex'. - -""" -import re, optparse - -def main(): - p = optparse.OptionParser(__doc__) - options, args = p.parse_args() - - if len(args) < 1: - p.error('no mode given') - - mode = args.pop(0) - - if mode not in ('html', 'tex'): - p.error('unknown mode %s' % mode) - - for fn in args: - f = open(fn, 'r') - try: - if mode == 'html': - lines = process_html(fn, f.readlines()) - elif mode == 'tex': - lines = process_tex(f.readlines()) - finally: - f.close() - - f = open(fn, 'w') - f.write("".join(lines)) - f.close() - -def process_html(fn, lines): - return lines - -def process_tex(lines): - """ - Remove unnecessary section titles from the LaTeX file. - - """ - new_lines = [] - for line in lines: - if re.match(r'^\\(section|subsection|subsubsection|paragraph|subparagraph){(numpy|scipy)\.', line): - pass # skip! - else: - new_lines.append(line) - return new_lines - -if __name__ == "__main__": - main() Copied: trunk/doc/Makefile (from rev 5126, scipy-docs/trunk/Makefile) Copied: trunk/doc/README.txt (from rev 5126, scipy-docs/trunk/README.txt) Copied: trunk/doc/frontpage (from rev 5126, scipy-docs/trunk/frontpage) Copied: trunk/doc/postprocess.py (from rev 5126, scipy-docs/trunk/postprocess.py) Copied: trunk/doc/source (from rev 5126, scipy-docs/trunk/source) From scipy-svn at scipy.org Sun Nov 16 06:37:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 05:37:10 -0600 (CST) Subject: [Scipy-svn] r5128 - / Message-ID: <20081116113710.3543F39C088@scipy.org> Author: ptvirtan Date: 2008-11-16 05:37:03 -0600 (Sun, 16 Nov 2008) New Revision: 5128 Removed: scipy-docs/ Log: Removing the separate scipy-docs branch now that it's under the main Scipy tree From scipy-svn at scipy.org Sun Nov 16 06:53:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 05:53:25 -0600 (CST) Subject: [Scipy-svn] r5129 - trunk/doc/release Message-ID: <20081116115325.D94A939C088@scipy.org> Author: ptvirtan Date: 2008-11-16 05:53:13 -0600 (Sun, 16 Nov 2008) New Revision: 5129 Modified: trunk/doc/release/0.7.0-notes.rst Log: Release notes: mention ZVODE Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-16 11:37:03 UTC (rev 5128) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-16 11:53:13 UTC (rev 5129) @@ -121,6 +121,13 @@ http://scipy.org/scipy/scipy/browser/trunk/scipy/interpolate/rbf.py +New complex ODE integrator +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``scipy.integrate.ode`` now contains a wrapper for the ZVODE +complex-valued ordinary differential equation solver +(by Peter N. Brown, Alan C. Hindmarsh, and George D. Byrne). + Major documentation improvements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From scipy-svn at scipy.org Sun Nov 16 07:50:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 06:50:43 -0600 (CST) Subject: [Scipy-svn] r5130 - in trunk/doc/source/tutorial: . examples Message-ID: <20081116125043.2E59639C088@scipy.org> Author: ptvirtan Date: 2008-11-16 06:50:11 -0600 (Sun, 16 Nov 2008) New Revision: 5130 Removed: trunk/doc/source/tutorial/examples/3-1 trunk/doc/source/tutorial/examples/3-2 Modified: trunk/doc/source/tutorial/examples/1-1 trunk/doc/source/tutorial/examples/10-2-1 trunk/doc/source/tutorial/examples/10-2-2 trunk/doc/source/tutorial/examples/10-3-1 trunk/doc/source/tutorial/examples/10-3-2 trunk/doc/source/tutorial/examples/10-3-6 trunk/doc/source/tutorial/examples/10-4-4 trunk/doc/source/tutorial/examples/4-1 trunk/doc/source/tutorial/examples/4-2 trunk/doc/source/tutorial/examples/4-3 trunk/doc/source/tutorial/examples/4-4 trunk/doc/source/tutorial/examples/4-5 trunk/doc/source/tutorial/examples/4-6 trunk/doc/source/tutorial/examples/5-1 trunk/doc/source/tutorial/examples/5-2 trunk/doc/source/tutorial/examples/5-3 trunk/doc/source/tutorial/examples/5-4 trunk/doc/source/tutorial/examples/5-5 trunk/doc/source/tutorial/examples/5-6 trunk/doc/source/tutorial/examples/5-9 trunk/doc/source/tutorial/index.rst Log: docs: Ensure that examples in the tutorial run with current Scipy Modified: trunk/doc/source/tutorial/examples/1-1 =================================================================== --- trunk/doc/source/tutorial/examples/1-1 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/1-1 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,37 +1,55 @@ >>> info(optimize.fmin) fmin(func, x0, args=(), xtol=0.0001, ftol=0.0001, maxiter=None, maxfun=None, - full_output=0, printmessg=1) + full_output=0, disp=1, retall=0, callback=None) -Minimize a function using the simplex algorithm. +Minimize a function using the downhill simplex algorithm. -Description: +:Parameters: - Uses a Nelder-Mead simplex algorithm to find the minimum of function - of one or more variables. + func : callable func(x,*args) + The objective function to be minimized. + x0 : ndarray + Initial guess. + args : tuple + Extra arguments passed to func, i.e. ``f(x,*args)``. + callback : callable + Called after each iteration, as callback(xk), where xk is the + current parameter vector. -Inputs: +:Returns: (xopt, {fopt, iter, funcalls, warnflag}) - func -- the Python function or method to be minimized. - x0 -- the initial guess. - args -- extra arguments for func. - xtol -- relative tolerance + xopt : ndarray + Parameter that minimizes function. + fopt : float + Value of function at minimum: ``fopt = func(xopt)``. + iter : int + Number of iterations performed. + funcalls : int + Number of function calls made. + warnflag : int + 1 : Maximum number of function evaluations made. + 2 : Maximum number of iterations reached. + allvecs : list + Solution at each iteration. -Outputs: (xopt, {fopt, warnflag}) +*Other Parameters*: - xopt -- minimizer of function + xtol : float + Relative error in xopt acceptable for convergence. + ftol : number + Relative error in func(xopt) acceptable for convergence. + maxiter : int + Maximum number of iterations to perform. + maxfun : number + Maximum number of function evaluations to make. + full_output : bool + Set to True if fval and warnflag outputs are desired. + disp : bool + Set to True to print convergence messages. + retall : bool + Set to True to return list of solutions at each iteration. - fopt -- value of function at minimum: fopt = func(xopt) - warnflag -- Integer warning flag: - 1 : 'Maximum number of function evaluations.' - 2 : 'Maximum number of iterations.' +:Notes: -Additional Inputs: - - xtol -- acceptable relative error in xopt for convergence. - ftol -- acceptable relative error in func(xopt) for convergence. - maxiter -- the maximum number of iterations to perform. - maxfun -- the maximum number of function evaluations. - full_output -- non-zero if fval and warnflag outputs are desired. - printmessg -- non-zero to print convergence messages. - - + Uses a Nelder-Mead simplex algorithm to find the minimum of + function of one or more variables. Modified: trunk/doc/source/tutorial/examples/10-2-1 =================================================================== --- trunk/doc/source/tutorial/examples/10-2-1 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/10-2-1 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,12 +1,13 @@ >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> A -Matrix([[1, 3, 5], - [2, 5, 1], - [2, 3, 8]]) +matrix([[1, 3, 5], + [2, 5, 1], + [2, 3, 8]]) >>> A.I -Matrix([[-1.48, 0.36, 0.88], - [ 0.56, 0.08, -0.36], - [ 0.16, -0.12, 0.04]]) +matrix([[-1.48, 0.36, 0.88], + [ 0.56, 0.08, -0.36], + [ 0.16, -0.12, 0.04]]) +>>> from scipy import linalg >>> linalg.inv(A) array([[-1.48, 0.36, 0.88], [ 0.56, 0.08, -0.36], Modified: trunk/doc/source/tutorial/examples/10-2-2 =================================================================== --- trunk/doc/source/tutorial/examples/10-2-2 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/10-2-2 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,9 +1,9 @@ >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> b = mat('[10;8;3]') >>> A.I*b -Matrix([[-9.28], - [ 5.16], - [ 0.76]]) +matrix([[-9.28], + [ 5.16], + [ 0.76]]) >>> linalg.solve(A,b) array([[-9.28], [ 5.16], Modified: trunk/doc/source/tutorial/examples/10-3-1 =================================================================== --- trunk/doc/source/tutorial/examples/10-3-1 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/10-3-1 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,3 +1,4 @@ +>>> from scipy import linalg >>> A = mat('[1 5 2; 2 4 1; 3 6 2]') >>> la,v = linalg.eig(A) >>> l1,l2,l3 = la @@ -5,14 +6,14 @@ (7.95791620491+0j) (-1.25766470568+0j) (0.299748500767+0j) >>> print v[:,0] -array([-0.5297, -0.4494, -0.7193]) +[-0.5297175 -0.44941741 -0.71932146] >>> print v[:,1] -[-0.9073 0.2866 0.3076] +[-0.90730751 0.28662547 0.30763439] >>> print v[:,2] -[ 0.2838 -0.3901 0.8759] +[ 0.28380519 -0.39012063 0.87593408] >>> print sum(abs(v**2),axis=0) [ 1. 1. 1.] >>> v1 = mat(v[:,0]).T >>> print max(ravel(abs(A*v1-l1*v1))) -4.4408920985e-16 +8.881784197e-16 Modified: trunk/doc/source/tutorial/examples/10-3-2 =================================================================== --- trunk/doc/source/tutorial/examples/10-3-2 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/10-3-2 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,22 +1,22 @@ >>> A = mat('[1 3 2; 1 2 3]') >>> M,N = A.shape >>> U,s,Vh = linalg.svd(A) ->>> Sig = mat(diagsvd(s,M,N)) +>>> Sig = mat(linalg.diagsvd(s,M,N)) >>> U, Vh = mat(U), mat(Vh) >>> print U -Matrix([[-0.7071, -0.7071], - [-0.7071, 0.7071]]) +[[-0.70710678 -0.70710678] + [-0.70710678 0.70710678]] >>> print Sig -Matrix([[ 5.1962, 0. , 0. ], - [ 0. , 1. , 0. ]]) +[[ 5.19615242 0. 0. ] + [ 0. 1. 0. ]] >>> print Vh -Matrix([[-0.2722, -0.6804, -0.6804], - [-0. , -0.7071, 0.7071], - [-0.9623, 0.1925, 0.1925]]) +[[ -2.72165527e-01 -6.80413817e-01 -6.80413817e-01] + [ -6.18652536e-16 -7.07106781e-01 7.07106781e-01] + [ -9.62250449e-01 1.92450090e-01 1.92450090e-01]] >>> print A -Matrix([[1, 3, 2], - [1, 2, 3]]) +[[1 3 2] + [1 2 3]] >>> print U*Sig*Vh -Matrix([[ 1., 3., 2.], - [ 1., 2., 3.]]) +[[ 1. 3. 2.] + [ 1. 2. 3.]] Modified: trunk/doc/source/tutorial/examples/10-3-6 =================================================================== --- trunk/doc/source/tutorial/examples/10-3-6 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/10-3-6 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,3 +1,4 @@ +>>> from scipy import linalg >>> A = mat('[1 3 2; 1 4 5; 2 3 6]') >>> T,Z = linalg.schur(A) >>> T1,Z1 = linalg.schur(A,'complex') @@ -3,33 +4,33 @@ >>> T2,Z2 = linalg.rsf2csf(T,Z) >>> print T -Matrix([[ 9.9001, 1.7895, -0.655 ], - [ 0. , 0.5499, -1.5775], - [ 0. , 0.5126, 0.5499]]) +[[ 9.90012467 1.78947961 -0.65498528] + [ 0. 0.54993766 -1.57754789] + [ 0. 0.51260928 0.54993766]] >>> print T2 -Matrix([[ 9.9001+0.j , -0.3244+1.5546j, -0.8862+0.569j ], - [ 0. +0.j , 0.5499+0.8993j, 1.0649-0.j ], - [ 0. +0.j , 0. +0.j , 0.5499-0.8993j]]) +[[ 9.90012467 +0.00000000e+00j -0.32436598 +1.55463542e+00j + -0.88619748 +5.69027615e-01j] + [ 0.00000000 +0.00000000e+00j 0.54993766 +8.99258408e-01j + 1.06493862 +1.37016050e-17j] + [ 0.00000000 +0.00000000e+00j 0.00000000 +0.00000000e+00j + 0.54993766 -8.99258408e-01j]] >>> print abs(T1-T2) # different -[[ 0. 2.1184 0.1949] - [ 0. 0. 1.2676] - [ 0. 0. 0. ]] +[[ 1.24357637e-14 2.09205364e+00 6.56028192e-01] + [ 0.00000000e+00 4.00296604e-16 1.83223097e+00] + [ 0.00000000e+00 0.00000000e+00 4.57756680e-16]] >>> print abs(Z1-Z2) # different -[[ 0.0683 1.1175 0.1973] - [ 0.1186 0.5644 0.247 ] - [ 0.1262 0.7645 0.1916]] +[[ 0.06833781 1.10591375 0.23662249] + [ 0.11857169 0.5585604 0.29617525] + [ 0.12624999 0.75656818 0.22975038]] >>> T,Z,T1,Z1,T2,Z2 = map(mat,(T,Z,T1,Z1,T2,Z2)) ->>> print abs(A-Z*T*Z.H) -Matrix([[ 0., 0., 0.], - [ 0., 0., 0.], - [ 0., 0., 0.]]) ->>> print abs(A-Z1*T1*Z1.H) -Matrix([[ 0., 0., 0.], - [ 0., 0., 0.], - [ 0., 0., 0.]]) ->>> print abs(A-Z2*T2*Z2.H) -Matrix([[ 0., 0., 0.], - [ 0., 0., 0.], - [ 0., 0., 0.]]) - - - +>>> print abs(A-Z*T*Z.H) # same +[[ 1.11022302e-16 4.44089210e-16 4.44089210e-16] + [ 4.44089210e-16 1.33226763e-15 8.88178420e-16] + [ 8.88178420e-16 4.44089210e-16 2.66453526e-15]] +>>> print abs(A-Z1*T1*Z1.H) # same +[[ 1.00043248e-15 2.22301403e-15 5.55749485e-15] + [ 2.88899660e-15 8.44927041e-15 9.77322008e-15] + [ 3.11291538e-15 1.15463228e-14 1.15464861e-14]] +>>> print abs(A-Z2*T2*Z2.H) # same +[[ 3.34058710e-16 8.88611201e-16 4.18773089e-18] + [ 1.48694940e-16 8.95109973e-16 8.92966151e-16] + [ 1.33228956e-15 1.33582317e-15 3.55373104e-15]] Modified: trunk/doc/source/tutorial/examples/10-4-4 =================================================================== --- trunk/doc/source/tutorial/examples/10-4-4 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/10-4-4 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,10 +1,17 @@ ->>> A = rand(3,3) +>>> from scipy import special, random, linalg +>>> A = random.rand(3,3) >>> B = linalg.funm(A,lambda x: special.jv(0,real(x))) >>> print A -[[ 0.0593 0.5612 0.4403] - [ 0.8797 0.2556 0.1452] - [ 0.964 0.9666 0.1243]] +[[ 0.72578091 0.34105276 0.79570345] + [ 0.65767207 0.73855618 0.541453 ] + [ 0.78397086 0.68043507 0.4837898 ]] >>> print B -[[ 0.8206 -0.1212 -0.0612] - [-0.1323 0.8256 -0.0627] - [-0.2073 -0.1946 0.8516]] +[[ 0.72599893 -0.20545711 -0.22721101] + [-0.27426769 0.77255139 -0.23422637] + [-0.27612103 -0.21754832 0.7556849 ]] +>>> print linalg.eigvals(A) +[ 1.91262611+0.j 0.21846476+0.j -0.18296399+0.j] +>>> print special.jv(0, linalg.eigvals(A)) +[ 0.27448286+0.j 0.98810383+0.j 0.99164854+0.j] +>>> print linalg.eigvals(B) +[ 0.27448286+0.j 0.98810383+0.j 0.99164854+0.j] Deleted: trunk/doc/source/tutorial/examples/3-1 =================================================================== --- trunk/doc/source/tutorial/examples/3-1 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/3-1 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,5 +0,0 @@ ->>> def addsubtract(a,b): - if a > b: - return a - b - else: - return a + b Deleted: trunk/doc/source/tutorial/examples/3-2 =================================================================== --- trunk/doc/source/tutorial/examples/3-2 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/3-2 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,2 +0,0 @@ ->>> vec_addsubtract([0,3,6,9],[1,3,5,7]) -array([1, 6, 1, 2]) Modified: trunk/doc/source/tutorial/examples/4-1 =================================================================== --- trunk/doc/source/tutorial/examples/4-1 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/4-1 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,13 +1,25 @@ >>> help(integrate) -Methods for Integrating Functions + Methods for Integrating Functions given function object. - odeint -- Integrate ordinary differential equations. - quad -- General purpose integration. - dblquad -- General purpose double integration. - tplquad -- General purpose triple integration. - gauss_quad -- Integrate func(x) using Gaussian quadrature of order n. - gauss_quadtol -- Integrate with given tolerance using Gaussian quadrature. + quad -- General purpose integration. + dblquad -- General purpose double integration. + tplquad -- General purpose triple integration. + fixed_quad -- Integrate func(x) using Gaussian quadrature of order n. + quadrature -- Integrate with given tolerance using Gaussian quadrature. + romberg -- Integrate func using Romberg integration. - See the orthogonal module (integrate.orthogonal) for Gaussian - quadrature roots and weights. + Methods for Integrating Functions given fixed samples. + trapz -- Use trapezoidal rule to compute integral from samples. + cumtrapz -- Use trapezoidal rule to cumulatively compute integral. + simps -- Use Simpson's rule to compute integral from samples. + romb -- Use Romberg Integration to compute integral from + (2**k + 1) evenly-spaced samples. + + See the special module's orthogonal polynomials (special) for Gaussian + quadrature roots and weights for other weighting factors and regions. + + Interface to numerical integrators of ODE systems. + + odeint -- General integration of ordinary differential equations. + ode -- Integrate ODE using VODE and ZVODE routines. Modified: trunk/doc/source/tutorial/examples/4-2 =================================================================== --- trunk/doc/source/tutorial/examples/4-2 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/4-2 2008-11-16 12:50:11 UTC (rev 5130) @@ -3,7 +3,7 @@ (1.1178179380783249, 7.8663172481899801e-09) >>> I = sqrt(2/pi)*(18.0/27*sqrt(2)*cos(4.5)-4.0/27*sqrt(2)*sin(4.5)+ - sqrt(2*pi)*special.fresnl(3/sqrt(pi))[0]) + sqrt(2*pi)*special.fresnel(3/sqrt(pi))[0]) >>> print I 1.117817938088701 Modified: trunk/doc/source/tutorial/examples/4-3 =================================================================== --- trunk/doc/source/tutorial/examples/4-3 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/4-3 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,9 +1,9 @@ ->>> from integrate import quad, Inf +>>> from scipy.integrate import quad >>> def integrand(t,n,x): - return exp(-x*t) / t**n +... return exp(-x*t) / t**n >>> def expint(n,x): - return quad(integrand, 1, Inf, args=(n, x))[0] +... return quad(integrand, 1, Inf, args=(n, x))[0] >>> vec_expint = vectorize(expint) Modified: trunk/doc/source/tutorial/examples/4-4 =================================================================== --- trunk/doc/source/tutorial/examples/4-4 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/4-4 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,4 +1,4 @@ ->>> result = quad(lambda x: expint(3, x), 0, Inf) +>>> result = quad(lambda x: expint(3, x), 0, inf) >>> print result (0.33333333324560266, 2.8548934485373678e-09) Modified: trunk/doc/source/tutorial/examples/4-5 =================================================================== --- trunk/doc/source/tutorial/examples/4-5 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/4-5 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,7 +1,6 @@ ->>> from __future__ import nested_scopes ->>> from integrate import quad, dblquad, Inf +>>> from scipy.integrate import quad, dblquad >>> def I(n): - return dblquad(lambda t, x: exp(-x*t)/t**n, 0, Inf, lambda x: 1, lambda x: Inf) +... return dblquad(lambda t, x: exp(-x*t)/t**n, 0, Inf, lambda x: 1, lambda x: Inf) >>> print I(4) (0.25000000000435768, 1.0518245707751597e-09) Modified: trunk/doc/source/tutorial/examples/4-6 =================================================================== --- trunk/doc/source/tutorial/examples/4-6 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/4-6 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,13 +1,13 @@ ->>> from integrate import odeint ->>> from special import gamma, airy +>>> from scipy.integrate import odeint +>>> from scipy.special import gamma, airy >>> y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0) >>> y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0) >>> y0 = [y0_0, y1_0] >>> def func(y, t): - return [t*y[1],y[0]] +... return [t*y[1],y[0]] >>> def gradient(y,t): - return [[0,t],[1,0]] +... return [[0,t],[1,0]] >>> x = arange(0,4.0, 0.01) >>> t = x @@ -15,8 +15,6 @@ >>> y = odeint(func, y0, t) >>> y2 = odeint(func, y0, t, Dfun=gradient) ->>> import sys ->>> sys.float_output_precision = 6 >>> print ychk[:36:6] [ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806] Modified: trunk/doc/source/tutorial/examples/5-1 =================================================================== --- trunk/doc/source/tutorial/examples/5-1 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-1 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,37 +1,91 @@ +from scipy import optimize >>> info(optimize) - Optimization Tools +Optimization Tools +================== -A collection of general-purpose optimization routines. + A collection of general-purpose optimization routines. - fmin -- Nelder-Mead Simplex algorithm - (uses only function calls) - fmin_powell -- Powell's (modified) level set method (uses only - function calls) - fmin_bfgs -- Quasi-Newton method (can use function and gradient) - fmin_ncg -- Line-search Newton Conjugate Gradient (can use - function, gradient and hessian). - leastsq -- Minimize the sum of squares of M equations in - N unknowns given a starting estimate. + fmin -- Nelder-Mead Simplex algorithm + (uses only function calls) + fmin_powell -- Powell's (modified) level set method (uses only + function calls) + fmin_cg -- Non-linear (Polak-Ribiere) conjugate gradient algorithm + (can use function and gradient). + fmin_bfgs -- Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno); + (can use function and gradient) + fmin_ncg -- Line-search Newton Conjugate Gradient (can use + function, gradient and Hessian). + leastsq -- Minimize the sum of squares of M equations in + N unknowns given a starting estimate. - Scalar function minimizers - fminbound -- Bounded minimization of a scalar function. - brent -- 1-D function minimization using Brent method. - golden -- 1-D function minimization using Golden Section method - bracket -- Bracket a minimum (given two starting points) - -Also a collection of general_purpose root-finding routines. + Constrained Optimizers (multivariate) - fsolve -- Non-linear multi-variable equation solver. + fmin_l_bfgs_b -- Zhu, Byrd, and Nocedal's L-BFGS-B constrained optimizer + (if you use this please quote their papers -- see help) - Scalar function solvers + fmin_tnc -- Truncated Newton Code originally written by Stephen Nash and + adapted to C by Jean-Sebastien Roy. - brentq -- quadratic interpolation Brent method - brenth -- Brent method (modified by Harris with - hyperbolic extrapolation) - ridder -- Ridder's method - bisect -- Bisection method - newton -- Secant method or Newton's method + fmin_cobyla -- Constrained Optimization BY Linear Approximation - fixed_point -- Single-variable fixed-point solver. + Global Optimizers + + anneal -- Simulated Annealing + brute -- Brute force searching optimizer + + + Scalar function minimizers + + fminbound -- Bounded minimization of a scalar function. + brent -- 1-D function minimization using Brent method. + golden -- 1-D function minimization using Golden Section method + bracket -- Bracket a minimum (given two starting points) + + + Also a collection of general-purpose root-finding routines. + + fsolve -- Non-linear multi-variable equation solver. + + + Scalar function solvers + + brentq -- quadratic interpolation Brent method + brenth -- Brent method (modified by Harris with hyperbolic + extrapolation) + ridder -- Ridder's method + bisect -- Bisection method + newton -- Secant method or Newton's method + + fixed_point -- Single-variable fixed-point solver. + + A collection of general-purpose nonlinear multidimensional solvers. + + broyden1 -- Broyden's first method - is a quasi-Newton-Raphson + method for updating an approximate Jacobian and then + inverting it + broyden2 -- Broyden's second method - the same as broyden1, but + updates the inverse Jacobian directly + broyden3 -- Broyden's second method - the same as broyden2, but + instead of directly computing the inverse Jacobian, + it remembers how to construct it using vectors, and + when computing inv(J)*F, it uses those vectors to + compute this product, thus avoding the expensive NxN + matrix multiplication. + broyden_generalized -- Generalized Broyden's method, the same as broyden2, + but instead of approximating the full NxN Jacobian, + it construct it at every iteration in a way that + avoids the NxN matrix multiplication. This is not + as precise as broyden3. + anderson -- extended Anderson method, the same as the + broyden_generalized, but added w_0^2*I to before + taking inversion to improve the stability + anderson2 -- the Anderson method, the same as anderson, but + formulated differently + + Utility Functions + + line_search -- Return a step that satisfies the strong Wolfe conditions. + check_grad -- Check the supplied derivative using finite difference + techniques. Modified: trunk/doc/source/tutorial/examples/5-2 =================================================================== --- trunk/doc/source/tutorial/examples/5-2 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-2 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,13 +1,14 @@ >>> from scipy.optimize import fmin ->>> def rosen(x): # The Rosenbrock function - return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) +>>> def rosen(x): +... """The Rosenbrock function""" +... return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin(rosen, x0) +>>> xopt = fmin(rosen, x0, xtol=1e-8) Optimization terminated successfully. Current function value: 0.000000 - Iterations: 516 - Function evaluations: 825 + Iterations: 339 + Function evaluations: 571 >>> print xopt [ 1. 1. 1. 1. 1.] Modified: trunk/doc/source/tutorial/examples/5-3 =================================================================== --- trunk/doc/source/tutorial/examples/5-3 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-3 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,10 +1,10 @@ >>> def rosen_der(x): - xm = x[1:-1] - xm_m1 = x[:-2] - xm_p1 = x[2:] - der = zeros(x.shape,x.typecode()) - der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm) - der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0]) - der[-1] = 200*(x[-1]-x[-2]**2) - return der +... xm = x[1:-1] +... xm_m1 = x[:-2] +... xm_p1 = x[2:] +... der = zeros_like(x) +... der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_p1 - xm**2)*xm - 2*(1-xm) +... der[0] = -400*x[0]*(x[1]-x[0]**2) - 2*(1-x[0]) +... der[-1] = 200*(x[-1]-x[-2]**2) +... return der Modified: trunk/doc/source/tutorial/examples/5-4 =================================================================== --- trunk/doc/source/tutorial/examples/5-4 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-4 2008-11-16 12:50:11 UTC (rev 5130) @@ -4,8 +4,8 @@ >>> xopt = fmin_bfgs(rosen, x0, fprime=rosen_der) Optimization terminated successfully. Current function value: 0.000000 - Iterations: 109 - Function evaluations: 262 - Gradient evaluations: 110 + Iterations: 53 + Function evaluations: 65 + Gradient evaluations: 65 >>> print xopt -[ 1. 1. 1. 1. 1.] +[ 1. 1. 1. 1. 1.] Modified: trunk/doc/source/tutorial/examples/5-5 =================================================================== --- trunk/doc/source/tutorial/examples/5-5 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-5 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,21 +1,21 @@ >>> from scipy.optimize import fmin_ncg >>> def rosen_hess(x): - x = asarray(x) - H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1) - diagonal = zeros(len(x),x.typecode()) - diagonal[0] = 1200*x[0]-400*x[1]+2 - diagonal[-1] = 200 - diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:] - H = H + diag(diagonal) - return H +... x = asarray(x) +... H = diag(-400*x[:-1],1) - diag(400*x[:-1],-1) +... diagonal = zeros_like(x) +... diagonal[0] = 1200*x[0]-400*x[1]+2 +... diagonal[-1] = 200 +... diagonal[1:-1] = 202 + 1200*x[1:-1]**2 - 400*x[2:] +... H = H + diag(diagonal) +... return H >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess=rosen_hess) +>>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess=rosen_hess, avextol=1e-8) Optimization terminated successfully. Current function value: 0.000000 - Iterations: 19 - Function evaluations: 40 - Gradient evaluations: 19 - Hessian evaluations: 19 + Iterations: 23 + Function evaluations: 26 + Gradient evaluations: 23 + Hessian evaluations: 23 >>> print xopt -[ 0.9999 0.9999 0.9998 0.9996 0.9991] +[ 1. 1. 1. 1. 1.] Modified: trunk/doc/source/tutorial/examples/5-6 =================================================================== --- trunk/doc/source/tutorial/examples/5-6 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-6 2008-11-16 12:50:11 UTC (rev 5130) @@ -1,20 +1,20 @@ >>> from scipy.optimize import fmin_ncg >>> def rosen_hess_p(x,p): - x = asarray(x) - Hp = zeros(len(x),x.typecode()) - Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1] - Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \ - -400*x[1:-1]*p[2:] - Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1] - return Hp +... x = asarray(x) +... Hp = zeros_like(x) +... Hp[0] = (1200*x[0]**2 - 400*x[1] + 2)*p[0] - 400*x[0]*p[1] +... Hp[1:-1] = -400*x[:-2]*p[:-2]+(202+1200*x[1:-1]**2-400*x[2:])*p[1:-1] \ +... -400*x[1:-1]*p[2:] +... Hp[-1] = -400*x[-2]*p[-2] + 200*p[-1] +... return Hp >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] ->>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess_p=rosen_hess_p) +>>> xopt = fmin_ncg(rosen, x0, rosen_der, fhess_p=rosen_hess_p, avextol=1e-8) Optimization terminated successfully. Current function value: 0.000000 - Iterations: 20 - Function evaluations: 42 - Gradient evaluations: 20 - Hessian evaluations: 44 + Iterations: 22 + Function evaluations: 25 + Gradient evaluations: 22 + Hessian evaluations: 54 >>> print xopt -[ 1. 1. 1. 0.9999 0.9999] +[ 1. 1. 1. 1. 1.] Modified: trunk/doc/source/tutorial/examples/5-9 =================================================================== --- trunk/doc/source/tutorial/examples/5-9 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/examples/5-9 2008-11-16 12:50:11 UTC (rev 5130) @@ -6,11 +6,11 @@ out.append(x[1]*x[0] - x[1] - 5) return out ->>> from optimize import fsolve +>>> from scipy.optimize import fsolve >>> x0 = fsolve(func, 0.3) >>> print x0 -1.02986652932 >>> x02 = fsolve(func2, [1, 1]) >>> print x02 -[ 6.5041 0.9084] +[ 6.50409711 0.90841421] Modified: trunk/doc/source/tutorial/index.rst =================================================================== --- trunk/doc/source/tutorial/index.rst 2008-11-16 11:53:13 UTC (rev 5129) +++ trunk/doc/source/tutorial/index.rst 2008-11-16 12:50:11 UTC (rev 5130) @@ -40,11 +40,15 @@ acquired by working through the Tutorial in the Python distribution. For further introductory help the user is directed to the Numpy documentation. Throughout this tutorial it is assumed that the user -has imported all of the names defined in the SciPy namespace using the -command +has imported all of the names defined in the SciPy top-level namespace +using the command >>> from scipy import * +Scipy sub-packages need to be imported separately, for example + + >>> from scipy import linalg, optimize + General Help ------------ @@ -226,7 +230,15 @@ for example that one wants to construct an array that begins with 3 followed by 5 zeros and then contains 10 numbers spanning the range -1 to 1 (inclusive on both ends). Before SciPy, you would need to enter -something like the following ``>>> concatenate(([3],[0]*5,arange(-1,1.002,2/9.0))`` . With the :obj:`r_` command one can enter this as ``>>> r_[3,[0]*5,-1:1:10j]`` which can ease typing and make for more readable code. Notice how +something like the following + + >>> concatenate(([3],[0]*5,arange(-1,1.002,2/9.0))) + +With the :obj:`r_` command one can enter this as + + >>> r_[3,[0]*5,-1:1:10j] + +which can ease typing and make for more readable code. Notice how objects are concatenated, and the slicing syntax is (ab)used to construct ranges. The other term that deserves a little explanation is the use of the complex number 10j as the step size in the slicing @@ -239,29 +251,33 @@ fashion. When the number of points is specified in this way, the end- point is inclusive. -The "r "stands for row concatenation because if the objects between commas are -2 dimensional arrays, they are stacked by rows (and thus must have -commensurate columns). There is an equivalent command :obj:`c_` that stacks 2d arrays by columns but works identically to :obj:`r_` for 1d arrays. +The "r" stands for row concatenation because if the objects between +commas are 2 dimensional arrays, they are stacked by rows (and thus +must have commensurate columns). There is an equivalent command +:obj:`c_` that stacks 2d arrays by columns but works identically to +:obj:`r_` for 1d arrays. Another very useful class instance which makes use of extended slicing -notation is the function :obj:`mgrid` . In the simplest case, this function can be used to construct 1d -ranges as a convenient substitute for arange. It also allows the use -of complex-numbers in the step-size to indicate the number of points -to place between the (inclusive) end-points. The real purpose of this -function however is to produce N, N-d arrays which provide coordinate -arrays for an N-dimensional volume. The easiest way to understand this -is with an example of its usage: +notation is the function :obj:`mgrid`. In the simplest case, this +function can be used to construct 1d ranges as a convenient substitute +for arange. It also allows the use of complex-numbers in the step-size +to indicate the number of points to place between the (inclusive) +end-points. The real purpose of this function however is to produce N, +N-d arrays which provide coordinate arrays for an N-dimensional +volume. The easiest way to understand this is with an example of its +usage: .. literalinclude:: examples/2-1 Having meshed arrays like this is sometimes very useful. However, it is not always needed just to evaluate some N-dimensional function over -a grid due to the array-broadcasting rules of Numpy and SciPy. If -this is the only purpose for generating a meshgrid, you should instead -use the function :obj:`ogrid` which generates an "open "grid using NewAxis judiciously to create N, N-d arrays where only one- -dimension in each array has length greater than 1. This will save -memory and create the same result if the only purpose for the meshgrid -is to generate sample points for evaluation of an N-d function. +a grid due to the array-broadcasting rules of Numpy and SciPy. If this +is the only purpose for generating a meshgrid, you should instead use +the function :obj:`ogrid` which generates an "open "grid using NewAxis +judiciously to create N, N-d arrays where only one dimension in each +array has length greater than 1. This will save memory and create the +same result if the only purpose for the meshgrid is to generate sample +points for evaluation of an N-d function. Shape manipulation @@ -270,8 +286,9 @@ In this category of functions are routines for squeezing out length- one dimensions from N-dimensional arrays, ensuring that an array is at least 1-, 2-, or 3-dimensional, and stacking (concatenating) arrays by -rows, columns, and "pages "(in the third dimension). Routines for splitting arrays (roughly the -opposite of stacking arrays) are also available. +rows, columns, and "pages "(in the third dimension). Routines for +splitting arrays (roughly the opposite of stacking arrays) are also +available. Matrix manipulations @@ -311,7 +328,11 @@ ufuncs). For example, suppose you have a Python function named :obj:`addsubtract` defined as: -.. literalinclude:: examples/3-1 + >>> def addsubtract(a,b): + ... if a > b: + ... return a - b + ... else: + ... return a + b which defines a function of two scalar variables and returns a scalar result. The class vectorize can be used to "vectorize "this function so that :: @@ -321,7 +342,8 @@ returns a function which takes array arguments and returns an array result: -.. literalinclude:: examples/3-2 + >>> vec_addsubtract([0,3,6,9],[1,3,5,7]) + array([1, 6, 1, 2]) This particular function could have been written in vector form without the use of :obj:`vectorize` . But, what if the function you have written is the result of some @@ -337,8 +359,9 @@ Numpy package. The reason for duplicating these functions is to allow SciPy to potentially alter their original interface and make it easier for users to know how to get access to functions -``>>> from scipy import \*.`` + >>> from scipy import * + New functions which should be mentioned are :obj:`mod(x,y)` which can replace ``x % y`` when it is desired that the result take the sign of *y* instead of *x* . Also included is :obj:`fix` which always rounds @@ -400,7 +423,7 @@ broadcasting rules as other math functions in Numerical Python. Many of these functions also accept complex-numbers as input. For a complete list of the available functions with a one-line description -type ``>>>info(special).`` Each function also has it's own +type ``>>> info(special).`` Each function also has it's own documentation accessible using help. If you don't see a function you need, consider writing it and contributing it to the library. You can write the function in either C, Fortran, or Python. Look in the source @@ -785,7 +808,8 @@ \[ \mathbf{H}\left(\mathbf{x}\right)\mathbf{p}=\left[\begin{array}{c} \left(1200x_{0}^{2}-400x_{1}+2\right)p_{0}-400x_{0}p_{1}\\ \vdots\\ -400x_{i-1}p_{i-1}+\left(202+1200x_{i}^{2}-400x_{i+1}\right)p_{i}-400x_{i}p_{i+1}\\ \vdots\\ -400x_{N-2}p_{N-2}+200p_{N-1}\end{array}\right].\] -Code which makes use of the *fhess_p* keyword to minimize the Rosenbrock function using :obj:`fmin_ncg` follows: +Code which makes use of the *fhess_p* keyword to minimize the +Rosenbrock function using :obj:`fmin_ncg` follows: .. literalinclude:: examples/5-6 @@ -1595,11 +1619,11 @@ ^^^^^^^^^^^^^^^^^^^^^ Solving linear systems of equations is straightforward using the scipy -command :obj:`linalg.solve`. This command expects an input matrix and a right-hand-side vector. The -solution vector is then computed. An option for entering a symmetrix -matrix is offered which can speed up the processing when applicable. -As an example, suppose it is desired to solve the following -simultaneous equations: +command :obj:`linalg.solve`. This command expects an input matrix and +a right-hand-side vector. The solution vector is then computed. An +option for entering a symmetrix matrix is offered which can speed up +the processing when applicable. As an example, suppose it is desired +to solve the following simultaneous equations: .. math:: :nowrap: @@ -1614,8 +1638,8 @@ \[ \left[\begin{array}{c} x\\ y\\ z\end{array}\right]=\left[\begin{array}{ccc} 1 & 3 & 5\\ 2 & 5 & 1\\ 2 & 3 & 8\end{array}\right]^{-1}\left[\begin{array}{c} 10\\ 8\\ 3\end{array}\right]=\frac{1}{25}\left[\begin{array}{c} -232\\ 129\\ 19\end{array}\right]=\left[\begin{array}{c} -9.28\\ 5.16\\ 0.76\end{array}\right].\] However, it is better to use the linalg.solve command which can be -faster and more numerically stable. In this case it gives the same -answer as shown in the following example: +faster and more numerically stable. In this case it however gives the +same answer as shown in the following example: .. literalinclude:: examples/10-2-2 From scipy-svn at scipy.org Sun Nov 16 08:09:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 07:09:32 -0600 (CST) Subject: [Scipy-svn] r5131 - trunk/doc/release Message-ID: <20081116130932.ADBD839C088@scipy.org> Author: ptvirtan Date: 2008-11-16 07:09:22 -0600 (Sun, 16 Nov 2008) New Revision: 5131 Modified: trunk/doc/release/0.7.0-notes.rst Log: Release notes: mention #289 and #660 that change interp1d behavior Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-16 12:50:11 UTC (rev 5130) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-16 13:09:22 UTC (rev 5131) @@ -133,6 +133,19 @@ TODO +Bug fixes in the interpolation package +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The shape of return values from ``scipy.interpolate.interp1d`` used +to be incorrect if interpolated data had more than 2 dimensions and +the axis keyword was set to a non-default value. This is fixed in 0.7.0: + + http://projects.scipy.org/scipy/scipy/ticket/289 + http://projects.scipy.org/scipy/scipy/ticket/660 + +Users of ``scipy.interpolate.interp1d`` may need to revise their code +if it relies on the incorrect behavior. + Running Tests ~~~~~~~~~~~~~ From scipy-svn at scipy.org Sun Nov 16 08:12:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 07:12:18 -0600 (CST) Subject: [Scipy-svn] r5132 - trunk/doc/release Message-ID: <20081116131218.49E4F39C088@scipy.org> Author: ptvirtan Date: 2008-11-16 07:12:04 -0600 (Sun, 16 Nov 2008) New Revision: 5132 Modified: trunk/doc/release/0.7.0-notes.rst Log: Release notes: fix rst Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-16 13:09:22 UTC (rev 5131) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-16 13:12:04 UTC (rev 5132) @@ -150,7 +150,7 @@ ~~~~~~~~~~~~~ We are moving away from having our own testing framework and are -adopting `nose `. +adopting `nose `__. Building SciPy ~~~~~~~~~~~~~~ From scipy-svn at scipy.org Sun Nov 16 08:34:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 07:34:06 -0600 (CST) Subject: [Scipy-svn] r5133 - in trunk/scipy: cluster linalg optimize Message-ID: <20081116133406.CA4D639C088@scipy.org> Author: ptvirtan Date: 2008-11-16 07:33:51 -0600 (Sun, 16 Nov 2008) New Revision: 5133 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/linalg/basic.py trunk/scipy/linalg/info.py trunk/scipy/optimize/info.py Log: Fix some docstring offending Sphinx Latex generation Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-16 13:12:04 UTC (rev 5132) +++ trunk/scipy/cluster/hierarchy.py 2008-11-16 13:33:51 UTC (rev 5133) @@ -966,7 +966,9 @@ deviation of the link heights, respectively; ``R[i,2]`` is the number of links included in the calculation; and ``R[i,3]`` is the inconsistency coefficient, - .. math: + + .. math:: + \frac{\mathtt{Z[i,2]}-\mathtt{R[i,0]}} {R[i,1]}. Modified: trunk/scipy/linalg/basic.py =================================================================== --- trunk/scipy/linalg/basic.py 2008-11-16 13:12:04 UTC (rev 5132) +++ trunk/scipy/linalg/basic.py 2008-11-16 13:33:51 UTC (rev 5133) @@ -400,14 +400,14 @@ ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm - 'fro' Frobenius norm - + 'fro' Frobenius norm -- inf max(sum(abs(x), axis=1)) max(abs(x)) -inf min(sum(abs(x), axis=1)) min(abs(x)) 1 max(sum(abs(x), axis=0)) as below -1 min(sum(abs(x), axis=0)) as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below - other - sum(abs(x)**ord)**(1./ord) + other -- sum(abs(x)**ord)**(1./ord) ===== ============================ ========================== Returns Modified: trunk/scipy/linalg/info.py =================================================================== --- trunk/scipy/linalg/info.py 2008-11-16 13:12:04 UTC (rev 5132) +++ trunk/scipy/linalg/info.py 2008-11-16 13:33:51 UTC (rev 5133) @@ -2,7 +2,7 @@ Linear algebra routines ======================= - Linear Algebra Basics: +Linear Algebra Basics:: inv --- Find the inverse of a square matrix solve --- Solve a linear system of equations @@ -14,7 +14,7 @@ pinv --- Pseudo-inverse (Moore-Penrose) using lstsq pinv2 --- Pseudo-inverse using svd - Eigenvalues and Decompositions: +Eigenvalues and Decompositions:: eig --- Find the eigenvalues and vectors of a square matrix eigvals --- Find the eigenvalues of a square matrix @@ -36,7 +36,7 @@ rsf2csf --- Real to complex schur form hessenberg --- Hessenberg form of a matrix - matrix Functions: +matrix Functions:: expm --- matrix exponential using Pade approx. expm2 --- matrix exponential using Eigenvalue decomp. @@ -52,7 +52,7 @@ sqrtm --- matrix square root funm --- Evaluating an arbitrary matrix function. - Iterative linear systems solutions +Iterative linear systems solutions:: cg --- Conjugate gradient (symmetric systems only) cgs --- Conjugate gradient squared Modified: trunk/scipy/optimize/info.py =================================================================== --- trunk/scipy/optimize/info.py 2008-11-16 13:12:04 UTC (rev 5132) +++ trunk/scipy/optimize/info.py 2008-11-16 13:33:51 UTC (rev 5133) @@ -2,7 +2,7 @@ Optimization Tools ================== - A collection of general-purpose optimization routines. +A collection of general-purpose optimization routines.:: fmin -- Nelder-Mead Simplex algorithm (uses only function calls) @@ -17,9 +17,8 @@ leastsq -- Minimize the sum of squares of M equations in N unknowns given a starting estimate. +Constrained Optimizers (multivariate):: - Constrained Optimizers (multivariate) - fmin_l_bfgs_b -- Zhu, Byrd, and Nocedal's L-BFGS-B constrained optimizer (if you use this please quote their papers -- see help) @@ -28,28 +27,24 @@ fmin_cobyla -- Constrained Optimization BY Linear Approximation +Global Optimizers:: - Global Optimizers - anneal -- Simulated Annealing brute -- Brute force searching optimizer +Scalar function minimizers:: - Scalar function minimizers - fminbound -- Bounded minimization of a scalar function. brent -- 1-D function minimization using Brent method. golden -- 1-D function minimization using Golden Section method bracket -- Bracket a minimum (given two starting points) +Also a collection of general-purpose root-finding routines:: - Also a collection of general-purpose root-finding routines. - fsolve -- Non-linear multi-variable equation solver. +Scalar function solvers:: - Scalar function solvers - brentq -- quadratic interpolation Brent method brenth -- Brent method (modified by Harris with hyperbolic extrapolation) @@ -59,7 +54,7 @@ fixed_point -- Single-variable fixed-point solver. - A collection of general-purpose nonlinear multidimensional solvers. +A collection of general-purpose nonlinear multidimensional solvers:: broyden1 -- Broyden's first method - is a quasi-Newton-Raphson method for updating an approximate Jacobian and then @@ -83,7 +78,7 @@ anderson2 -- the Anderson method, the same as anderson, but formulated differently - Utility Functions +Utility Functions:: line_search -- Return a step that satisfies the strong Wolfe conditions. check_grad -- Check the supplied derivative using finite difference From scipy-svn at scipy.org Sun Nov 16 08:43:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 07:43:11 -0600 (CST) Subject: [Scipy-svn] r5134 - trunk/doc/source/tutorial Message-ID: <20081116134311.06BE139C088@scipy.org> Author: ptvirtan Date: 2008-11-16 07:43:00 -0600 (Sun, 16 Nov 2008) New Revision: 5134 Modified: trunk/doc/source/tutorial/index.rst Log: Tutorial: update linear_1d -> interp1d Modified: trunk/doc/source/tutorial/index.rst =================================================================== --- trunk/doc/source/tutorial/index.rst 2008-11-16 13:33:51 UTC (rev 5133) +++ trunk/doc/source/tutorial/index.rst 2008-11-16 13:43:00 UTC (rev 5134) @@ -980,10 +980,10 @@ 2-dimensional (smoothed) cubic-spline interpolation. -Linear 1-d interpolation (interpolate.linear_1d) ------------------------------------------------- +Linear 1-d interpolation (interpolate.interp1d) +----------------------------------------------- -The linear_1d class in scipy.interpolate is a convenient method to +The interp1d class in scipy.interpolate is a convenient method to create a function based on fixed data points which can be evaluated anywhere within the domain defined by the given data using linear interpolation. An instance of this class is created by passing the 1-d @@ -1002,7 +1002,7 @@ :align: center .. **Figure 2** One-dimensional interpolation using the - class :obj:`interpolate.linear_1d` + class :obj:`interpolate.interp1d` Spline interpolation in 1-d (interpolate.splXXX) @@ -1042,8 +1042,8 @@ :align: center -Two-dimensionsal spline representation (interpolate.bisplrep) -------------------------------------------------------------- +Two-dimensional spline representation (interpolate.bisplrep) +------------------------------------------------------------ For (smooth) spline-fitting to a two dimensional surface, the function :obj:`interpolate.bisplrep` is available. This function takes as From scipy-svn at scipy.org Sun Nov 16 09:36:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 08:36:38 -0600 (CST) Subject: [Scipy-svn] r5135 - trunk/scipy/stats Message-ID: <20081116143638.1721839C088@scipy.org> Author: josef Date: 2008-11-16 08:36:35 -0600 (Sun, 16 Nov 2008) New Revision: 5135 Modified: trunk/scipy/stats/distributions.py Log: skip nbinom.sf and calculate it indirectly, fix for n<1, tickets #583, #697 Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-16 13:43:00 UTC (rev 5134) +++ trunk/scipy/stats/distributions.py 2008-11-16 14:36:35 UTC (rev 5135) @@ -4011,7 +4011,8 @@ def _cdf(self, x, n, pr): k = floor(x) return special.betainc(n, k+1, pr) - def _sf(self, x, n, pr): + def _sf_skip(self, x, n, pr): + #skip because special.nbdtrc doesn't work for 0 Author: wnbell Date: 2008-11-16 14:36:10 -0600 (Sun, 16 Nov 2008) New Revision: 5136 Modified: trunk/doc/release/0.7.0-notes.rst Log: minor edits to list of sparse changes Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-16 14:36:35 UTC (rev 5135) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-16 20:36:10 UTC (rev 5136) @@ -14,7 +14,7 @@ * added support for integer dtypes such ``int8``, ``uint32``, etc. * new class ``dia_matrix`` : the sparse DIAgonal format -* new class ``bsr_matrix`` : sparse Block CSR format +* new class ``bsr_matrix`` : the Block CSR format * new sparse matrix construction functions * ``sparse.kron`` : sparse Kronecker product @@ -25,7 +25,7 @@ * extraction of submatrices and nonzero values * ``sparse.tril`` : extract lower triangle - * ``sparse.kron`` : extract upper triangle + * ``sparse.triu`` : extract upper triangle * ``sparse.find`` : nonzero values and their indices * ``csr_matrix`` and ``csc_matrix`` now support slicing and fancy indexing @@ -34,9 +34,11 @@ * conversions among all sparse formats are now possible - * all formats have member functions such as ``.tocsr()`` and ``.tolil()`` + * using member functions such as ``.tocsr()`` and ``.tolil()`` + * using the ``.asformat()`` member function, e.g. ``A.asformat('csr')`` + * using constructors ``A = lil_matrix([[1,2]]); B = csr_matrix(A)`` -* sparse constructors now accept dense matrices and other sparse formats +* all sparse constructors now accept dense matrices and lists of lists * e.g. ``A = csr_matrix( rand(3,3) )`` and ``B = lil_matrix( [[1,2],[3,4]] )`` From scipy-svn at scipy.org Sun Nov 16 18:27:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 17:27:18 -0600 (CST) Subject: [Scipy-svn] r5137 - trunk/scipy/stats/tests Message-ID: <20081116232718.925EB39C05F@scipy.org> Author: josef Date: 2008-11-16 17:27:15 -0600 (Sun, 16 Nov 2008) New Revision: 5137 Modified: trunk/scipy/stats/tests/test_continuous_basic.py trunk/scipy/stats/tests/test_continuous_extra.py trunk/scipy/stats/tests/test_discrete_basic.py Log: add skew, kurtosis and entropy test to discrete rv, add tests for 2 tickets, some cleanup of messages Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-16 20:36:10 UTC (rev 5136) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-16 23:27:15 UTC (rev 5137) @@ -71,6 +71,7 @@ ['levy_l', ()], # ['levy_stable', (0.35667405469844993, # -0.67450531578494011)], #NotImplementedError + # rvs not tested ['loggamma', (0.41411931826052117,)], ['logistic', ()], ['loglaplace', (3.2505926592051435,)], @@ -89,6 +90,7 @@ ['powernorm', (4.4453652254590779,)], ['rayleigh', ()], ['rdist', (3.8266985793976525,)], + ['rdist', (541.0,)], # from ticket #758 ['recipinvgauss', (0.63004267809369119,)], ['reciprocal', (0.0062309367010521255, 1.0062309367010522)], ['rice', (0.7749725210111873,)], Modified: trunk/scipy/stats/tests/test_continuous_extra.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-16 20:36:10 UTC (rev 5136) +++ trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-16 23:27:15 UTC (rev 5137) @@ -24,9 +24,8 @@ yield check_loc_scale, distfn, arg, distname + \ ' loc, scale test' #entropy test checks only for isnan, currently 6 isnan - # ## yield check_entropy, distfn, arg, distname + \ -## ' loc, scale test' +## ' entropy nan test' def check_ppf_limits(distfn,arg,msg): Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-16 20:36:10 UTC (rev 5136) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-16 23:27:15 UTC (rev 5137) @@ -4,6 +4,8 @@ from scipy import stats +DECIMAL_meanvar = 0#1 # was 0 + distdiscrete = [ ['bernoulli',(0.3,)], ['binom', (5, 0.4)], @@ -13,12 +15,16 @@ ['hypergeom',(30, 12, 6)], ['logser', (0.6,)], ['nbinom', (5, 0.5)], + ['nbinom', (0.4, 0.4)], #from tickets: 583 ['planck', (0.51,)], #4.1 ['poisson', (0.6,)], ['randint', (7, 31)], ['zipf', (4,)] ] # arg=4 is ok, # Zipf broken for arg = 2, e.g. weird .stats + # looking closer, mean, var should be inf for arg=2 + + def test_discrete_basic(): for distname, arg in distdiscrete: distfn = getattr(stats,distname) @@ -27,11 +33,16 @@ m,v = distfn.stats(*arg) #yield npt.assert_almost_equal(rvs.mean(), m, decimal=4,err_msg='mean') #yield npt.assert_almost_equal, rvs.mean(), m, 2, 'mean' # does not work - yield check_sample_mean, rvs.mean(), m, distname + 'sample mean test' - yield check_sample_mean, rvs.var(), v, distname + 'sample var test' - yield check_cdf_ppf, distfn, arg - yield check_pmf_cdf, distfn, arg - yield check_oth, distfn, arg + yield check_sample_meanvar, rvs.mean(), m, distname + 'sample mean test' + yield check_sample_meanvar, rvs.var(), v, distname + 'sample var test' + yield check_cdf_ppf, distfn, arg, distname + yield check_pmf_cdf, distfn, arg, distname + yield check_oth, distfn, arg, distname + skurt = stats.kurtosis(rvs) + sskew = stats.skew(rvs) + yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + yield check_entropy, distfn, arg, distname + \ + ' entropy nan test' def test_discrete_private(): #testing private methods mostly for debugging @@ -43,36 +54,36 @@ m,v = distfn.stats(*arg) yield check_ppf_ppf, distfn, arg - yield check_cdf_ppf_private, distfn, arg + yield check_cdf_ppf_private, distfn, arg, distname yield check_generic_moment, distfn, arg, m, 1, 3 # last is decimal yield check_generic_moment, distfn, arg, v+m*m, 2, 3 # last is decimal yield check_moment_frozen, distfn, arg, m, 1, 3 # last is decimal yield check_moment_frozen, distfn, arg, v+m*m, 2, 3 # last is decimal -def check_sample_mean(sm,m,msg): - if m < np.inf: - npt.assert_almost_equal(sm, m, decimal=0, err_msg=msg + \ +def check_sample_meanvar(sm,m,msg): + if not np.isinf(m): + npt.assert_almost_equal(sm, m, decimal=DECIMAL_meanvar, err_msg=msg + \ ' - finite moment') else: assert sm > 10000, 'infinite moment, sm = ' + str(sm) -def check_sample_var(sm,m): - npt.assert_almost_equal(sm, m, decimal=0, err_msg= 'var') +def check_sample_var(sm,m,msg): + npt.assert_almost_equal(sm, m, decimal=DECIMAL_meanvar, err_msg= msg + 'var') -def check_cdf_ppf(distfn,arg): +def check_cdf_ppf(distfn,arg,msg): ppf05 = distfn.ppf(0.5,*arg) cdf05 = distfn.cdf(ppf05,*arg) npt.assert_almost_equal(distfn.ppf(cdf05-1e-6,*arg),ppf05, - err_msg=str(distfn) + 'ppf-cdf-median') - assert (distfn.ppf(cdf05+1e-4,*arg)>ppf05), str(distfn) + 'ppf-cdf-next' + err_msg=msg + 'ppf-cdf-median') + assert (distfn.ppf(cdf05+1e-4,*arg)>ppf05), msg + 'ppf-cdf-next' -def check_cdf_ppf_private(distfn,arg): +def check_cdf_ppf_private(distfn,arg,msg): ppf05 = distfn._ppf(0.5,*arg) cdf05 = distfn.cdf(ppf05,*arg) npt.assert_almost_equal(distfn._ppf(cdf05-1e-6,*arg),ppf05, - err_msg=str(distfn) + 'ppf-cdf-median') - assert (distfn._ppf(cdf05+1e-4,*arg)>ppf05), str(distfn) + 'ppf-cdf-next' + err_msg=msg + '_ppf-cdf-median ') + assert (distfn._ppf(cdf05+1e-4,*arg)>ppf05), msg + '_ppf-cdf-next' def check_ppf_ppf(distfn, arg): assert distfn.ppf(0.5,*arg) < np.inf @@ -84,13 +95,13 @@ assert ppf_s[0] == ppfs[0] assert ppf_s[1] == ppfs[1] -def check_pmf_cdf(distfn, arg): +def check_pmf_cdf(distfn, arg, msg): startind = np.int(distfn._ppf(0.01,*arg)-1) index = range(startind,startind+10) cdfs = distfn.cdf(index,*arg) npt.assert_almost_equal(cdfs, distfn.pmf(index, *arg).cumsum() + \ cdfs[0] - distfn.pmf(index[0],*arg), - decimal=4, err_msg='pmf-cdf') + decimal=4, err_msg= msg + 'pmf-cdf') def check_generic_moment(distfn, arg, m, k, decim): npt.assert_almost_equal(distfn.generic_moment(k,*arg), m, decimal=decim, @@ -100,7 +111,7 @@ npt.assert_almost_equal(distfn(*arg).moment(k), m, decimal=decim, err_msg= str(distfn) + ' frozen moment test') -def check_oth(distfn, arg): +def check_oth(distfn, arg, msg): #checking other methods of distfn meanint = round(distfn.stats(*arg)[0]) # closest integer to mean npt.assert_almost_equal(distfn.sf(meanint, *arg), 1 - \ @@ -112,5 +123,17 @@ npt.assert_equal(distfn.isf(0.5, *arg), distfn.ppf(0.5, *arg)) +def check_sample_skew_kurt(distfn, arg, sk, ss, msg): + k,s = distfn.stats(moment='ks',*arg) + check_sample_meanvar, sk, k, msg + 'sample skew test' + check_sample_meanvar, ss, s, msg + 'sample kurtosis test' + + +def check_entropy(distfn,arg,msg): + ent = distfn.entropy(*arg) + #print 'Entropy =', ent + assert not np.isnan(ent), msg + 'test Entropy is nan'\ + if __name__ == "__main__": - nose.run(argv=['', __file__]) + #nose.run(argv=['', __file__]) + nose.runmodule(argv=[__file__,'-s'], exit=False) From scipy-svn at scipy.org Sun Nov 16 19:11:29 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 18:11:29 -0600 (CST) Subject: [Scipy-svn] r5138 - trunk/doc/release Message-ID: <20081117001129.6332B39C05F@scipy.org> Author: damian.eads Date: 2008-11-16 18:11:28 -0600 (Sun, 16 Nov 2008) New Revision: 5138 Modified: trunk/doc/release/0.7.0-notes.rst Log: Polished release notes for spatial.distance and cluster. Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-16 23:27:15 UTC (rev 5137) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-17 00:11:28 UTC (rev 5138) @@ -68,20 +68,21 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module adds new hierarchical clustering functionality to the -cluster package. Its interface is similar to the hierarchical -clustering functions provided in MATLAB(TM)'s Statistics Toolbox to -facilitate easier migration to the NumPy/SciPy framework. Linkage -methods implemented include single, complete, average, weighted, -centroid, median, and ward. Several functions are provided for -computing statistics on clusters including inconsistency statistics, -cophenetic distance, and maximum distance of descendants. The fcluster -and fclusterdata functions take hierarchical tree clusterings -generated by these algorithms, cuts the tree, and labels the flat -clusters. The leaders function finds the root of each flat cluster -given a hierarchical clustering and labellings of its leaves. Finally, a -matplotlib extension is provided for plotting dendrograms, which -may be outputted to postscript or any other supported format. +``scipy.cluster`` package. The function interfaces are similar to the +functions provided MATLAB(TM)'s Statistics Toolbox to help facilitate +easier migration to the NumPy/SciPy framework. Linkage methods +implemented include single, complete, average, weighted, centroid, +median, and ward. +In addition, several functions are provided for computing +inconsistency statistics, cophenetic distance, and maximum distance +between descendants. The ``fcluster`` and ``fclusterdata`` functions +transform a hierarchical clustering into a set of flat clusters. Since +these flat clusters are generated by cutting the tree into a forest of +trees, the ``leaders`` function takes a linkage and a flat clustering +and finds the root of each tree in the forest. Finally, a matplotlib +extension is provided for plotting dendrograms. + New Spatial package ~~~~~~~~~~~~~~~~~~~ @@ -92,20 +93,22 @@ of other algorithms. The API for both modules may change somewhat as user requirements become clearer. -Also includes a submodule ``distance`` containing fast code for many definitions -of *distance* between vectors. These common distance functions are useful for -for many agorthms including spatial statistics, clustering, and kd-trees. -Distance and dissimilarity functions provided include Bray-Curtis, Canberra, -Chebyshev, City Block, Cosine, Dice, Euclidean, Hamming, Jaccard, Kulsinski, -Mahalanobis, Matching, Minkowski, Rogers-Tanimoto, Russell-Rao, -Squared Euclidean, Standardized Euclidean, Sokal-Michener, Sokal-Sneath, -and Yule. Two functions are provided for computing distances between -collections of vectors: ``pdist`` and ``cdist``. ``pdist`` is similar to the -MATLAB(TM) function and computes pairwise distances between a collection of -vectors. ``cdist`` computes distances between vectors in two sets of vectors. -``squareform`` converts between square distance matrices and condensed -distance matrices. +Also includes a ``distance`` module containing a collection of +distance and dissimilarity functions for computing distances between +vectors, which is useful for spatial statistics, clustering, and +kd-trees. Distance and dissimilarity functions provided include +Bray-Curtis, Canberra, Chebyshev, City Block, Cosine, Dice, Euclidean, +Hamming, Jaccard, Kulsinski, Mahalanobis, Matching, Minkowski, +Rogers-Tanimoto, Russell-Rao, Squared Euclidean, Standardized +Euclidean, Sokal-Michener, Sokal-Sneath, and Yule. +The ``pdist`` function computes pairwise distance between all +unordered pairs of vectors in a set of vectors. The ``cdist`` computes +the distance on all pairs of vectors in the Cartesian product of two +sets of vectors. Pairwise distance matrices are stored in condensed +form, only the upper triangular is stored. ``squareform`` converts +between square distance matrices and condensed distance matrices. + Reworked fftpack package ~~~~~~~~~~~~~~~~~~~~~~~~ From scipy-svn at scipy.org Sun Nov 16 20:06:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 19:06:58 -0600 (CST) Subject: [Scipy-svn] r5139 - trunk/scipy/spatial Message-ID: <20081117010658.CE2DB39C05F@scipy.org> Author: damian.eads Date: 2008-11-16 19:06:57 -0600 (Sun, 16 Nov 2008) New Revision: 5139 Modified: trunk/scipy/spatial/distance.py Log: Minor tweaks to docstring RST in spatial. Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-17 00:11:28 UTC (rev 5138) +++ trunk/scipy/spatial/distance.py 2008-11-17 01:06:57 UTC (rev 5139) @@ -208,7 +208,7 @@ .. math:: - \sum {(w_i*|u_i - v_i|)^p})^(1/p). + \left(\sum {(w_i*|u_i - v_i|\right)^p}^(1/p). :Parameters: u : ndarray @@ -285,7 +285,8 @@ .. math:: - \frac{1-uv^T}/\frac{||u||_2 ||v||_2}. + \frac{1-uv^T} + {||u||_2 ||v||_2}. :Parameters: u : ndarray @@ -309,11 +310,11 @@ .. math:: - \frac{1 - (u - n{|u|}_1){(v - n{|v|}_1)}^T} - {{|(u - n{|u|}_1)|}_2 {|(v - n{|v|}_1)|}^T} + \frac{1 - (u - \bar{u}){(v - \bar{v})}^T} + {{||(u - \bar{u})||}_2 {||(v - \bar{v})||}_2^T} - where :math:`|*|_1` is the Manhattan norm and ``n`` is the - common dimensionality of the vectors. + where :math:`\bar{u}` is the mean of a vectors elements and ``n`` + is the common dimensionality of ``u`` and ``v``. :Parameters: u : ndarray @@ -668,7 +669,7 @@ .. math: - \frac{c_{TF} + c_{FT} + \frac{c_{TF} + c_{FT}} {2c_{TT} + c_{FT} + c_{TF}} where :math:`c_{ij}` is the number of occurrences of @@ -767,7 +768,7 @@ where :math:`c_{ij}` is the number of occurrences of :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for - :math:`k < n`, :math:`R = 2 * (c_{TF} + c{FT})` and + :math:`k < n`, :math:`R = 2 * (c_{TF} + c_{FT})` and :math:`S = c_{FF} + c_{TT}`. :Parameters: @@ -803,7 +804,7 @@ where :math:`c_{ij}` is the number of occurrences of :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for - :math:`k < n` and :math:`R = 2(c_{TF} + c{FT})`. + :math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`. :Parameters: u : ndarray @@ -915,12 +916,10 @@ .. math: - \frac{1 - (u - n{|u|}_1){(v - n{|v|}_1)}^T} - {{|(u - n{|u|}_1)|}_2 {|(v - n{|v|}_1)|}^T} + \frac{1 - (u - \bar{u})(v - \bar{v})^T} + {{|(u - \bar{u})|}{|(v - \bar{v})|}^T} - where :math:`|*|_1` is the Manhattan (or 1-norm) of its - argument, and :math:`n` is the common dimensionality of the - vectors. + where :math:`\bar{v}` is the mean of the elements of vector v. 8. ``Y = pdist(X, 'hamming')`` @@ -1558,12 +1557,12 @@ def cdist(XA, XB, metric='euclidean', p=2, V=None, VI=None, w=None): """ - Computes distance between each pair of observations between two - collections of vectors. ``XA`` is a :math:`m_A` by :math:`n` - array while ``XB`` is a :math:`m_B` by :math:`n` array. A - :math:`m_A` by :math:`m_B` array is returned. An exception is - thrown if ``XA`` and ``XB`` do not have the same number of - columns. + Computes distance between each pair of observation vectors in the + Cartesian product of two collections of vectors. ``XA`` is a + :math:`m_A` by :math:`n` array while ``XB`` is a :math:`m_B` by + :math:`n` array. A :math:`m_A` by :math:`m_B` array is + returned. An exception is thrown if ``XA`` and ``XB`` do not have + the same number of columns. A rectangular distance matrix ``Y`` is returned. For each :math:`i` and :math:`j`, the metric ``dist(u=XA[i], v=XB[j])`` is computed From scipy-svn at scipy.org Sun Nov 16 23:55:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 16 Nov 2008 22:55:25 -0600 (CST) Subject: [Scipy-svn] r5140 - trunk/scipy/stats Message-ID: <20081117045525.878CB39C05F@scipy.org> Author: josef Date: 2008-11-16 22:55:22 -0600 (Sun, 16 Nov 2008) New Revision: 5140 Modified: trunk/scipy/stats/distributions.py Log: fix limiting behavior of genextreme._pdf at c*x=1 Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-17 01:06:57 UTC (rev 5139) +++ trunk/scipy/stats/distributions.py 2008-11-17 04:55:22 UTC (rev 5140) @@ -1756,7 +1756,9 @@ ex2 = 1-c*x pex2 = pow(ex2,1.0/c) p2 = exp(-pex2)*pex2/ex2 - return p2 + limit = where(c == 1.0, 1.0, 0.0) + return where(c*x == 1.0, limit, p2) + #return p2 def _cdf(self, x, c): return exp(-pow(1-c*x,1.0/c)) def _ppf(self, q, c): From scipy-svn at scipy.org Mon Nov 17 13:29:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 17 Nov 2008 12:29:12 -0600 (CST) Subject: [Scipy-svn] r5141 - trunk/scipy/stats Message-ID: <20081117182912.14D9539C088@scipy.org> Author: josef Date: 2008-11-17 12:29:09 -0600 (Mon, 17 Nov 2008) New Revision: 5141 Modified: trunk/scipy/stats/distributions.py Log: new version of genextreme distribution by Per Brodtkorb which includes gumbel as boundary case, see ticket:767 Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-17 04:55:22 UTC (rev 5140) +++ trunk/scipy/stats/distributions.py 2008-11-17 18:29:09 UTC (rev 5141) @@ -1747,22 +1747,67 @@ ## This version does not accept c==0 ## Use gumbel_r for c==0 +# new version by Per Brodtkorb, see ticket:767 +# also works for c==0, special case is gumbel_r +# increased precision for small c + class genextreme_gen(rv_continuous): def _argcheck(self, c): self.b = where(c > 0, 1.0 / c, inf) self.a = where(c < 0, 1.0 / c, -inf) - return (c!=0) + return True #(c!=0) def _pdf(self, x, c): - ex2 = 1-c*x - pex2 = pow(ex2,1.0/c) - p2 = exp(-pex2)*pex2/ex2 - limit = where(c == 1.0, 1.0, 0.0) - return where(c*x == 1.0, limit, p2) - #return p2 + ## ex2 = 1-c*x + ## pex2 = pow(ex2,1.0/c) + ## p2 = exp(-pex2)*pex2/ex2 + ## return p2 + cx = c*x + logex2 = where(c==0,0.0,np.log1p(-cx)) + logpex2 = where(c==0,-x,logex2/c) + pex2 = exp(logpex2) + # % Handle special cases + logpdf = where((cx==1) | (cx==-inf),-inf,-pex2+logpex2-logex2) + putmask(logpdf,(c==1) & (x==1),0.0) # logpdf(c==1 & x==1) = 0; % 0^0 situation + + return exp(logpdf) + + def _cdf(self, x, c): - return exp(-pow(1-c*x,1.0/c)) + #return exp(-pow(1-c*x,1.0/c)) + loglogcdf = where(c==0,-x,np.log1p(-c*x)/c) + return exp(-exp(loglogcdf)) + def _ppf(self, q, c): - return 1.0/c*(1-(-log(q))**c) + #return 1.0/c*(1.-(-log(q))**c) + logq = log(q); + x = -log(-logq) + # _rvs requires that _ppf allows vectorized q + return where((q==q)*(c==0),x,-np.expm1(-c*x)/c) + def _stats(self,c): + + g = lambda n : gam(n*c+1) + g1 = g(1) + g2 = g(2) + g3 = g(3); + g4 = g(4) + g2mg12 = where(abs(c)<1e-7,(c*pi)**2.0/6.0,g2-g1**2.0) + gam2k = where(abs(c)<1e-7,pi**2.0/6.0, np.expm1(gamln(2.0*c+1.0)-2*gamln(c+1.0))/c**2.0); + eps = 1e-14 + gamk = where(abs(c) 0 """ From scipy-svn at scipy.org Tue Nov 18 01:15:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 00:15:18 -0600 (CST) Subject: [Scipy-svn] r5142 - trunk/scipy/stats Message-ID: <20081118061518.92B9D39C088@scipy.org> Author: josef Date: 2008-11-18 00:15:12 -0600 (Tue, 18 Nov 2008) New Revision: 5142 Modified: trunk/scipy/stats/distributions.py Log: correction to genextreme for vector arguments in _pdf Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-17 18:29:09 UTC (rev 5141) +++ trunk/scipy/stats/distributions.py 2008-11-18 06:15:12 UTC (rev 5142) @@ -1762,8 +1762,9 @@ ## p2 = exp(-pex2)*pex2/ex2 ## return p2 cx = c*x - logex2 = where(c==0,0.0,np.log1p(-cx)) - logpex2 = where(c==0,-x,logex2/c) + # Note: fit method requires that _pdf accepts vector x + logex2 = where((x==x)*(c==0),0.0,np.log1p(-cx)) + logpex2 = where((x==x)*(c==0),-x,logex2/c) pex2 = exp(logpex2) # % Handle special cases logpdf = where((cx==1) | (cx==-inf),-inf,-pex2+logpex2-logex2) From scipy-svn at scipy.org Tue Nov 18 01:19:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 00:19:39 -0600 (CST) Subject: [Scipy-svn] r5143 - trunk/scipy/stats/tests Message-ID: <20081118061939.DFB1C39C088@scipy.org> Author: josef Date: 2008-11-18 00:19:37 -0600 (Tue, 18 Nov 2008) New Revision: 5143 Added: trunk/scipy/stats/tests/test_fit.py Log: add fit test for record, test is renamed so nose doesn't run it Added: trunk/scipy/stats/tests/test_fit.py =================================================================== --- trunk/scipy/stats/tests/test_fit.py 2008-11-18 06:15:12 UTC (rev 5142) +++ trunk/scipy/stats/tests/test_fit.py 2008-11-18 06:19:37 UTC (rev 5143) @@ -0,0 +1,68 @@ +# NOTE: contains only one test, _est_cont_fit, that is renamed so that +# nose doesn't run it +# I put this here for the record and for the case when someone wants to +# verify the quality of fit +# with current parameters: + + +import numpy.testing as npt +import numpy as np + +from scipy import stats + +from test_continuous_basic import distcont + +# this is not a proper statistical test for convergence, but only +# verifies that the estimate and true values don't differ by too much +n_repl1 = 1000 # sample size for first run +n_repl2 = 5000 # sample size for second run, if first run fails +thresh_percent = 0.25 # percent of true parameters for fail cut-off +thresh_min = 0.75 # minimum difference estimate - true to fail test + +#distcont = [['genextreme', (3.3184017469423535,)]] + +def test_cont_fit(): + # this tests the closeness of the estimated parameters to the true + # parameters with fit method of continuous distributions + # Note: is slow, some distributions don't converge with sample size <= 10000 + + for distname, arg in distcont: + yield check_cont_fit, distname,arg + + +def check_cont_fit(distname,arg): + distfn = getattr(stats, distname) + rvs = distfn.rvs(size=n_repl1,*arg) + est = distfn.fit(rvs) #,*arg) # start with default values + + truearg = np.hstack([arg,[0.0,1.0]]) + diff = est-truearg + + txt = '' + diffthreshold = np.max(np.vstack([truearg*thresh_percent, + np.ones(distfn.numargs+2)*thresh_min]),0) + # threshold for location + diffthreshold[-2] = np.max([np.abs(rvs.mean())*thresh_percent,thresh_min]) + + if np.any(np.isnan(est)): + raise AssertionError, 'nan returned in fit' + else: + if np.any((np.abs(diff) - diffthreshold) > 0.0): +## txt = 'WARNING - diff too large with small sample' +## print 'parameter diff =', diff - diffthreshold, txt + rvs = np.concatenate([rvs,distfn.rvs(size=n_repl2-n_repl1,*arg)]) + est = distfn.fit(rvs) #,*arg) + truearg = np.hstack([arg,[0.0,1.0]]) + diff = est-truearg + if np.any((np.abs(diff) - diffthreshold) > 0.0): + txt = 'parameter: %s\n' % str(truearg) + txt += 'estimated: %s\n' % str(est) + txt += 'diff : %s\n' % str(diff) + raise AssertionError, 'fit not very good in %s\n' % distfn.name + txt + + + +if __name__ == "__main__": + import nose + #nose.run(argv=['', __file__]) + nose.runmodule(argv=[__file__,'-s'], exit=False) From scipy-svn at scipy.org Tue Nov 18 01:23:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 00:23:09 -0600 (CST) Subject: [Scipy-svn] r5144 - trunk/scipy/stats/tests Message-ID: <20081118062309.01D3E39C088@scipy.org> Author: josef Date: 2008-11-18 00:23:05 -0600 (Tue, 18 Nov 2008) New Revision: 5144 Modified: trunk/scipy/stats/tests/test_continuous_basic.py trunk/scipy/stats/tests/test_continuous_extra.py trunk/scipy/stats/tests/test_discrete_basic.py Log: some test cleanup, add some test, make sure, some extra tests are renamed, so that nose doesn't run them Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-18 06:19:37 UTC (rev 5143) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-18 06:23:05 UTC (rev 5144) @@ -113,6 +113,12 @@ ## ['fatiguelife', (29,)], #correction numargs = 1 ## ['loggamma', (0.41411931826052117,)]] +# for testing ticket:767 +##distcont = [ +## ['genextreme', (3.3184017469423535,)], +## ['genextreme', (0.01,)], +## ['genextreme', (0.00001,)] +## ] def test_cont_basic(): for distname, arg in distcont[:]: @@ -122,10 +128,11 @@ sv = rvs.var() skurt = stats.kurtosis(rvs) sskew = stats.skew(rvs) - yield check_sample_meanvar_, distfn, arg, sm, sv, distname + \ + m,v = distfn.stats(*arg) + yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, distname + \ 'sample mean test' yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname - yield check_moment, distfn, arg, distname + yield check_moment, distfn, arg, m, v, distname yield check_cdf_ppf, distfn, arg, distname yield check_sf_isf, distfn, arg, distname yield check_pdf, distfn, arg, distname @@ -133,27 +140,25 @@ -def check_moment(distfn, arg, msg): - m,v = distfn.stats(*arg) +def check_moment(distfn, arg, m, v, msg): m1 = distfn.moment(1,*arg) m2 = distfn.moment(2,*arg) if not np.isinf(m): npt.assert_almost_equal(m1, m, decimal=10, err_msg= msg + \ ' - 1st moment') - else: - assert np.isinf(m1) or np.isnan(m1), \ + else: # or np.isnan(m1), + assert np.isinf(m1), \ msg + ' - 1st moment -infinite, m1=%s' % str(m1) #np.isnan(m1) temporary special treatment for loggamma if not np.isinf(v): npt.assert_almost_equal(m2-m1*m1, v, decimal=10, err_msg= msg + \ ' - 2ndt moment') - else: - assert np.isinf(m2) or np.isnan(m2), \ + else: #or np.isnan(m2), + assert np.isinf(m2), \ msg + ' - 2nd moment -infinite, m2=%s' % str(m2) #np.isnan(m2) temporary special treatment for loggamma -def check_sample_meanvar_(distfn, arg, sm, sv, msg): - m,v = distfn.stats(*arg) +def check_sample_meanvar_(distfn, arg, m, v, sm, sv, msg): check_sample_meanvar, sm, m, msg + 'sample mean test' check_sample_meanvar, sv, v, msg + 'sample var test' @@ -167,7 +172,7 @@ npt.assert_almost_equal(sm, m, decimal=DECIMAL, err_msg= msg + \ ' - finite moment') else: - assert sm > 10000, 'infinite moment, sm = ' + str(sm) + assert abs(sm) > 10000, 'infinite moment, sm = ' + str(sm) def check_cdf_ppf(distfn,arg,msg): npt.assert_almost_equal(distfn.cdf(distfn.ppf([0.001,0.5,0.990], *arg), *arg), @@ -184,6 +189,7 @@ ' - cdf-sf relationship') def check_pdf(distfn, arg, msg): + # compares pdf at median with numerical derivative of cdf median = distfn.ppf(0.5, *arg) eps = 1e-6 pdfv = distfn.pdf(median, *arg) @@ -193,7 +199,8 @@ pdfv = distfn.pdf(median, *arg) cdfdiff = (distfn.cdf(median + eps, *arg) - distfn.cdf(median - eps, *arg))/eps/2.0 - #replace with better diff and better test (more points) + #replace with better diff and better test (more points), + #actually, this works pretty well npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg= msg + ' - cdf-pdf relationship') @@ -204,9 +211,11 @@ 'johnsonsb', 'truncexpon', 'rice', 'invnorm', 'invgamma', 'powerlognorm'] +distmiss = [[dist,args] for dist,args in distcont if dist in distmissing] + def test_missing_distributions(): - #test from scipy.stats.tests - for dist, args in distcont: + # K-S test of distributions missing in test_distributions.py + for dist, args in distmiss: distfunc = getattr(stats, dist) alpha = 0.01 yield check_distribution, dist, args, alpha @@ -221,5 +230,6 @@ "; alpha = " + str(alpha) + "\nargs = " + str(args) if __name__ == "__main__": - nose.run(argv=['', __file__]) + #nose.run(argv=['', __file__]) + nose.runmodule(argv=[__file__,'-s'], exit=False) Modified: trunk/scipy/stats/tests/test_continuous_extra.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-18 06:19:37 UTC (rev 5143) +++ trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-18 06:23:05 UTC (rev 5144) @@ -1,3 +1,11 @@ +# contains additional tests for continuous distributions +# +# NOTE: one test, _est_cont_skip, that is renamed so that nose doesn't +# run it, +# 6 distributions return nan for entropy +# truncnorm fails by design for private method _ppf test + + import numpy.testing as npt import numpy as np import nose @@ -11,23 +19,35 @@ def test_cont_extra(): for distname, arg in distcont[:]: distfn = getattr(stats, distname) -## rvs = distfn.rvs(size=1000,*arg) -## sm = rvs.mean() -## sv = rvs.var() -## skurt = stats.kurtosis(rvs) -## sskew = stats.skew(rvs) - + yield check_ppf_limits, distfn, arg, distname + \ ' ppf limit test' yield check_isf_limits, distfn, arg, distname + \ ' isf limit test' yield check_loc_scale, distfn, arg, distname + \ ' loc, scale test' - #entropy test checks only for isnan, currently 6 isnan -## yield check_entropy, distfn, arg, distname + \ -## ' entropy nan test' +def _est_cont_skip(): + for distname, arg in distcont: + distfn = getattr(stats, distname) + #entropy test checks only for isnan, currently 6 isnan left + yield check_entropy, distfn, arg, distname + \ + ' entropy nan test' + # _ppf test has 1 failure be design + yield check_ppf_private, distfn, arg, distname + \ + ' _ppf private test' +def test_540_567(): + # test for nan returned in tickets 540, 567 + npt.assert_almost_equal(stats.norm.cdf(-1.7624320982),0.03899815971089126, + decimal=10, err_msg = 'test_540_567') + npt.assert_almost_equal(stats.norm.cdf(-1.7624320983),0.038998159702449846, + decimal=10, err_msg = 'test_540_567') + npt.assert_almost_equal(stats.norm.cdf(1.38629436112, loc=0.950273420309, + scale=0.204423758009),0.98353464004309321, + decimal=10, err_msg = 'test_540_567') + + def check_ppf_limits(distfn,arg,msg): below,low,upp,above = distfn.ppf([-1,0,1,2], *arg) #print distfn.name, distfn.a, low, distfn.b, upp @@ -37,6 +57,12 @@ assert np.isnan(below), msg + 'ppf out of bounds - below' assert np.isnan(above), msg + 'ppf out of bounds - above' +def check_ppf_private(distfn,arg,msg): + #fails by design for trunk norm self.nb not defined + ppfs = distfn._ppf(np.array([0.1,0.5,0.9]), *arg) + assert not np.any(np.isnan(ppfs)), msg + 'ppf private is nan' + + def check_isf_limits(distfn,arg,msg): below,low,upp,above = distfn.isf([-1,0,1,2], *arg) #print distfn.name, distfn.a, low, distfn.b, upp @@ -62,7 +88,7 @@ def assert_equal_inf_nan(v1,v2,msg): assert not np.isnan(v1) if not np.isinf(v1): - npt.assert_almost_equal(v1, v2, decimal=DECIMAL, err_msg= msg + \ + npt.assert_almost_equal(v1, v2, decimal=DECIMAL, err_msg = msg + \ ' - finite') else: assert np.isinf(v2) or np.isnan(v2), \ @@ -71,7 +97,5 @@ if __name__ == "__main__": import nose #nose.run(argv=['', __file__]) - #print distcont[:5] - #test_cont_extra() nose.runmodule(argv=[__file__,'-s'], exit=False) Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-18 06:19:37 UTC (rev 5143) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-18 06:23:05 UTC (rev 5144) @@ -44,7 +44,7 @@ yield check_entropy, distfn, arg, distname + \ ' entropy nan test' -def test_discrete_private(): +def _est_discrete_private(): #testing private methods mostly for debugging # some tests might fail by design, # e.g. incorrect definition of distfn.a and distfn.b From scipy-svn at scipy.org Tue Nov 18 01:25:39 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 00:25:39 -0600 (CST) Subject: [Scipy-svn] r5145 - trunk/scipy/stats/tests Message-ID: <20081118062539.4E51D39C088@scipy.org> Author: josef Date: 2008-11-18 00:25:34 -0600 (Tue, 18 Nov 2008) New Revision: 5145 Modified: trunk/scipy/stats/tests/test_fit.py Log: forgot to save some changes before last committ Modified: trunk/scipy/stats/tests/test_fit.py =================================================================== --- trunk/scipy/stats/tests/test_fit.py 2008-11-18 06:23:05 UTC (rev 5144) +++ trunk/scipy/stats/tests/test_fit.py 2008-11-18 06:25:34 UTC (rev 5145) @@ -2,7 +2,9 @@ # nose doesn't run it # I put this here for the record and for the case when someone wants to # verify the quality of fit -# with current parameters: +# with current parameters: relatively small sample size, default starting values +# Ran 84 tests in 401.797s +# FAILED (failures=15) import numpy.testing as npt @@ -21,7 +23,7 @@ #distcont = [['genextreme', (3.3184017469423535,)]] -def test_cont_fit(): +def _est_cont_fit(): # this tests the closeness of the estimated parameters to the true # parameters with fit method of continuous distributions # Note: is slow, some distributions don't converge with sample size <= 10000 From scipy-svn at scipy.org Tue Nov 18 10:32:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 09:32:56 -0600 (CST) Subject: [Scipy-svn] r5146 - trunk/scipy/stats Message-ID: <20081118153256.C6E2439C088@scipy.org> Author: josef Date: 2008-11-18 09:32:54 -0600 (Tue, 18 Nov 2008) New Revision: 5146 Modified: trunk/scipy/stats/distributions.py Log: another dimension correction for genextreme, but just to get a useful traceback, see #793 Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-18 06:25:34 UTC (rev 5145) +++ trunk/scipy/stats/distributions.py 2008-11-18 15:32:54 UTC (rev 5146) @@ -1755,7 +1755,7 @@ def _argcheck(self, c): self.b = where(c > 0, 1.0 / c, inf) self.a = where(c < 0, 1.0 / c, -inf) - return True #(c!=0) + return (c==c) #True #(c!=0) def _pdf(self, x, c): ## ex2 = 1-c*x ## pex2 = pow(ex2,1.0/c) From scipy-svn at scipy.org Tue Nov 18 13:38:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 12:38:36 -0600 (CST) Subject: [Scipy-svn] r5147 - in trunk/scipy/stats: . tests Message-ID: <20081118183836.75D1339C088@scipy.org> Author: josef Date: 2008-11-18 12:35:08 -0600 (Tue, 18 Nov 2008) New Revision: 5147 Modified: trunk/scipy/stats/distributions.py trunk/scipy/stats/tests/test_discrete_basic.py Log: correct boundary and out-of-boundary return of isf analogously to ppf, add test for this Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-18 15:32:54 UTC (rev 5146) +++ trunk/scipy/stats/distributions.py 2008-11-18 18:35:08 UTC (rev 5147) @@ -1754,8 +1754,8 @@ class genextreme_gen(rv_continuous): def _argcheck(self, c): self.b = where(c > 0, 1.0 / c, inf) - self.a = where(c < 0, 1.0 / c, -inf) - return (c==c) #True #(c!=0) + self.a = where(c < 0, 1.0 / c, -inf) + return (c==c) #True #(c!=0) #see ticket:793 def _pdf(self, x, c): ## ex2 = 1-c*x ## pex2 = pow(ex2,1.0/c) @@ -3789,15 +3789,19 @@ cond1 = (q > 0) & (q < 1) cond2 = (q==1) & cond0 cond = cond0 & cond1 - output = valarray(shape(cond),value=self.b,typecode='d') - #typecode 'd' to handle nin and inf - place(output,(1-cond0)*(cond1==cond1), self.badvalue) - place(output,cond2,self.a-1) + #old: +## output = valarray(shape(cond),value=self.b,typecode='d') +## #typecode 'd' to handle nin and inf +## place(output,(1-cond0)*(cond1==cond1), self.badvalue) +## place(output,cond2,self.a-1) - #same problem as with ppf + # copied from ppf and changed + output = valarray(shape(cond),value=self.badvalue,typecode='d') + #output type 'd' to handle nin and inf + place(output,(q==0)*(cond==cond), self.b) + place(output,cond2,self.a-1) - # call place only if at least 1 valid argument if any(cond): goodargs = argsreduce(cond, *((q,)+args+(loc,))) Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-18 15:32:54 UTC (rev 5146) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-18 18:35:08 UTC (rev 5147) @@ -44,6 +44,14 @@ yield check_entropy, distfn, arg, distname + \ ' entropy nan test' +def test_discrete_extra(): + for distname, arg in distdiscrete: + distfn = getattr(stats,distname) + yield check_ppf_limits, distfn, arg, distname + \ + ' ppf limit test' + yield check_isf_limits, distfn, arg, distname + \ + ' isf limit test' + def _est_discrete_private(): #testing private methods mostly for debugging # some tests might fail by design, @@ -122,7 +130,36 @@ assert distfn.cdf(median_sf + 1, *arg) > 0.5 npt.assert_equal(distfn.isf(0.5, *arg), distfn.ppf(0.5, *arg)) +#next 3 functions copied from test_continous_extra +# adjusted + +def check_ppf_limits(distfn,arg,msg): + below,low,upp,above = distfn.ppf([-1,0,1,2], *arg) + #print distfn.name, distfn.a, low, distfn.b, upp + #print distfn.name,below,low,upp,above + assert_equal_inf_nan(distfn.a-1,low, msg + 'ppf lower bound') + assert_equal_inf_nan(distfn.b,upp, msg + 'ppf upper bound') + assert np.isnan(below), msg + 'ppf out of bounds - below' + assert np.isnan(above), msg + 'ppf out of bounds - above' +def check_isf_limits(distfn,arg,msg): + below,low,upp,above = distfn.isf([-1,0,1,2], *arg) + #print distfn.name, distfn.a, low, distfn.b, upp + #print distfn.name,below,low,upp,above + assert_equal_inf_nan(distfn.a-1,upp, msg + 'isf lower bound') + assert_equal_inf_nan(distfn.b,low, msg + 'isf upper bound') + assert np.isnan(below), msg + 'isf out of bounds - below' + assert np.isnan(above), msg + 'isf out of bounds - above' + +def assert_equal_inf_nan(v1,v2,msg): + assert not np.isnan(v1) + if not np.isinf(v1): + npt.assert_almost_equal(v1, v2, decimal=10, err_msg = msg + \ + ' - finite') + else: + assert np.isinf(v2) or np.isnan(v2), \ + msg + ' - infinite, v2=%s' % str(v2) + def check_sample_skew_kurt(distfn, arg, sk, ss, msg): k,s = distfn.stats(moment='ks',*arg) check_sample_meanvar, sk, k, msg + 'sample skew test' From scipy-svn at scipy.org Tue Nov 18 15:48:14 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 18 Nov 2008 14:48:14 -0600 (CST) Subject: [Scipy-svn] r5148 - in trunk/doc/source: . tutorial Message-ID: <20081118204814.81ACF39C088@scipy.org> Author: ptvirtan Date: 2008-11-18 14:47:56 -0600 (Tue, 18 Nov 2008) New Revision: 5148 Modified: trunk/doc/source/integrate.rst trunk/doc/source/linalg.rst trunk/doc/source/maxentropy.rst trunk/doc/source/optimize.rst trunk/doc/source/signal.rst trunk/doc/source/special.rst trunk/doc/source/stats.rst trunk/doc/source/tutorial/index.rst Log: docs: remove trailing whitespace Modified: trunk/doc/source/integrate.rst =================================================================== --- trunk/doc/source/integrate.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/integrate.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -10,35 +10,35 @@ .. autosummary:: :toctree: generated/ - - quad - dblquad - tplquad - fixed_quad - quadrature - romberg - + + quad + dblquad + tplquad + fixed_quad + quadrature + romberg + Integrating functions, given fixed samples ========================================== - + .. autosummary:: :toctree: generated/ - - trapz - cumtrapz - simps - romb + trapz + cumtrapz + simps + romb + .. seealso:: :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian quadrature roots and weights for other weighting factors and regions. - + Integrators of ODE systems ========================== - + .. autosummary:: :toctree: generated/ - - odeint - ode + + odeint + ode Modified: trunk/doc/source/linalg.rst =================================================================== --- trunk/doc/source/linalg.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/linalg.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -10,15 +10,15 @@ .. autosummary:: :toctree: generated/ - inv - solve + inv + solve solve_banded solveh_banded - det - norm - lstsq - pinv - pinv2 + det + norm + lstsq + pinv + pinv2 Eigenvalues and Decompositions ============================== @@ -26,24 +26,24 @@ .. autosummary:: :toctree: generated/ - eig - eigvals + eig + eigvals eig_banded eigvals_banded - lu - lu_factor - lu_solve - svd - svdvals - diagsvd - orth - cholesky - cholesky_banded + lu + lu_factor + lu_solve + svd + svdvals + diagsvd + orth + cholesky + cholesky_banded cho_factor - cho_solve - qr - schur - rsf2csf + cho_solve + qr + schur + rsf2csf hessenberg Matrix Functions @@ -52,19 +52,19 @@ .. autosummary:: :toctree: generated/ - expm - expm2 - expm3 - logm - cosm - sinm - tanm - coshm - sinhm - tanhm - signm - sqrtm - funm + expm + expm2 + expm3 + logm + cosm + sinm + tanm + coshm + sinhm + tanhm + signm + sqrtm + funm Iterative linear systems solutions ================================== @@ -72,10 +72,10 @@ .. autosummary:: :toctree: generated/ - cg - cgs - qmr - gmres - bicg - bicgstab + cg + cgs + qmr + gmres + bicg + bicgstab Modified: trunk/doc/source/maxentropy.rst =================================================================== --- trunk/doc/source/maxentropy.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/maxentropy.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -47,7 +47,7 @@ bigmodel.settestsamples bigmodel.stochapprox bigmodel.test - + .. autoclass:: conditionalmodel .. autosummary:: Modified: trunk/doc/source/optimize.rst =================================================================== --- trunk/doc/source/optimize.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/optimize.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -13,12 +13,12 @@ .. autosummary:: :toctree: generated/ - fmin + fmin fmin_powell - fmin_cg - fmin_bfgs - fmin_ncg - leastsq + fmin_cg + fmin_bfgs + fmin_ncg + leastsq Constrained (multivariate) @@ -28,8 +28,8 @@ :toctree: generated/ fmin_l_bfgs_b - fmin_tnc - fmin_cobyla + fmin_tnc + fmin_cobyla Global ------ @@ -37,8 +37,8 @@ .. autosummary:: :toctree: generated/ - anneal - brute + anneal + brute Scalar function minimizers -------------------------- @@ -46,18 +46,18 @@ .. autosummary:: :toctree: generated/ - fminbound - golden + fminbound + golden bracket brent Root finding ============ - + .. autosummary:: :toctree: generated/ - fsolve + fsolve Scalar function solvers ----------------------- @@ -65,14 +65,14 @@ .. autosummary:: :toctree: generated/ - brentq - brenth - ridder - bisect + brentq + brenth + ridder + bisect newton Fixed point finding: - + .. autosummary:: :toctree: generated/ @@ -84,12 +84,12 @@ .. autosummary:: :toctree: generated/ - broyden1 - broyden2 - broyden3 + broyden1 + broyden2 + broyden3 broyden_generalized - anderson - anderson2 + anderson + anderson2 Utility Functions ================= @@ -98,4 +98,4 @@ :toctree: generated/ line_search - check_grad + check_grad Modified: trunk/doc/source/signal.rst =================================================================== --- trunk/doc/source/signal.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/signal.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -10,12 +10,12 @@ .. autosummary:: :toctree: generated/ - convolve - correlate - fftconvolve - convolve2d - correlate2d - sepfir2d + convolve + correlate + fftconvolve + convolve2d + correlate2d + sepfir2d B-splines ========= @@ -23,12 +23,12 @@ .. autosummary:: :toctree: generated/ - bspline - gauss_spline - cspline1d - qspline1d - cspline2d - qspline2d + bspline + gauss_spline + cspline1d + qspline1d + cspline2d + qspline2d spline_filter Filtering @@ -37,22 +37,22 @@ .. autosummary:: :toctree: generated/ - order_filter - medfilt - medfilt2 - wiener + order_filter + medfilt + medfilt2 + wiener - symiirorder1 - symiirorder2 - lfilter + symiirorder1 + symiirorder2 + lfilter - deconvolve + deconvolve - hilbert - get_window + hilbert + get_window - detrend - resample + detrend + resample Filter design ============= @@ -60,17 +60,17 @@ .. autosummary:: :toctree: generated/ - remez - firwin - iirdesign - iirfilter - freqs - freqz + remez + firwin + iirdesign + iirfilter + freqs + freqz - unique_roots - residue - residuez - invres + unique_roots + residue + residuez + invres Matlab-style IIR filter design ============================== @@ -94,10 +94,10 @@ .. autosummary:: :toctree: generated/ - lti - lsim + lti + lsim impulse - step + step LTI Reresentations ================== @@ -107,8 +107,8 @@ tf2zpk zpk2tf - tf2ss - ss2tf + tf2ss + ss2tf zpk2ss ss2zpk @@ -118,10 +118,10 @@ .. autosummary:: :toctree: generated/ - sawtooth - square + sawtooth + square gausspulse - chirp + chirp Window functions ================ @@ -129,22 +129,22 @@ .. autosummary:: :toctree: generated/ - boxcar - triang - parzen - bohman - blackman - blackmanharris - nuttall - flattop - bartlett - hann - barthann - hamming - kaiser - gaussian + boxcar + triang + parzen + bohman + blackman + blackmanharris + nuttall + flattop + bartlett + hann + barthann + hamming + kaiser + gaussian general_gaussian - slepian + slepian Wavelets ======== @@ -152,6 +152,6 @@ .. autosummary:: :toctree: generated/ - daub - qmf + daub + qmf cascade Modified: trunk/doc/source/special.rst =================================================================== --- trunk/doc/source/special.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/special.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -9,13 +9,13 @@ Error handling ============== - + Errors are handled by returning nans, or other appropriate values. Some of the special function routines will print an error message when an error occurs. By default this printing is disabled. To enable such messages use errprint(1) To disable such messages use errprint(0). - + Example: >>> print scipy.special.bdtr(-1,10,0.3) >>> scipy.special.errprint(1) @@ -26,10 +26,10 @@ errprint errstate - + Available functions =================== - + Airy functions -------------- @@ -44,62 +44,62 @@ Elliptic Functions and Integrals -------------------------------- - + .. autosummary:: :toctree: generated/ - ellipj - ellipk + ellipj + ellipk ellipkinc - ellipe + ellipe ellipeinc - + Bessel Functions ---------------- - + .. autosummary:: :toctree: generated/ - jn - jv - jve - yn - yv - yve - kn - kv - kve - iv - ive - hankel1 + jn + jv + jve + yn + yv + yve + kn + kv + kve + iv + ive + hankel1 hankel1e - hankel2 + hankel2 hankel2e The following is not an universal function: - + .. autosummary:: :toctree: generated/ - lmbda + lmbda Zeros of Bessel Functions ^^^^^^^^^^^^^^^^^^^^^^^^^ These are not universal functions: - + .. autosummary:: :toctree: generated/ jnjnp_zeros - jnyn_zeros - jn_zeros - jnp_zeros - yn_zeros - ynp_zeros - y0_zeros - y1_zeros - y1p_zeros + jnyn_zeros + jn_zeros + jnp_zeros + yn_zeros + ynp_zeros + y0_zeros + y1_zeros + y1p_zeros Faster versions of common Bessel Functions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -107,18 +107,18 @@ .. autosummary:: :toctree: generated/ - j0 - j1 - y0 - y1 - i0 - i0e - i1 - i1e - k0 - k0e - k1 - k1e + j0 + j1 + y0 + y1 + i0 + i0e + i1 + i1e + k0 + k0e + k1 + k1e Integrals of Bessel Functions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -126,10 +126,10 @@ .. autosummary:: :toctree: generated/ - itj0y0 - it2j0y0 - iti0k0 - it2i0k0 + itj0y0 + it2j0y0 + iti0k0 + it2i0k0 besselpoly Derivatives of Bessel Functions @@ -138,33 +138,33 @@ .. autosummary:: :toctree: generated/ - jvp - yvp - kvp - ivp - h1vp - h2vp + jvp + yvp + kvp + ivp + h1vp + h2vp Spherical Bessel Functions ^^^^^^^^^^^^^^^^^^^^^^^^^^ These are not universal functions: - + .. autosummary:: :toctree: generated/ - sph_jn - sph_yn + sph_jn + sph_yn sph_jnyn - sph_in - sph_kn + sph_in + sph_kn sph_inkn Ricatti-Bessel Functions ^^^^^^^^^^^^^^^^^^^^^^^^ These are not universal functions: - + .. autosummary:: :toctree: generated/ @@ -179,8 +179,8 @@ struve modstruve - itstruve0 - it2struve0 + itstruve0 + it2struve0 itmodstruve0 @@ -192,38 +192,38 @@ .. autosummary:: :toctree: generated/ - bdtr - bdtrc - bdtri - btdtr - btdtri - fdtr - fdtrc - fdtri - gdtr - gdtrc + bdtr + bdtrc + bdtri + btdtr + btdtri + fdtr + fdtrc + fdtri + gdtr + gdtrc gdtria gdtrib gdtrix - nbdtr - nbdtrc - nbdtri - pdtr - pdtrc - pdtri - stdtr + nbdtr + nbdtrc + nbdtri + pdtr + pdtrc + pdtri + stdtr stdtridf stdtrit - chdtr - chdtrc - chdtri - ndtr - ndtri - smirnov - smirnovi + chdtr + chdtrc + chdtri + ndtr + ndtri + smirnov + smirnovi kolmogorov - kolmogi - tklmbda + kolmogi + tklmbda Gamma and Related Functions --------------------------- @@ -231,19 +231,19 @@ .. autosummary:: :toctree: generated/ - gamma - gammaln - gammainc - gammaincinv - gammaincc + gamma + gammaln + gammainc + gammaincinv + gammaincc gammainccinv - beta - betaln - betainc - betaincinv + beta + betaln + betainc + betaincinv psi - rgamma - polygamma + rgamma + polygamma Error Function and Fresnel Integrals @@ -252,18 +252,18 @@ .. autosummary:: :toctree: generated/ - erf - erfc - erfinv - erfcinv - erf_zeros - fresnel + erf + erfc + erfinv + erfcinv + erf_zeros + fresnel fresnel_zeros - modfresnelp - modfresnelm + modfresnelp + modfresnelm These are not universal functions: - + .. autosummary:: :toctree: generated/ @@ -276,18 +276,18 @@ .. autosummary:: :toctree: generated/ - lpmv + lpmv sph_harm These are not universal functions: - + .. autosummary:: :toctree: generated/ - lpn - lqn - lpmn - lqmn + lpn + lqn + lpmn + lqmn Orthogonal polynomials ---------------------- @@ -305,20 +305,20 @@ :toctree: generated/ legendre - chebyt - chebyu - chebyc - chebys - jacobi - laguerre + chebyt + chebyu + chebyc + chebys + jacobi + laguerre genlaguerre - hermite + hermite hermitenorm - gegenbauer + gegenbauer sh_legendre - sh_chebyt - sh_chebyu - sh_jacobi + sh_chebyt + sh_chebyu + sh_jacobi Hypergeometric Functions ------------------------ @@ -326,13 +326,13 @@ .. autosummary:: :toctree: generated/ - hyp2f1 - hyp1f1 - hyperu - hyp0f1 - hyp2f0 - hyp1f2 - hyp3f0 + hyp2f1 + hyp1f1 + hyperu + hyp0f1 + hyp2f0 + hyp1f2 + hyp3f0 Parabolic Cylinder Functions @@ -341,12 +341,12 @@ .. autosummary:: :toctree: generated/ - pbdv - pbvv + pbdv + pbvv pbwa These are not universal functions: - + .. autosummary:: :toctree: generated/ @@ -360,24 +360,24 @@ .. autosummary:: :toctree: generated/ - mathieu_a - mathieu_b + mathieu_a + mathieu_b These are not universal functions: - + .. autosummary:: :toctree: generated/ mathieu_even_coef - mathieu_odd_coef + mathieu_odd_coef The following return both function and first derivative: .. autosummary:: :toctree: generated/ - mathieu_cem - mathieu_sem + mathieu_cem + mathieu_sem mathieu_modcem1 mathieu_modcem2 mathieu_modsem1 @@ -389,14 +389,14 @@ .. autosummary:: :toctree: generated/ - pro_ang1 - pro_rad1 - pro_rad2 - obl_ang1 - obl_rad1 - obl_rad2 - pro_cv - obl_cv + pro_ang1 + pro_rad1 + pro_rad2 + obl_ang1 + obl_rad1 + obl_rad2 + pro_cv + obl_cv pro_cv_seq obl_cv_seq @@ -418,30 +418,30 @@ .. autosummary:: :toctree: generated/ - kelvin + kelvin kelvin_zeros - ber - bei - berp - beip - ker - kei - kerp - keip + ber + bei + berp + beip + ker + kei + kerp + keip These are not universal functions: - + .. autosummary:: :toctree: generated/ - ber_zeros - bei_zeros - berp_zeros - beip_zeros - ker_zeros - kei_zeros - kerp_zeros - keip_zeros + ber_zeros + bei_zeros + berp_zeros + beip_zeros + ker_zeros + kei_zeros + kerp_zeros + keip_zeros Other Special Functions ----------------------- @@ -449,16 +449,16 @@ .. autosummary:: :toctree: generated/ - expn - exp1 + expn + exp1 expi - wofz - dawsn - shichi - sici - spence - zeta - zetac + wofz + dawsn + shichi + sici + spence + zeta + zetac Convenience Functions --------------------- @@ -466,15 +466,15 @@ .. autosummary:: :toctree: generated/ - cbrt - exp10 - exp2 - radian - cosdg - sindg - tandg - cotdg - log1p - expm1 - cosm1 + cbrt + exp10 + exp2 + radian + cosdg + sindg + tandg + cotdg + log1p + expm1 + cosm1 round Modified: trunk/doc/source/stats.rst =================================================================== --- trunk/doc/source/stats.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/stats.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -6,12 +6,12 @@ This module contains a large number of probability distributions as well as a growing library of statistical functions. - + Each included continuous distribution is an instance of the class rv_continous: .. autosummary:: :toctree: generated/ - + rv_continuous rv_continuous.pdf rv_continuous.cdf @@ -38,7 +38,7 @@ .. autosummary:: :toctree: generated/ - + norm alpha anglit @@ -72,53 +72,53 @@ gamma gengamma genhalflogistic - gompertz - gumbel_r - gumbel_l - halfcauchy - halflogistic - halfnorm - hypsecant - invgamma - invnorm - invweibull - johnsonsb - johnsonsu - laplace - logistic - loggamma - loglaplace - lognorm - gilbrat - lomax - maxwell - mielke - nakagami - ncx2 - ncf - t - nct - pareto - powerlaw - powerlognorm - powernorm - rdist - reciprocal - rayleigh - rice - recipinvgauss - semicircular - triang - truncexpon - truncnorm - tukeylambda - uniform - von_mises - wald - weibull_min - weibull_max - wrapcauchy - ksone + gompertz + gumbel_r + gumbel_l + halfcauchy + halflogistic + halfnorm + hypsecant + invgamma + invnorm + invweibull + johnsonsb + johnsonsu + laplace + logistic + loggamma + loglaplace + lognorm + gilbrat + lomax + maxwell + mielke + nakagami + ncx2 + ncf + t + nct + pareto + powerlaw + powerlognorm + powernorm + rdist + reciprocal + rayleigh + rice + recipinvgauss + semicircular + triang + truncexpon + truncnorm + tukeylambda + uniform + von_mises + wald + weibull_min + weibull_max + wrapcauchy + ksone kstwobign Discrete distributions @@ -127,17 +127,17 @@ .. autosummary:: :toctree: generated/ - binom - bernoulli - nbinom - geom - hypergeom - logser - poisson - planck - boltzmann - randint - zipf + binom + bernoulli + nbinom + geom + hypergeom + logser + poisson + planck + boltzmann + randint + zipf dlaplace Statistical functions @@ -146,121 +146,121 @@ .. autosummary:: :toctree: generated/ - gmean - hmean - mean - cmedian - median - mode - tmean - tvar - tmin - tmax - tstd - tsem - moment - variation - skew - kurtosis - describe - skewtest - kurtosistest - normaltest + gmean + hmean + mean + cmedian + median + mode + tmean + tvar + tmin + tmax + tstd + tsem + moment + variation + skew + kurtosis + describe + skewtest + kurtosistest + normaltest .. autosummary:: :toctree: generated/ - itemfreq - scoreatpercentile - percentileofscore - histogram2 - histogram - cumfreq - relfreq + itemfreq + scoreatpercentile + percentileofscore + histogram2 + histogram + cumfreq + relfreq .. autosummary:: :toctree: generated/ - obrientransform - samplevar - samplestd - signaltonoise - bayes_mvs - var - std - stderr - sem - z - zs - zmap - + obrientransform + samplevar + samplestd + signaltonoise + bayes_mvs + var + std + stderr + sem + z + zs + zmap + .. autosummary:: :toctree: generated/ - threshold - trimboth - trim1 - cov - corrcoef - + threshold + trimboth + trim1 + cov + corrcoef + .. autosummary:: :toctree: generated/ - f_oneway - paired - pearsonr - spearmanr - pointbiserialr - kendalltau - linregress - + f_oneway + paired + pearsonr + spearmanr + pointbiserialr + kendalltau + linregress + .. autosummary:: :toctree: generated/ - ttest_1samp - ttest_ind - ttest_rel - kstest - chisquare - ks_2samp - meanwhitneyu - tiecorrect - ranksums - wilcoxon - kruskal - friedmanchisquare - + ttest_1samp + ttest_ind + ttest_rel + kstest + chisquare + ks_2samp + meanwhitneyu + tiecorrect + ranksums + wilcoxon + kruskal + friedmanchisquare + .. autosummary:: :toctree: generated/ - ansari - bartlett - levene - shapiro - anderson - binom_test - fligner - mood - oneway - - + ansari + bartlett + levene + shapiro + anderson + binom_test + fligner + mood + oneway + + .. autosummary:: :toctree: generated/ - glm - anova - + glm + anova + Plot-tests ========== .. autosummary:: :toctree: generated/ - probplot - ppcc_max - ppcc_plot - - + probplot + ppcc_max + ppcc_plot + + For many more stat related functions install the software R and the interface package rpy. Modified: trunk/doc/source/tutorial/index.rst =================================================================== --- trunk/doc/source/tutorial/index.rst 2008-11-18 18:35:08 UTC (rev 5147) +++ trunk/doc/source/tutorial/index.rst 2008-11-18 20:47:56 UTC (rev 5148) @@ -21,7 +21,7 @@ user to high-level commands and classes for the manipulation and visualization of data. With SciPy, an interactive Python session becomes a data-processing and system-prototyping environment rivaling -sytems such as Matlab, IDL, Octave, R-Lab, and SciLab. +sytems such as Matlab, IDL, Octave, R-Lab, and SciLab. The additional power of using SciPy within Python, however, is that a powerful programming language is also available for use in developing @@ -31,7 +31,7 @@ developers across the world. Everything from parallel programming to web and data-base subroutines and classes have been made available to the Python programmer. All of this power is available in addition to -the mathematical libraries in SciPy. +the mathematical libraries in SciPy. This document provides a tutorial for the first-time user of SciPy to help get started with some of the features available in this powerful @@ -70,7 +70,7 @@ printed to standard output (or to a writeable object passed as the third argument). The second keyword argument of "scipy.info "defines the maximum width of the line for printing. If a module is passed as the argument to help than a list of the functions and -classes defined in that module is printed. For example: +classes defined in that module is printed. For example: .. literalinclude:: examples/1-1 @@ -94,32 +94,32 @@ Two other packages are installed at the higher-level: scipy_distutils and weave. These two packages while distributed with main scipy package could see use independently of scipy and so are treated as -separate packages and described elsewhere. +separate packages and described elsewhere. The remaining subpackages are summarized in the following table (a * denotes an optional sub-package that requires additional libraries to -function or is not available on all platforms). +function or is not available on all platforms). =========== ===================================================================== -Subpackage Description +Subpackage Description =========== ===================================================================== -cluster Clustering algorithms -cow Cluster of Workstations code for parallel programming -fftpack FFT based on fftpack -- default -fftw* FFT based on fftw --- requires FFTW libraries (is this still needed?) -ga Genetic algorithms -gplt* Plotting --- requires gnuplot -integrate Integration -interpolate Interpolation -io Input and Output -linalg Linear algebra -optimize Optimization and root-finding routines -plt* Plotting --- requires wxPython -signal Signal processing -special Special functions -stats Statistical distributions and functions -xplt Plotting with gist +cluster Clustering algorithms +cow Cluster of Workstations code for parallel programming +fftpack FFT based on fftpack -- default +fftw* FFT based on fftw --- requires FFTW libraries (is this still needed?) +ga Genetic algorithms +gplt* Plotting --- requires gnuplot +integrate Integration +interpolate Interpolation +io Input and Output +linalg Linear algebra +optimize Optimization and root-finding routines +plt* Plotting --- requires wxPython +signal Signal processing +special Special functions +stats Statistical distributions and functions +xplt Plotting with gist =========== ===================================================================== @@ -153,7 +153,7 @@ part is compared). Also, with the new universal functions in SciPy, the logical operations (except logical_XXX functions) all return arrays of unsigned bytes (8-bits per element instead of the old -32-bits, or even 64-bits) per element [#]_ . +32-bits, or even 64-bits) per element [#]_ . In an effort to get a consistency for default arguments, some of the default arguments have changed from Numpy. The idea is for you to use @@ -164,10 +164,10 @@ NaN's where appropriate (*i.e.* ``scipy.sqrt(-1)`` returns ``1j``). .. [#] Be careful when treating logical expressions as integers as the 8-bit - integers may silently overflow at 256. - - + integers may silently overflow at 256. + + Top-level scipy routines ------------------------ @@ -192,7 +192,7 @@ Note the difference between :func:`iscomplex` ( :func:`isreal` ) and :func:`iscomplexobj` ( :func:`isrealobj` ). The former command is array based and returns byte arrays of ones and zeros providing the result of the element-wise test. The latter command is object based and returns a scalar describing the result of -the test on the entire object. +the test on the entire object. Often it is required to get just the real and/or imaginary part of a complex number. While complex numbers and arrays have attributes that @@ -206,7 +206,7 @@ Occasionally the need to check whether or not a number is a scalar (Python (long)int, Python float, Python complex, or rank-0 array) occurs in coding. This functionality is provided in the convenient -function :func:`isscalar` which returns a 1 or a 0. +function :func:`isscalar` which returns a 1 or a 0. Finally, ensuring that objects are a certain Numpy type occurs often enough that it has been given a convenient interface in SciPy through @@ -223,7 +223,7 @@ Thre are some class instances that make special use of the slicing functionality to provide efficient means for array construction. This -part will discuss the operation of :obj:`mgrid` , :obj:`ogrid` , :obj:`r_` , and :obj:`c_` for quickly constructing arrays. +part will discuss the operation of :obj:`mgrid` , :obj:`ogrid` , :obj:`r_` , and :obj:`c_` for quickly constructing arrays. One familiar with Matlab may complain that it is difficult to construct arrays from the interactive session with Python. Suppose, @@ -234,7 +234,7 @@ >>> concatenate(([3],[0]*5,arange(-1,1.002,2/9.0))) -With the :obj:`r_` command one can enter this as +With the :obj:`r_` command one can enter this as >>> r_[3,[0]*5,-1:1:10j] @@ -249,7 +249,7 @@ non-standard usage may be unsightly to some, but it gives the user the ability to quickly construct complicated vectors in a very readable fashion. When the number of points is specified in this way, the end- -point is inclusive. +point is inclusive. The "r" stands for row concatenation because if the objects between commas are 2 dimensional arrays, they are stacked by rows (and thus @@ -296,7 +296,7 @@ These are functions specifically suited for 2-dimensional arrays that were part of MLab in the Numpy distribution, but have been placed in -scipy_base for completeness so that users are not importing Numpy. +scipy_base for completeness so that users are not importing Numpy. Polynomials @@ -315,7 +315,7 @@ with the first element of the array giving the coefficient of the highest power. There are explicit functions to add, subtract, multiply, divide, integrate, differentiate, and evaluate polynomials -represented as sequences of coefficients. +represented as sequences of coefficients. Vectorizing functions (vectorize) @@ -340,7 +340,7 @@ >>> vec_addsubtract = vectorize(addsubtract) returns a function which takes array arguments and returns an array -result: +result: >>> vec_addsubtract([0,3,6,9],[1,3,5,7]) array([1, 6, 1, 2]) @@ -348,7 +348,7 @@ This particular function could have been written in vector form without the use of :obj:`vectorize` . But, what if the function you have written is the result of some optimization or integration routine. Such functions can likely only be -vectorized using ``vectorize.`` +vectorized using ``vectorize.`` Other useful functions @@ -376,7 +376,7 @@ construction of a function which returns an array of results based on a list of conditions. Each element of the return array is taken from the array in a ``choicelist`` corresponding to the first condition in -``condlist`` that is true. For example +``condlist`` that is true. For example .. literalinclude:: examples/2-3 @@ -404,7 +404,7 @@ approximation. This function is intended for use when only samples of the function are avaiable. When the function is an object that can be handed to a routine and evaluated, the function :obj:`derivative` can be used to automatically evaluate the object at the correct points -to obtain an N-point approximation to the :math:`o^{\textrm{th}}` -derivative at a given point. +to obtain an N-point approximation to the :math:`o^{\textrm{th}}` -derivative at a given point. Special functions (special) @@ -465,14 +465,14 @@ limits of integration. The return value is a tuple, with the first element holding the estimated value of the integral and the second element holding an upper bound on the error. Notice, that in this -case, the true value of this integral is +case, the true value of this integral is .. math:: :nowrap: \[ I=\sqrt{\frac{2}{\pi}}\left(\frac{18}{27}\sqrt{2}\cos\left(4.5\right)-\frac{4}{27}\sqrt{2}\sin\left(4.5\right)+\sqrt{2\pi}\textrm{Si}\left(\frac{3}{\sqrt{\pi}}\right)\right),\] -where +where .. math:: :nowrap: @@ -480,7 +480,7 @@ \[ \textrm{Si}\left(x\right)=\int_{0}^{x}\sin\left(\frac{\pi}{2}t^{2}\right)\, dt.\] is the Fresnel sine integral. Note that the numerically-computed -integral is within :math:`1.04\times10^{-11}` of the exact result --- well below the reported error bound. +integral is within :math:`1.04\times10^{-11}` of the exact result --- well below the reported error bound. Infinite inputs are also allowed in :obj:`quad` by using :math:`\pm` ``inf`` as one of the arguments. For example, suppose that a numerical @@ -500,7 +500,7 @@ The function which is integrated can even use the quad argument (though the error bound may underestimate the error due to possible -numerical error in the integrand from the use of :obj:`quad` ). The integral in this case is +numerical error in the integrand from the use of :obj:`quad` ). The integral in this case is .. math:: :nowrap: @@ -545,7 +545,7 @@ non-equally-spaced samples. The trapezoidal rule approximates the function as a straight line between adjacent points, while Simpson's rule approximates the function between three adjacent points as a -parabola. +parabola. If the samples are equally-spaced and the number of samples available is :math:`2^{k}+1` for some integer :math:`k` , then Romberg integration can be used to obtain high-precision @@ -554,7 +554,7 @@ of two and then performs Richardson extrapolation on these estimates to approximate the integral with a higher-degree of accuracy. (A different interface to Romberg integration useful when the function -can be provided is also available as :func:`integrate.romberg`). +can be provided is also available as :func:`integrate.romberg`). Ordinary differential equations (integrate.odeint) @@ -562,7 +562,7 @@ Integrating a set of ordinary differential equations (ODEs) given initial conditions is another useful example. The function :obj:`odeint` is available in SciPy for integrating a first-order vector -differential equation: +differential equation: .. math:: :nowrap: @@ -571,10 +571,10 @@ given initial conditions :math:`\mathbf{y}\left(0\right)=y_{0},` where :math:`\mathbf{y}` is a length :math:`N` vector and :math:`\mathbf{f}` is a mapping from :math:`\mathcal{R}^{N}` to :math:`\mathcal{R}^{N}.` A higher-order ordinary differential equation can always be reduced to a differential equation of this type by introducing intermediate -derivatives into the :math:`\mathbf{y}` vector. +derivatives into the :math:`\mathbf{y}` vector. For example suppose it is desired to find the solution to the -following second-order differential equation: +following second-order differential equation: .. math:: :nowrap: @@ -582,23 +582,23 @@ \[ \frac{d^{2}w}{dz^{2}}-zw(z)=0\] with initial conditions :math:`w\left(0\right)=\frac{1}{\sqrt[3]{3^{2}}\Gamma\left(\frac{2}{3}\right)}` and :math:`\left.\frac{dw}{dz}\right|_{z=0}=-\frac{1}{\sqrt[3]{3}\Gamma\left(\frac{1}{3}\right)}.` It is known that the solution to this differential equation with these -boundary conditions is the Airy function +boundary conditions is the Airy function .. math:: :nowrap: \[ w=\textrm{Ai}\left(z\right),\] -which gives a means to check the integrator using :func:`special.airy`. +which gives a means to check the integrator using :func:`special.airy`. -First, convert this ODE into standard form by setting :math:`\mathbf{y}=\left[\frac{dw}{dz},w\right]` and :math:`t=z.` Thus, the differential equation becomes +First, convert this ODE into standard form by setting :math:`\mathbf{y}=\left[\frac{dw}{dz},w\right]` and :math:`t=z.` Thus, the differential equation becomes .. math:: :nowrap: \[ \frac{d\mathbf{y}}{dt}=\left[\begin{array}{c} ty_{1}\\ y_{0}\end{array}\right]=\left[\begin{array}{cc} 0 & t\\ 1 & 0\end{array}\right]\left[\begin{array}{c} y_{0}\\ y_{1}\end{array}\right]=\left[\begin{array}{cc} 0 & t\\ 1 & 0\end{array}\right]\mathbf{y}.\] -In other words, +In other words, .. math:: :nowrap: @@ -608,14 +608,14 @@ As an interesting reminder, if :math:`\mathbf{A}\left(t\right)` commutes with :math:`\int_{0}^{t}\mathbf{A}\left(\tau\right)\, d\tau` under matrix multiplication, then this linear differential equation -has an exact solution using the matrix exponential: +has an exact solution using the matrix exponential: .. math:: :nowrap: \[ \mathbf{y}\left(t\right)=\exp\left(\int_{0}^{t}\mathbf{A}\left(\tau\right)d\tau\right)\mathbf{y}\left(0\right),\] -However, in this case, :math:`\mathbf{A}\left(t\right)` and its integral do not commute. +However, in this case, :math:`\mathbf{A}\left(t\right)` and its integral do not commute. There are many optional inputs and outputs available when using odeint which can help tune the solver. These additional inputs and outputs @@ -652,7 +652,7 @@ minimization over a specified interval. The last algorithm actually finds the roots of a general function of possibly many variables. It is included in the optimization package because at the (non-boundary) -extreme points of a function, the gradient is equal to zero. +extreme points of a function, the gradient is equal to zero. Nelder-Mead Simplex algorithm (optimize.fmin) @@ -664,19 +664,19 @@ problems. However, because it does not use any gradient evaluations, it may take longer to find the minimum. To demonstrate the minimization function consider the problem of minimizing the -Rosenbrock function of :math:`N` variables: +Rosenbrock function of :math:`N` variables: .. math:: :nowrap: \[ f\left(\mathbf{x}\right)=\sum_{i=1}^{N-1}100\left(x_{i}-x_{i-1}^{2}\right)^{2}+\left(1-x_{i-1}\right)^{2}.\] -The minimum value of this function is 0 which is achieved when :math:`x_{i}=1.` This minimum can be found using the :obj:`fmin` routine as shown in the example below: +The minimum value of this function is 0 which is achieved when :math:`x_{i}=1.` This minimum can be found using the :obj:`fmin` routine as shown in the example below: .. literalinclude:: examples/5-2 Another optimization algorithm that needs only function calls to find -the minimum is Powell's method available as :func:`optimize.fmin_powell`. +the minimum is Powell's method available as :func:`optimize.fmin_powell`. Broyden-Fletcher-Goldfarb-Shanno algorithm (optimize.fmin_bfgs) @@ -687,10 +687,10 @@ by the user, then it is estimated using first-differences. The Broyden-Fletcher-Goldfarb-Shanno (BFGS) method typically requires fewer function calls than the simplex algorithm even when the gradient -must be estimated. +must be estimated. To demonstrate this algorithm, the Rosenbrock function is again used. -The gradient of the Rosenbrock function is the vector: +The gradient of the Rosenbrock function is the vector: .. math:: :nowrap: @@ -698,7 +698,7 @@ \begin{eqnarray*} \frac{\partial f}{\partial x_{j}} & = & \sum_{i=1}^{N}200\left(x_{i}-x_{i-1}^{2}\right)\left(\delta_{i,j}-2x_{i-1}\delta_{i-1,j}\right)-2\left(1-x_{i-1}\right)\delta_{i-1,j}.\\ & = & 200\left(x_{j}-x_{j-1}^{2}\right)-400x_{j}\left(x_{j+1}-x_{j}^{2}\right)-2\left(1-x_{j}\right).\end{eqnarray*} This expression is valid for the interior derivatives. Special cases -are +are .. math:: :nowrap: @@ -706,7 +706,7 @@ \begin{eqnarray*} \frac{\partial f}{\partial x_{0}} & = & -400x_{0}\left(x_{1}-x_{0}^{2}\right)-2\left(1-x_{0}\right),\\ \frac{\partial f}{\partial x_{N-1}} & = & 200\left(x_{N-1}-x_{N-2}^{2}\right).\end{eqnarray*} A Python function which computes this gradient is constructed by the -code-segment: +code-segment: .. literalinclude:: examples/5-3 @@ -735,7 +735,7 @@ where :math:`\mathbf{H}\left(\mathbf{x}_{0}\right)` is a matrix of second-derivatives (the Hessian). If the Hessian is positive definite then the local minimum of this function can be found -by setting the gradient of the quadratic form to zero, resulting in +by setting the gradient of the quadratic form to zero, resulting in .. math:: :nowrap: @@ -751,27 +751,27 @@ vector needs to be available to the minimization routine. As a result, the user can provide either a function to compute the Hessian matrix, or a function to compute the product of the Hessian with an arbitrary -vector. +vector. Full Hessian example: ^^^^^^^^^^^^^^^^^^^^^ -The Hessian of the Rosenbrock function is +The Hessian of the Rosenbrock function is .. math:: :nowrap: \begin{eqnarray*} H_{ij}=\frac{\partial^{2}f}{\partial x_{i}\partial x_{j}} & = & 200\left(\delta_{i,j}-2x_{i-1}\delta_{i-1,j}\right)-400x_{i}\left(\delta_{i+1,j}-2x_{i}\delta_{i,j}\right)-400\delta_{i,j}\left(x_{i+1}-x_{i}^{2}\right)+2\delta_{i,j},\\ & = & \left(202+1200x_{i}^{2}-400x_{i+1}\right)\delta_{i,j}-400x_{i}\delta_{i+1,j}-400x_{i-1}\delta_{i-1,j},\end{eqnarray*} -if :math:`i,j\in\left[1,N-2\right]` with :math:`i,j\in\left[0,N-1\right]` defining the :math:`N\times N` matrix. Other non-zero entries of the matrix are +if :math:`i,j\in\left[1,N-2\right]` with :math:`i,j\in\left[0,N-1\right]` defining the :math:`N\times N` matrix. Other non-zero entries of the matrix are .. math:: :nowrap: \begin{eqnarray*} \frac{\partial^{2}f}{\partial x_{0}^{2}} & = & 1200x_{0}^{2}-400x_{1}+2,\\ \frac{\partial^{2}f}{\partial x_{0}\partial x_{1}}=\frac{\partial^{2}f}{\partial x_{1}\partial x_{0}} & = & -400x_{0},\\ \frac{\partial^{2}f}{\partial x_{N-1}\partial x_{N-2}}=\frac{\partial^{2}f}{\partial x_{N-2}\partial x_{N-1}} & = & -400x_{N-2},\\ \frac{\partial^{2}f}{\partial x_{N-1}^{2}} & = & 200.\end{eqnarray*} -For example, the Hessian when :math:`N=5` is +For example, the Hessian when :math:`N=5` is .. math:: :nowrap: @@ -779,7 +779,7 @@ \[ \mathbf{H}=\left[\begin{array}{ccccc} 1200x_{0}^{2}-400x_{1}+2 & -400x_{0} & 0 & 0 & 0\\ -400x_{0} & 202+1200x_{1}^{2}-400x_{2} & -400x_{1} & 0 & 0\\ 0 & -400x_{1} & 202+1200x_{2}^{2}-400x_{3} & -400x_{2} & 0\\ 0 & & -400x_{2} & 202+1200x_{3}^{2}-400x_{4} & -400x_{3}\\ 0 & 0 & 0 & -400x_{3} & 200\end{array}\right].\] The code which computes this Hessian along with the code to minimize -the function using :obj:`fmin_ncg` is shown in the following example: +the function using :obj:`fmin_ncg` is shown in the following example: .. literalinclude:: examples/5-5 @@ -801,7 +801,7 @@ minimize the function. In this case, the product of the Rosenbrock Hessian with an arbitrary -vector is not difficult to compute. If :math:`\mathbf{p}` is the arbitrary vector, then :math:`\mathbf{H}\left(\mathbf{x}\right)\mathbf{p}` has elements: +vector is not difficult to compute. If :math:`\mathbf{p}` is the arbitrary vector, then :math:`\mathbf{H}\left(\mathbf{x}\right)\mathbf{p}` has elements: .. math:: :nowrap: @@ -823,7 +823,7 @@ set of data :math:`\left\{ \mathbf{x}_{i},\mathbf{y}_{i}\right\} ` to a known model, :math:`\mathbf{y}=\mathbf{f}\left(\mathbf{x},\mathbf{p}\right)` where :math:`\mathbf{p}` is a vector of parameters for the model that need to be found. A common method for determining which parameter vector gives the best fit to the data is to minimize the sum of squares of the residuals. -The residual is usually defined for each observed data-point as +The residual is usually defined for each observed data-point as .. math:: :nowrap: @@ -831,7 +831,7 @@ \[ e_{i}\left(\mathbf{p},\mathbf{y}_{i},\mathbf{x}_{i}\right)=\left\Vert \mathbf{y}_{i}-\mathbf{f}\left(\mathbf{x}_{i},\mathbf{p}\right)\right\Vert .\] An objective function to pass to any of the previous minization -algorithms to obtain a least-squares fit is. +algorithms to obtain a least-squares fit is. .. math:: :nowrap: @@ -843,17 +843,17 @@ The :obj:`leastsq` algorithm performs this squaring and summing of the residuals automatically. It takes as an input argument the vector function :math:`\mathbf{e}\left(\mathbf{p}\right)` and returns the value of :math:`\mathbf{p}` which minimizes :math:`J\left(\mathbf{p}\right)=\mathbf{e}^{T}\mathbf{e}` directly. The user is also encouraged to provide the Jacobian matrix of the function (with derivatives down the columns or across the -rows). If the Jacobian is not provided, it is estimated. +rows). If the Jacobian is not provided, it is estimated. An example should clarify the usage. Suppose it is believed some -measured data follow a sinusoidal pattern +measured data follow a sinusoidal pattern .. math:: :nowrap: \[ y_{i}=A\sin\left(2\pi kx_{i}+\theta\right)\] -where the parameters :math:`A,` :math:`k` , and :math:`\theta` are unknown. The residual vector is +where the parameters :math:`A,` :math:`k` , and :math:`\theta` are unknown. The residual vector is .. math:: :nowrap: @@ -863,7 +863,7 @@ By defining a function to compute the residuals and (selecting an appropriate starting position), the least-squares fit routine can be used to find the best-fit parameters :math:`\hat{A},\,\hat{k},\,\hat{\theta}` . This is shown in the following example and a plot of the results is -shown in Figure `1 <#fig-least-squares-fit>`__ . +shown in Figure `1 <#fig-least-squares-fit>`__ . .. _`fig:least_squares_fit`: @@ -872,7 +872,7 @@ :doctest-format: :align: center -.. XXX: **Figure 1** Least-square fitting to noisy data using +.. XXX: **Figure 1** Least-square fitting to noisy data using .. XXX: :obj:`scipy.optimize.leastsq` @@ -882,7 +882,7 @@ Often only the minimum of a scalar function is needed (a scalar function is one that takes a scalar as input and returns a scalar output). In these circumstances, other optimization techniques have -been developed that can work faster. +been developed that can work faster. Unconstrained minimization (optimize.brent) @@ -911,9 +911,9 @@ minimization occurs. The :obj:`fminbound` function is an example of a constrained minimization procedure that provides a rudimentary interval constraint for scalar functions. The interval constraint allows the minimization to occur only between two -fixed endpoints. +fixed endpoints. -For example, to find the minimum of :math:`J_{1}\left(x\right)` near :math:`x=5` , :obj:`fminbound` can be called using the interval :math:`\left[4,7\right]` as a constraint. The result is :math:`x_{\textrm{min}}=5.3314` : +For example, to find the minimum of :math:`J_{1}\left(x\right)` near :math:`x=5` , :obj:`fminbound` can be called using the interval :math:`\left[4,7\right]` as a constraint. The result is :math:`x_{\textrm{min}}=5.3314` : .. literalinclude:: examples/5-8 @@ -929,21 +929,21 @@ To find the roots of a polynomial, the command :obj:`roots` is useful. To find a root of a set of non-linear equations, the command :obj:`optimize.fsolve` is needed. For example, the following example finds the roots of the -single-variable transcendental equation +single-variable transcendental equation .. math:: :nowrap: \[ x+2\cos\left(x\right)=0,\] -and the set of non-linear equations +and the set of non-linear equations .. math:: :nowrap: \begin{eqnarray*} x_{0}\cos\left(x_{1}\right) & = & 4,\\ x_{0}x_{1}-x_{1} & = & 5.\end{eqnarray*} -The results are :math:`x=-1.0299` and :math:`x_{0}=6.5041,\, x_{1}=0.9084` . +The results are :math:`x=-1.0299` and :math:`x_{0}=6.5041,\, x_{1}=0.9084` . .. literalinclude:: examples/5-9 @@ -957,7 +957,7 @@ finder algorithms that can be tried. Each of these root finding algorithms requires the endpoints of an interval where a root is suspected (because the function changes signs). In general :obj:`brentq` is the best choice, but the other methods may be useful in certain -circumstances or for academic purposes. +circumstances or for academic purposes. Fixed-point solving @@ -967,7 +967,7 @@ problem of finding a fixed-point of a function. A fixed point of a function is the point at which evaluation of the function returns the point: :math:`g\left(x\right)=x.` Clearly the fixed point of :math:`g` is the root of :math:`f\left(x\right)=g\left(x\right)-x.` Equivalently, the root of :math:`f` is the fixed_point of :math:`g\left(x\right)=f\left(x\right)+x.` The routine :obj:`fixed_point` provides a simple iterative method using Aitkens sequence acceleration -to estimate the fixed point of :math:`g` given a starting point. +to estimate the fixed point of :math:`g` given a starting point. Interpolation (interpolate) @@ -977,7 +977,7 @@ first facility is an interpolation class which performs linear 1-dimensional interpolation. The second facility is based on the FORTRAN library FITPACK and provides functions for 1- and -2-dimensional (smoothed) cubic-spline interpolation. +2-dimensional (smoothed) cubic-spline interpolation. Linear 1-d interpolation (interpolate.interp1d) @@ -1001,8 +1001,8 @@ :include-source: :align: center -.. **Figure 2** One-dimensional interpolation using the - class :obj:`interpolate.interp1d` +.. **Figure 2** One-dimensional interpolation using the + class :obj:`interpolate.interp1d` Spline interpolation in 1-d (interpolate.splXXX) @@ -1016,15 +1016,15 @@ The direct method finds the spline representation of a curve in a two- dimensional plane using the function :obj:`interpolate.splrep`. The first two arguments are the only ones required, and these provide the :math:`x` and :math:`y` components of the curve. The normal output is a 3-tuple, :math:`\left(t,c,k\right)` , containing the knot-points, :math:`t` , the coefficients :math:`c` and the order :math:`k` of the spline. The default spline order is cubic, but this can be -changed with the input keyword, *k.* +changed with the input keyword, *k.* For curves in :math:`N` -dimensional space the function :obj:`interpolate.splprep` allows defining the curve parametrically. For this function only 1 input argument is required. This input is a list of :math:`N` -arrays representing the curve in :math:`N` -dimensional space. The length of each array is the number of curve points, and each array provides one component of the :math:`N` -dimensional data point. The parameter variable is given with the -keword argument, *u,* which defaults to an equally-spaced monotonic sequence between :math:`0` and :math:`1` . The default output consists of two objects: a 3-tuple, :math:`\left(t,c,k\right)` , containing the spline representation and the parameter variable :math:`u.` +keword argument, *u,* which defaults to an equally-spaced monotonic sequence between :math:`0` and :math:`1` . The default output consists of two objects: a 3-tuple, :math:`\left(t,c,k\right)` , containing the spline representation and the parameter variable :math:`u.` The keyword argument, *s* , is used to specify the amount of smoothing to perform during the -spline fit. The default value of :math:`s` is :math:`s=m-\sqrt{2m}` where :math:`m` is the number of data-points being fit. Therefore, **if no smoothing is desired a value of** :math:`\mathbf{s}=0` **should be passed to the routines.** +spline fit. The default value of :math:`s` is :math:`s=m-\sqrt{2m}` where :math:`m` is the number of data-points being fit. Therefore, **if no smoothing is desired a value of** :math:`\mathbf{s}=0` **should be passed to the routines.** Once the spline representation of the data has been determined, functions are available for evaluating the spline @@ -1079,7 +1079,7 @@ dimensional function as shown in the example that follows (See also Figure `4 <#fig-2d-interp>`__ ). This example uses the :obj:`mgrid` command in SciPy which is useful for defining a "mesh-grid "in many dimensions. (See also the :obj:`ogrid` command if the full-mesh is not needed). The number of output arguments and the number of dimensions of each argument is determined -by the number of indexing objects passed in :obj:`mgrid`[]. +by the number of indexing objects passed in :obj:`mgrid`[]. .. _`fig:2d_interp`: @@ -1088,8 +1088,8 @@ :include-source: :align: center -.. XXX: **Figure 4** -.. XXX: Example of two-dimensional spline interpolation. +.. XXX: **Figure 4** +.. XXX: Example of two-dimensional spline interpolation. Signal Processing (signal) @@ -1103,7 +1103,7 @@ with equally-spaced data and make heavy use of filter-theory and transfer-function formalism to provide a fast B-spline transform. To understand this section you will need to understand that a signal in -SciPy is an array of real or complex numbers. +SciPy is an array of real or complex numbers. B-splines @@ -1112,14 +1112,14 @@ A B-spline is an approximation of a continuous function over a finite- domain in terms of B-spline coefficients and knot points. If the knot- points are equally spaced with spacing :math:`\Delta x` , then the B-spline approximation to a 1-dimensional function is the -finite-basis expansion. +finite-basis expansion. .. math:: :nowrap: \[ y\left(x\right)\approx\sum_{j}c_{j}\beta^{o}\left(\frac{x}{\Delta x}-j\right).\] -In two dimensions with knot-spacing :math:`\Delta x` and :math:`\Delta y` , the function representation is +In two dimensions with knot-spacing :math:`\Delta x` and :math:`\Delta y` , the function representation is .. math:: :nowrap: @@ -1129,35 +1129,35 @@ In these expressions, :math:`\beta^{o}\left(\cdot\right)` is the space-limited B-spline basis function of order, :math:`o` . The requirement of equally-spaced knot-points and equally-spaced data points, allows the development of fast (inverse-filtering) algorithms for determining the coefficients, :math:`c_{j}` , from sample-values, :math:`y_{n}` . Unlike the general spline interpolation algorithms, these algorithms -can quickly find the spline coefficients for large images. +can quickly find the spline coefficients for large images. The advantage of representing a set of samples via B-spline basis functions is that continuous-domain operators (derivatives, re- sampling, integral, etc.) which assume that the data samples are drawn from an underlying continuous function can be computed with relative ease from the spline coefficients. For example, the second-derivative -of a spline is +of a spline is .. math:: :nowrap: \[ y{}^{\prime\prime}\left(x\right)=\frac{1}{\Delta x^{2}}\sum_{j}c_{j}\beta^{o\prime\prime}\left(\frac{x}{\Delta x}-j\right).\] -Using the property of B-splines that +Using the property of B-splines that .. math:: :nowrap: \[ \frac{d^{2}\beta^{o}\left(w\right)}{dw^{2}}=\beta^{o-2}\left(w+1\right)-2\beta^{o-2}\left(w\right)+\beta^{o-2}\left(w-1\right)\] -it can be seen that +it can be seen that .. math:: :nowrap: \[ y^{\prime\prime}\left(x\right)=\frac{1}{\Delta x^{2}}\sum_{j}c_{j}\left[\beta^{o-2}\left(\frac{x}{\Delta x}-j+1\right)-2\beta^{o-2}\left(\frac{x}{\Delta x}-j\right)+\beta^{o-2}\left(\frac{x}{\Delta x}-j-1\right)\right].\] -If :math:`o=3` , then at the sample points, +If :math:`o=3` , then at the sample points, .. math:: :nowrap: @@ -1166,7 +1166,7 @@ Thus, the second-derivative signal can be easily calculated from the spline fit. if desired, smoothing splines can be found to make the -second-derivative less sensitive to random-errors. +second-derivative less sensitive to random-errors. The savvy reader will have already noticed that the data samples are related to the knot coefficients via a convolution operator, so that @@ -1178,7 +1178,7 @@ processing sub package assume mirror-symmetric boundary conditions. Thus, spline coefficients are computed based on that assumption, and data-samples can be recovered exactly from the spline coefficients by -assuming them to be mirror-symmetric also. +assuming them to be mirror-symmetric also. Currently the package provides functions for determining second- and third-order cubic spline coefficients from equally spaced samples in @@ -1215,9 +1215,9 @@ :include-source: :align: center -.. **Figure 5** +.. **Figure 5** .. .. image: figs/lena_edge.pdf -.. Example of using smoothing splines to filter images. +.. Example of using smoothing splines to filter images. Filtering @@ -1249,9 +1249,9 @@ in the signal and it implies that the filtering matrix can be constructed from knowledge of one row (or column) of the matrix alone. In this case, the matrix multiplication can be accomplished using -Fourier transforms. +Fourier transforms. -Let :math:`x\left[n\right]` define a one-dimensional signal indexed by the integer :math:`n.` Full convolution of two one-dimensional signals can be expressed as +Let :math:`x\left[n\right]` define a one-dimensional signal indexed by the integer :math:`n.` Full convolution of two one-dimensional signals can be expressed as .. math:: :nowrap: @@ -1260,46 +1260,46 @@ This equation can only be implemented directly if we limit the sequences to finite support sequences that can be stored in a -computer, choose :math:`n=0` to be the starting point of both sequences, let :math:`K+1` be that value for which :math:`y\left[n\right]=0` for all :math:`n>K+1` and :math:`M+1` be that value for which :math:`x\left[n\right]=0` for all :math:`n>M+1` , then the discrete convolution expression is +computer, choose :math:`n=0` to be the starting point of both sequences, let :math:`K+1` be that value for which :math:`y\left[n\right]=0` for all :math:`n>K+1` and :math:`M+1` be that value for which :math:`x\left[n\right]=0` for all :math:`n>M+1` , then the discrete convolution expression is .. math:: :nowrap: \[ y\left[n\right]=\sum_{k=\max\left(n-M,0\right)}^{\min\left(n,K\right)}x\left[k\right]h\left[n-k\right].\] -For convenience assume :math:`K\geq M.` Then, more explicitly the output of this operation is +For convenience assume :math:`K\geq M.` Then, more explicitly the output of this operation is .. math:: :nowrap: \begin{eqnarray*} y\left[0\right] & = & x\left[0\right]h\left[0\right]\\ y\left[1\right] & = & x\left[0\right]h\left[1\right]+x\left[1\right]h\left[0\right]\\ y\left[2\right] & = & x\left[0\right]h\left[2\right]+x\left[1\right]h\left[1\right]+x\left[2\right]h\left[0\right]\\ \vdots & \vdots & \vdots\\ y\left[M\right] & = & x\left[0\right]h\left[M\right]+x\left[1\right]h\left[M-1\right]+\cdots+x\left[M\right]h\left[0\right]\\ y\left[M+1\right] & = & x\left[1\right]h\left[M\right]+x\left[2\right]h\left[M-1\right]+\cdots+x\left[M+1\right]h\left[0\right]\\ \vdots & \vdots & \vdots\\ y\left[K\right] & = & x\left[K-M\right]h\left[M\right]+\cdots+x\left[K\right]h\left[0\right]\\ y\left[K+1\right] & = & x\left[K+1-M\right]h\left[M\right]+\cdots+x\left[K\right]h\left[1\right]\\ \vdots & \vdots & \vdots\\ y\left[K+M-1\right] & = & x\left[K-1\right]h\left[M\right]+x\left[K\right]h\left[M-1\right]\\ y\left[K+M\right] & = & x\left[K\right]h\left[M\right].\end{eqnarray*} -Thus, the full discrete convolution of two finite sequences of lengths :math:`K+1` and :math:`M+1` respectively results in a finite sequence of length :math:`K+M+1=\left(K+1\right)+\left(M+1\right)-1.` +Thus, the full discrete convolution of two finite sequences of lengths :math:`K+1` and :math:`M+1` respectively results in a finite sequence of length :math:`K+M+1=\left(K+1\right)+\left(M+1\right)-1.` One dimensional convolution is implemented in SciPy with the function ``signal.convolve`` . This function takes as inputs the signals :math:`x,` :math:`h` , and an optional flag and returns the signal :math:`y.` The optional flag allows for specification of which part of the output signal to return. The default value of 'full' returns the entire signal. If the flag has a value of 'same' then only the middle :math:`K` values are returned starting at :math:`y\left[\left\lfloor \frac{M-1}{2}\right\rfloor \right]` so that the output has the same length as the largest input. If the -flag has a value of 'valid' then only the middle :math:`K-M+1=\left(K+1\right)-\left(M+1\right)+1` output values are returned where :math:`z` depends on all of the values of the smallest input from :math:`h\left[0\right]` to :math:`h\left[M\right].` In other words only the values :math:`y\left[M\right]` to :math:`y\left[K\right]` inclusive are returned. +flag has a value of 'valid' then only the middle :math:`K-M+1=\left(K+1\right)-\left(M+1\right)+1` output values are returned where :math:`z` depends on all of the values of the smallest input from :math:`h\left[0\right]` to :math:`h\left[M\right].` In other words only the values :math:`y\left[M\right]` to :math:`y\left[K\right]` inclusive are returned. This same function ``signal.convolve`` can actually take :math:`N` -dimensional arrays as inputs and will return the :math:`N` -dimensional convolution of the two arrays. The same input flags are -available for that case as well. +available for that case as well. Correlation is very similar to convolution except for the minus sign -becomes a plus sign. Thus +becomes a plus sign. Thus .. math:: :nowrap: \[ w\left[n\right]=\sum_{k=-\infty}^{\infty}y\left[k\right]x\left[n+k\right]\] -is the (cross) correlation of the signals :math:`y` and :math:`x.` For finite-length signals with :math:`y\left[n\right]=0` outside of the range :math:`\left[0,K\right]` and :math:`x\left[n\right]=0` outside of the range :math:`\left[0,M\right],` the summation can simplify to +is the (cross) correlation of the signals :math:`y` and :math:`x.` For finite-length signals with :math:`y\left[n\right]=0` outside of the range :math:`\left[0,K\right]` and :math:`x\left[n\right]=0` outside of the range :math:`\left[0,M\right],` the summation can simplify to .. math:: :nowrap: \[ w\left[n\right]=\sum_{k=\max\left(0,-n\right)}^{\min\left(K,M-n\right)}y\left[k\right]x\left[n+k\right].\] -Assuming again that :math:`K\geq M` this is +Assuming again that :math:`K\geq M` this is .. math:: :nowrap: @@ -1311,23 +1311,23 @@ The SciPy function ``signal.correlate`` implements this operation. Equivalent flags are available for this operation to return the full :math:`K+M+1` length sequence ('full') or a sequence with the same size as the largest sequence starting at :math:`w\left[-K+\left\lfloor \frac{M-1}{2}\right\rfloor \right]` ('same') or a sequence where the values depend on all the values of -the smallest sequence ('valid'). This final option returns the :math:`K-M+1` values :math:`w\left[M-K\right]` to :math:`w\left[0\right]` inclusive. +the smallest sequence ('valid'). This final option returns the :math:`K-M+1` values :math:`w\left[M-K\right]` to :math:`w\left[0\right]` inclusive. -The function :obj:`signal.correlate` can also take arbitrary :math:`N` -dimensional arrays as input and return the :math:`N` -dimensional convolution of the two arrays on output. +The function :obj:`signal.correlate` can also take arbitrary :math:`N` -dimensional arrays as input and return the :math:`N` -dimensional convolution of the two arrays on output. When :math:`N=2,` :obj:`signal.correlate` and/or :obj:`signal.convolve` can be used to construct arbitrary image filters to perform actions -such as blurring, enhancing, and edge-detection for an image. +such as blurring, enhancing, and edge-detection for an image. Convolution is mainly used for filtering when one of the signals is much smaller than the other ( :math:`K\gg M` ), otherwise linear filtering is more easily accomplished in the -frequency domain (see Fourier Transforms). +frequency domain (see Fourier Transforms). Difference-equation filtering ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A general class of linear one-dimensional filters (that includes -convolution filters) are filters described by the difference equation +convolution filters) are filters described by the difference equation .. math:: :nowrap: @@ -1336,9 +1336,9 @@ where :math:`x\left[n\right]` is the input sequence and :math:`y\left[n\right]` is the output sequence. If we assume initial rest so that :math:`y\left[n\right]=0` for :math:`n<0` , then this kind of filter can be implemented using convolution. However, the convolution filter sequence :math:`h\left[n\right]` could be infinite if :math:`a_{k}\neq0` for :math:`k\geq1.` In addition, this general class of linear filter allows initial -conditions to be placed on :math:`y\left[n\right]` for :math:`n<0` resulting in a filter that cannot be expressed using convolution. +conditions to be placed on :math:`y\left[n\right]` for :math:`n<0` resulting in a filter that cannot be expressed using convolution. -The difference equation filter can be thought of as finding :math:`y\left[n\right]` recursively in terms of it's previous values +The difference equation filter can be thought of as finding :math:`y\left[n\right]` recursively in terms of it's previous values .. math:: :nowrap: @@ -1349,37 +1349,37 @@ general difference equation filter is a little more complicated then would be implied by the previous equation. It is implemented so that only one signal needs to be delayed. The actual implementation -equations are (assuming :math:`a_{0}=1` ). +equations are (assuming :math:`a_{0}=1` ). .. math:: :nowrap: \begin{eqnarray*} y\left[n\right] & = & b_{0}x\left[n\right]+z_{0}\left[n-1\right]\\ z_{0}\left[n\right] & = & b_{1}x\left[n\right]+z_{1}\left[n-1\right]-a_{1}y\left[n\right]\\ z_{1}\left[n\right] & = & b_{2}x\left[n\right]+z_{2}\left[n-1\right]-a_{2}y\left[n\right]\\ \vdots & \vdots & \vdots\\ z_{K-2}\left[n\right] & = & b_{K-1}x\left[n\right]+z_{K-1}\left[n-1\right]-a_{K-1}y\left[n\right]\\ z_{K-1}\left[n\right] & = & b_{K}x\left[n\right]-a_{K}y\left[n\right],\end{eqnarray*} -where :math:`K=\max\left(N,M\right).` Note that :math:`b_{K}=0` if :math:`K>M` and :math:`a_{K}=0` if :math:`K>N.` In this way, the output at time :math:`n` depends only on the input at time :math:`n` and the value of :math:`z_{0}` at the previous time. This can always be calculated as long as the :math:`K` values :math:`z_{0}\left[n-1\right]\ldots z_{K-1}\left[n-1\right]` are computed and stored at each time step. +where :math:`K=\max\left(N,M\right).` Note that :math:`b_{K}=0` if :math:`K>M` and :math:`a_{K}=0` if :math:`K>N.` In this way, the output at time :math:`n` depends only on the input at time :math:`n` and the value of :math:`z_{0}` at the previous time. This can always be calculated as long as the :math:`K` values :math:`z_{0}\left[n-1\right]\ldots z_{K-1}\left[n-1\right]` are computed and stored at each time step. The difference-equation filter is called using the command :obj:`signal.lfilter` in SciPy. This command takes as inputs the vector :math:`b,` the vector, :math:`a,` a signal :math:`x` and returns the vector :math:`y` (the same length as :math:`x` ) computed using the equation given above. If :math:`x` is :math:`N` -dimensional, then the filter is computed along the axis provided. If, desired, initial conditions providing the values of :math:`z_{0}\left[-1\right]` to :math:`z_{K-1}\left[-1\right]` can be provided or else it will be assumed that they are all zero. If initial conditions are provided, then the final conditions on the intermediate variables are also returned. These could be used, for -example, to restart the calculation in the same state. +example, to restart the calculation in the same state. Sometimes it is more convenient to express the initial conditions in terms of the signals :math:`x\left[n\right]` and :math:`y\left[n\right].` In other words, perhaps you have the values of :math:`x\left[-M\right]` to :math:`x\left[-1\right]` and the values of :math:`y\left[-N\right]` to :math:`y\left[-1\right]` and would like to determine what values of :math:`z_{m}\left[-1\right]` should be delivered as initial conditions to the difference-equation -filter. It is not difficult to show that for :math:`0\leq mN` the generalized inverse is +singular value decomposition. Let :math:`\mathbf{A}` be an :math:`M\times N` matrix, then if :math:`M>N` the generalized inverse is .. math:: :nowrap: \[ \mathbf{A}^{\dagger}=\left(\mathbf{A}^{H}\mathbf{A}\right)^{-1}\mathbf{A}^{H}\] -while if :math:`M Author: tzito Date: 2008-11-19 05:28:49 -0600 (Wed, 19 Nov 2008) New Revision: 5149 Modified: trunk/scipy/linalg/decomp.py trunk/scipy/linalg/generic_flapack.pyf trunk/scipy/linalg/tests/test_decomp.py Log: Added new functionality and corresponding unit tests to linalg.eigh and linalg.eigvalsh. This is the result of symeig integration in scipy. Modified: trunk/scipy/linalg/decomp.py =================================================================== --- trunk/scipy/linalg/decomp.py 2008-11-18 20:47:56 UTC (rev 5148) +++ trunk/scipy/linalg/decomp.py 2008-11-19 11:28:49 UTC (rev 5149) @@ -8,6 +8,7 @@ # additions by Johannes Loehnert, June 2006 # additions by Bart Vandereycken, June 2006 # additions by Andrew D Straw, May 2007 +# additions by Tiziano Zito, November 2008 __all__ = ['eig','eigh','eig_banded','eigvals','eigvalsh', 'eigvals_banded', 'lu','svd','svdvals','diagsvd','cholesky','qr','qr_old','rq', @@ -24,7 +25,7 @@ from scipy.linalg import calc_lwork import numpy from numpy import array, asarray_chkfinite, asarray, diag, zeros, ones, \ - single, isfinite, inexact, complexfloating + single, isfinite, inexact, complexfloating, nonzero, iscomplexobj cast = numpy.cast r_ = numpy.r_ @@ -203,97 +204,195 @@ return w, vl return w, vr -def eigh(a, lower=True, eigvals_only=False, overwrite_a=False): - """Solve the eigenvalue problem for a Hermitian or real symmetric matrix. +def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False, + overwrite_b=False, turbo=True, eigvals=None, type=1): + """Solve an ordinary or generalized eigenvalue problem for a complex + Hermitian or real symmetric matrix. - Find eigenvalues w and optionally right eigenvectors v of a:: + Find eigenvalues w and optionally eigenvectors v of matrix a, where + b is positive definite:: - a v[:,i] = w[i] v[:,i] - v.H v = identity + a v[:,i] = w[i] b v[:,i] + v[i,:].conj() a v[:,i] = w[i] + v[i,:].conj() b v[:,i] = 1 + Parameters ---------- a : array, shape (M, M) - A complex Hermitian or symmetric real matrix whose eigenvalues - and eigenvectors will be computed. + A complex Hermitian or real symmetric matrix whose eigenvalues and + eigenvectors will be computed. + b : array, shape (M, M) + A complex Hermitian or real symmetric definite positive matrix in. + If omitted, identity matrix is assumed. lower : boolean Whether the pertinent array data is taken from the lower or upper triangle of a. (Default: lower) eigvals_only : boolean Whether to calculate only eigenvalues and no eigenvectors. (Default: both are calculated) + turbo : boolean + Use divide and conquer algorithm (faster but expensive in memory, + only for generalized eigenvalue problem and if eigvals=None) + eigvals : tuple (lo, hi) + Indexes of the smallest and largest (in ascending order) eigenvalues + and corresponding eigenvectors to be returned: 0 <= lo < hi <= M-1. + If omitted, all eigenvalues and eigenvectors are returned. + type: integer + Specifies the problem type to be solved: + type = 1: a v[:,i] = w[i] b v[:,i] + type = 2: a b v[:,i] = w[i] v[:,i] + type = 3: b a v[:,i] = w[i] v[:,i] overwrite_a : boolean - Whether data in a is overwritten (may improve performance). + Whether to overwrite data in a (may improve performance) + overwrite_b : boolean + Whether to overwrite data in b (may improve performance) Returns ------- - w : double array, shape (M,) - The eigenvalues, in ascending order, each repeated according to its - multiplicity. + w : real array, shape (N,) + The N (1<=N<=M) selected eigenvalues, in ascending order, each + repeated according to its multiplicity. (if eigvals_only == False) - v : double or complex double array, shape (M, M) - The normalized eigenvector corresponding to the eigenvalue w[i] is - the column v[:,i]. + v : complex array, shape (M, N) + The normalized selected eigenvector corresponding to the + eigenvalue w[i] is the column v[:,i]. Normalization: + type 1 and 3: v.conj() a v = w + type 2: inv(v).conj() a inv(v) = w + type = 1 or 2: v.conj() b v = I + type = 3 : v.conj() inv(b) v = I + + Raises LinAlgError if eigenvalue computation does not converge, + an error occurred, or b matrix is not definite positive. Note that + if input matrices are not symmetric or hermitian, no error is reported + but results will be wrong. - Raises LinAlgError if eigenvalue computation does not converge - See Also -------- eig : eigenvalues and right eigenvectors for non-symmetric arrays """ - if eigvals_only or overwrite_a: - a1 = asarray_chkfinite(a) - overwrite_a = overwrite_a or (_datanotshared(a1,a)) - else: - a1 = array(a) - if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all(): - raise ValueError, "array must not contain infs or NaNs" - overwrite_a = 1 - + a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' + overwrite_a = overwrite_a or (_datanotshared(a1,a)) + if iscomplexobj(a1): + cplx = True + else: + cplx = False + if b is not None: + b1 = asarray_chkfinite(b) + overwrite_b = overwrite_b or _datanotshared(b1,b) + if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]: + raise ValueError, 'expected square matrix' - if a1.dtype.char in 'FD': - heev, = get_lapack_funcs(('heev',),(a1,)) - if heev.module_name[:7] == 'flapack': - lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) - w,v,info = heev(a1,lwork = lwork, - compute_v = not eigvals_only, - lower = lower, - overwrite_a = overwrite_a) - else: # 'clapack' - w,v,info = heev(a1, - compute_v = not eigvals_only, - lower = lower, - overwrite_a = overwrite_a) - if info<0: raise ValueError,\ - 'illegal value in %-th argument of internal heev'%(-info) - if info>0: raise LinAlgError,"eig algorithm did not converge" - else: # a1.dtype.char in 'fd': - syev, = get_lapack_funcs(('syev',),(a1,)) - if syev.module_name[:7] == 'flapack': - lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) - w,v,info = syev(a1,lwork = lwork, - compute_v = not eigvals_only, - lower = lower, - overwrite_a = overwrite_a) - else: # 'clapack' - w,v,info = syev(a1, - compute_v = not eigvals_only, - lower = lower, - overwrite_a = overwrite_a) - if info<0: raise ValueError,\ - 'illegal value in %-th argument of internal syev'%(-info) - if info>0: raise LinAlgError,"eig algorithm did not converge" + if b1.shape != a1.shape: + raise ValueError("wrong b dimensions %s, should " + "be %s" % (str(b1.shape), str(a1.shape))) + if iscomplexobj(b1): + cplx = True + else: + cplx = cplx or False + else: + b1 = None + + # Set job for fortran routines + _job = (eigvals_only and 'N') or 'V' - if eigvals_only: - return w - return w, v + # port eigenvalue range from python to fortran convention + if eigvals is not None: + lo, hi = eigvals + if lo < 0 or hi >= a1.shape[0]: + raise ValueError('The eigenvalue range specified is not valid.\n' + 'Valid range is [%s,%s]' % (0, a1.shape[0]-1)) + lo += 1 + hi += 1 + eigvals = (lo, hi) + # set lower + if lower: + uplo = 'L' + else: + uplo = 'U' + # fix prefix for lapack routines + if cplx: + pfx = 'he' + else: + pfx = 'sy' + + # Standard Eigenvalue Problem + # Use '*evr' routines + # FIXME: implement calculation of optimal lwork + # for all lapack routines + if b1 is None: + (evr,) = get_lapack_funcs((pfx+'evr',), (a1,)) + if eigvals is None: + w, v, info = evr(a1, uplo=uplo, jobz=_job, range="A", il=1, + iu=a1.shape[0], overwrite_a=overwrite_a) + else: + (lo, hi)= eigvals + w_tot, v, info = evr(a1, uplo=uplo, jobz=_job, range="I", + il=lo, iu=hi, overwrite_a=overwrite_a) + w = w_tot[0:hi-lo+1] + # Generalized Eigenvalue Problem + else: + # Use '*gvx' routines if range is specified + if eigvals is not None: + (gvx,) = get_lapack_funcs((pfx+'gvx',), (a1,b1)) + (lo, hi) = eigvals + w_tot, v, ifail, info = gvx(a1, b1, uplo=uplo, iu=hi, + itype=type,jobz=_job, il=lo, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + w = w_tot[0:hi-lo+1] + # Use '*gvd' routine if turbo is on and no eigvals are specified + elif turbo: + (gvd,) = get_lapack_funcs((pfx+'gvd',), (a1,b1)) + v, w, info = gvd(a1, b1, uplo=uplo, itype=type, jobz=_job, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + # Use '*gv' routine if turbo is off and no eigvals are specified + else: + (gv,) = get_lapack_funcs((pfx+'gv',), (a1,b1)) + v, w, info = gv(a1, b1, uplo=uplo, itype= type, jobz=_job, + overwrite_a=overwrite_a, + overwrite_b=overwrite_b) + + # Check if we had a successful exit + if info == 0: + if eigvals_only: + return w + else: + return w, v + + elif info < 0: + raise LinAlgError("illegal value in %i-th argument of internal" + " fortran routine." % (-info)) + elif info > 0 and b1 is None: + raise LinAlgError("unrecoverable internal error.") + + # The algorithm failed to converge. + elif info > 0 and info <= b1.shape[0]: + if eigvals is not None: + raise LinAlgError("the eigenvectors %s failed to" + " converge." % nonzero(ifail)-1) + else: + raise LinAlgError("internal fortran routine failed to converge: " + "%i off-diagonal elements of an " + "intermediate tridiagonal form did not converge" + " to zero." % info) + + # This occurs when b is not positive definite + else: + raise LinAlgError("the leading minor of order %i" + " of 'b' is not positive definite. The" + " factorization of 'b' could not be completed" + " and no eigenvalues or eigenvectors were" + " computed." % (info-b1.shape[0])) + def eig_banded(a_band, lower=0, eigvals_only=0, overwrite_a_band=0, select='a', select_range=None, max_ev = 0): """Solve real symmetric or complex hermetian band matrix eigenvalue problem. @@ -477,32 +576,56 @@ """ return eig(a,b=b,left=0,right=0,overwrite_a=overwrite_a) -def eigvalsh(a,lower=1,overwrite_a=0): - """Solve the eigenvalue problem for a Hermitian or real symmetric matrix. +def eigvalsh(a, b=None, lower=True, overwrite_a=False, + overwrite_b=False, turbo=True, eigvals=None, type=1): + """Solve an ordinary or generalized eigenvalue problem for a complex + Hermitian or real symmetric matrix. - Find eigenvalues w of a:: + Find eigenvalues w of matrix a, where b is positive definite:: - a v[:,i] = w[i] v[:,i] - v.H v = identity + a v[:,i] = w[i] b v[:,i] + v[i,:].conj() a v[:,i] = w[i] + v[i,:].conj() b v[:,i] = 1 + Parameters ---------- a : array, shape (M, M) - A complex Hermitian or symmetric real matrix whose eigenvalues - and eigenvectors will be computed. + A complex Hermitian or real symmetric matrix whose eigenvalues and + eigenvectors will be computed. + b : array, shape (M, M) + A complex Hermitian or real symmetric definite positive matrix in. + If omitted, identity matrix is assumed. lower : boolean Whether the pertinent array data is taken from the lower or upper triangle of a. (Default: lower) + turbo : boolean + Use divide and conquer algorithm (faster but expensive in memory, + only for generalized eigenvalue problem and if eigvals=None) + eigvals : tuple (lo, hi) + Indexes of the smallest and largest (in ascending order) eigenvalues + and corresponding eigenvectors to be returned: 0 <= lo < hi <= M-1. + If omitted, all eigenvalues and eigenvectors are returned. + type: integer + Specifies the problem type to be solved: + type = 1: a v[:,i] = w[i] b v[:,i] + type = 2: a b v[:,i] = w[i] v[:,i] + type = 3: b a v[:,i] = w[i] v[:,i] overwrite_a : boolean - Whether data in a is overwritten (may improve performance). + Whether to overwrite data in a (may improve performance) + overwrite_b : boolean + Whether to overwrite data in b (may improve performance) Returns ------- - w : double array, shape (M,) - The eigenvalues, in ascending order, each repeated according to its - multiplicity. + w : real array, shape (N,) + The N (1<=N<=M) selected eigenvalues, in ascending order, each + repeated according to its multiplicity. - Raises LinAlgError if eigenvalue computation does not converge + Raises LinAlgError if eigenvalue computation does not converge, + an error occurred, or b matrix is not definite positive. Note that + if input matrices are not symmetric or hermitian, no error is reported + but results will be wrong. See Also -------- @@ -511,11 +634,13 @@ eig : eigenvalues and right eigenvectors for non-symmetric arrays """ - return eigh(a,lower=lower,eigvals_only=1,overwrite_a=overwrite_a) + return eigh(a, b=b, lower=lower, eigvals_only=True, + overwrite_a=overwrite_a, overwrite_b=overwrite_b, + turbo=turbo, eigvals=eigvals, type=type) def eigvals_banded(a_band,lower=0,overwrite_a_band=0, select='a', select_range=None): - """Solve real symmetric or complex hermetian band matrix eigenvalue problem. + """Solve real symmetric or complex hermitian band matrix eigenvalue problem. Find eigenvalues w of a:: Modified: trunk/scipy/linalg/generic_flapack.pyf =================================================================== --- trunk/scipy/linalg/generic_flapack.pyf 2008-11-18 20:47:56 UTC (rev 5148) +++ trunk/scipy/linalg/generic_flapack.pyf 2008-11-19 11:28:49 UTC (rev 5149) @@ -6,7 +6,7 @@ ! $Revision$ $Date$ ! ! Additions by Travis Oliphant -! +! Additions by Tiziano Zito ! Usage: ! f2py -c flapack.pyf -L/usr/local/lib/atlas -llapack -lf77blas -lcblas -latlas -lg2c @@ -1378,7 +1378,420 @@ integer intent(out):: info end subroutine gbtrs +! +! RRR routines for standard eigenvalue problem +! +subroutine ssyevr(jobz,range,uplo,n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,isuppz,work,lwork,iwork,liwork,info) + ! Standard Eigenvalue Problem + ! simple/expert driver: all eigenvectors or optionally selected eigenvalues + ! algorithm: Relatively Robust Representation + ! matrix storage + ! Real - Single precision + character intent(in) :: jobz='V' + character intent(in) :: range='A' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + real intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + real intent(hide) :: vl=0 + real intent(hide) :: vu=1 + integer optional,intent(in) :: il=1 + integer optional,intent(in),depend(n) :: iu=n + real intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + real intent(out),dimension(n),depend(n) :: w + real intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(hide),dimension(2*m) :: isuppz + integer intent(in),depend(n) :: lwork=26*n + real intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n):: liwork=10*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine ssyevr +subroutine dsyevr(jobz,range,uplo,n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,isuppz,work,lwork,iwork,liwork,info) + ! Standard Eigenvalue Problem + ! simple/expert driver: all eigenvectors or optionally selected eigenvalues + ! algorithm: Relatively Robust Representation + ! matrix storage + ! Real - Double precision + character intent(in) :: jobz='V' + character intent(in) :: range='A' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + double precision intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + double precision intent(hide) :: vl=0 + double precision intent(hide) :: vu=1 + integer optional,intent(in) :: il=1 + integer optional,intent(in),depend(n) :: iu=n + double precision intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + double precision intent(out),dimension(n),depend(n) :: w + double precision intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(hide),dimension(2*m) :: isuppz + integer intent(in),depend(n) :: lwork=26*n + double precision intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n):: liwork=10*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine dsyevr +subroutine cheevr(jobz,range,uplo,n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,isuppz,work,lwork,rwork,lrwork,iwork,liwork,info) + ! Standard Eigenvalue Problem + ! simple/expert driver: all eigenvectors or optionally selected eigenvalues + ! algorithm: Relatively Robust Representation + ! matrix storage + ! Complex - Single precision + character intent(in) :: jobz='V' + character intent(in) :: range='A' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + real intent(hide) :: vl=0 + real intent(hide) :: vu=1 + integer optional,intent(in) :: il=1 + integer optional,intent(in),depend(n) :: iu=n + real intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + real intent(out),dimension(n),depend(n) :: w + complex intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(hide),dimension(2*m) :: isuppz + integer intent(in),depend(n) :: lwork=2*n + complex intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n) :: lrwork=24*n + real intent(hide),dimension(lrwork) :: rwork + integer intent(hide),depend(n):: liwork=10*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine cheevr +subroutine zheevr(jobz,range,uplo,n,a,lda,vl,vu,il,iu,abstol,m,w,z,ldz,isuppz,work,lwork,rwork,lrwork,iwork,liwork,info) + ! Standard Eigenvalue Problem + ! simple/expert driver: all eigenvectors or optionally selected eigenvalues + ! algorithm: Relatively Robust Representation + ! matrix storage + ! Complex - Double precision + character intent(in) :: jobz='V' + character intent(in) :: range='A' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex*16 intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + double precision intent(hide) :: vl=0 + double precision intent(hide) :: vu=1 + integer optional,intent(in) :: il=1 + integer optional,intent(in),depend(n) :: iu=n + double precision intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + double precision intent(out),dimension(n),depend(n) :: w + complex*16 intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(hide),dimension(2*m) :: isuppz + integer intent(in),depend(n) :: lwork=2*n + complex*16 intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n) :: lrwork=24*n + double precision intent(hide),dimension(lrwork) :: rwork + integer intent(hide),depend(n):: liwork=10*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine zheevr +subroutine ssygv(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: standard + ! matrix storage + ! Real - Single precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + real intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + real intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + real intent(out),dimension(n),depend(n) :: w + integer intent(hide) :: lwork=3*n-1 + real intent(hide),dimension(lwork) :: work + integer intent(out) :: info +end subroutine ssygv +subroutine dsygv(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: standard + ! matrix storage + ! Real - Double precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + double precision intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + double precision intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + double precision intent(out),dimension(n),depend(n) :: w + integer intent(hide) :: lwork=3*n-1 + double precision intent(hide),dimension(lwork) :: work + integer intent(out) :: info +end subroutine dsygv +subroutine chegv(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,rwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: standard + ! matrix storage + ! Complex - Single precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + complex intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + real intent(out),dimension(n),depend(n) :: w + integer intent(hide) :: lwork=2*n-1 + complex intent(hide),dimension(lwork) :: work + real intent(hide),dimension(3*n-2) :: rwork + integer intent(out) :: info +end subroutine chegv +subroutine zhegv(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,rwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: standard + ! matrix storage + ! Complex - Double precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex*16 intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + complex*16 intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + double precision intent(out),dimension(n),depend(n) :: w + integer intent(hide) :: lwork=2*n-1 + complex*16 intent(hide),dimension(lwork) :: work + double precision intent(hide),dimension(3*n-2) :: rwork + integer intent(out) :: info +end subroutine zhegv +! +! Divide and conquer routines for generalized eigenvalue problem +! +subroutine ssygvd(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,iwork,liwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: divide and conquer + ! matrix storage + ! Real - Single precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + real intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + real intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + real intent(out),dimension(n),depend(n) :: w + integer intent(in),depend(n) :: lwork=1+6*n+2*n*n + real intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n) :: liwork=3+5*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine ssygvd +subroutine dsygvd(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,iwork,liwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: divide and conquer + ! matrix storage + ! Real - Double precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + double precision intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + double precision intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + double precision intent(out),dimension(n),depend(n) :: w + integer intent(in),depend(n) :: lwork=1+6*n+2*n*n + double precision intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n) :: liwork=3+5*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine dsygvd +subroutine chegvd(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,rwork,lrwork,iwork,liwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: divide and conquer + ! matrix storage + ! Complex - Single precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + complex intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + real intent(out),dimension(n),depend(n) :: w + integer intent(in),depend(n) :: lwork=2*n+n*n + complex intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n) :: lrwork=1+5*n+2*n*n + real intent(hide),dimension(lrwork) :: rwork + integer intent(hide),depend(n) :: liwork=3+5*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine chegvd +subroutine zhegvd(itype,jobz,uplo,n,a,lda,b,ldb,w,work,lwork,rwork,lrwork,iwork,liwork,info) + ! Generalized Eigenvalue Problem + ! simple driver (all eigenvectors) + ! algorithm: divide and conquer + ! matrix storage + ! Complex - Double precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex*16 intent(in,copy,out),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + complex*16 intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + double precision intent(out),dimension(n),depend(n) :: w + integer intent(in),depend(n) :: lwork=2*n+n*n + complex*16 intent(hide),dimension(lwork) :: work + integer intent(hide),depend(n) :: lrwork=1+5*n+2*n*n + double precision intent(hide),dimension(lrwork) :: rwork + integer intent(hide),depend(n) :: liwork=3+5*n + integer intent(hide),dimension(liwork) :: iwork + integer intent(out) :: info +end subroutine zhegvd +! Expert routines for generalized eigenvalue problem +! +subroutine ssygvx(itype,jobz,range,uplo,n,a,lda,b,ldb,vl,vu,il,iu,abstol,m,w,z,ldz,work,lwork,iwork,ifail,info) + ! Generalized Eigenvalue Problem + ! expert driver (selected eigenvectors) + ! algorithm: standard + ! matrix storage + ! Real - Single precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(hide) :: range='I' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + real intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + real intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + real intent(hide) :: vl=0. + real intent(hide) :: vu=0. + integer optional,intent(in) :: il=1 + integer intent(in) :: iu + real intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + real intent(out),dimension(n),depend(n) :: w + real intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(in),depend(n) :: lwork=8*n + real intent(hide),dimension(lwork),depend(n,lwork) :: work + integer intent(hide),dimension(5*n) :: iwork + integer intent(out),dimension(n),depend(n) :: ifail + integer intent(out) :: info +end subroutine ssygvx +subroutine dsygvx(itype,jobz,range,uplo,n,a,lda,b,ldb,vl,vu,il,iu,abstol,m,w,z,ldz,work,lwork,iwork,ifail,info) + ! Generalized Eigenvalue Problem + ! expert driver (selected eigenvectors) + ! algorithm: standard + ! matrix storage + ! Real - Double precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(hide) :: range='I' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + double precision intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + double precision intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + double precision intent(hide) :: vl=0. + double precision intent(hide) :: vu=0. + integer optional,intent(in) :: il=1 + integer intent(in) :: iu + double precision intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + double precision intent(out),dimension(n),depend(n) :: w + double precision intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(in),depend(n) :: lwork=8*n + double precision intent(hide),dimension(lwork),depend(n,lwork) :: work + integer intent(hide),dimension(5*n) :: iwork + integer intent(out),dimension(n),depend(n) :: ifail + integer intent(out) :: info +end subroutine dsygvx +subroutine chegvx(itype,jobz,range,uplo,n,a,lda,b,ldb,vl,vu,il,iu,abstol,m,w,z,ldz,work,lwork,rwork,iwork,ifail,info) + ! Generalized Eigenvalue Problem + ! expert driver (selected eigenvectors) + ! algorithm: standard + ! matrix storage + ! Complex - Single precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(hide) :: range='I' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + complex intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + real intent(hide) :: vl=0. + real intent(hide) :: vu=0. + integer optional,intent(in) :: il=1 + integer intent(in) :: iu + real intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + real intent(out),dimension(n),depend(n) :: w + complex intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(in),depend(n) :: lwork=2*n + complex intent(hide),dimension(lwork),depend(n,lwork) :: work + real intent(hide),dimension(7*n) :: rwork + integer intent(hide),dimension(5*n) :: iwork + integer intent(out),dimension(n),depend(n) :: ifail + integer intent(out) :: info +end subroutine chegvx +subroutine zhegvx(itype,jobz,range,uplo,n,a,lda,b,ldb,vl,vu,il,iu,abstol,m,w,z,ldz,work,lwork,rwork,iwork,ifail,info) + ! Generalized Eigenvalue Problem + ! expert driver (selected eigenvectors) + ! algorithm: standard + ! matrix storage + ! Complex - Double precision + integer optional,intent(in) :: itype=1 + character intent(in) :: jobz='V' + character intent(hide) :: range='I' + character intent(in) :: uplo='L' + integer intent(hide) :: n=shape(a,0) + complex*16 intent(in,copy),dimension(n,n) :: a + integer intent(hide),depend(n,a) :: lda=n + complex*16 intent(in,copy),dimension(n,n) :: b + integer intent(hide),depend(n,b) :: ldb=n + double precision intent(hide) :: vl=0. + double precision intent(hide) :: vu=0. + integer optional,intent(in) :: il=1 + integer intent(in) :: iu + double precision intent(hide) :: abstol=0. + integer intent(hide),depend(iu) :: m=iu-il+1 + double precision intent(out),dimension(n),depend(n) :: w + complex*16 intent(out),dimension(n,m),depend(n,m) :: z + integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n + integer intent(in),depend(n) :: lwork=2*n + complex*16 intent(hide),dimension(lwork),depend(n,lwork) :: work + double precision intent(hide),dimension(7*n) :: rwork + integer intent(hide),dimension(5*n) :: iwork + integer intent(out),dimension(n),depend(n) :: ifail + integer intent(out) :: info +end subroutine zhegvx + end interface end python module flapack Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-11-18 20:47:56 UTC (rev 5148) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-11-19 11:28:49 UTC (rev 5149) @@ -25,16 +25,14 @@ from numpy import array, transpose, sometrue, diag, ones, linalg, \ argsort, zeros, arange, float32, complex64, dot, conj, identity, \ ravel, sqrt, iscomplex, shape, sort, conjugate, bmat, sign, \ - asarray, matrix, isfinite, all, ndarray, outer, eye, dtype + asarray, matrix, isfinite, all, ndarray, outer, eye, dtype, empty,\ + triu, tril from numpy.random import rand, normal # digit precision to use in asserts for different types -DIGITS = {'d':12, 'D':12, 'f':6, 'F':6} +DIGITS = {'d':11, 'D':11, 'f':4, 'F':4} -# matrix dimension in tests -DIM = 5 - # XXX: This function should be available through numpy.testing def assert_dtype_equal(act, des): if isinstance(act, ndarray): @@ -51,24 +49,18 @@ # XXX: This function should not be defined here, but somewhere in # scipy.linalg namespace -def hermitian(x): - """Return the Hermitian, i.e. conjugate transpose, of x.""" - return x.T.conj() - -# XXX: This function should not be defined here, but somewhere in -# scipy.linalg namespace -def symrand(dim_or_eigv, dtype="d"): +def symrand(dim_or_eigv): """Return a random symmetric (Hermitian) matrix. If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues - uniformly distributed on (0.1,1]. + uniformly distributed on (-1,1). If 'dim_or_eigv' is 1-D real array 'a', return a matrix whose - eigenvalues are sort(a). + eigenvalues are 'a'. """ if isinstance(dim_or_eigv, int): dim = dim_or_eigv - d = (rand(dim)*0.9)+0.1 + d = (rand(dim)*2)-1 elif (isinstance(dim_or_eigv, ndarray) and len(dim_or_eigv.shape) == 1): dim = dim_or_eigv.shape[0] @@ -76,14 +68,15 @@ else: raise TypeError("input type not supported.") - v = random_rot(dim, dtype=dtype) - h = dot(dot(hermitian(v), diag(d)), v) + v = random_rot(dim) + h = dot(dot(v.T.conj(), diag(d)), v) # to avoid roundoff errors, symmetrize the matrix (again) - return (0.5*(hermitian(h)+h)).astype(dtype) + h = 0.5*(h.T+h) + return h # XXX: This function should not be defined here, but somewhere in # scipy.linalg namespace -def random_rot(dim, dtype='d'): +def random_rot(dim): """Return a random rotation matrix, drawn from the Haar distribution (the only uniform distribution on SO(n)). The algorithm is described in the paper @@ -92,16 +85,16 @@ on Numerical Analysis, 17(3), pp. 403-409, 1980. For more information see http://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization""" - H = eye(dim, dtype=dtype) - D = ones((dim, ), dtype=dtype) + H = eye(dim) + D = ones((dim, )) for n in range(1, dim): - x = normal(size=(dim-n+1, )).astype(dtype) + x = normal(size=(dim-n+1, )) D[n-1] = sign(x[0]) x[0] -= D[n-1]*sqrt((x*x).sum()) # Householder transformation - Hx = eye(dim-n+1, dtype=dtype) - 2.*outer(x, x)/(x*x).sum() - mat = eye(dim, dtype=dtype) + Hx = eye(dim-n+1) - 2.*outer(x, x)/(x*x).sum() + mat = eye(dim) mat[n-1:,n-1:] = Hx H = dot(H, mat) # Fix the last sign such that the determinant is 1 @@ -493,37 +486,86 @@ y_lin = linalg.solve(self.comp_mat, self.bc) assert_array_almost_equal(y, y_lin) -class TestEigH(TestCase): - def eigenproblem_standard(self, dim, dtype, overwrite, lower): - """Solve a standard eigenvalue problem.""" - a = symrand(dim, dtype) - if overwrite: - a_c = a.copy() - else: - a_c = a - w, z = eigh(a, lower=lower, overwrite_a = overwrite) - assert_dtype_equal(z.dtype, dtype) - w = w.astype(dtype) - diag_ = diag(dot(hermitian(z), dot(a_c, z))).real - assert_array_almost_equal(diag_, w, DIGITS[dtype]) +def test_eigh(): + DIM = 6 + v = {'dim': (DIM, ), + 'dtype': ('f','d','F','D'), + 'overwrite': (True, False), + 'lower': (True, False), + 'turbo': (True, False), + 'eigvals': (None, (2, DIM-2))} - def test_eigh_real_standard(self): - self.eigenproblem_standard(DIM, 'd', False, False) - self.eigenproblem_standard(DIM, 'd', False, True) - self.eigenproblem_standard(DIM, 'd', True, True) - self.eigenproblem_standard(DIM, 'f', False, False) - self.eigenproblem_standard(DIM, 'f', False, True) - self.eigenproblem_standard(DIM, 'f', True, True) + for dim in v['dim']: + for typ in v['dtype']: + for overwrite in v['overwrite']: + for turbo in v['turbo']: + for eigvals in v['eigvals']: + for lower in v['lower']: + yield (eigenhproblem_standard, + 'ordinary', + dim, typ, overwrite, lower, + turbo, eigvals) + yield (eigenhproblem_general, + 'general ', + dim, typ, overwrite, lower, + turbo, eigvals) - def test_eigh_complex_standard(self): - self.eigenproblem_standard(DIM, 'D', False, False) - self.eigenproblem_standard(DIM, 'D', False, True) - self.eigenproblem_standard(DIM, 'D', True, True) - self.eigenproblem_standard(DIM, 'F', False, False) - self.eigenproblem_standard(DIM, 'F', False, True) - self.eigenproblem_standard(DIM, 'F', True, True) +def _complex_symrand(dim, dtype): + a1, a2 = symrand(dim), symrand(dim) + # add antisymmetric matrix as imag part + a = a1 +1j*(triu(a2)-tril(a2)) + return a.astype(dtype) + +def eigenhproblem_standard(desc, dim, dtype, + overwrite, lower, turbo, + eigvals): + """Solve a standard eigenvalue problem.""" + if iscomplex(empty(1, dtype=dtype)): + a = _complex_symrand(dim, dtype) + else: + a = symrand(dim).astype(dtype) + + if overwrite: + a_c = a.copy() + else: + a_c = a + w, z = eigh(a, overwrite_a=overwrite, lower=lower, eigvals=eigvals) + assert_dtype_equal(z.dtype, dtype) + w = w.astype(dtype) + diag_ = diag(dot(z.T.conj(), dot(a_c, z))).real + assert_array_almost_equal(diag_, w, DIGITS[dtype]) +def eigenhproblem_general(desc, dim, dtype, + overwrite, lower, turbo, + eigvals): + """Solve a generalized eigenvalue problem.""" + if iscomplex(empty(1, dtype=dtype)): + a = _complex_symrand(dim, dtype) + b = _complex_symrand(dim, dtype)+diag([2.1]*dim).astype(dtype) + else: + a = symrand(dim).astype(dtype) + b = symrand(dim).astype(dtype)+diag([2.1]*dim).astype(dtype) + if overwrite: + a_c, b_c = a.copy(), b.copy() + else: + a_c, b_c = a, b + + w, z = eigh(a, b, overwrite_a=overwrite, lower=lower, + overwrite_b=overwrite, turbo=turbo, eigvals=eigvals) + assert_dtype_equal(z.dtype, dtype) + w = w.astype(dtype) + diag1_ = diag(dot(z.T.conj(), dot(a_c, z))).real + assert_array_almost_equal(diag1_, w, DIGITS[dtype]) + diag2_ = diag(dot(z.T.conj(), dot(b_c, z))).real + assert_array_almost_equal(diag2_, ones(diag2_.shape[0]), DIGITS[dtype]) + +def test_eigh_integer(): + a = array([[1,2],[2,7]]) + b = array([[3,1],[1,5]]) + w,z = eigh(a) + w,z = eigh(a,b) + class TestLU(TestCase): def __init__(self, *args, **kw): From scipy-svn at scipy.org Wed Nov 19 06:41:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 19 Nov 2008 05:41:55 -0600 (CST) Subject: [Scipy-svn] r5150 - trunk/doc/release Message-ID: <20081119114155.9855C39C05F@scipy.org> Author: tzito Date: 2008-11-19 05:41:39 -0600 (Wed, 19 Nov 2008) New Revision: 5150 Modified: trunk/doc/release/0.7.0-notes.rst Log: Added linalg.eigh to the release notes. Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-19 11:28:49 UTC (rev 5149) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-19 11:41:39 UTC (rev 5150) @@ -133,6 +133,16 @@ complex-valued ordinary differential equation solver (by Peter N. Brown, Alan C. Hindmarsh, and George D. Byrne). +New generalized symmetric and hermitian eigenvalue problem solver +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``scipy.linalg.eigh`` now contains wrappers for more LAPACK +symmetric and hermitian eigenvalue problem solvers. Users +can now solve generalized problems, select just a range of +eigenvalues, and choose to use a faster algorithm at the expense +of increased memory usage. The signature of the ``scipy.linalg.eigh`` +changed accordingly. + Major documentation improvements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From scipy-svn at scipy.org Wed Nov 19 06:57:06 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 19 Nov 2008 05:57:06 -0600 (CST) Subject: [Scipy-svn] r5151 - trunk/doc/source Message-ID: <20081119115706.76DB139C05F@scipy.org> Author: tzito Date: 2008-11-19 05:57:01 -0600 (Wed, 19 Nov 2008) New Revision: 5151 Modified: trunk/doc/source/linalg.rst Log: Added eigh and eigvalsh in the linalg reference documentation. Modified: trunk/doc/source/linalg.rst =================================================================== --- trunk/doc/source/linalg.rst 2008-11-19 11:41:39 UTC (rev 5150) +++ trunk/doc/source/linalg.rst 2008-11-19 11:57:01 UTC (rev 5151) @@ -28,6 +28,8 @@ eig eigvals + eigh + eigvalsh eig_banded eigvals_banded lu From scipy-svn at scipy.org Thu Nov 20 14:24:43 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 20 Nov 2008 13:24:43 -0600 (CST) Subject: [Scipy-svn] r5152 - trunk/scipy/spatial Message-ID: <20081120192443.05F5939C088@scipy.org> Author: ptvirtan Date: 2008-11-20 13:24:32 -0600 (Thu, 20 Nov 2008) New Revision: 5152 Modified: trunk/scipy/spatial/distance.py Log: Fix bad latex in docstrings Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-19 11:57:01 UTC (rev 5151) +++ trunk/scipy/spatial/distance.py 2008-11-20 19:24:32 UTC (rev 5152) @@ -181,7 +181,7 @@ .. math:: - {||u-v||}_p = (\sum {|u_i - v_i|^p})^(1/p). + {||u-v||}_p = (\sum{|u_i - v_i|^p})^{1/p}. :Parameters: u : ndarray @@ -208,7 +208,7 @@ .. math:: - \left(\sum {(w_i*|u_i - v_i|\right)^p}^(1/p). + \left(\sum{(w_i |u_i - v_i|^p)}\right)^{1/p}. :Parameters: u : ndarray From scipy-svn at scipy.org Fri Nov 21 02:50:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 01:50:32 -0600 (CST) Subject: [Scipy-svn] r5153 - trunk/scipy/sparse/linalg/isolve Message-ID: <20081121075032.EA16339C088@scipy.org> Author: wnbell Date: 2008-11-21 01:50:30 -0600 (Fri, 21 Nov 2008) New Revision: 5153 Modified: trunk/scipy/sparse/linalg/isolve/utils.py Log: force b to be rank-1 as docstring suggests Modified: trunk/scipy/sparse/linalg/isolve/utils.py =================================================================== --- trunk/scipy/sparse/linalg/isolve/utils.py 2008-11-20 19:24:32 UTC (rev 5152) +++ trunk/scipy/sparse/linalg/isolve/utils.py 2008-11-21 07:50:30 UTC (rev 5153) @@ -96,6 +96,7 @@ raise ValueError, "xtype must be 'f', 'd', 'F', or 'D'" b = asarray(b,dtype=xtype) #make b the same type as x + b = b.ravel() if x0 is None: x = zeros(N, dtype=xtype) From scipy-svn at scipy.org Fri Nov 21 05:23:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 04:23:02 -0600 (CST) Subject: [Scipy-svn] r5154 - trunk/scipy/sparse/linalg/eigen Message-ID: <20081121102302.8B15139C088@scipy.org> Author: cdavid Date: 2008-11-21 04:22:53 -0600 (Fri, 21 Nov 2008) New Revision: 5154 Added: trunk/scipy/sparse/linalg/eigen/arpack/ trunk/scipy/sparse/linalg/eigen/setup.py trunk/scipy/sparse/linalg/eigen/setupscons.py Removed: trunk/scipy/sparse/linalg/eigen/setup.py trunk/scipy/sparse/linalg/eigen/setupscons.py Log: Restore ARPACK since the license issue has been cleared up. Copied: trunk/scipy/sparse/linalg/eigen/arpack (from rev 5153, tags/scipy-with-arpack/scipy/sparse/linalg/eigen/arpack) Deleted: trunk/scipy/sparse/linalg/eigen/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/setup.py 2008-11-21 07:50:30 UTC (rev 5153) +++ trunk/scipy/sparse/linalg/eigen/setup.py 2008-11-21 10:22:53 UTC (rev 5154) @@ -1,14 +0,0 @@ -#!/usr/bin/env python - -def configuration(parent_package='',top_path=None): - from numpy.distutils.misc_util import Configuration - - config = Configuration('eigen',parent_package,top_path) - - config.add_subpackage(('lobpcg')) - - return config - -if __name__ == '__main__': - from numpy.distutils.core import setup - setup(**configuration(top_path='').todict()) Copied: trunk/scipy/sparse/linalg/eigen/setup.py (from rev 5082, tags/scipy-with-arpack/scipy/sparse/linalg/eigen/setup.py) Deleted: trunk/scipy/sparse/linalg/eigen/setupscons.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/setupscons.py 2008-11-21 07:50:30 UTC (rev 5153) +++ trunk/scipy/sparse/linalg/eigen/setupscons.py 2008-11-21 10:22:53 UTC (rev 5154) @@ -1,14 +0,0 @@ -#!/usr/bin/env python - -def configuration(parent_package='',top_path=None): - from numpy.distutils.misc_util import Configuration - - config = Configuration('eigen',parent_package,top_path, setup_name = 'setupscons.py') - - config.add_subpackage(('lobpcg')) - - return config - -if __name__ == '__main__': - from numpy.distutils.core import setup - setup(**configuration(top_path='').todict()) Copied: trunk/scipy/sparse/linalg/eigen/setupscons.py (from rev 5082, tags/scipy-with-arpack/scipy/sparse/linalg/eigen/setupscons.py) From scipy-svn at scipy.org Fri Nov 21 05:24:34 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 04:24:34 -0600 (CST) Subject: [Scipy-svn] r5155 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081121102434.C590639C088@scipy.org> Author: cdavid Date: 2008-11-21 04:24:29 -0600 (Fri, 21 Nov 2008) New Revision: 5155 Modified: trunk/scipy/sparse/linalg/eigen/arpack/README Log: Update ARPACK License to new 'straight' BSD license. Modified: trunk/scipy/sparse/linalg/eigen/arpack/README =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/README 2008-11-21 10:22:53 UTC (rev 5154) +++ trunk/scipy/sparse/linalg/eigen/arpack/README 2008-11-21 10:24:29 UTC (rev 5155) @@ -54,45 +54,38 @@ --- -Rice BSD Software License -Permits source and binary redistribution of the software ARPACK and -P_ARPACK for both non-commercial and commercial use. +BSD Software License - Copyright (?) 2001, Rice University - Developed by D.C. Sorensen, R.B. Lehoucq, C. Yang, and K. Maschhoff. - All rights reserved. +Pertains to ARPACK and P_ARPACK +Copyright (c) 1996-2008 Rice University. +Developed by D.C. Sorensen, R.B. Lehoucq, C. Yang, and K. Maschhoff. +All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - . Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - . Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - . If you modify the source for these routines we ask that you change the - name of the routine and comment the changes made to the original. - . Written notification is provided to the developers of intent to use - this software. Also, we ask that use of ARPACK is properly cited in - any resulting publications or software documentation. - . Neither the name of Rice University (RICE) nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. -THIS SOFTWARE IS PROVIDED BY RICE AND CONTRIBUTORS "AS IS" AND ANY EXPRESS -OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL RICE OR CONTRIBUTORS BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. +- Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. - - +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. From scipy-svn at scipy.org Fri Nov 21 16:08:09 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 15:08:09 -0600 (CST) Subject: [Scipy-svn] r5156 - trunk/scipy/interpolate Message-ID: <20081121210809.96D2339C088@scipy.org> Author: ptvirtan Date: 2008-11-21 15:07:57 -0600 (Fri, 21 Nov 2008) New Revision: 5156 Modified: trunk/scipy/interpolate/interpolate.py Log: Implement kind='nearest' interpolation, code adapted from #305 Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-21 10:24:29 UTC (rev 5155) +++ trunk/scipy/interpolate/interpolate.py 2008-11-21 21:07:57 UTC (rev 5156) @@ -8,7 +8,7 @@ from numpy import shape, sometrue, rank, array, transpose, searchsorted, \ ones, logical_or, atleast_1d, atleast_2d, meshgrid, ravel, \ - dot, poly1d, asarray + dot, poly1d, asarray, intp import numpy as np import scipy.special as spec import math @@ -198,14 +198,14 @@ self.bounds_error = bounds_error self.fill_value = fill_value - if kind in ['zero', 'slinear', 'quadratic', 'cubic', 'nearest']: + if kind in ['zero', 'slinear', 'quadratic', 'cubic']: order = {'nearest':0, 'zero':0,'slinear':1, 'quadratic':2, 'cubic':3}[kind] kind = 'spline' elif isinstance(kind, int): order = kind kind = 'spline' - elif kind != 'linear': + elif kind not in ('linear', 'nearest'): raise NotImplementedError("%s is unsupported: Use fitpack "\ "routines for other types." % kind) x = array(x, copy=self.copy) @@ -220,7 +220,7 @@ self.axis = axis % len(y.shape) self._kind = kind - if kind == 'linear': + if kind in ('linear', 'nearest'): # Make a "view" of the y array that is rotated to the interpolation # axis. axes = range(y.ndim) @@ -229,7 +229,11 @@ oriented_y = y.transpose(axes) minval = 2 len_y = oriented_y.shape[-1] - self._call = self._call_linear + if kind == 'linear': + self._call = self._call_linear + elif kind == 'nearest': + self.x_bds = (x[1:] + x[:-1]) / 2.0 + self._call = self._call_nearest else: axes = range(y.ndim) del axes[self.axis] @@ -242,10 +246,10 @@ len_x = len(x) if len_x != len_y: - raise ValueError("x and y arrays must be equal in length along" - "interpolation axis.") + raise ValueError("x and y arrays must be equal in length along " + "interpolation axis.") if len_x < minval: - raise ValueError("x and y arrays must have at " \ + raise ValueError("x and y arrays must have at " "least %d entries" % minval) self.x = x self.y = oriented_y @@ -280,6 +284,23 @@ return y_new + def _call_nearest(self, x_new): + """ Find nearest neighbour interpolated y_new = f(x_new).""" + + # 2. Find where in the averaged data the values to interpolate + # would be inserted. + # Note: use side='left' (right) to searchsorted() to define the + # halfway point to be nearest to the left (right) neighbour + x_new_indices = searchsorted(self.x_bds, x_new, side='left') + + # 3. Clip x_new_indices so that they are within the range of x indices. + x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp) + + # 4. Calculate the actual value for each entry in x_new. + y_new = self.y[..., x_new_indices] + + return y_new + def _call_spline(self, x_new): x_new =np.asarray(x_new) result = spleval(self._spline,x_new.ravel()) @@ -327,7 +348,7 @@ else: y_new[...] = self.fill_value return asarray(y_new) - elif self._kind == 'linear': + elif self._kind in ('linear', 'nearest'): y_new[..., out_of_bounds] = self.fill_value axes = range(ny - nx) axes[self.axis:self.axis] = range(ny - nx, ny) From scipy-svn at scipy.org Fri Nov 21 16:08:44 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 15:08:44 -0600 (CST) Subject: [Scipy-svn] r5157 - trunk/scipy/interpolate/tests Message-ID: <20081121210844.CC3D039C088@scipy.org> Author: ptvirtan Date: 2008-11-21 15:08:20 -0600 (Fri, 21 Nov 2008) New Revision: 5157 Modified: trunk/scipy/interpolate/tests/test_interpolate.py Log: Tests for kind='nearest' interpolation Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-21 21:07:57 UTC (rev 5156) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-21 21:08:20 UTC (rev 5157) @@ -50,6 +50,7 @@ interp1d(self.x10, self.y10, kind='slinear') interp1d(self.x10, self.y10, kind='quadratic') interp1d(self.x10, self.y10, kind='zero') + interp1d(self.x10, self.y10, kind='nearest') interp1d(self.x10, self.y10, kind=0) interp1d(self.x10, self.y10, kind=1) interp1d(self.x10, self.y10, kind=2) @@ -150,6 +151,24 @@ np.array([2.4, 5.6, 6.0]), ) + def test_nearest(self): + """Check the actual implementation of nearest-neighbour interpolation. + """ + + interp10 = interp1d(self.x10, self.y10, kind='nearest') + assert_array_almost_equal( + interp10(self.x10), + self.y10, + ) + assert_array_almost_equal( + interp10(1.2), + np.array(1.), + ) + assert_array_almost_equal( + interp10([2.4, 5.6, 6.0]), + np.array([2., 6., 6.]), + ) + def _bounds_check(self, kind='linear'): """ Test that our handling of out-of-bounds input is correct. """ @@ -180,18 +199,19 @@ raises_bounds_error([0.0, 5.0, 9.0]) def test_bounds(self): - for kind in ('linear', 'cubic'): + for kind in ('linear', 'cubic', 'nearest', + 'slinear', 'zero', 'quadratic'): self._bounds_check(kind=kind) - def _nd_check(self, kind='linear'): + def _nd_check_interp(self, kind='linear'): """ Check the behavior when the inputs and outputs are multidimensional. """ # Multidimensional input. interp10 = interp1d(self.x10, self.y10, kind=kind) assert_array_almost_equal( - interp10(np.array([[3.4, 5.6], [2.4, 7.8]])), - np.array([[3.4, 5.6], [2.4, 7.8]]), + interp10(np.array([[3., 5.], [2., 7.]])), + np.array([[3., 5.], [2., 7.]]), ) # Scalar input -> 0-dim scalar array output @@ -201,55 +221,57 @@ # Multidimensional outputs. interp210 = interp1d(self.x10, self.y210, kind=kind) assert_array_almost_equal( - interp210(1.5), - np.array([1.5, 11.5]), + interp210(1.), + np.array([1., 11.]), ) assert_array_almost_equal( - interp210(np.array([1.5, 2.4])), - np.array([[1.5, 2.4], - [11.5, 12.4]]), + interp210(np.array([1., 2.])), + np.array([[1., 2.], + [11., 12.]]), ) interp102 = interp1d(self.x10, self.y102, axis=0, kind=kind) assert_array_almost_equal( - interp102(1.5), - np.array([3.0, 4.0]), + interp102(1.), + np.array([2.0, 3.0]), ) assert_array_almost_equal( - interp102(np.array([1.5, 2.4])), - np.array([[3.0, 4.0], - [4.8, 5.8]]), + interp102(np.array([1., 3.])), + np.array([[2., 3.], + [6., 7.]]), ) # Both at the same time! - x_new = np.array([[3.4, 5.6], [2.4, 7.8]]) + x_new = np.array([[3., 5.], [2., 7.]]) assert_array_almost_equal( interp210(x_new), - np.array([[[3.4, 5.6], [2.4, 7.8]], - [[13.4, 15.6], [12.4, 17.8]]]), + np.array([[[3., 5.], [2., 7.]], + [[13., 15.], [12., 17.]]]), ) assert_array_almost_equal( interp102(x_new), - np.array([[[6.8, 7.8], [11.2, 12.2]], - [[4.8, 5.8], [15.6, 16.6]]]), + np.array([[[6., 7.], [10., 11.]], + [[4., 5.], [14., 15.]]]), ) - # Check large ndim output + def _nd_check_shape(self, kind='linear'): + # Check large ndim output shape a = [4, 5, 6, 7] y = np.arange(np.prod(a)).reshape(*a) for n, s in enumerate(a): x = np.arange(s) z = interp1d(x, y, axis=n, kind=kind) - assert_array_almost_equal(z(x), y) + assert_array_almost_equal(z(x), y, err_msg=kind) x2 = np.arange(2*3*1).reshape((2,3,1)) / 12. b = list(a) b[n:n+1] = [2,3,1] - assert_array_almost_equal(z(x2).shape, b) + assert_array_almost_equal(z(x2).shape, b, err_msg=kind) def test_nd(self): - for kind in ('linear', 'cubic'): - self._nd_check(kind=kind) + for kind in ('linear', 'cubic', 'slinear', 'quadratic', 'nearest'): + self._nd_check_interp(kind=kind) + self._nd_check_shape(kind=kind) class TestLagrange(TestCase): From scipy-svn at scipy.org Fri Nov 21 16:09:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 15:09:16 -0600 (CST) Subject: [Scipy-svn] r5158 - trunk/scipy/interpolate/tests Message-ID: <20081121210916.CDDE439C088@scipy.org> Author: ptvirtan Date: 2008-11-21 15:09:00 -0600 (Fri, 21 Nov 2008) New Revision: 5158 Modified: trunk/scipy/interpolate/tests/test_interpolate.py Log: test_interpolate: use test generators + add two known failures for zero-spline Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-21 21:08:20 UTC (rev 5157) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-21 21:09:00 UTC (rev 5158) @@ -23,7 +23,7 @@ I = interp2d(x, y, z) assert_almost_equal(I(1.0, 2.0), sin(2.0), decimal=2) -class TestInterp1D(TestCase): +class TestInterp1D(object): def setUp(self): self.x10 = np.arange(10.) @@ -57,22 +57,22 @@ interp1d(self.x10, self.y10, kind=3) # x array must be 1D. - self.assertRaises(ValueError, interp1d, self.x25, self.y10) + assert_raises(ValueError, interp1d, self.x25, self.y10) # y array cannot be a scalar. - self.assertRaises(ValueError, interp1d, self.x10, np.array(0)) + assert_raises(ValueError, interp1d, self.x10, np.array(0)) # Check for x and y arrays having the same length. - self.assertRaises(ValueError, interp1d, self.x10, self.y2) - self.assertRaises(ValueError, interp1d, self.x2, self.y10) - self.assertRaises(ValueError, interp1d, self.x10, self.y102) + assert_raises(ValueError, interp1d, self.x10, self.y2) + assert_raises(ValueError, interp1d, self.x2, self.y10) + assert_raises(ValueError, interp1d, self.x10, self.y102) interp1d(self.x10, self.y210) interp1d(self.x10, self.y102, axis=0) # Check for x and y having at least 1 element. - self.assertRaises(ValueError, interp1d, self.x1, self.y10) - self.assertRaises(ValueError, interp1d, self.x10, self.y1) - self.assertRaises(ValueError, interp1d, self.x1, self.y1) + assert_raises(ValueError, interp1d, self.x1, self.y10) + assert_raises(ValueError, interp1d, self.x10, self.y1) + assert_raises(ValueError, interp1d, self.x1, self.y1) def test_init(self): @@ -80,24 +80,24 @@ constructor. """ - self.assert_(interp1d(self.x10, self.y10).copy) - self.assert_(not interp1d(self.x10, self.y10, copy=False).copy) - self.assert_(interp1d(self.x10, self.y10).bounds_error) - self.assert_(not interp1d(self.x10, self.y10, bounds_error=False).bounds_error) - self.assert_(np.isnan(interp1d(self.x10, self.y10).fill_value)) - self.assertEqual( + assert interp1d(self.x10, self.y10).copy + assert not interp1d(self.x10, self.y10, copy=False).copy + assert interp1d(self.x10, self.y10).bounds_error + assert not interp1d(self.x10, self.y10, bounds_error=False).bounds_error + assert np.isnan(interp1d(self.x10, self.y10).fill_value) + assert_equal( interp1d(self.x10, self.y10, fill_value=3.0).fill_value, 3.0, ) - self.assertEqual( + assert_equal( interp1d(self.x10, self.y10).axis, 0, ) - self.assertEqual( + assert_equal( interp1d(self.x10, self.y210).axis, 1, ) - self.assertEqual( + assert_equal( interp1d(self.x10, self.y102, axis=0).axis, 0, ) @@ -169,6 +169,16 @@ np.array([2., 6., 6.]), ) + @dec.knownfailureif(True, "zero-order splines fail for the last point") + def test_zero(self): + """Check the actual implementation of zero-order spline interpolation. + """ + interp10 = interp1d(self.x10, self.y10, kind='zero') + assert_array_almost_equal(interp10(self.x10), self.y10) + assert_array_almost_equal(interp10(1.2), np.array(1.)) + assert_array_almost_equal(interp10([2.4, 5.6, 6.0]), + np.array([2., 6., 6.])) + def _bounds_check(self, kind='linear'): """ Test that our handling of out-of-bounds input is correct. """ @@ -194,17 +204,17 @@ raises_bounds_error = interp1d(self.x10, self.y10, bounds_error=True, kind=kind) - self.assertRaises(ValueError, raises_bounds_error, -1.0) - self.assertRaises(ValueError, raises_bounds_error, 11.0) + assert_raises(ValueError, raises_bounds_error, -1.0) + assert_raises(ValueError, raises_bounds_error, 11.0) raises_bounds_error([0.0, 5.0, 9.0]) def test_bounds(self): for kind in ('linear', 'cubic', 'nearest', 'slinear', 'zero', 'quadratic'): - self._bounds_check(kind=kind) + yield self._bounds_check, kind def _nd_check_interp(self, kind='linear'): - """ Check the behavior when the inputs and outputs are multidimensional. + """Check the behavior when the inputs and outputs are multidimensional. """ # Multidimensional input. @@ -215,7 +225,7 @@ ) # Scalar input -> 0-dim scalar array output - self.failUnless(isinstance(interp10(1.2), np.ndarray)) + assert isinstance(interp10(1.2), np.ndarray) assert_equal(interp10(1.2).shape, ()) # Multidimensional outputs. @@ -270,9 +280,17 @@ def test_nd(self): for kind in ('linear', 'cubic', 'slinear', 'quadratic', 'nearest'): - self._nd_check_interp(kind=kind) - self._nd_check_shape(kind=kind) + yield self._nd_check_interp, kind + yield self._nd_check_shape, kind + @dec.knownfailureif(True, "zero-order splines fail for the last point") + def test_nd_zero_spline(self): + # zero-order splines don't get the last point right, + # see test_zero above + #yield self._nd_check_interp, 'zero' + #yield self._nd_check_interp, 'zero' + pass + class TestLagrange(TestCase): def test_lagrange(self): From scipy-svn at scipy.org Fri Nov 21 16:22:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 15:22:55 -0600 (CST) Subject: [Scipy-svn] r5159 - in trunk/scipy/interpolate: . tests Message-ID: <20081121212255.AC27539C088@scipy.org> Author: ptvirtan Date: 2008-11-21 15:09:29 -0600 (Fri, 21 Nov 2008) New Revision: 5159 Modified: trunk/scipy/interpolate/interpolate.py trunk/scipy/interpolate/tests/test_interpolate.py Log: interp1d: cast input arrays to a floating-point type (possibly complex), so that eg. fill values don't cause surprises Modified: trunk/scipy/interpolate/interpolate.py =================================================================== --- trunk/scipy/interpolate/interpolate.py 2008-11-21 21:09:00 UTC (rev 5158) +++ trunk/scipy/interpolate/interpolate.py 2008-11-21 21:09:29 UTC (rev 5159) @@ -216,6 +216,10 @@ if y.ndim == 0: raise ValueError("the y array must have at least one dimension.") + # Force-cast y to a floating-point type, if it's not yet one + if not isinstance(y.dtype.type, np.inexact): + y = y.astype(np.float_) + # Normalize the axis to ensure that it is positive. self.axis = axis % len(y.shape) self._kind = kind Modified: trunk/scipy/interpolate/tests/test_interpolate.py =================================================================== --- trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-21 21:09:00 UTC (rev 5158) +++ trunk/scipy/interpolate/tests/test_interpolate.py 2008-11-21 21:09:29 UTC (rev 5159) @@ -208,10 +208,19 @@ assert_raises(ValueError, raises_bounds_error, 11.0) raises_bounds_error([0.0, 5.0, 9.0]) + def _bounds_check_int_nan_fill(self, kind='linear'): + x = np.arange(10).astype(np.int_) + y = np.arange(10).astype(np.int_) + c = interp1d(x, y, kind=kind, fill_value=np.nan, bounds_error=False) + yi = c(x - 1) + assert np.isnan(yi[0]) + assert_array_almost_equal(yi, np.r_[np.nan, y[:-1]]) + def test_bounds(self): for kind in ('linear', 'cubic', 'nearest', 'slinear', 'zero', 'quadratic'): yield self._bounds_check, kind + yield self._bounds_check_int_nan_fill, kind def _nd_check_interp(self, kind='linear'): """Check the behavior when the inputs and outputs are multidimensional. From scipy-svn at scipy.org Sat Nov 22 00:26:54 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 23:26:54 -0600 (CST) Subject: [Scipy-svn] r5160 - in trunk/scipy/stats: . tests Message-ID: <20081122052654.9BE4439C088@scipy.org> Author: josef Date: 2008-11-21 23:26:45 -0600 (Fri, 21 Nov 2008) New Revision: 5160 Added: trunk/scipy/stats/mstats_basic.py trunk/scipy/stats/mstats_extras.py trunk/scipy/stats/tests/test_mstats_basic.py trunk/scipy/stats/tests/test_mstats_extras.py Removed: trunk/scipy/stats/mmorestats.py trunk/scipy/stats/mstats.py trunk/scipy/stats/tests/test_mmorestats.py trunk/scipy/stats/tests/test_mstats.py Log: rename masked array stats files Deleted: trunk/scipy/stats/mmorestats.py =================================================================== --- trunk/scipy/stats/mmorestats.py 2008-11-21 21:09:29 UTC (rev 5159) +++ trunk/scipy/stats/mmorestats.py 2008-11-22 05:26:45 UTC (rev 5160) @@ -1,385 +0,0 @@ -""" -Additional statistics functions, with support to MA. - -:author: Pierre GF Gerard-Marchant -:contact: pierregm_at_uga_edu -:date: $Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $ -:version: $Id: morestats.py 3473 2007-10-29 15:18:13Z jarrod.millman $ -""" -__author__ = "Pierre GF Gerard-Marchant" -__docformat__ = "restructuredtext en" - - -__all__ = ['compare_median_ms', - 'hdquantiles', 'hdmedian', 'hdquantiles_sd', - 'idealfourths', - 'median_cihs','mjci','mquantiles_cimj', - 'rsh', - 'trimmed_mean_ci',] - -import numpy as np -from numpy import float_, int_, ndarray - -import numpy.ma as ma -from numpy.ma import MaskedArray - -import scipy.stats.mstats as mstats - -from scipy.stats.distributions import norm, beta, t, binom - - -#####-------------------------------------------------------------------------- -#---- --- Quantiles --- -#####-------------------------------------------------------------------------- -def hdquantiles(data, prob=list([.25,.5,.75]), axis=None, var=False,): - """Computes quantile estimates with the Harrell-Davis method, where the estimates -are calculated as a weighted linear combination of order statistics. - -Parameters ----------- - data: ndarray - Data array. - prob: sequence - Sequence of quantiles to compute. - axis : int - Axis along which to compute the quantiles. If None, use a flattened array. - var : boolean - Whether to return the variance of the estimate. - -Returns -------- - A (p,) array of quantiles (if ``var`` is False), or a (2,p) array of quantiles - and variances (if ``var`` is True), where ``p`` is the number of quantiles. - -Notes ------ - The function is restricted to 2D arrays. - - """ - def _hd_1D(data,prob,var): - "Computes the HD quantiles for a 1D array. Returns nan for invalid data." - xsorted = np.squeeze(np.sort(data.compressed().view(ndarray))) - # Don't use length here, in case we have a numpy scalar - n = xsorted.size - #......... - hd = np.empty((2,len(prob)), float_) - if n < 2: - hd.flat = np.nan - if var: - return hd - return hd[0] - #......... - v = np.arange(n+1) / float(n) - betacdf = beta.cdf - for (i,p) in enumerate(prob): - _w = betacdf(v, (n+1)*p, (n+1)*(1-p)) - w = _w[1:] - _w[:-1] - hd_mean = np.dot(w, xsorted) - hd[0,i] = hd_mean - # - hd[1,i] = np.dot(w, (xsorted-hd_mean)**2) - # - hd[0, prob == 0] = xsorted[0] - hd[0, prob == 1] = xsorted[-1] - if var: - hd[1, prob == 0] = hd[1, prob == 1] = np.nan - return hd - return hd[0] - # Initialization & checks --------- - data = ma.array(data, copy=False, dtype=float_) - p = np.array(prob, copy=False, ndmin=1) - # Computes quantiles along axis (or globally) - if (axis is None) or (data.ndim == 1): - result = _hd_1D(data, p, var) - else: - assert data.ndim <= 2, "Array should be 2D at most !" - result = ma.apply_along_axis(_hd_1D, axis, data, p, var) - # - return ma.fix_invalid(result, copy=False) - -#.............................................................................. -def hdmedian(data, axis=-1, var=False): - """Returns the Harrell-Davis estimate of the median along the given axis. - -Parameters ----------- - data: ndarray - Data array. - axis : int - Axis along which to compute the quantiles. If None, use a flattened array. - var : boolean - Whether to return the variance of the estimate. - - """ - result = hdquantiles(data,[0.5], axis=axis, var=var) - return result.squeeze() - - -#.............................................................................. -def hdquantiles_sd(data, prob=list([.25,.5,.75]), axis=None): - """Computes the standard error of the Harrell-Davis quantile estimates by jackknife. - - -Parameters ----------- - data: ndarray - Data array. - prob: sequence - Sequence of quantiles to compute. - axis : int - Axis along which to compute the quantiles. If None, use a flattened array. - -Notes ------ - The function is restricted to 2D arrays. - - """ - def _hdsd_1D(data,prob): - "Computes the std error for 1D arrays." - xsorted = np.sort(data.compressed()) - n = len(xsorted) - #......... - hdsd = np.empty(len(prob), float_) - if n < 2: - hdsd.flat = np.nan - #......... - vv = np.arange(n) / float(n-1) - betacdf = beta.cdf - # - for (i,p) in enumerate(prob): - _w = betacdf(vv, (n+1)*p, (n+1)*(1-p)) - w = _w[1:] - _w[:-1] - mx_ = np.fromiter([np.dot(w,xsorted[np.r_[range(0,k), - range(k+1,n)].astype(int_)]) - for k in range(n)], dtype=float_) - mx_var = np.array(mx_.var(), copy=False, ndmin=1) * n / float(n-1) - hdsd[i] = float(n-1) * np.sqrt(np.diag(mx_var).diagonal() / float(n)) - return hdsd - # Initialization & checks --------- - data = ma.array(data, copy=False, dtype=float_) - p = np.array(prob, copy=False, ndmin=1) - # Computes quantiles along axis (or globally) - if (axis is None): - result = _hdsd_1D(data, p) - else: - assert data.ndim <= 2, "Array should be 2D at most !" - result = ma.apply_along_axis(_hdsd_1D, axis, data, p) - # - return ma.fix_invalid(result, copy=False).ravel() - - -#####-------------------------------------------------------------------------- -#---- --- Confidence intervals --- -#####-------------------------------------------------------------------------- - -def trimmed_mean_ci(data, limits=(0.2,0.2), inclusive=(True,True), - alpha=0.05, axis=None): - """Returns the selected confidence interval of the trimmed mean along the -given axis. - -Parameters ----------- - data : sequence - Input data. The data is transformed to a masked array - proportiontocut : float - Proportion of the data to cut from each side of the data . - As a result, (2*proportiontocut*n) values are actually trimmed. - alpha : float - Confidence level of the intervals. - inclusive : tuple of boolean - If relative==False, tuple indicating whether values exactly equal to the - absolute limits are allowed. - If relative==True, tuple indicating whether the number of data being masked - on each side should be rounded (True) or truncated (False). - axis : int - Axis along which to cut. If None, uses a flattened version of the input. - - """ - data = ma.array(data, copy=False) - trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis) - tmean = trimmed.mean(axis) - tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis) - df = trimmed.count(axis) - 1 - tppf = t.ppf(1-alpha/2.,df) - return np.array((tmean - tppf*tstde, tmean+tppf*tstde)) - -#.............................................................................. -def mjci(data, prob=[0.25,0.5,0.75], axis=None): - """Returns the Maritz-Jarrett estimators of the standard error of selected -experimental quantiles of the data. - -Parameters ------------ - data: ndarray - Data array. - prob: sequence - Sequence of quantiles to compute. - axis : int - Axis along which to compute the quantiles. If None, use a flattened array. - - """ - def _mjci_1D(data, p): - data = np.sort(data.compressed()) - n = data.size - prob = (np.array(p) * n + 0.5).astype(int_) - betacdf = beta.cdf - # - mj = np.empty(len(prob), float_) - x = np.arange(1,n+1, dtype=float_) / n - y = x - 1./n - for (i,m) in enumerate(prob): - (m1,m2) = (m-1, n-m) - W = betacdf(x,m-1,n-m) - betacdf(y,m-1,n-m) - C1 = np.dot(W,data) - C2 = np.dot(W,data**2) - mj[i] = np.sqrt(C2 - C1**2) - return mj - # - data = ma.array(data, copy=False) - assert data.ndim <= 2, "Array should be 2D at most !" - p = np.array(prob, copy=False, ndmin=1) - # Computes quantiles along axis (or globally) - if (axis is None): - return _mjci_1D(data, p) - else: - return ma.apply_along_axis(_mjci_1D, axis, data, p) - -#.............................................................................. -def mquantiles_cimj(data, prob=[0.25,0.50,0.75], alpha=0.05, axis=None): - """Computes the alpha confidence interval for the selected quantiles of the -data, with Maritz-Jarrett estimators. - -Parameters ----------- - data: ndarray - Data array. - prob: sequence - Sequence of quantiles to compute. - alpha : float - Confidence level of the intervals. - axis : integer - Axis along which to compute the quantiles. If None, use a flattened array. - """ - alpha = min(alpha, 1-alpha) - z = norm.ppf(1-alpha/2.) - xq = mstats.mquantiles(data, prob, alphap=0, betap=0, axis=axis) - smj = mjci(data, prob, axis=axis) - return (xq - z * smj, xq + z * smj) - - -#............................................................................. -def median_cihs(data, alpha=0.05, axis=None): - """Computes the alpha-level confidence interval for the median of the data, -following the Hettmasperger-Sheather method. - -Parameters ----------- - data : sequence - Input data. Masked values are discarded. The input should be 1D only, or - axis should be set to None. - alpha : float - Confidence level of the intervals. - axis : integer - Axis along which to compute the quantiles. If None, use a flattened array. - """ - def _cihs_1D(data, alpha): - data = np.sort(data.compressed()) - n = len(data) - alpha = min(alpha, 1-alpha) - k = int(binom._ppf(alpha/2., n, 0.5)) - gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5) - if gk < 1-alpha: - k -= 1 - gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5) - gkk = binom.cdf(n-k-1,n,0.5) - binom.cdf(k,n,0.5) - I = (gk - 1 + alpha)/(gk - gkk) - lambd = (n-k) * I / float(k + (n-2*k)*I) - lims = (lambd*data[k] + (1-lambd)*data[k-1], - lambd*data[n-k-1] + (1-lambd)*data[n-k]) - return lims - data = ma.rray(data, copy=False) - # Computes quantiles along axis (or globally) - if (axis is None): - result = _cihs_1D(data.compressed(), alpha) - else: - assert data.ndim <= 2, "Array should be 2D at most !" - result = ma.apply_along_axis(_cihs_1D, axis, data, alpha) - # - return result - -#.............................................................................. -def compare_medians_ms(group_1, group_2, axis=None): - """Compares the medians from two independent groups along the given axis. - -The comparison is performed using the McKean-Schrader estimate of the standard -error of the medians. - -Parameters ----------- - group_1 : {sequence} - First dataset. - group_2 : {sequence} - Second dataset. - axis : {integer} - Axis along which the medians are estimated. If None, the arrays are flattened. - -Returns -------- - A (p,) array of comparison values. - - """ - (med_1, med_2) = (ma.median(group_1,axis=axis), ma.median(group_2,axis=axis)) - (std_1, std_2) = (mstats.stde_median(group_1, axis=axis), - mstats.stde_median(group_2, axis=axis)) - W = np.abs(med_1 - med_2) / ma.sqrt(std_1**2 + std_2**2) - return 1 - norm.cdf(W) - - -def idealfourths(data, axis=None): - """Returns an estimate of the lower and upper quartiles of the data along - the given axis, as computed with the ideal fourths. - """ - def _idf(data): - x = data.compressed() - n = len(x) - if n < 3: - return [np.nan,np.nan] - (j,h) = divmod(n/4. + 5/12.,1) - qlo = (1-h)*x[j-1] + h*x[j] - k = n - j - qup = (1-h)*x[k] + h*x[k-1] - return [qlo, qup] - data = ma.sort(data, axis=axis).view(MaskedArray) - if (axis is None): - return _idf(data) - else: - return ma.apply_along_axis(_idf, axis, data) - - -def rsh(data, points=None): - """Evaluates Rosenblatt's shifted histogram estimators for each point -on the dataset 'data'. - -Parameters - data : sequence - Input data. Masked values are ignored. - points : sequence - Sequence of points where to evaluate Rosenblatt shifted histogram. - If None, use the data. - """ - data = ma.array(data, copy=False) - if points is None: - points = data - else: - points = np.array(points, copy=False, ndmin=1) - if data.ndim != 1: - raise AttributeError("The input array should be 1D only !") - n = data.count() - r = idealfourths(data, axis=None) - h = 1.2 * (r[-1]-r[0]) / n**(1./5) - nhi = (data[:,None] <= points[None,:] + h).sum(0) - nlo = (data[:,None] < points[None,:] - h).sum(0) - return (nhi-nlo) / (2.*n*h) - - -############################################################################### Deleted: trunk/scipy/stats/mstats.py =================================================================== --- trunk/scipy/stats/mstats.py 2008-11-21 21:09:29 UTC (rev 5159) +++ trunk/scipy/stats/mstats.py 2008-11-22 05:26:45 UTC (rev 5160) @@ -1,1914 +0,0 @@ -""" -An extension of scipy.stats.stats to support masked arrays - -:author: Pierre GF Gerard-Marchant -:contact: pierregm_at_uga_edu -""" -#TODO : f_value_wilks_lambda looks botched... what are dfnum & dfden for ? -#TODO : ttest_reel looks botched: what are x1,x2,v1,v2 for ? -#TODO : reimplement ksonesamp - -__author__ = "Pierre GF Gerard-Marchant" -__docformat__ = "restructuredtext en" - -__all__ = ['argstoarray', - 'betai', - 'chisquare','count_tied_groups', - 'describe', - 'f_oneway','f_value_wilks_lambda','find_repeats','friedmanchisquare', - 'gmean', - 'hmean', - 'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis', - 'ks_twosamp','ks_2samp','kurtosis','kurtosistest', - 'linregress', - 'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign', - 'normaltest', - 'obrientransform', - 'pearsonr','plotting_positions','pointbiserialr', - 'rankdata', - 'samplestd','samplevar','scoreatpercentile','sem','std', - 'sen_seasonal_slopes','signaltonoise','skew','skewtest','spearmanr', - 'stderr', - 'theilslopes','threshold','tmax','tmean','tmin','trim','trimboth', - 'trimtail','trima','trimr','trimmed_mean','trimmed_std', - 'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp', - 'ttest_ind','ttest_rel','tvar', - 'var','variation', - 'winsorize', - 'z','zmap','zs' - ] - -import numpy as np -from numpy import ndarray -import numpy.ma as ma -from numpy.ma import MaskedArray, masked, nomask - -import itertools -import warnings - - -import scipy.stats as stats -import scipy.special as special -import scipy.misc as misc -import scipy.stats.futil as futil - - -genmissingvaldoc = """ -Notes ------ - Missing values are considered pair-wise: if a value is missing in x, - the corresponding value in y is masked. -""" -#------------------------------------------------------------------------------ -def _chk_asarray(a, axis): - if axis is None: - a = ma.ravel(a) - outaxis = 0 - else: - a = ma.asanyarray(a) - outaxis = axis - return a, outaxis - -def _chk2_asarray(a, b, axis): - if axis is None: - a = ma.ravel(a) - b = ma.ravel(b) - outaxis = 0 - else: - a = ma.asanyarray(a) - b = ma.asanyarray(b) - outaxis = axis - return a, b, outaxis - -def _chk_size(a,b): - a = ma.asanyarray(a) - b = ma.asanyarray(b) - (na, nb) = (a.size, b.size) - if na != nb: - raise ValueError("The size of the input array should match!"\ - " (%s <> %s)" % (na,nb)) - return (a,b,na) - -def argstoarray(*args): - """Constructs a 2D array from a sequence of sequences. Sequences are filled - with missing values to match the length of the longest sequence. - - Returns - ------- - output : MaskedArray - a (mxn) masked array, where m is the number of arguments and n the - length of the longest argument. - """ - if len(args) == 1 and not isinstance(args[0], ndarray): - output = ma.asarray(args[0]) - assert(output.ndim == 2, "The input should be 2D!") - else: - n = len(args) - m = max([len(k) for k in args]) - output = ma.array(np.empty((n,m), dtype=float), mask=True) - for (k,v) in enumerate(args): - output[k,:len(v)] = v - output[np.logical_not(np.isfinite(output._data))] = masked - return output - - - -#####-------------------------------------------------------------------------- -#---- --- Ranking --- -#####-------------------------------------------------------------------------- - -def find_repeats(arr): - """Find repeats in arr and return a tuple (repeats, repeat_count). - Masked values are discarded. - -Parameters ----------- - arr : sequence - Input array. The array is flattened if it is not 1D. - -Returns -------- - repeats : ndarray - Array of repeated values. - counts : ndarray - Array of counts. - - """ - marr = ma.compressed(arr) - if not marr.size: - return (np.array(0), np.array(0)) - (v1, v2, n) = futil.dfreps(ma.array(ma.compressed(arr), copy=True)) - return (v1[:n], v2[:n]) - - -def count_tied_groups(x, use_missing=False): - """Counts the number of tied values in x, and returns a dictionary - (nb of ties: nb of groups). - -Parameters ----------- - x : sequence - Sequence of data on which to counts the ties - use_missing : boolean - Whether to consider missing values as tied. - -Example -------- - >>>z = [0, 0, 0, 2, 2, 2, 3, 3, 4, 5, 6] - >>>count_tied_groups(z) - >>>{2:1, 3:2} - >>># The ties were 0 (3x), 2 (3x) and 3 (2x) - >>>z = ma.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 6]) - >>>count_tied_groups(z) - >>>{2:2, 3:1} - >>># The ties were 0 (2x), 2 (3x) and 3 (2x) - >>>z[[1,-1]] = masked - >>>count_tied_groups(z) - >>>{2:2, 3:1} - >>># The ties were 2 (3x), 3 (2x) and masked (2x) - """ - nmasked = ma.getmask(x).sum() - # We need the copy as find_repeats will overwrite the initial data - data = ma.compressed(x).copy() - (ties, counts) = find_repeats(data) - nties = {} - if len(ties): - nties = dict(zip(np.unique(counts), itertools.repeat(1))) - nties.update(dict(zip(*find_repeats(counts)))) - if nmasked and use_missing: - try: - nties[nmasked] += 1 - except KeyError: - nties[nmasked] = 1 - return nties - - -def rankdata(data, axis=None, use_missing=False): - """Returns the rank (also known as order statistics) of each data point - along the given axis. - - If some values are tied, their rank is averaged. - If some values are masked, their rank is set to 0 if use_missing is False, - or set to the average rank of the unmasked values if use_missing is True. - - Parameters - ---------- - data : sequence - Input data. The data is transformed to a masked array - axis : {None,int} optional - Axis along which to perform the ranking. - If None, the array is first flattened. An exception is raised if - the axis is specified for arrays with a dimension larger than 2 - use_missing : {boolean} optional - Whether the masked values have a rank of 0 (False) or equal to the - average rank of the unmasked values (True). - """ - # - def _rank1d(data, use_missing=False): - n = data.count() - rk = np.empty(data.size, dtype=float) - idx = data.argsort() - rk[idx[:n]] = np.arange(1,n+1) - # - if use_missing: - rk[idx[n:]] = (n+1)/2. - else: - rk[idx[n:]] = 0 - # - repeats = find_repeats(data.copy()) - for r in repeats[0]: - condition = (data==r).filled(False) - rk[condition] = rk[condition].mean() - return rk - # - data = ma.array(data, copy=False) - if axis is None: - if data.ndim > 1: - return _rank1d(data.ravel(), use_missing).reshape(data.shape) - else: - return _rank1d(data, use_missing) - else: - return ma.apply_along_axis(_rank1d,axis,data,use_missing).view(ndarray) - - -#####-------------------------------------------------------------------------- -#---- --- Central tendency --- -#####-------------------------------------------------------------------------- - -def gmean(a, axis=0): - a, axis = _chk_asarray(a, axis) - log_a = ma.log(a) - return ma.exp(log_a.mean(axis=axis)) -gmean.__doc__ = stats.gmean.__doc__ - - -def hmean(a, axis=0): - a, axis = _chk_asarray(a, axis) - if isinstance(a, MaskedArray): - size = a.count(axis) - else: - size = a.shape[axis] - return size / (1.0/a).sum(axis) -hmean.__doc__ = stats.hmean.__doc__ - - -def mode(a, axis=0): - def _mode1D(a): - (rep,cnt) = find_repeats(a) - if not cnt.ndim: - return (0, 0) - elif cnt.size: - return (rep[cnt.argmax()], cnt.max()) - return (a[0], 1) - # - if axis is None: - output = _mode1D(ma.ravel(a)) - output = (ma.array(output[0]), ma.array(output[1])) - else: - output = ma.apply_along_axis(_mode1D, axis, a) - newshape = list(a.shape) - newshape[axis] = 1 - slices = [slice(None)] * output.ndim - slices[axis] = 0 - modes = output[tuple(slices)].reshape(newshape) - slices[axis] = 1 - counts = output[tuple(slices)].reshape(newshape) - output = (modes, counts) - return output -mode.__doc__ = stats.mode.__doc__ - - -#####-------------------------------------------------------------------------- -#---- --- Probabilities --- -#####-------------------------------------------------------------------------- - -def betai(a, b, x): - x = np.asanyarray(x) - x = ma.where(x < 1.0, x, 1.0) # if x > 1 then return 1.0 - return special.betainc(a, b, x) -betai.__doc__ = stats.betai.__doc__ - - -#####-------------------------------------------------------------------------- -#---- --- Correlation --- -#####-------------------------------------------------------------------------- - -def msign(x): - """Returns the sign of x, or 0 if x is masked.""" - return ma.filled(np.sign(x), 0) - -cov = ma.cov - -corrcoef = ma.corrcoef - - -def pearsonr(x,y): - """Calculates a Pearson correlation coefficient and the p-value for testing - non-correlation. - - The Pearson correlation coefficient measures the linear relationship - between two datasets. Strictly speaking, Pearson's correlation requires - that each dataset be normally distributed. Like other correlation - coefficients, this one varies between -1 and +1 with 0 implying no - correlation. Correlations of -1 or +1 imply an exact linear - relationship. Positive correlations imply that as x increases, so does - y. Negative correlations imply that as x increases, y decreases. - - The p-value roughly indicates the probability of an uncorrelated system - producing datasets that have a Pearson correlation at least as extreme - as the one computed from these datasets. The p-values are not entirely - reliable but are probably reasonable for datasets larger than 500 or so. - - Parameters - ---------- - x : 1D array - y : 1D array the same length as x - - Returns - ------- - (Pearson's correlation coefficient, - 2-tailed p-value) - - References - ---------- - http://www.statsoft.com/textbook/glosp.html#Pearson%20Correlation - """ - (x, y, n) = _chk_size(x, y) - (x, y) = (x.ravel(), y.ravel()) - # Get the common mask and the total nb of unmasked elements - m = ma.mask_or(ma.getmask(x), ma.getmask(y)) - n -= m.sum() - df = n-2 - if df < 0: - return (masked, masked) - # - (mx, my) = (x.mean(), y.mean()) - (xm, ym) = (x-mx, y-my) - # - r_num = n*(ma.add.reduce(xm*ym)) - r_den = n*ma.sqrt(ma.dot(xm,xm)*ma.dot(ym,ym)) - r = (r_num / r_den) - # Presumably, if r > 1, then it is only some small artifact of floating - # point arithmetic. - r = min(r, 1.0) - r = max(r, -1.0) - df = n-2 - # - t = ma.sqrt(df/((1.0-r)*(1.0+r))) * r - if t is masked: - prob = 0. - else: - prob = betai(0.5*df,0.5,df/(df+t*t)) - return (r,prob) - - -def spearmanr(x, y, use_ties=True): - """Calculates a Spearman rank-order correlation coefficient and the p-value - to test for non-correlation. - - The Spearman correlation is a nonparametric measure of the linear - relationship between two datasets. Unlike the Pearson correlation, the - Spearman correlation does not assume that both datasets are normally - distributed. Like other correlation coefficients, this one varies - between -1 and +1 with 0 implying no correlation. Correlations of -1 or - +1 imply an exact linear relationship. Positive correlations imply that - as x increases, so does y. Negative correlations imply that as x - increases, y decreases. - - Missing values are discarded pair-wise: if a value is missing in x, the - corresponding value in y is masked. - - The p-value roughly indicates the probability of an uncorrelated system - producing datasets that have a Spearman correlation at least as extreme - as the one computed from these datasets. The p-values are not entirely - reliable but are probably reasonable for datasets larger than 500 or so. - -Parameters ----------- - x : 1D array - y : 1D array the same length as x - The lengths of both arrays must be > 2. - use_ties : {True, False} optional - Whether the correction for ties should be computed. - -Returns -------- - (Spearman correlation coefficient, - 2-tailed p-value) - - References - ---------- - [CRCProbStat2000] section 14.7 - """ - (x, y, n) = _chk_size(x, y) - (x, y) = (x.ravel(), y.ravel()) - # - m = ma.mask_or(ma.getmask(x), ma.getmask(y)) - n -= m.sum() - if m is not nomask: - x = ma.array(x, mask=m, copy=True) - y = ma.array(y, mask=m, copy=True) - df = n-2 - if df < 0: - raise ValueError("The input must have at least 3 entries!") - # Gets the ranks and rank differences - rankx = rankdata(x) - ranky = rankdata(y) - dsq = np.add.reduce((rankx-ranky)**2) - # Tie correction - if use_ties: - xties = count_tied_groups(x) - yties = count_tied_groups(y) - corr_x = np.sum(v*k*(k**2-1) for (k,v) in xties.iteritems())/12. - corr_y = np.sum(v*k*(k**2-1) for (k,v) in yties.iteritems())/12. - else: - corr_x = corr_y = 0 - denom = n*(n**2 - 1)/6. - if corr_x != 0 or corr_y != 0: - rho = denom - dsq - corr_x - corr_y - rho /= ma.sqrt((denom-2*corr_x)*(denom-2*corr_y)) - else: - rho = 1. - dsq/denom - # - t = ma.sqrt(ma.divide(df,(rho+1.0)*(1.0-rho))) * rho - if t is masked: - prob = 0. - else: - prob = betai(0.5*df,0.5,df/(df+t*t)) - return rho, prob - - -def kendalltau(x, y, use_ties=True, use_missing=False): - """Computes Kendall's rank correlation tau on two variables *x* and *y*. - - Parameters - ---------- - xdata: sequence - First data list (for example, time). - ydata: sequence - Second data list. - use_ties: {True, False} optional - Whether ties correction should be performed. - use_missing: {False, True} optional - Whether missing data should be allocated a rank of 0 (False) or the - average rank (True) - - Returns - ------- - tau : float - Kendall tau - prob : float - Approximate 2-side p-value. - """ - (x, y, n) = _chk_size(x, y) - (x, y) = (x.flatten(), y.flatten()) - m = ma.mask_or(ma.getmask(x), ma.getmask(y)) - if m is not nomask: - x = ma.array(x, mask=m, copy=True) - y = ma.array(y, mask=m, copy=True) - n -= m.sum() - # - if n < 2: - return (np.nan, np.nan) - # - rx = ma.masked_equal(rankdata(x, use_missing=use_missing),0) - ry = ma.masked_equal(rankdata(y, use_missing=use_missing),0) - idx = rx.argsort() - (rx, ry) = (rx[idx], ry[idx]) - C = np.sum((((ry[i+1:]>ry[i])*(rx[i+1:]>rx[i])).filled(0).sum() - for i in range(len(ry)-1))) - D = np.sum((((ry[i+1:]rx[i])).filled(0).sum() - for i in range(len(ry)-1))) - if use_ties: - xties = count_tied_groups(x) - yties = count_tied_groups(y) - corr_x = np.sum(v*k*(k-1) for (k,v) in xties.iteritems()) - corr_y = np.sum(v*k*(k-1) for (k,v) in yties.iteritems()) - denom = ma.sqrt((n*(n-1)-corr_x) * (n*(n-1)-corr_y)) / 2. - else: - denom = n*(n-1)/2. - tau = (C-D) / denom - # - var_s = n*(n-1)*(2*n+5) - if use_ties: - var_s -= np.sum(v*k*(k-1)*(2*k+5) for (k,v) in xties.iteritems()) - var_s -= np.sum(v*k*(k-1)*(2*k+5) for (k,v) in yties.iteritems()) - v1 = np.sum(v*k*(k-1) for (k,v) in xties.iteritems()) * \ - np.sum(v*k*(k-1) for (k,v) in yties.iteritems()) - v1 /= 2.*n*(n-1) - if n > 2: - v2 = np.sum(v*k*(k-1)*(k-2) for (k,v) in xties.iteritems()) * \ - np.sum(v*k*(k-1)*(k-2) for (k,v) in yties.iteritems()) - v2 /= 9.*n*(n-1)*(n-2) - else: - v2 = 0 - else: - v1 = v2 = 0 - var_s /= 18. - var_s += (v1 + v2) - z = (C-D)/np.sqrt(var_s) - prob = special.erfc(abs(z)/np.sqrt(2)) - return (tau,prob) - - -def kendalltau_seasonal(x): - """Computes a multivariate extension Kendall's rank correlation tau, designed - for seasonal data. - -Parameters ----------- - x: 2D array - Array of seasonal data, with seasons in columns. - """ - x = ma.array(x, subok=True, copy=False, ndmin=2) - (n,m) = x.shape - n_p = x.count(0) - # - S_szn = np.sum(msign(x[i:]-x[i]).sum(0) for i in range(n)) - S_tot = S_szn.sum() - # - n_tot = x.count() - ties = count_tied_groups(x.compressed()) - corr_ties = np.sum(v*k*(k-1) for (k,v) in ties.iteritems()) - denom_tot = ma.sqrt(n_tot*(n_tot-1)*(n_tot*(n_tot-1)-corr_ties))/2. - # - R = rankdata(x, axis=0, use_missing=True) - K = ma.empty((m,m), dtype=int) - covmat = ma.empty((m,m), dtype=float) -# cov_jj = ma.empty(m, dtype=float) - denom_szn = ma.empty(m, dtype=float) - for j in range(m): - ties_j = count_tied_groups(x[:,j].compressed()) - corr_j = np.sum(v*k*(k-1) for (k,v) in ties_j.iteritems()) - cmb = n_p[j]*(n_p[j]-1) - for k in range(j,m,1): - K[j,k] = np.sum(msign((x[i:,j]-x[i,j])*(x[i:,k]-x[i,k])).sum() - for i in range(n)) - covmat[j,k] = (K[j,k] +4*(R[:,j]*R[:,k]).sum() - \ - n*(n_p[j]+1)*(n_p[k]+1))/3. - K[k,j] = K[j,k] - covmat[k,j] = covmat[j,k] -# cov_jj[j] = (nn_p*(2*n_p[j]+5)) -# cov_jj[j] -= np.sum(v*k*(k-1)*(2*k+5) for (k,v) in ties_j.iteritems()) -# cov_jj[j] /= 18. - denom_szn[j] = ma.sqrt(cmb*(cmb-corr_j)) / 2. - var_szn = covmat.diagonal() - # - z_szn = msign(S_szn) * (abs(S_szn)-1) / ma.sqrt(var_szn) - z_tot_ind = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(var_szn.sum()) - z_tot_dep = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(covmat.sum()) - # - prob_szn = special.erfc(abs(z_szn)/np.sqrt(2)) - prob_tot_ind = special.erfc(abs(z_tot_ind)/np.sqrt(2)) - prob_tot_dep = special.erfc(abs(z_tot_dep)/np.sqrt(2)) - # - chi2_tot = (z_szn*z_szn).sum() - chi2_trd = m * z_szn.mean()**2 - output = {'seasonal tau': S_szn/denom_szn, - 'global tau': S_tot/denom_tot, - 'global tau (alt)': S_tot/denom_szn.sum(), - 'seasonal p-value': prob_szn, - 'global p-value (indep)': prob_tot_ind, - 'global p-value (dep)': prob_tot_dep, - 'chi2 total': chi2_tot, - 'chi2 trend': chi2_trd, - } - return output - - -def pointbiserialr(x, y): - x = ma.fix_invalid(x, copy=True).astype(bool) - y = ma.fix_invalid(y, copy=True).astype(float) - # Get rid of the missing data .......... - m = ma.mask_or(ma.getmask(x), ma.getmask(y)) - if m is not nomask: - unmask = np.logical_not(m) - x = x[unmask] - y = y[unmask] - # - n = len(x) - # phat is the fraction of x values that are True - phat = x.sum() / float(n) - y0 = y[~x] # y-values where x is False - y1 = y[x] # y-values where x is True - y0m = y0.mean() - y1m = y1.mean() - # - rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / y.std() - # - df = n-2 - t = rpb*ma.sqrt(df/(1.0-rpb**2)) - prob = betai(0.5*df, 0.5, df/(df+t*t)) - return rpb, prob - -if stats.pointbiserialr.__doc__: - pointbiserialr.__doc__ = stats.pointbiserialr.__doc__ + genmissingvaldoc - - -def linregress(*args): - if len(args) == 1: # more than 1D array? - args = ma.array(args[0], copy=True) - if len(args) == 2: - x = args[0] - y = args[1] - else: - x = args[:,0] - y = args[:,1] - else: - x = ma.array(args[0]).flatten() - y = ma.array(args[1]).flatten() - m = ma.mask_or(ma.getmask(x), ma.getmask(y)) - if m is not nomask: - x = ma.array(x,mask=m) - y = ma.array(y,mask=m) - n = len(x) - (xmean, ymean) = (x.mean(), y.mean()) - (xm, ym) = (x-xmean, y-ymean) - (Sxx, Syy) = (ma.add.reduce(xm*xm), ma.add.reduce(ym*ym)) - Sxy = ma.add.reduce(xm*ym) - r_den = ma.sqrt(Sxx*Syy) - if r_den == 0.0: - r = 0.0 - else: - r = Sxy / r_den - if (r > 1.0): - r = 1.0 # from numerical error - #z = 0.5*log((1.0+r+TINY)/(1.0-r+TINY)) - df = n-2 - t = r * ma.sqrt(df/(1.0-r*r)) - prob = betai(0.5*df,0.5,df/(df+t*t)) - slope = Sxy / Sxx - intercept = ymean - slope*xmean - sterrest = ma.sqrt(1.-r*r) * y.std() - return slope, intercept, r, prob, sterrest, Syy/Sxx - -if stats.linregress.__doc__: - linregress.__doc__ = stats.linregress.__doc__ + genmissingvaldoc - - -def theilslopes(y, x=None, alpha=0.05): - """Computes the Theil slope over the dataset (x,y), as the median of all slopes - between paired values. - - Parameters - ---------- - y : sequence - Dependent variable. - x : {None, sequence} optional - Independent variable. If None, use arange(len(y)) instead. - alpha : float - Confidence degree. - - Returns - ------- - medslope : float - Theil slope - medintercept : float - Intercept of the Theil line, as median(y)-medslope*median(x) - lo_slope : float - Lower bound of the confidence interval on medslope - up_slope : float - Upper bound of the confidence interval on medslope - - """ - y = ma.asarray(y).flatten() - y[-1] = masked - n = len(y) - if x is None: - x = ma.arange(len(y), dtype=float) - else: - x = ma.asarray(x).flatten() - if len(x) != n: - raise ValueError, "Incompatible lengths ! (%s<>%s)" % (n,len(x)) - m = ma.mask_or(ma.getmask(x), ma.getmask(y)) - y._mask = x._mask = m - ny = y.count() - # - slopes = ma.hstack([(y[i+1:]-y[i])/(x[i+1:]-x[i]) for i in range(n-1)]) - slopes.sort() - medslope = ma.median(slopes) - medinter = ma.median(y) - medslope*ma.median(x) - # - if alpha > 0.5: - alpha = 1.-alpha - z = stats.distributions.norm.ppf(alpha/2.) - # - (xties, yties) = (count_tied_groups(x), count_tied_groups(y)) - nt = ny*(ny-1)/2. - sigsq = (ny*(ny-1)*(2*ny+5)/18.) - sigsq -= np.sum(v*k*(k-1)*(2*k+5) for (k,v) in xties.iteritems()) - sigsq -= np.sum(v*k*(k-1)*(2*k+5) for (k,v) in yties.iteritems()) - sigma = np.sqrt(sigsq) - - Ru = min(np.round((nt - z*sigma)/2. + 1), len(slopes)-1) - Rl = max(np.round((nt + z*sigma)/2.), 0) - delta = slopes[[Rl,Ru]] - return medslope, medinter, delta[0], delta[1] - - -def sen_seasonal_slopes(x): - x = ma.array(x, subok=True, copy=False, ndmin=2) - (n,_) = x.shape - # Get list of slopes per season - szn_slopes = ma.vstack([(x[i+1:]-x[i])/np.arange(1,n-i)[:,None] - for i in range(n)]) - szn_medslopes = ma.median(szn_slopes, axis=0) - medslope = ma.median(szn_slopes, axis=None) - return szn_medslopes, medslope - - -#####-------------------------------------------------------------------------- -#---- --- Inferential statistics --- -#####-------------------------------------------------------------------------- - -def ttest_onesamp(a, popmean): - a = ma.asarray(a) - x = a.mean(axis=None) - v = a.var(axis=None,ddof=1) - n = a.count(axis=None) - df = n-1 - svar = ((n-1)*v) / float(df) - t = (x-popmean)/ma.sqrt(svar*(1.0/n)) - prob = betai(0.5*df,0.5,df/(df+t*t)) - return t,prob -ttest_onesamp.__doc__ = stats.ttest_1samp.__doc__ -ttest_1samp = ttest_onesamp - - -def ttest_ind(a, b, axis=0): - a, b, axis = _chk2_asarray(a, b, axis) - (x1, x2) = (a.mean(axis), b.mean(axis)) - (v1, v2) = (a.var(axis=axis, ddof=1), b.var(axis=axis, ddof=1)) - (n1, n2) = (a.count(axis), b.count(axis)) - df = n1+n2-2 - svar = ((n1-1)*v1+(n2-1)*v2) / float(df) - svar == 0 - t = (x1-x2)/ma.sqrt(svar*(1.0/n1 + 1.0/n2)) # N-D COMPUTATION HERE!!!!!! - t = ma.filled(t, 1) # replace NaN t-values with 1.0 - probs = betai(0.5*df,0.5,float(df)/(df+t*t)).reshape(t.shape) - return t, probs.squeeze() -ttest_ind.__doc__ = stats.ttest_ind.__doc__ - - -def ttest_rel(a,b,axis=None): - a, b, axis = _chk2_asarray(a, b, axis) - if len(a)!=len(b): - raise ValueError, 'unequal length arrays' - (x1, x2) = (a.mean(axis), b.mean(axis)) - (v1, v2) = (a.var(axis=axis, ddof=1), b.var(axis=axis, ddof=1)) - n = a.count(axis) - df = (n-1.0) - d = (a-b).astype('d') - denom = ma.sqrt((n*ma.add.reduce(d*d,axis) - ma.add.reduce(d,axis)**2) /df) - #zerodivproblem = denom == 0 - t = ma.add.reduce(d, axis) / denom - t = ma.filled(t, 1) - probs = betai(0.5*df,0.5,df/(df+t*t)).reshape(t.shape).squeeze() - return t, probs -ttest_rel.__doc__ = stats.ttest_rel.__doc__ - - -def chisquare(f_obs, f_exp=None): - f_obs = ma.asarray(f_obs) - if f_exp is None: - f_exp = ma.array([f_obs.mean(axis=0)] * len(f_obs)) - f_exp = f_exp.astype(float) - chisq = ma.add.reduce((f_obs-f_exp)**2 / f_exp) - return chisq, stats.chisqprob(chisq, f_obs.count(0)-1) -chisquare.__doc__ = stats.chisquare.__doc__ - - -def mannwhitneyu(x,y, use_continuity=True): - """Computes the Mann-Whitney on samples x and y. - Missing values in x and/or y are discarded. - - Parameters - ---------- - x : sequence - y : sequence - use_continuity : {True, False} optional - Whether a continuity correction (1/2.) should be taken into account. - - Returns - ------- - u : float - The Mann-Whitney statistics - prob : float - Approximate p-value assuming a normal distribution. - - """ - x = ma.asarray(x).compressed().view(ndarray) - y = ma.asarray(y).compressed().view(ndarray) - ranks = rankdata(np.concatenate([x,y])) - (nx, ny) = (len(x), len(y)) - nt = nx + ny - U = ranks[:nx].sum() - nx*(nx+1)/2. - U = max(U, nx*ny - U) - u = nx*ny - U - # - mu = (nx*ny)/2. - sigsq = (nt**3 - nt)/12. - ties = count_tied_groups(ranks) - sigsq -= np.sum(v*(k**3-k) for (k,v) in ties.iteritems())/12. - sigsq *= nx*ny/float(nt*(nt-1)) - # - if use_continuity: - z = (U - 1/2. - mu) / ma.sqrt(sigsq) - else: - z = (U - mu) / ma.sqrt(sigsq) - prob = special.erfc(abs(z)/np.sqrt(2)) - return (u, prob) - - -def kruskalwallis(*args): - output = argstoarray(*args) - ranks = ma.masked_equal(rankdata(output, use_missing=False), 0) - sumrk = ranks.sum(-1) - ngrp = ranks.count(-1) - ntot = ranks.count() -# ssbg = (sumrk**2/ranks.count(-1)).sum() - ranks.sum()**2/ntotal -# H = ssbg / (ntotal*(ntotal+1)/12.) - H = 12./(ntot*(ntot+1)) * (sumrk**2/ngrp).sum() - 3*(ntot+1) - # Tie correction - ties = count_tied_groups(ranks) - T = 1. - np.sum(v*(k**3-k) for (k,v) in ties.iteritems())/float(ntot**3-ntot) - if T == 0: - raise ValueError, 'All numbers are identical in kruskal' - H /= T - # - df = len(output) - 1 - prob = stats.chisqprob(H,df) - return (H, prob) -kruskal = kruskalwallis -kruskalwallis.__doc__ = stats.kruskal.__doc__ - - -_kolmog2 = special.kolmogorov -def _kolmog1(x,n): - if x <= 0: - return 0 - if x >= 1: - return 1 - j = np.arange(np.floor(n*(1-x))+1) - return 1 - x * np.sum(np.exp(np.log(misc.comb(n,j)) - + (n-j) * np.log(1-x-j/float(n)) - + (j-1) * np.log(x+j/float(n)))) - - -def ks_twosamp(data1, data2, alternative="two_sided"): - """Computes the Kolmogorov-Smirnov test on two samples. - Missing values are discarded. - - Parameters - ---------- - data1 : sequence - First data set - data2 : sequence - Second data set - alternative : {'two_sided', 'less', 'greater'} optional - Indicates the alternative hypothesis. - - Returns - ------- - d : float - Value of the Kolmogorov Smirnov test - p : float - Corresponding p-value. - - """ - (data1, data2) = (ma.asarray(data1), ma.asarray(data2)) - (n1, n2) = (data1.count(), data2.count()) - n = (n1*n2/float(n1+n2)) - mix = ma.concatenate((data1.compressed(), data2.compressed())) - mixsort = mix.argsort(kind='mergesort') - csum = np.where(mixsort threshmax).filled(False) - a[mask] = newval - return a - - -def trima(a, limits=None, inclusive=(True,True)): - """Trims an array by masking the data outside some given limits. - Returns a masked version of the input array. - - Parameters - ---------- - a : sequence - Input array. - limits : {None, tuple} optional - Tuple of (lower limit, upper limit) in absolute values. - Values of the input array lower (greater) than the lower (upper) limit - will be masked. A limit is None indicates an open interval. - inclusive : {(True,True) tuple} optional - Tuple of (lower flag, upper flag), indicating whether values exactly - equal to the lower (upper) limit are allowed. - - """ - a = ma.asarray(a) - a.unshare_mask() - if limits is None: - return a - (lower_lim, upper_lim) = limits - (lower_in, upper_in) = inclusive - condition = False - if lower_lim is not None: - if lower_in: - condition |= (a < lower_lim) - else: - condition |= (a <= lower_lim) - if upper_lim is not None: - if upper_in: - condition |= (a > upper_lim) - else: - condition |= (a >= upper_lim) - a[condition.filled(True)] = masked - return a - - -def trimr(a, limits=None, inclusive=(True, True), axis=None): - """Trims an array by masking some proportion of the data on each end. - Returns a masked version of the input array. - - Parameters - ---------- - a : sequence - Input array. - limits : {None, tuple} optional - Tuple of the percentages to cut on each side of the array, with respect - to the number of unmasked data, as floats between 0. and 1. - Noting n the number of unmasked data before trimming, the (n*limits[0])th - smallest data and the (n*limits[1])th largest data are masked, and the - total number of unmasked data after trimming is n*(1.-sum(limits)) - The value of one limit can be set to None to indicate an open interval. - inclusive : {(True,True) tuple} optional - Tuple of flags indicating whether the number of data being masked on the - left (right) end should be truncated (True) or rounded (False) to integers. - axis : {None,int} optional - Axis along which to trim. If None, the whole array is trimmed, but its - shape is maintained. - - """ - def _trimr1D(a, low_limit, up_limit, low_inclusive, up_inclusive): - n = a.count() - idx = a.argsort() - if low_limit: - if low_inclusive: - lowidx = int(low_limit*n) - else: - lowidx = np.round(low_limit*n) - a[idx[:lowidx]] = masked - if up_limit is not None: - if up_inclusive: - upidx = n - int(n*up_limit) - else: - upidx = n- np.round(n*up_limit) - a[idx[upidx:]] = masked - return a - # - a = ma.asarray(a) - a.unshare_mask() - if limits is None: - return a - # Check the limits - (lolim, uplim) = limits - errmsg = "The proportion to cut from the %s should be between 0. and 1." - if lolim is not None: - if lolim > 1. or lolim < 0: - raise ValueError(errmsg % 'beginning' + "(got %s)" % lolim) - if uplim is not None: - if uplim > 1. or uplim < 0: - raise ValueError(errmsg % 'end' + "(got %s)" % uplim) - # - (loinc, upinc) = inclusive - # - if axis is None: - shp = a.shape - return _trimr1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp) - else: - return ma.apply_along_axis(_trimr1D, axis, a, lolim,uplim,loinc,upinc) - -trimdoc = """ - Parameters - ---------- - a : sequence - Input array - limits : {None, tuple} optional - If relative == False, tuple (lower limit, upper limit) in absolute values. - Values of the input array lower (greater) than the lower (upper) limit are - masked. - If relative == True, tuple (lower percentage, upper percentage) to cut - on each side of the array, with respect to the number of unmasked data. - Noting n the number of unmasked data before trimming, the (n*limits[0])th - smallest data and the (n*limits[1])th largest data are masked, and the - total number of unmasked data after trimming is n*(1.-sum(limits)) - In each case, the value of one limit can be set to None to indicate an - open interval. - If limits is None, no trimming is performed - inclusive : {(True, True) tuple} optional - If relative==False, tuple indicating whether values exactly equal to the - absolute limits are allowed. - If relative==True, tuple indicating whether the number of data being masked - on each side should be rounded (True) or truncated (False). - relative : {False, True} optional - Whether to consider the limits as absolute values (False) or proportions - to cut (True). - axis : {None, integer}, optional - Axis along which to trim. -""" - - -def trim(a, limits=None, inclusive=(True,True), relative=False, axis=None): - """Trims an array by masking the data outside some given limits. - Returns a masked version of the input array. - %s - - Examples - -------- - >>>z = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10] - >>>trim(z,(3,8)) - [--,--, 3, 4, 5, 6, 7, 8,--,--] - >>>trim(z,(0.1,0.2),relative=True) - [--, 2, 3, 4, 5, 6, 7, 8,--,--] - - - """ - if relative: - return trimr(a, limits=limits, inclusive=inclusive, axis=axis) - else: - return trima(a, limits=limits, inclusive=inclusive) - -if trim.__doc__: - trim.__doc__ = trim.__doc__ % trimdoc - - -def trimboth(data, proportiontocut=0.2, inclusive=(True,True), axis=None): - """Trims the data by masking the int(proportiontocut*n) smallest and - int(proportiontocut*n) largest values of data along the given axis, where n - is the number of unmasked values before trimming. - -Parameters ----------- - data : ndarray - Data to trim. - proportiontocut : {0.2, float} optional - Percentage of trimming (as a float between 0 and 1). - If n is the number of unmasked values before trimming, the number of - values after trimming is: - (1-2*proportiontocut)*n. - inclusive : {(True, True) tuple} optional - Tuple indicating whether the number of data being masked on each side - should be rounded (True) or truncated (False). - axis : {None, integer}, optional - Axis along which to perform the trimming. - If None, the input array is first flattened. - - """ - return trimr(data, limits=(proportiontocut,proportiontocut), - inclusive=inclusive, axis=axis) - -#.............................................................................. -def trimtail(data, proportiontocut=0.2, tail='left', inclusive=(True,True), - axis=None): - """Trims the data by masking int(trim*n) values from ONE tail of the - data along the given axis, where n is the number of unmasked values. - -Parameters ----------- - data : {ndarray} - Data to trim. - proportiontocut : {0.2, float} optional - Percentage of trimming. If n is the number of unmasked values - before trimming, the number of values after trimming is - (1-proportiontocut)*n. - tail : {'left','right'} optional - If left (right), the ``proportiontocut`` lowest (greatest) values will - be masked. - inclusive : {(True, True) tuple} optional - Tuple indicating whether the number of data being masked on each side - should be rounded (True) or truncated (False). - axis : {None, integer}, optional - Axis along which to perform the trimming. - If None, the input array is first flattened. - - """ - tail = str(tail).lower()[0] - if tail == 'l': - limits = (proportiontocut,None) - elif tail == 'r': - limits = (None, proportiontocut) - else: - raise TypeError("The tail argument should be in ('left','right')") - return trimr(data, limits=limits, axis=axis, inclusive=inclusive) - -trim1 = trimtail - -def trimmed_mean(a, limits=(0.1,0.1), inclusive=(1,1), relative=True, - axis=None): - """Returns the trimmed mean of the data along the given axis. - - %s - - """ % trimdoc - if (not isinstance(limits,tuple)) and isinstance(limits,float): - limits = (limits, limits) - if relative: - return trimr(a,limits=limits,inclusive=inclusive,axis=axis).mean(axis=axis) - else: - return trima(a,limits=limits,inclusive=inclusive).mean(axis=axis) - - -def trimmed_var(a, limits=(0.1,0.1), inclusive=(1,1), relative=True, - axis=None, ddof=0): - """Returns the trimmed variance of the data along the given axis. - - %s - ddof : {0,integer}, optional - Means Delta Degrees of Freedom. The denominator used during computations - is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un- - biased estimate of the variance. - - """ % trimdoc - if (not isinstance(limits,tuple)) and isinstance(limits,float): - limits = (limits, limits) - if relative: - out = trimr(a,limits=limits, inclusive=inclusive,axis=axis) - else: - out = trima(a,limits=limits,inclusive=inclusive) - return out.var(axis=axis, ddof=ddof) - - -def trimmed_std(a, limits=(0.1,0.1), inclusive=(1,1), relative=True, - axis=None, ddof=0): - """Returns the trimmed standard deviation of the data along the given axis. - - %s - ddof : {0,integer}, optional - Means Delta Degrees of Freedom. The denominator used during computations - is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un- - biased estimate of the variance. - - """ % trimdoc - if (not isinstance(limits,tuple)) and isinstance(limits,float): - limits = (limits, limits) - if relative: - out = trimr(a,limits=limits,inclusive=inclusive,axis=axis) - else: - out = trima(a,limits=limits,inclusive=inclusive) - return out.std(axis=axis,ddof=ddof) - - -def trimmed_stde(a, limits=(0.1,0.1), inclusive=(1,1), axis=None): - """Returns the standard error of the trimmed mean of the data along the given - axis. - Parameters - ---------- - a : sequence - Input array - limits : {(0.1,0.1), tuple of float} optional - tuple (lower percentage, upper percentage) to cut on each side of the - array, with respect to the number of unmasked data. - Noting n the number of unmasked data before trimming, the (n*limits[0])th - smallest data and the (n*limits[1])th largest data are masked, and the - total number of unmasked data after trimming is n*(1.-sum(limits)) - In each case, the value of one limit can be set to None to indicate an - open interval. - If limits is None, no trimming is performed - inclusive : {(True, True) tuple} optional - Tuple indicating whether the number of data being masked on each side - should be rounded (True) or truncated (False). - axis : {None, integer}, optional - Axis along which to trim. - """ - #........................ - def _trimmed_stde_1D(a, low_limit, up_limit, low_inclusive, up_inclusive): - "Returns the standard error of the trimmed mean for a 1D input data." - n = a.count() - idx = a.argsort() - if low_limit: - if low_inclusive: - lowidx = int(low_limit*n) - else: - lowidx = np.round(low_limit*n) - a[idx[:lowidx]] = masked - if up_limit is not None: - if up_inclusive: - upidx = n - int(n*up_limit) - else: - upidx = n- np.round(n*up_limit) - a[idx[upidx:]] = masked - nsize = a.count() - a[idx[:lowidx]] = a[idx[lowidx]] - a[idx[upidx:]] = a[idx[upidx-1]] - winstd = a.std(ddof=1) - return winstd / ((1-low_limit-up_limit)*np.sqrt(len(a))) - #........................ - a = ma.array(a, copy=True, subok=True) - a.unshare_mask() - if limits is None: - return a.std(axis=axis,ddof=1)/ma.sqrt(a.count(axis)) - if (not isinstance(limits,tuple)) and isinstance(limits,float): - limits = (limits, limits) - # Check the limits - (lolim, uplim) = limits - errmsg = "The proportion to cut from the %s should be between 0. and 1." - if lolim is not None: - if lolim > 1. or lolim < 0: - raise ValueError(errmsg % 'beginning' + "(got %s)" % lolim) - if uplim is not None: - if uplim > 1. or uplim < 0: - raise ValueError(errmsg % 'end' + "(got %s)" % uplim) - # - (loinc, upinc) = inclusive - if (axis is None): - shp = a.shape - return _trimmed_stde_1D(a.ravel(),lolim,uplim,loinc,upinc) - else: - assert a.ndim <= 2, "Array should be 2D at most !" - return ma.apply_along_axis(_trimmed_stde_1D, axis, a, - lolim,uplim,loinc,upinc) - - -def tmean(a, limits=None, inclusive=(True,True)): - return trima(a, limits=limits, inclusive=inclusive).mean() -tmean.__doc__ = stats.tmean.__doc__ - -def tvar(a, limits=None, inclusive=(True,True)): - return trima(a, limits=limits, inclusive=inclusive).var() -tvar.__doc__ = stats.tvar.__doc__ - -def tmin(a, lowerlimit=None, axis=0, inclusive=True): - a, axis = _chk_asarray(a, axis) - am = trima(a, (lowerlimit, None), (inclusive, False)) - return ma.minimum.reduce(am, axis) -tmin.__doc__ = stats.tmin.__doc__ - -def tmax(a, upperlimit, axis=0, inclusive=True): - a, axis = _chk_asarray(a, axis) - am = trima(a, (None, upperlimit), (False, inclusive)) - return ma.maximum.reduce(am, axis) -tmax.__doc__ = stats.tmax.__doc__ - -def tsem(a, limits=None, inclusive=(True,True)): - a = ma.asarray(a).ravel() - if limits is None: - n = float(a.count()) - return a.std()/ma.sqrt(n) - am = trima(a.ravel(), limits, inclusive) - sd = np.sqrt(am.var()) - return sd / am.count() -tsem.__doc__ = stats.tsem.__doc__ - - -def winsorize(a, limits=None, inclusive=(True,True), inplace=False, axis=None): - """Returns a Winsorized version of the input array. - - The (limits[0])th lowest values are set to the (limits[0])th percentile, - and the (limits[1])th highest values are set to the (limits[1])th - percentile. - Masked values are skipped. - - - Parameters - ---------- - a : sequence - Input array. - limits : {None, tuple of float} optional - Tuple of the percentages to cut on each side of the array, with respect - to the number of unmasked data, as floats between 0. and 1. - Noting n the number of unmasked data before trimming, the (n*limits[0])th - smallest data and the (n*limits[1])th largest data are masked, and the - total number of unmasked data after trimming is n*(1.-sum(limits)) - The value of one limit can be set to None to indicate an open interval. - inclusive : {(True, True) tuple} optional - Tuple indicating whether the number of data being masked on each side - should be rounded (True) or truncated (False). - inplace : {False, True} optional - Whether to winsorize in place (True) or to use a copy (False) - axis : {None, int} optional - Axis along which to trim. If None, the whole array is trimmed, but its - shape is maintained. - - """ - def _winsorize1D(a, low_limit, up_limit, low_include, up_include): - n = a.count() - idx = a.argsort() - if low_limit: - if low_include: - lowidx = int(low_limit*n) - else: - lowidx = np.round(low_limit*n) - a[idx[:lowidx]] = a[idx[lowidx]] - if up_limit is not None: - if up_include: - upidx = n - int(n*up_limit) - else: - upidx = n- np.round(n*up_limit) - a[idx[upidx:]] = a[idx[upidx-1]] - return a - # We gonna modify a: better make a copy - a = ma.array(a, copy=np.logical_not(inplace)) - # - if limits is None: - return a - if (not isinstance(limits,tuple)) and isinstance(limits,float): - limits = (limits, limits) - # Check the limits - (lolim, uplim) = limits - errmsg = "The proportion to cut from the %s should be between 0. and 1." - if lolim is not None: - if lolim > 1. or lolim < 0: - raise ValueError(errmsg % 'beginning' + "(got %s)" % lolim) - if uplim is not None: - if uplim > 1. or uplim < 0: - raise ValueError(errmsg % 'end' + "(got %s)" % uplim) - # - (loinc, upinc) = inclusive - # - if axis is None: - shp = a.shape - return _winsorize1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp) - else: - return ma.apply_along_axis(_winsorize1D, axis,a,lolim,uplim,loinc,upinc) - - -#####-------------------------------------------------------------------------- -#---- --- Moments --- -#####-------------------------------------------------------------------------- - -def moment(a, moment=1, axis=0): - a, axis = _chk_asarray(a, axis) - if moment == 1: - # By definition the first moment about the mean is 0. - shape = list(a.shape) - del shape[axis] - if shape: - # return an actual array of the appropriate shape - return np.zeros(shape, dtype=float) - else: - # the input was 1D, so return a scalar instead of a rank-0 array - return np.float64(0.0) - else: - mn = ma.expand_dims(a.mean(axis=axis), axis) - s = ma.power((a-mn), moment) - return s.mean(axis=axis) -moment.__doc__ = stats.moment.__doc__ - - -def variation(a, axis=0): - a, axis = _chk_asarray(a, axis) - return a.std(axis)/a.mean(axis) -variation.__doc__ = stats.variation.__doc__ - - -def skew(a, axis=0, bias=True): - a, axis = _chk_asarray(a,axis) - n = a.count(axis) - m2 = moment(a, 2, axis) - m3 = moment(a, 3, axis) - vals = ma.where(m2 == 0, 0, m3 / m2**1.5) - if not bias: - can_correct = (n > 2) & (m2 > 0) - if can_correct.any(): - m2 = np.extract(can_correct, m2) - m3 = np.extract(can_correct, m3) - nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5 - np.place(vals, can_correct, nval) - return vals -skew.__doc__ = stats.skew.__doc__ - - -def kurtosis(a, axis=0, fisher=True, bias=True): - a, axis = _chk_asarray(a, axis) - n = a.count(axis) - m2 = moment(a,2,axis) - m4 = moment(a,4,axis) - vals = ma.where(m2 == 0, 0, m4/ m2**2.0) - if not bias: - can_correct = (n > 3) & (m2 > 0) - if can_correct.any(): - m2 = np.extract(can_correct, m2) - m4 = np.extract(can_correct, m4) - nval = 1.0/(n-2)/(n-3)*((n*n-1.0)*m4/m2**2.0-3*(n-1)**2.0) - np.place(vals, can_correct, nval+3.0) - if fisher: - return vals - 3 - else: - return vals -kurtosis.__doc__ = stats.kurtosis.__doc__ - -def describe(a, axis=0): - """Computes several descriptive statistics of the passed array. - - Parameters - ---------- - a : array - axis : int or None - - Returns - ------- - (size of the data (discarding missing values), - (min, max), - arithmetic mean, - unbiased variance, - biased skewness, - biased kurtosis) - """ - a, axis = _chk_asarray(a, axis) - n = a.count(axis) - mm = (ma.minimum.reduce(a), ma.maximum.reduce(a)) - m = a.mean(axis) - v = a.var(axis) - sk = skew(a, axis) - kurt = kurtosis(a, axis) - return n, mm, m, v, sk, kurt - -#............................................................................. -def stde_median(data, axis=None): - """Returns the McKean-Schrader estimate of the standard error of the sample -median along the given axis. masked values are discarded. - - Parameters - ---------- - data : ndarray - Data to trim. - axis : {None,int} optional - Axis along which to perform the trimming. - If None, the input array is first flattened. - - """ - def _stdemed_1D(data): - data = np.sort(data.compressed()) - n = len(sorted) - z = 2.5758293035489004 - k = int(np.round((n+1)/2. - z * np.sqrt(n/4.),0)) - return ((data[n-k] - data[k-1])/(2.*z)) - # - data = ma.array(data, copy=False, subok=True) - if (axis is None): - return _stdemed_1D(data) - else: - assert data.ndim <= 2, "Array should be 2D at most !" - return ma.apply_along_axis(_stdemed_1D, axis, data) - -#####-------------------------------------------------------------------------- -#---- --- Normality Tests --- -#####-------------------------------------------------------------------------- - -def skewtest(a, axis=0): - a, axis = _chk_asarray(a, axis) - if axis is None: - a = a.ravel() - axis = 0 - b2 = skew(a,axis) - n = a.count(axis) - if np.min(n) < 8: - warnings.warn( - "skewtest only valid for n>=8 ... continuing anyway, n=%i" % - np.min(n)) - y = b2 * ma.sqrt(((n+1)*(n+3)) / (6.0*(n-2)) ) - beta2 = ( 3.0*(n*n+27*n-70)*(n+1)*(n+3) ) / ( (n-2.0)*(n+5)*(n+7)*(n+9) ) - W2 = -1 + ma.sqrt(2*(beta2-1)) - delta = 1/ma.sqrt(0.5*ma.log(W2)) - alpha = ma.sqrt(2.0/(W2-1)) - y = ma.where(y==0, 1, y) - Z = delta*ma.log(y/alpha + ma.sqrt((y/alpha)**2+1)) - return Z, (1.0 - stats.zprob(Z))*2 -skewtest.__doc__ = stats.skewtest.__doc__ - -def kurtosistest(a, axis=0): - a, axis = _chk_asarray(a, axis) - n = a.count(axis=axis).astype(float) - if np.min(n) < 20: - warnings.warn( - "kurtosistest only valid for n>=20 ... continuing anyway, n=%i" % - np.min(n)) - b2 = kurtosis(a, axis, fisher=False) - E = 3.0*(n-1) /(n+1) - varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1)*(n+3)*(n+5)) - x = (b2-E)/ma.sqrt(varb2) - sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5))/ - (n*(n-2)*(n-3))) - A = 6.0 + 8.0/sqrtbeta1 *(2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2))) - term1 = 1 - 2./(9.0*A) - denom = 1 + x*ma.sqrt(2/(A-4.0)) - denom[denom < 0] = masked - term2 = ma.power((1-2.0/A)/denom,1/3.0) - Z = ( term1 - term2 ) / np.sqrt(2/(9.0*A)) - return Z, (1.0-stats.zprob(Z))*2 -kurtosistest.__doc__ = stats.kurtosistest.__doc__ - - -def normaltest(a, axis=0): - a, axis = _chk_asarray(a, axis) - s,_ = skewtest(a,axis) - k,_ = kurtosistest(a,axis) - k2 = s*s + k*k - return k2, stats.chisqprob(k2,2) -normaltest.__doc__ = stats.normaltest.__doc__ - -# Martinez-Iglewicz test -# K-S test - - -#####-------------------------------------------------------------------------- -#---- --- Percentiles --- -#####-------------------------------------------------------------------------- - - -def mquantiles(data, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, - limit=()): - """Computes empirical quantiles for a *1xN* data array. -Samples quantile are defined by: -*Q(p) = (1-g).x[i] +g.x[i+1]* -where *x[j]* is the jth order statistic, -with *i = (floor(n*p+m))*, *m=alpha+p*(1-alpha-beta)* and *g = n*p + m - i)*. - -Typical values of (alpha,beta) are: - - - (0,1) : *p(k) = k/n* : linear interpolation of cdf (R, type 4) - - (.5,.5) : *p(k) = (k+1/2.)/n* : piecewise linear function (R, type 5) - - (0,0) : *p(k) = k/(n+1)* : (R type 6) - - (1,1) : *p(k) = (k-1)/(n-1)*. In this case, p(k) = mode[F(x[k])]. - That's R default (R type 7) - - (1/3,1/3): *p(k) = (k-1/3)/(n+1/3)*. Then p(k) ~ median[F(x[k])]. - The resulting quantile estimates are approximately median-unbiased - regardless of the distribution of x. (R type 8) - - (3/8,3/8): *p(k) = (k-3/8)/(n+1/4)*. Blom. - The resulting quantile estimates are approximately unbiased - if x is normally distributed (R type 9) - - (.4,.4) : approximately quantile unbiased (Cunnane) - - (.35,.35): APL, used with PWM - -Parameters ----------- - x : sequence - Input data, as a sequence or array of dimension at most 2. - prob : sequence - List of quantiles to compute. - alpha : {0.4, float} optional - Plotting positions parameter. - beta : {0.4, float} optional - Plotting positions parameter. - axis : {None, int} optional - Axis along which to perform the trimming. - If None, the input array is first flattened. - limit : tuple - Tuple of (lower, upper) values. Values of a outside this closed interval - are ignored. - """ - def _quantiles1D(data,m,p): - x = np.sort(data.compressed()) - n = len(x) - if n == 0: - return ma.array(np.empty(len(p), dtype=float), mask=True) - elif n == 1: - return ma.array(np.resize(x, p.shape), mask=nomask) - aleph = (n*p + m) - k = np.floor(aleph.clip(1, n-1)).astype(int) - gamma = (aleph-k).clip(0,1) - return (1.-gamma)*x[(k-1).tolist()] + gamma*x[k.tolist()] - - # Initialization & checks --------- - data = ma.array(data, copy=False) - if limit: - condition = (limit[0] 100.): - raise ValueError("The percentile should be between 0. and 100. !"\ - " (got %s)" % per) - return mquantiles(data, prob=[per/100.], alphap=alphap, betap=betap, - limit=limit, axis=0).squeeze() - - -def plotting_positions(data, alpha=0.4, beta=0.4): - """Returns the plotting positions (or empirical percentile points) for the - data. - Plotting positions are defined as (i-alpha)/(n-alpha-beta), where: - - i is the rank order statistics - - n is the number of unmasked values along the given axis - - alpha and beta are two parameters. - - Typical values for alpha and beta are: - - (0,1) : *p(k) = k/n* : linear interpolation of cdf (R, type 4) - - (.5,.5) : *p(k) = (k-1/2.)/n* : piecewise linear function (R, type 5) - - (0,0) : *p(k) = k/(n+1)* : Weibull (R type 6) - - (1,1) : *p(k) = (k-1)/(n-1)*. In this case, p(k) = mode[F(x[k])]. - That's R default (R type 7) - - (1/3,1/3): *p(k) = (k-1/3)/(n+1/3)*. Then p(k) ~ median[F(x[k])]. - The resulting quantile estimates are approximately median-unbiased - regardless of the distribution of x. (R type 8) - - (3/8,3/8): *p(k) = (k-3/8)/(n+1/4)*. Blom. - The resulting quantile estimates are approximately unbiased - if x is normally distributed (R type 9) - - (.4,.4) : approximately quantile unbiased (Cunnane) - - (.35,.35): APL, used with PWM - -Parameters ----------- - x : sequence - Input data, as a sequence or array of dimension at most 2. - prob : sequence - List of quantiles to compute. - alpha : {0.4, float} optional - Plotting positions parameter. - beta : {0.4, float} optional - Plotting positions parameter. - - """ - data = ma.array(data, copy=False).reshape(1,-1) - n = data.count() - plpos = np.empty(data.size, dtype=float) - plpos[n:] = 0 - plpos[data.argsort()[:n]] = (np.arange(1,n+1) - alpha)/(n+1-alpha-beta) - return ma.array(plpos, mask=data._mask) - -meppf = plotting_positions - -#####-------------------------------------------------------------------------- -#---- --- Variability --- -#####-------------------------------------------------------------------------- - -def obrientransform(*args): - """ -Computes a transform on input data (any number of columns). Used to -test for homogeneity of variance prior to running one-way stats. Each -array in *args is one level of a factor. If an F_oneway() run on the -transformed data and found significant, variances are unequal. From -Maxwell and Delaney, p.112. - -Returns: transformed data for use in an ANOVA - """ - data = argstoarray(*args).T - v = data.var(axis=0,ddof=1) - m = data.mean(0) - n = data.count(0).astype(float) - # result = ((N-1.5)*N*(a-m)**2 - 0.5*v*(n-1))/((n-1)*(n-2)) - data -= m - data **= 2 - data *= (n-1.5)*n - data -= 0.5*v*(n-1) - data /= (n-1.)*(n-2.) - if not ma.allclose(v,data.mean(0)): - raise ValueError("Lack of convergence in obrientransform.") - return data - - -def signaltonoise(data, axis=0): - """Calculates the signal-to-noise ratio, as the ratio of the mean over - standard deviation along the given axis. - - Parameters - ---------- - data : sequence - Input data - axis : {0, int} optional - Axis along which to compute. If None, the computation is performed - on a flat version of the array. -""" - data = ma.array(data, copy=False) - m = data.mean(axis) - sd = data.std(axis, ddof=0) - return m/sd - - -def samplevar(data, axis=0): - """Returns a biased estimate of the variance of the data, as the average - of the squared deviations from the mean. - - Parameters - ---------- - data : sequence - Input data - axis : {0, int} optional - Axis along which to compute. If None, the computation is performed - on a flat version of the array. - """ - return ma.asarray(data).var(axis=axis,ddof=0) - - -def samplestd(data, axis=0): - """Returns a biased estimate of the standard deviation of the data, as the - square root of the average squared deviations from the mean. - - Parameters - ---------- - data : sequence - Input data - axis : {0,int} optional - Axis along which to compute. If None, the computation is performed - on a flat version of the array. - - Notes - ----- - samplestd(a) is equivalent to a.std(ddof=0) - - """ - return ma.asarray(data).std(axis=axis,ddof=0) - - -def var(a,axis=None): - return ma.asarray(a).var(axis=axis,ddof=1) -var.__doc__ = stats.var.__doc__ - -def std(a,axis=None): - return ma.asarray(a).std(axis=axis,ddof=1) -std.__doc__ = stats.std.__doc__ - -def stderr(a, axis=0): - a, axis = _chk_asarray(a, axis) - return a.std(axis=axis, ddof=1) / ma.sqrt(a.count(axis=axis)) -stderr.__doc__ = stats.stderr.__doc__ - -def sem(a, axis=0): - a, axis = _chk_asarray(a, axis) - n = a.count(axis=axis) - s = a.std(axis=axis,ddof=0) / ma.sqrt(n-1) - return s -sem.__doc__ = stats.sem.__doc__ - -def z(a, score): - a = ma.asarray(a) - z = (score-a.mean(None)) / a.std(axis=None, ddof=1) - return z -z.__doc__ = stats.z.__doc__ - -def zs(a): - a = ma.asarray(a) - mu = a.mean(axis=0) - sigma = a.std(axis=0,ddof=0) - return (a-mu)/sigma -zs.__doc__ = stats.zs.__doc__ - -def zmap(scores, compare, axis=0): - (scores, compare) = (ma.asarray(scores), ma.asarray(compare)) - mns = compare.mean(axis=axis) - sstd = compare.std(axis=0, ddof=0) - return (scores - mns) / sstd -zmap.__doc__ = stats.zmap.__doc__ - - -#####-------------------------------------------------------------------------- -#---- --- ANOVA --- -#####-------------------------------------------------------------------------- - - -def f_oneway(*args): - """ -Performs a 1-way ANOVA, returning an F-value and probability given -any number of groups. From Heiman, pp.394-7. - -Usage: f_oneway (*args) where *args is 2 or more arrays, one per - treatment group -Returns: f-value, probability -""" - # Construct a single array of arguments: each row is a group - data = argstoarray(*args) - ngroups = len(data) - ntot = data.count() - sstot = (data**2).sum() - (data.sum())**2/float(ntot) - ssbg = (data.count(-1) * (data.mean(-1)-data.mean())**2).sum() - sswg = sstot-ssbg - dfbg = ngroups-1 - dfwg = ntot - ngroups - msb = ssbg/float(dfbg) - msw = sswg/float(dfwg) - f = msb/msw - prob = stats.fprob(dfbg,dfwg,f) - return f, prob - - -def f_value_wilks_lambda(ER, EF, dfnum, dfden, a, b): - """Calculation of Wilks lambda F-statistic for multivarite data, per - Maxwell & Delaney p.657. - """ - ER = ma.array(ER, copy=False, ndmin=2) - EF = ma.array(EF, copy=False, ndmin=2) - if ma.getmask(ER).any() or ma.getmask(EF).any(): - raise NotImplementedError("Not implemented when the inputs "\ - "have missing data") - lmbda = np.linalg.det(EF) / np.linalg.det(ER) - q = ma.sqrt( ((a-1)**2*(b-1)**2 - 2) / ((a-1)**2 + (b-1)**2 -5) ) - q = ma.filled(q, 1) - n_um = (1 - lmbda**(1.0/q))*(a-1)*(b-1) - d_en = lmbda**(1.0/q) / (n_um*q - 0.5*(a-1)*(b-1) + 1) - return n_um / d_en - - - -def friedmanchisquare(*args): - """Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. - This function calculates the Friedman Chi-square test for repeated measures - and returns the result, along with the associated probability value. - - Each input is considered a given group. Ideally, the number of treatments - among each group should be equal. If this is not the case, only the first - n treatments are taken into account, where n is the number of treatments - of the smallest group. - If a group has some missing values, the corresponding treatments are masked - in the other groups. - The test statistic is corrected for ties. - - Masked values in one group are propagated to the other groups. - - Returns: chi-square statistic, associated p-value - """ - data = argstoarray(*args).astype(float) - k = len(data) - if k < 3: - raise ValueError("Less than 3 groups (%i): " % k +\ - "the Friedman test is NOT appropriate.") - ranked = ma.masked_values(rankdata(data, axis=0), 0) - if ranked._mask is not nomask: - ranked = ma.mask_cols(ranked) - ranked = ranked.compressed().reshape(k,-1).view(ndarray) - else: - ranked = ranked._data - (k,n) = ranked.shape - # Ties correction - repeats = np.array([find_repeats(_) for _ in ranked.T], dtype=object) - ties = repeats[repeats.nonzero()].reshape(-1,2)[:,-1].astype(int) - tie_correction = 1 - (ties**3-ties).sum()/float(n*(k**3-k)) - # - ssbg = np.sum((ranked.sum(-1) - n*(k+1)/2.)**2) - chisq = ssbg * 12./(n*k*(k+1)) * 1./tie_correction - return chisq, stats.chisqprob(chisq,k-1) - -#-############################################################################-# Copied: trunk/scipy/stats/mstats_basic.py (from rev 5134, trunk/scipy/stats/mstats.py) Copied: trunk/scipy/stats/mstats_extras.py (from rev 5134, trunk/scipy/stats/mmorestats.py) Deleted: trunk/scipy/stats/tests/test_mmorestats.py =================================================================== --- trunk/scipy/stats/tests/test_mmorestats.py 2008-11-21 21:09:29 UTC (rev 5159) +++ trunk/scipy/stats/tests/test_mmorestats.py 2008-11-22 05:26:45 UTC (rev 5160) @@ -1,102 +0,0 @@ -# pylint: disable-msg=W0611, W0612, W0511,R0201 -"""Tests suite for maskedArray statistics. - -:author: Pierre Gerard-Marchant -:contact: pierregm_at_uga_dot_edu -""" -__author__ = "Pierre GF Gerard-Marchant ($Author: backtopop $)" - -import numpy as np - -import numpy.ma as ma - -import scipy.stats.mstats as ms -import scipy.stats.mmorestats as mms - -from numpy.testing import * - - -class TestMisc(TestCase): - # - def __init__(self, *args, **kwargs): - TestCase.__init__(self, *args, **kwargs) - # - def test_mjci(self): - "Tests the Marits-Jarrett estimator" - data = ma.array([ 77, 87, 88,114,151,210,219,246,253,262, - 296,299,306,376,428,515,666,1310,2611]) - assert_almost_equal(mms.mjci(data),[55.76819,45.84028,198.87875],5) - # - def test_trimmedmeanci(self): - "Tests the confidence intervals of the trimmed mean." - data = ma.array([545,555,558,572,575,576,578,580, - 594,605,635,651,653,661,666]) - assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1) - assert_equal(np.round(mms.trimmed_mean_ci(data,(0.2,0.2)),1), - [561.8, 630.6]) - # - def test_idealfourths(self): - "Tests ideal-fourths" - test = np.arange(100) - assert_almost_equal(np.asarray(mms.idealfourths(test)), - [24.416667,74.583333],6) - test_2D = test.repeat(3).reshape(-1,3) - assert_almost_equal(mms.idealfourths(test_2D, axis=0), - [[24.416667,24.416667,24.416667], - [74.583333,74.583333,74.583333]],6) - assert_almost_equal(mms.idealfourths(test_2D, axis=1), - test.repeat(2).reshape(-1,2)) - test = [0,0] - _result = mms.idealfourths(test) - assert(np.isnan(_result).all()) - -#.............................................................................. -class TestQuantiles(TestCase): - # - def __init__(self, *args, **kwargs): - TestCase.__init__(self, *args, **kwargs) - # - def test_hdquantiles(self): - data = [0.706560797,0.727229578,0.990399276,0.927065621,0.158953014, - 0.887764025,0.239407086,0.349638551,0.972791145,0.149789972, - 0.936947700,0.132359948,0.046041972,0.641675031,0.945530547, - 0.224218684,0.771450991,0.820257774,0.336458052,0.589113496, - 0.509736129,0.696838829,0.491323573,0.622767425,0.775189248, - 0.641461450,0.118455200,0.773029450,0.319280007,0.752229111, - 0.047841438,0.466295911,0.583850781,0.840581845,0.550086491, - 0.466470062,0.504765074,0.226855960,0.362641207,0.891620942, - 0.127898691,0.490094097,0.044882048,0.041441695,0.317976349, - 0.504135618,0.567353033,0.434617473,0.636243375,0.231803616, - 0.230154113,0.160011327,0.819464108,0.854706985,0.438809221, - 0.487427267,0.786907310,0.408367937,0.405534192,0.250444460, - 0.995309248,0.144389588,0.739947527,0.953543606,0.680051621, - 0.388382017,0.863530727,0.006514031,0.118007779,0.924024803, - 0.384236354,0.893687694,0.626534881,0.473051932,0.750134705, - 0.241843555,0.432947602,0.689538104,0.136934797,0.150206859, - 0.474335206,0.907775349,0.525869295,0.189184225,0.854284286, - 0.831089744,0.251637345,0.587038213,0.254475554,0.237781276, - 0.827928620,0.480283781,0.594514455,0.213641488,0.024194386, - 0.536668589,0.699497811,0.892804071,0.093835427,0.731107772] - # - assert_almost_equal(mms.hdquantiles(data,[0., 1.]), - [0.006514031, 0.995309248]) - hdq = mms.hdquantiles(data,[0.25, 0.5, 0.75]) - assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,]) - hdq = mms.hdquantiles_sd(data,[0.25, 0.5, 0.75]) - assert_almost_equal(hdq, [0.03786954, 0.03805389, 0.03800152,], 4) - # - data = np.array(data).reshape(10,10) - hdq = mms.hdquantiles(data,[0.25,0.5,0.75],axis=0) - assert_almost_equal(hdq[:,0], mms.hdquantiles(data[:,0],[0.25,0.5,0.75])) - assert_almost_equal(hdq[:,-1], mms.hdquantiles(data[:,-1],[0.25,0.5,0.75])) - hdq = mms.hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True) - assert_almost_equal(hdq[...,0], - mms.hdquantiles(data[:,0],[0.25,0.5,0.75],var=True)) - assert_almost_equal(hdq[...,-1], - mms.hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True)) - - -############################################################################### - -if __name__ == "__main__": - run_module_suite() Deleted: trunk/scipy/stats/tests/test_mstats.py =================================================================== --- trunk/scipy/stats/tests/test_mstats.py 2008-11-21 21:09:29 UTC (rev 5159) +++ trunk/scipy/stats/tests/test_mstats.py 2008-11-22 05:26:45 UTC (rev 5160) @@ -1,509 +0,0 @@ -""" -Tests for the stats.mstats module (support for maskd arrays) -""" - - -import numpy as np -from numpy import nan -import numpy.ma as ma -from numpy.ma import masked, nomask - -import scipy.stats.mstats as mstats -from numpy.testing import * -from numpy.ma.testutils import assert_equal, assert_almost_equal, \ - assert_array_almost_equal - - -class TestGMean(TestCase): - def test_1D(self): - a = (1,2,3,4) - actual= mstats.gmean(a) - desired = np.power(1*2*3*4,1./4.) - assert_almost_equal(actual, desired,decimal=14) - - desired1 = mstats.gmean(a,axis=-1) - assert_almost_equal(actual, desired1, decimal=14) - assert not isinstance(desired1, ma.MaskedArray) - # - a = ma.array((1,2,3,4),mask=(0,0,0,1)) - actual= mstats.gmean(a) - desired = np.power(1*2*3,1./3.) - assert_almost_equal(actual, desired,decimal=14) - - desired1 = mstats.gmean(a,axis=-1) - assert_almost_equal(actual, desired1, decimal=14) - # - def test_2D(self): - a = ma.array(((1,2,3,4),(1,2,3,4),(1,2,3,4)), - mask=((0,0,0,0),(1,0,0,1),(0,1,1,0))) - actual= mstats.gmean(a) - desired = np.array((1,2,3,4)) - assert_array_almost_equal(actual, desired, decimal=14) - # - desired1 = mstats.gmean(a,axis=0) - assert_array_almost_equal(actual, desired1, decimal=14) - # - actual= mstats.gmean(a, -1) - desired = ma.array((np.power(1*2*3*4,1./4.), - np.power(2*3,1./2.), - np.power(1*4,1./2.))) - assert_array_almost_equal(actual, desired, decimal=14) - -class TestHMean(TestCase): - def test_1D(self): - a = (1,2,3,4) - actual= mstats.hmean(a) - desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) - assert_almost_equal(actual, desired, decimal=14) - desired1 = mstats.hmean(ma.array(a),axis=-1) - assert_almost_equal(actual, desired1, decimal=14) - # - a = ma.array((1,2,3,4),mask=(0,0,0,1)) - actual= mstats.hmean(a) - desired = 3. / (1./1 + 1./2 + 1./3) - assert_almost_equal(actual, desired,decimal=14) - desired1 = mstats.hmean(a,axis=-1) - assert_almost_equal(actual, desired1, decimal=14) - - def test_2D(self): - a = ma.array(((1,2,3,4),(1,2,3,4),(1,2,3,4)), - mask=((0,0,0,0),(1,0,0,1),(0,1,1,0))) - actual= mstats.hmean(a) - desired = ma.array((1,2,3,4)) - assert_array_almost_equal(actual, desired, decimal=14) - # - actual1 = mstats.hmean(a,axis=-1) - desired = (4./(1/1.+1/2.+1/3.+1/4.), - 2./(1/2.+1/3.), - 2./(1/1.+1/4.) - ) - assert_array_almost_equal(actual1, desired, decimal=14) - - -class TestRanking(TestCase): - # - def __init__(self, *args, **kwargs): - TestCase.__init__(self, *args, **kwargs) - # - def test_ranking(self): - x = ma.array([0,1,1,1,2,3,4,5,5,6,]) - assert_almost_equal(mstats.rankdata(x),[1,3,3,3,5,6,7,8.5,8.5,10]) - x[[3,4]] = masked - assert_almost_equal(mstats.rankdata(x),[1,2.5,2.5,0,0,4,5,6.5,6.5,8]) - assert_almost_equal(mstats.rankdata(x,use_missing=True), - [1,2.5,2.5,4.5,4.5,4,5,6.5,6.5,8]) - x = ma.array([0,1,5,1,2,4,3,5,1,6,]) - assert_almost_equal(mstats.rankdata(x),[1,3,8.5,3,5,7,6,8.5,3,10]) - x = ma.array([[0,1,1,1,2], [3,4,5,5,6,]]) - assert_almost_equal(mstats.rankdata(x),[[1,3,3,3,5],[6,7,8.5,8.5,10]]) - assert_almost_equal(mstats.rankdata(x,axis=1),[[1,3,3,3,5],[1,2,3.5,3.5,5]]) - assert_almost_equal(mstats.rankdata(x,axis=0),[[1,1,1,1,1],[2,2,2,2,2,]]) - - -class TestCorr(TestCase): - # - def test_pearsonr(self): - "Tests some computations of Pearson's r" - x = ma.arange(10) - assert_almost_equal(mstats.pearsonr(x,x)[0], 1.0) - assert_almost_equal(mstats.pearsonr(x,x[::-1])[0], -1.0) - # - x = ma.array(x, mask=True) - pr = mstats.pearsonr(x,x) - assert(pr[0] is masked) - assert(pr[1] is masked) - # - def test_spearmanr(self): - "Tests some computations of Spearman's rho" - (x, y) = ([5.05,6.75,3.21,2.66],[1.65,2.64,2.64,6.95]) - assert_almost_equal(mstats.spearmanr(x,y)[0], -0.6324555) - (x, y) = ([5.05,6.75,3.21,2.66,np.nan],[1.65,2.64,2.64,6.95,np.nan]) - (x, y) = (ma.fix_invalid(x), ma.fix_invalid(y)) - assert_almost_equal(mstats.spearmanr(x,y)[0], -0.6324555) - # - x = [ 2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1, - 1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7] - y = [22.6, 08.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6, - 0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4] - assert_almost_equal(mstats.spearmanr(x,y)[0], 0.6887299) - x = [ 2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1, - 1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7, np.nan] - y = [22.6, 08.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6, - 0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4, np.nan] - (x, y) = (ma.fix_invalid(x), ma.fix_invalid(y)) - assert_almost_equal(mstats.spearmanr(x,y)[0], 0.6887299) - # - def test_kendalltau(self): - "Tests some computations of Kendall's tau" - x = ma.fix_invalid([5.05, 6.75, 3.21, 2.66,np.nan]) - y = ma.fix_invalid([1.65, 26.5, -5.93, 7.96, np.nan]) - z = ma.fix_invalid([1.65, 2.64, 2.64, 6.95, np.nan]) - assert_almost_equal(np.asarray(mstats.kendalltau(x,y)), - [+0.3333333,0.4969059]) - assert_almost_equal(np.asarray(mstats.kendalltau(x,z)), - [-0.5477226,0.2785987]) - # - x = ma.fix_invalid([ 0, 0, 0, 0,20,20, 0,60, 0,20, - 10,10, 0,40, 0,20, 0, 0, 0, 0, 0, np.nan]) - y = ma.fix_invalid([ 0,80,80,80,10,33,60, 0,67,27, - 25,80,80,80,80,80,80, 0,10,45, np.nan, 0]) - result = mstats.kendalltau(x,y) - assert_almost_equal(np.asarray(result), [-0.1585188, 0.4128009]) - # - def test_kendalltau_seasonal(self): - "Tests the seasonal Kendall tau." - x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], - [ 4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], - [ 3, 2, 5, 6, 18, 4, 9, 1, 1,nan, 1, 1,nan], - [nan, 6, 11, 4, 17,nan, 6, 1, 1, 2, 5, 1, 1]] - x = ma.fix_invalid(x).T - output = mstats.kendalltau_seasonal(x) - assert_almost_equal(output['global p-value (indep)'], 0.008, 3) - assert_almost_equal(output['seasonal p-value'].round(2), - [0.18,0.53,0.20,0.04]) - # - def test_pointbiserial(self): - "Tests point biserial" - x = [1,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0, - 0,0,0,0,1,-1] - y = [14.8,13.8,12.4,10.1,7.1,6.1,5.8,4.6,4.3,3.5,3.3,3.2,3.0, - 2.8,2.8,2.5,2.4,2.3,2.1,1.7,1.7,1.5,1.3,1.3,1.2,1.2,1.1, - 0.8,0.7,0.6,0.5,0.2,0.2,0.1,np.nan] - assert_almost_equal(mstats.pointbiserialr(x, y)[0], 0.36149, 5) - # - def test_cov(self): - "Tests the cov function." - x = ma.array([[1,2,3],[4,5,6]], mask=[[1,0,0],[0,0,0]]) - c = mstats.cov(x[0]) - assert_equal(c, x[0].var(ddof=1)) - c = mstats.cov(x[1]) - assert_equal(c, x[1].var(ddof=1)) - c = mstats.cov(x) - assert_equal(c[1,0], (x[0].anom()*x[1].anom()).sum()) - # - x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], - [ 4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], - [ 3, 2, 5, 6, 18, 4, 9, 1, 1,nan, 1, 1,nan], - [nan, 6, 11, 4, 17,nan, 6, 1, 1, 2, 5, 1, 1]] - x = ma.fix_invalid(x).T - (winter,spring,summer,fall) = x.T - # - assert_almost_equal(mstats.cov(winter,winter,bias=True), - winter.var(ddof=0)) - assert_almost_equal(mstats.cov(winter,winter,bias=False), - winter.var(ddof=1)) - assert_almost_equal(mstats.cov(winter,spring)[0,1], 7.7) - assert_almost_equal(mstats.cov(winter,spring)[1,0], 7.7) - assert_almost_equal(mstats.cov(winter,summer)[0,1], 19.1111111, 7) - assert_almost_equal(mstats.cov(winter,summer)[1,0], 19.1111111, 7) - assert_almost_equal(mstats.cov(winter,fall)[0,1], 20) - assert_almost_equal(mstats.cov(winter,fall)[1,0], 20) - - -class TestTrimming(TestCase): - # - def test_trim(self): - "Tests trimming" - a = ma.arange(10) - assert_equal(mstats.trim(a), [0,1,2,3,4,5,6,7,8,9]) - a = ma.arange(10) - assert_equal(mstats.trim(a,(2,8)), [None,None,2,3,4,5,6,7,8,None]) - a = ma.arange(10) - assert_equal(mstats.trim(a,limits=(2,8),inclusive=(False,False)), - [None,None,None,3,4,5,6,7,None,None]) - a = ma.arange(10) - assert_equal(mstats.trim(a,limits=(0.1,0.2),relative=True), - [None,1,2,3,4,5,6,7,None,None]) - # - a = ma.arange(12) - a[[0,-1]] = a[5] = masked - assert_equal(mstats.trim(a,(2,8)), - [None,None,2,3,4,None,6,7,8,None,None,None]) - # - x = ma.arange(100).reshape(10,10) - trimx = mstats.trim(x,(0.1,0.2),relative=True,axis=None) - assert_equal(trimx._mask.ravel(),[1]*10+[0]*70+[1]*20) - trimx = mstats.trim(x,(0.1,0.2),relative=True,axis=0) - assert_equal(trimx._mask.ravel(),[1]*10+[0]*70+[1]*20) - trimx = mstats.trim(x,(0.1,0.2),relative=True,axis=-1) - assert_equal(trimx._mask.T.ravel(),[1]*10+[0]*70+[1]*20) - # - x = ma.arange(110).reshape(11,10) - x[1] = masked - trimx = mstats.trim(x,(0.1,0.2),relative=True,axis=None) - assert_equal(trimx._mask.ravel(),[1]*20+[0]*70+[1]*20) - trimx = mstats.trim(x,(0.1,0.2),relative=True,axis=0) - assert_equal(trimx._mask.ravel(),[1]*20+[0]*70+[1]*20) - trimx = mstats.trim(x.T,(0.1,0.2),relative=True,axis=-1) - assert_equal(trimx.T._mask.ravel(),[1]*20+[0]*70+[1]*20) - # - def test_trim_old(self): - "Tests trimming." - x = ma.arange(100) - assert_equal(mstats.trimboth(x).count(), 60) - assert_equal(mstats.trimtail(x,tail='r').count(), 80) - x[50:70] = masked - trimx = mstats.trimboth(x) - assert_equal(trimx.count(), 48) - assert_equal(trimx._mask, [1]*16 + [0]*34 + [1]*20 + [0]*14 + [1]*16) - x._mask = nomask - x.shape = (10,10) - assert_equal(mstats.trimboth(x).count(), 60) - assert_equal(mstats.trimtail(x).count(), 80) - # - def test_trimmedmean(self): - "Tests the trimmed mean." - data = ma.array([ 77, 87, 88,114,151,210,219,246,253,262, - 296,299,306,376,428,515,666,1310,2611]) - assert_almost_equal(mstats.trimmed_mean(data,0.1), 343, 0) - assert_almost_equal(mstats.trimmed_mean(data,(0.1,0.1)), 343, 0) - assert_almost_equal(mstats.trimmed_mean(data,(0.2,0.2)), 283, 0) - # - def test_trimmed_stde(self): - "Tests the trimmed mean standard error." - data = ma.array([ 77, 87, 88,114,151,210,219,246,253,262, - 296,299,306,376,428,515,666,1310,2611]) - assert_almost_equal(mstats.trimmed_stde(data,(0.2,0.2)), 56.13193, 5) - assert_almost_equal(mstats.trimmed_stde(data,0.2), 56.13193, 5) - # - def test_winsorization(self): - "Tests the Winsorization of the data." - data = ma.array([ 77, 87, 88,114,151,210,219,246,253,262, - 296,299,306,376,428,515,666,1310,2611]) - assert_almost_equal(mstats.winsorize(data,(0.2,0.2)).var(ddof=1), - 21551.4, 1) - data[5] = masked - winsorized = mstats.winsorize(data) - assert_equal(winsorized.mask, data.mask) - - -class TestMoments(TestCase): - """ - Comparison numbers are found using R v.1.5.1 - note that length(testcase) = 4 - testmathworks comes from documentation for the - Statistics Toolbox for Matlab and can be found at both - http://www.mathworks.com/access/helpdesk/help/toolbox/stats/kurtosis.shtml - http://www.mathworks.com/access/helpdesk/help/toolbox/stats/skewness.shtml - Note that both test cases came from here. - """ - testcase = [1,2,3,4] - testmathworks = ma.fix_invalid([1.165 , 0.6268, 0.0751, 0.3516, -0.6965, - np.nan]) - def test_moment(self): - """ - mean((testcase-mean(testcase))**power,axis=0),axis=0))**power))""" - y = mstats.moment(self.testcase,1) - assert_almost_equal(y,0.0,10) - y = mstats.moment(self.testcase,2) - assert_almost_equal(y,1.25) - y = mstats.moment(self.testcase,3) - assert_almost_equal(y,0.0) - y = mstats.moment(self.testcase,4) - assert_almost_equal(y,2.5625) - def test_variation(self): - """variation = samplestd/mean """ -## y = stats.variation(self.shoes[0]) -## assert_almost_equal(y,21.8770668) - y = mstats.variation(self.testcase) - assert_almost_equal(y,0.44721359549996, 10) - - def test_skewness(self): - """ - sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0)/((sqrt(var(testmathworks)*4/5))**3)/5 - """ - y = mstats.skew(self.testmathworks) - assert_almost_equal(y,-0.29322304336607,10) - y = mstats.skew(self.testmathworks,bias=0) - assert_almost_equal(y,-0.437111105023940,10) - y = mstats.skew(self.testcase) - assert_almost_equal(y,0.0,10) - - def test_kurtosis(self): - """ - sum((testcase-mean(testcase,axis=0))**4,axis=0)/((sqrt(var(testcase)*3/4))**4)/4 - sum((test2-mean(testmathworks,axis=0))**4,axis=0)/((sqrt(var(testmathworks)*4/5))**4)/5 - Set flags for axis = 0 and - fisher=0 (Pearson's definition of kurtosis for compatibility with Matlab) - """ - y = mstats.kurtosis(self.testmathworks,0,fisher=0,bias=1) - assert_almost_equal(y, 2.1658856802973,10) - # Note that MATLAB has confusing docs for the following case - # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness - # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) - # The MATLAB docs imply that both should give Fisher's - y = mstats.kurtosis(self.testmathworks,fisher=0,bias=0) - assert_almost_equal(y, 3.663542721189047,10) - y = mstats.kurtosis(self.testcase,0,0) - assert_almost_equal(y,1.64) - # - def test_mode(self): - "Tests the mode" - # - a1 = [0,0,0,1,1,1,2,3,3,3,3,4,5,6,7] - a2 = np.reshape(a1, (3,5)) - ma1 = ma.masked_where(ma.array(a1)>2,a1) - ma2 = ma.masked_where(a2>2, a2) - assert_equal(mstats.mode(a1, axis=None), (3,4)) - assert_equal(mstats.mode(ma1, axis=None), (0,3)) - assert_equal(mstats.mode(a2, axis=None), (3,4)) - assert_equal(mstats.mode(ma2, axis=None), (0,3)) - assert_equal(mstats.mode(a2, axis=0), ([[0,0,0,1,1]],[[1,1,1,1,1]])) - assert_equal(mstats.mode(ma2, axis=0), ([[0,0,0,1,1]],[[1,1,1,1,1]])) - assert_equal(mstats.mode(a2, axis=-1), ([[0],[3],[3]], [[3],[3],[1]])) - assert_equal(mstats.mode(ma2, axis=-1), ([[0],[1],[0]], [[3],[1],[0]])) - - -class TestPercentile(TestCase): - def setUp(self): - self.a1 = [3,4,5,10,-3,-5,6] - self.a2 = [3,-6,-2,8,7,4,2,1] - self.a3 = [3.,4,5,10,-3,-5,-6,7.0] - - def test_percentile(self): - x = np.arange(8) * 0.5 - assert_equal(mstats.scoreatpercentile(x, 0), 0.) - assert_equal(mstats.scoreatpercentile(x, 100), 3.5) - assert_equal(mstats.scoreatpercentile(x, 50), 1.75) - - def test_2D(self): - x = ma.array([[1, 1, 1], - [1, 1, 1], - [4, 4, 3], - [1, 1, 1], - [1, 1, 1]]) - assert_equal(mstats.scoreatpercentile(x,50), [1,1,1]) - - -class TestVariability(TestCase): - """ Comparison numbers are found using R v.1.5.1 - note that length(testcase) = 4 - """ - testcase = ma.fix_invalid([1,2,3,4,np.nan]) - # - def test_std(self): - y = mstats.std(self.testcase) - assert_almost_equal(y,1.290994449) - - def test_var(self): - """ - var(testcase) = 1.666666667 """ - #y = stats.var(self.shoes[0]) - #assert_approx_equal(y,6.009) - y = mstats.var(self.testcase) - assert_almost_equal(y,1.666666667) - - def test_samplevar(self): - """ - R does not have 'samplevar' so the following was used - var(testcase)*(4-1)/4 where 4 = length(testcase) - """ - #y = stats.samplevar(self.shoes[0]) - #assert_approx_equal(y,5.4081) - y = mstats.samplevar(self.testcase) - assert_almost_equal(y,1.25) - - def test_samplestd(self): - #y = stats.samplestd(self.shoes[0]) - #assert_approx_equal(y,2.325532197) - y = mstats.samplestd(self.testcase) - assert_almost_equal(y,1.118033989) - - def test_signaltonoise(self): - """ - this is not in R, so used - mean(testcase,axis=0)/(sqrt(var(testcase)*3/4)) """ - #y = stats.signaltonoise(self.shoes[0]) - #assert_approx_equal(y,4.5709967) - y = mstats.signaltonoise(self.testcase) - assert_almost_equal(y,2.236067977) - - def test_stderr(self): - """ - this is not in R, so used - sqrt(var(testcase))/sqrt(4) - """ -## y = stats.stderr(self.shoes[0]) -## assert_approx_equal(y,0.775177399) - y = mstats.stderr(self.testcase) - assert_almost_equal(y,0.6454972244) - - def test_sem(self): - """ - this is not in R, so used - sqrt(var(testcase)*3/4)/sqrt(3) - """ - #y = stats.sem(self.shoes[0]) - #assert_approx_equal(y,0.775177399) - y = mstats.sem(self.testcase) - assert_almost_equal(y,0.6454972244) - - def test_z(self): - """ - not in R, so used - (10-mean(testcase,axis=0))/sqrt(var(testcase)*3/4) - """ - y = mstats.z(self.testcase, ma.array(self.testcase).mean()) - assert_almost_equal(y,0.0) - - def test_zs(self): - """ - not in R, so tested by using - (testcase[i]-mean(testcase,axis=0))/sqrt(var(testcase)*3/4) - """ - y = mstats.zs(self.testcase) - desired = ma.fix_invalid([-1.3416407864999, -0.44721359549996 , - 0.44721359549996 , 1.3416407864999, np.nan]) - assert_almost_equal(desired,y,decimal=12) - - - -class TestMisc(TestCase): - # - def test_obrientransform(self): - "Tests Obrien transform" - args = [[5]*5+[6]*11+[7]*9+[8]*3+[9]*2+[10]*2, - [6]+[7]*2+[8]*4+[9]*9+[10]*16] - result = [5*[3.1828]+11*[0.5591]+9*[0.0344]+3*[1.6086]+2*[5.2817]+2*[11.0538], - [10.4352]+2*[4.8599]+4*[1.3836]+9*[0.0061]+16*[0.7277]] - assert_almost_equal(np.round(mstats.obrientransform(*args).T,4), - result,4) - # - def test_kstwosamp(self): - "Tests the Kolmogorov-Smirnov 2 samples test" - x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], - [ 4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], - [ 3, 2, 5, 6, 18, 4, 9, 1, 1,nan, 1, 1,nan], - [nan, 6, 11, 4, 17,nan, 6, 1, 1, 2, 5, 1, 1]] - x = ma.fix_invalid(x).T - (winter,spring,summer,fall) = x.T - # - assert_almost_equal(np.round(mstats.ks_twosamp(winter,spring),4), - (0.1818,0.9892)) - assert_almost_equal(np.round(mstats.ks_twosamp(winter,spring,'g'),4), - (0.1469,0.7734)) - assert_almost_equal(np.round(mstats.ks_twosamp(winter,spring,'l'),4), - (0.1818,0.6744)) - # - def test_friedmanchisq(self): - "Tests the Friedman Chi-square test" - # No missing values - args = ([9.0,9.5,5.0,7.5,9.5,7.5,8.0,7.0,8.5,6.0], - [7.0,6.5,7.0,7.5,5.0,8.0,6.0,6.5,7.0,7.0], - [6.0,8.0,4.0,6.0,7.0,6.5,6.0,4.0,6.5,3.0]) - result = mstats.friedmanchisquare(*args) - assert_almost_equal(result[0], 10.4737, 4) - assert_almost_equal(result[1], 0.005317, 6) - # Missing values - x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1], - [ 4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3], - [ 3, 2, 5, 6, 18, 4, 9, 1, 1,nan, 1, 1,nan], - [nan, 6, 11, 4, 17,nan, 6, 1, 1, 2, 5, 1, 1]] - x = ma.fix_invalid(x) - result = mstats.friedmanchisquare(*x) - assert_almost_equal(result[0], 2.0156, 4) - assert_almost_equal(result[1], 0.5692, 4) - - -if __name__ == "__main__": - run_module_suite() Copied: trunk/scipy/stats/tests/test_mstats_basic.py (from rev 5134, trunk/scipy/stats/tests/test_mstats.py) Copied: trunk/scipy/stats/tests/test_mstats_extras.py (from rev 5134, trunk/scipy/stats/tests/test_mmorestats.py) From scipy-svn at scipy.org Sat Nov 22 00:41:10 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 23:41:10 -0600 (CST) Subject: [Scipy-svn] r5161 - in trunk/scipy/stats: . tests Message-ID: <20081122054110.06B5839C088@scipy.org> Author: josef Date: 2008-11-21 23:41:08 -0600 (Fri, 21 Nov 2008) New Revision: 5161 Modified: trunk/scipy/stats/__init__.py trunk/scipy/stats/mstats_basic.py trunk/scipy/stats/mstats_extras.py trunk/scipy/stats/tests/test_mstats_extras.py Log: add mstats to stats.__all__, correct imports Modified: trunk/scipy/stats/__init__.py =================================================================== --- trunk/scipy/stats/__init__.py 2008-11-22 05:26:45 UTC (rev 5160) +++ trunk/scipy/stats/__init__.py 2008-11-22 05:41:08 UTC (rev 5161) @@ -9,6 +9,7 @@ from rv import * from morestats import * from kde import gaussian_kde +import mstats __all__ = filter(lambda s:not s.startswith('_'),dir()) from numpy.testing import Tester Modified: trunk/scipy/stats/mstats_basic.py =================================================================== --- trunk/scipy/stats/mstats_basic.py 2008-11-22 05:26:45 UTC (rev 5160) +++ trunk/scipy/stats/mstats_basic.py 2008-11-22 05:41:08 UTC (rev 5161) @@ -13,6 +13,7 @@ __all__ = ['argstoarray', 'betai', + 'cov', # from np.ma 'chisquare','count_tied_groups', 'describe', 'f_oneway','f_value_wilks_lambda','find_repeats','friedmanchisquare', @@ -47,12 +48,13 @@ import warnings -import scipy.stats as stats +#import scipy.stats as stats +import stats import scipy.special as special import scipy.misc as misc -import scipy.stats.futil as futil +#import scipy.stats.futil as futil +import futil - genmissingvaldoc = """ Notes ----- Modified: trunk/scipy/stats/mstats_extras.py =================================================================== --- trunk/scipy/stats/mstats_extras.py 2008-11-22 05:26:45 UTC (rev 5160) +++ trunk/scipy/stats/mstats_extras.py 2008-11-22 05:41:08 UTC (rev 5161) @@ -10,7 +10,7 @@ __docformat__ = "restructuredtext en" -__all__ = ['compare_median_ms', +__all__ = ['compare_medians_ms', 'hdquantiles', 'hdmedian', 'hdquantiles_sd', 'idealfourths', 'median_cihs','mjci','mquantiles_cimj', @@ -23,7 +23,7 @@ import numpy.ma as ma from numpy.ma import MaskedArray -import scipy.stats.mstats as mstats +import mstats_basic as mstats from scipy.stats.distributions import norm, beta, t, binom Modified: trunk/scipy/stats/tests/test_mstats_extras.py =================================================================== --- trunk/scipy/stats/tests/test_mstats_extras.py 2008-11-22 05:26:45 UTC (rev 5160) +++ trunk/scipy/stats/tests/test_mstats_extras.py 2008-11-22 05:41:08 UTC (rev 5161) @@ -11,7 +11,7 @@ import numpy.ma as ma import scipy.stats.mstats as ms -import scipy.stats.mmorestats as mms +#import scipy.stats.mmorestats as mms from numpy.testing import * @@ -25,29 +25,29 @@ "Tests the Marits-Jarrett estimator" data = ma.array([ 77, 87, 88,114,151,210,219,246,253,262, 296,299,306,376,428,515,666,1310,2611]) - assert_almost_equal(mms.mjci(data),[55.76819,45.84028,198.87875],5) + assert_almost_equal(ms.mjci(data),[55.76819,45.84028,198.87875],5) # def test_trimmedmeanci(self): "Tests the confidence intervals of the trimmed mean." data = ma.array([545,555,558,572,575,576,578,580, 594,605,635,651,653,661,666]) assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1) - assert_equal(np.round(mms.trimmed_mean_ci(data,(0.2,0.2)),1), + assert_equal(np.round(ms.trimmed_mean_ci(data,(0.2,0.2)),1), [561.8, 630.6]) # def test_idealfourths(self): "Tests ideal-fourths" test = np.arange(100) - assert_almost_equal(np.asarray(mms.idealfourths(test)), + assert_almost_equal(np.asarray(ms.idealfourths(test)), [24.416667,74.583333],6) test_2D = test.repeat(3).reshape(-1,3) - assert_almost_equal(mms.idealfourths(test_2D, axis=0), + assert_almost_equal(ms.idealfourths(test_2D, axis=0), [[24.416667,24.416667,24.416667], [74.583333,74.583333,74.583333]],6) - assert_almost_equal(mms.idealfourths(test_2D, axis=1), + assert_almost_equal(ms.idealfourths(test_2D, axis=1), test.repeat(2).reshape(-1,2)) test = [0,0] - _result = mms.idealfourths(test) + _result = ms.idealfourths(test) assert(np.isnan(_result).all()) #.............................................................................. @@ -78,22 +78,22 @@ 0.827928620,0.480283781,0.594514455,0.213641488,0.024194386, 0.536668589,0.699497811,0.892804071,0.093835427,0.731107772] # - assert_almost_equal(mms.hdquantiles(data,[0., 1.]), + assert_almost_equal(ms.hdquantiles(data,[0., 1.]), [0.006514031, 0.995309248]) - hdq = mms.hdquantiles(data,[0.25, 0.5, 0.75]) + hdq = ms.hdquantiles(data,[0.25, 0.5, 0.75]) assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,]) - hdq = mms.hdquantiles_sd(data,[0.25, 0.5, 0.75]) + hdq = ms.hdquantiles_sd(data,[0.25, 0.5, 0.75]) assert_almost_equal(hdq, [0.03786954, 0.03805389, 0.03800152,], 4) # data = np.array(data).reshape(10,10) - hdq = mms.hdquantiles(data,[0.25,0.5,0.75],axis=0) - assert_almost_equal(hdq[:,0], mms.hdquantiles(data[:,0],[0.25,0.5,0.75])) - assert_almost_equal(hdq[:,-1], mms.hdquantiles(data[:,-1],[0.25,0.5,0.75])) - hdq = mms.hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True) + hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0) + assert_almost_equal(hdq[:,0], ms.hdquantiles(data[:,0],[0.25,0.5,0.75])) + assert_almost_equal(hdq[:,-1], ms.hdquantiles(data[:,-1],[0.25,0.5,0.75])) + hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True) assert_almost_equal(hdq[...,0], - mms.hdquantiles(data[:,0],[0.25,0.5,0.75],var=True)) + ms.hdquantiles(data[:,0],[0.25,0.5,0.75],var=True)) assert_almost_equal(hdq[...,-1], - mms.hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True)) + ms.hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True)) ############################################################################### From scipy-svn at scipy.org Sat Nov 22 00:48:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Fri, 21 Nov 2008 23:48:32 -0600 (CST) Subject: [Scipy-svn] r5162 - trunk/scipy/stats Message-ID: <20081122054832.B57C839C088@scipy.org> Author: josef Date: 2008-11-21 23:48:30 -0600 (Fri, 21 Nov 2008) New Revision: 5162 Added: trunk/scipy/stats/mstats.py Log: forgott to add file, for adding mstats to stats.__all__ Added: trunk/scipy/stats/mstats.py =================================================================== --- trunk/scipy/stats/mstats.py 2008-11-22 05:41:08 UTC (rev 5161) +++ trunk/scipy/stats/mstats.py 2008-11-22 05:48:30 UTC (rev 5162) @@ -0,0 +1,4 @@ + + +from mstats_basic import * +from mstats_extras import * From scipy-svn at scipy.org Sat Nov 22 01:30:21 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 00:30:21 -0600 (CST) Subject: [Scipy-svn] r5163 - trunk/scipy/stats Message-ID: <20081122063021.2692839C088@scipy.org> Author: ariel.rokem Date: 2008-11-22 00:30:18 -0600 (Sat, 22 Nov 2008) New Revision: 5163 Modified: trunk/scipy/stats/stats.py Log: Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-22 05:48:30 UTC (rev 5162) +++ trunk/scipy/stats/stats.py 2008-11-22 06:30:18 UTC (rev 5163) @@ -1014,22 +1014,51 @@ return _interpolate(values[int(idx)], values[int(idx) + 1], idx % 1) -def percentileofscore(a, score, histbins=10, defaultlimits=None): - # fixme: Again with the histogramming. This probably should be replaced by - # an empirical CDF approach. +def percentileofscore(a, score): """ -Note: result of this function depends on the values used to histogram -the data(!). - -Returns: percentile-position of score (0-100) relative to a -""" - h, lrl, binsize, extras = histogram(a,histbins,defaultlimits) - cumhist = np.cumsum(h*1, axis=0) - i = int((score - lrl)/float(binsize)) - pct = (cumhist[i-1]+((score-(lrl+binsize*i))/float(binsize))*h[i])/float(len(a)) * 100 + Percentile of a score. + + The percentile of a score is the proportion of the values in a given array equal to or + smaller than the score. + + Parameters + ----------- + a: ndarray + + score: float or int. + + Returns + ------- + pct: float (0-100), the percentile of score relative to a + + Examples + -------- + >>> percentileofscore([20,80,100],80) + 66.666666666666657 + >>>percentileofscore([20,80,100],99) + 66.666666666666657 + >>>percentileofscore([20,80,100],100) + 100.0 + >>>percentileofscore([20,80,100],1) + 0.0 + + """ + l=len(a) + a = np.array(a) + if not(any(a == score)): + a = np.append(a,score) + a_len = np.array(range(len(a))) + else: + a_len = np.array(range(len(a))) + 1.0 + + a = np.sort(a) + idx = [a == score] + pct = (np.mean(a_len[idx])/(l))*100.0 + return pct + def histogram2(a, bins): # comment: probably obsoleted by numpy.histogram() """ histogram2(a,bins) -- Compute histogram of a using divisions in bins From scipy-svn at scipy.org Sat Nov 22 03:03:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 02:03:48 -0600 (CST) Subject: [Scipy-svn] r5164 - in trunk/scipy/stats: . tests Message-ID: <20081122080348.E85FB39C088@scipy.org> Author: josef Date: 2008-11-22 02:03:44 -0600 (Sat, 22 Nov 2008) New Revision: 5164 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_stats.py Log: percentileofscore2, renamed because of committ conflict Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-22 06:30:18 UTC (rev 5163) +++ trunk/scipy/stats/stats.py 2008-11-22 08:03:44 UTC (rev 5164) @@ -1057,8 +1057,134 @@ return pct +def percentileofscore2(a, score, kind = 'mean' ): + ''' + The percentile rank of a score relative to a list of scores a. + A percentileofscore2 of, for example, 80% means that 80% of the scores in a + are below the given score. In the case of gaps or ties, the exact + definition depends on the optional kind: + "weak": This kind corresponds to the definition of a cumulative + distribution function, and means that 80% have a score lower + or equal to the given score + "strict": A percentileofscore2 of 80% means that 80% have a strictly + lower score + "mean": is the average score between "weak" and "strict" and is used in + testing + see: http://en.wikipedia.org/wiki/Percentile_rank + + + Parameters + ---------- + a: array_like + list or array of scores to which score is compared + score: int or float + score that is compared with elements in a + kind: kind/type of percentile + 'weak': percent of elements in a smaller or equal to score + 'strict': percent of elements in a strictly smaller than to score + 'mean' (default): average score between 'weak' and 'strict' + + Returns + ------- + float: percentile-position of score (0-100) relative to a + + >>> percentileofscore2([20,80,100],80) + 50.0 + >>> percentileofscore2([20,80,100],80,kind='strict') + 33.333333333333329 + >>> percentileofscore2([20,80,100],80,kind='weak') + 66.666666666666657 + >>> percentileofscore2([1,2,3,4,5,6,7,8,9,10],4) #default kind = 'mean' + 35.0 + >>> percentileofscore2([1,2,3,4,5,6,7,8,9,10],4,kind = 'strict') + 30.0 + >>> percentileofscore2([1,2,3,4,5,6,7,8,9,10],4,kind = 'weak') + 40.0 + + # multiple - 2 + >>> percentileofscore2([1,2,3,4,4,5,6,7,8,9],4,kind = 'strict') + 30.0 + >>> percentileofscore2([1,2,3,4,4,5,6,7,8,9],4,kind = 'weak') + 50.0 + >>> percentileofscore2([1,2,3,4,4,5,6,7,8,9],4,kind = 'mean') + 40.0 + + # multiple - 3 + >>> percentileofscore2([1,2,3,4,4,4,5,6,7,8],4,kind = 'mean') + 45.0 + >>> percentileofscore2([1,2,3,4,4,4,5,6,7,8],4,kind = 'strict') + 30.0 + >>> percentileofscore2([1,2,3,4,4,4,5,6,7,8],4,kind = 'weak') + 60.0 + + # missing + >>> percentileofscore2([1,2,3,5,6,7,8,9,10,11],4) + 30.0 + >>> percentileofscore2([1,2,3,5,6,7,8,9,10,11],4,kind = 'strict') + 30.0 + >>> percentileofscore2([1,2,3,5,6,7,8,9,10,11],4,kind = 'weak') + 30.0 + + #larger numbers + >>> percentileofscore2([10,20,30,40,50,60,70,80,90,100],40) + 35.0 + >>> percentileofscore2([10,20,30,40,50,60,70,80,90,100],40,kind = 'strict') + 30.0 + >>> percentileofscore2([10,20,30,40,50,60,70,80,90,100],40,kind = 'weak') + 40.0 + >>> percentileofscore2([10,20,30,40,40,40,50,60,70,80],40,kind = 'mean') + 45.0 + >>> percentileofscore2([10,20,30,40,40,40,50,60,70,80],40,kind = 'strict') + 30.0 + >>> percentileofscore2([10,20,30,40,40,40,50,60,70,80],40,kind = 'weak') + 60.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'mean') + 30.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'strict') + 30.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'weak') + 30.0 + + #boundaries + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],10) + 5.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'strict') + 0.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'weak') + 10.0 + + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],110) + 95.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'strict') + 90.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'weak') + 100.0 + + + + #out of bounds + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],200) + 100.0 + >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],0) + 0.0 + +''' + + + a=np.array(a) + n = len(a) + if kind == 'strict': + return sum(a Author: damian.eads Date: 2008-11-22 04:40:35 -0600 (Sat, 22 Nov 2008) New Revision: 5165 Modified: trunk/scipy/cluster/hierarchy.py Log: RSTifying docs in hierarchy. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-22 08:03:44 UTC (rev 5164) +++ trunk/scipy/cluster/hierarchy.py 2008-11-22 10:40:35 UTC (rev 5165) @@ -1274,60 +1274,80 @@ def fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None): """ + Forms flat clusters from the hierarchical clustering defined by + the linkage matrix ``Z``. The threshold ``t`` is a required parameter. - T = fcluster(Z, t, criterion, depth=2, R=None, monocrit=None): + :Arguments: - Forms flat clusters from the hierarchical clustering defined by - the linkage matrix Z. The threshold t is a required parameter. + - Z : ndarray + The hierarchical clustering encoded with the matrix returned + by the ``linkage`` function. - T is a vector of length n; T[i] is the flat cluster number to which - original observation i belongs. + - t : double + The threshold to apply when forming flat clusters. - The criterion parameter can be any of the following values, + - criterion : string (optional) + The criterion to use in forming flat clusters. This can + be any of the following values: - * 'inconsistent': If a cluster node and all its decendents have an - inconsistent value less than or equal to c then all its leaf - descendents belong to the same flat cluster. When no non-singleton - cluster meets this criterion, every node is assigned to its - own cluster. The depth parameter is the maximum depth to perform - the inconsistency calculation; it has no meaning for the other - criteria. + * 'inconsistent': If a cluster node and all its + decendents have an inconsistent value less than or equal + to ``t`` then all its leaf descendents belong to the + same flat cluster. When no non-singleton cluster meets + this criterion, every node is assigned to its own + cluster. (Default) - * 'distance': Forms flat clusters so that the original - observations in each flat cluster have no greater a cophenetic - distance than t. + * 'distance': Forms flat clusters so that the original + observations in each flat cluster have no greater a + cophenetic distance than ``t``. - * 'maxclust': Finds a minimum threshold r so that the cophenetic - distance between any two original observations in the same flat - cluster is no more than r and no more than t flat clusters are - formed. + * 'maxclust': Finds a minimum threshold ``r`` so that + the cophenetic distance between any two original + observations in the same flat cluster is no more than + ``r`` and no more than ``t`` flat clusters are formed. - * 'monocrit': Forms a flat cluster from a cluster node c with - index i when monocrit[j] <= t. monocrit must be monotonic. + * 'monocrit': Forms a flat cluster from a cluster node c + with index i when ``monocrit[j] <= t``. - monocrit is a (n-1) numpy vector of doubles; monocrit[i] is - the criterion upon which non-singleton i is thresholded. The - monocrit vector must be monotonic, i.e. given a node c with - index i, for all node indices j corresponding to nodes below c, - monocrit[i] >= monocrit[j]. + For example, to threshold on the maximum mean distance + as computed in the inconsistency matrix R with a + threshold of 0.8 do:: - For example, to threshold on the maximum mean distance as computed - in the inconsistency matrix R with a threshold of 0.8 do + MR = maxRstat(Z, R, 3) + cluster(Z, t=0.8, criterion='monocrit', monocrit=MR) - MR = maxRstat(Z, R, 3) - cluster(Z, t=0.8, criterion='monocrit', monocrit=MR) + * 'maxclust_monocrit': Forms a flat cluster from a + non-singleton cluster node ``c`` when ``monocrit[i] <= + r`` for all cluster indices ``i`` below and including + ``c``. ``r`` is minimized such that no more than ``t`` + flat clusters are formed. monocrit must be + monotonic. For example, to minimize the threshold t on + maximum inconsistency values so that no more than 3 flat + clusters are formed, do: - * 'maxclust_monocrit': Forms a flat cluster from a non-singleton - cluster node c when monocrit[i] <= r for all cluster indices i below - and including c. r is minimized such that no more than t flat clusters - are formed. monocrit must be monotonic. + MI = maxinconsts(Z, R) + cluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI) - For example, to minimize the threshold t on maximum inconsistency - values so that no more than 3 flat clusters are formed, do: + - depth : int (optional) + The maximum depth to perform the inconsistency calculation. + It has no meaning for the other criteria. (default=2) - MI = maxinconsts(Z, R) - cluster(Z, t=3, criterion='maxclust_monocrit', monocrit=MI) + - R : ndarray (optional) + The inconsistency matrix to use for the 'inconsistent' + criterion. This matrix is computed if not provided. + - monocrit : ndarray (optional) + A ``(n-1)`` numpy vector of doubles. ``monocrit[i]`` is the + statistics upon which non-singleton ``i`` is thresholded. The + monocrit vector must be monotonic, i.e. given a node ``c`` with + index ``i``, for all node indices j corresponding to nodes + below ``c``, ``monocrit[i] >= monocrit[j]``. + + :Returns: + + - T : ndarray + A vector of length ``n``. ``T[i]`` is the flat cluster number to + which original observation ``i`` belongs. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') @@ -1367,50 +1387,66 @@ def fclusterdata(X, t, criterion='inconsistent', \ metric='euclidean', depth=2, method='single', R=None): """ - T = fclusterdata(X, t) + ``T = fclusterdata(X, t)`` - Clusters the original observations in the n by m data matrix X - (n observations in m dimensions), using the euclidean distance - metric to calculate distances between original observations, - performs hierarchical clustering using the single linkage - algorithm, and forms flat clusters using the inconsistency - method with t as the cut-off threshold. + Clusters the original observations in the ``n`` by ``m`` data + matrix ``X`` (``n`` observations in ``m`` dimensions), using the + euclidean distance metric to calculate distances between original + observations, performs hierarchical clustering using the single + linkage algorithm, and forms flat clusters using the inconsistency + method with t as the cut-off threshold. - A one-dimensional numpy array T of length n is returned. T[i] - is the index of the flat cluster to which the original - observation i belongs. + A one-dimensional numpy array ``T`` of length ``n`` is + returned. ``T[i]`` is the index of the flat cluster to which the + original observation ``i`` belongs. - T = fclusterdata(X, t, criterion='inconsistent', method='single', - metric='euclid', depth=2, R=None) + :Arguments: - Clusters the original observations in the n by m data matrix X using - the thresholding criterion, linkage method, and distance metric - specified. + - Z : ndarray + The hierarchical clustering encoded with the matrix returned + by the ``linkage`` function. - Named parameters are described below. + - t : double + The threshold to apply when forming flat clusters. - criterion: specifies the criterion for forming flat clusters. - Valid values are 'inconsistent', 'distance', or - 'maxclust' cluster formation algorithms. See - cluster for descriptions. - method: the linkage method to use. See linkage for - descriptions. + - criterion : string + Specifies the criterion for forming flat clusters. Valid + values are 'inconsistent', 'distance', or 'maxclust' cluster + formation algorithms. See ``fcluster`` for descriptions. - metric: the distance metric for calculating pairwise - distances. See distance.pdist for descriptions and - linkage to verify compatibility with the linkage - method. + - method : string + The linkage method to use (single, complete, average, + weighted, median centroid, ward). See ``linkage`` for more + information. - t: the cut-off threshold for the cluster function or - the maximum number of clusters (criterion='maxclust'). + - metric : string + The distance metric for calculating pairwise distances. See + distance.pdist for descriptions and linkage to verify + compatibility with the linkage method. - depth: the maximum depth for the inconsistency calculation. - See inconsistent for more information. + - t : double + The cut-off threshold for the cluster function or the + maximum number of clusters (criterion='maxclust'). - R: the inconsistency matrix. It will be computed if - necessary if it is not passed. + - depth : int + The maximum depth for the inconsistency calculation. See + ``inconsistent`` for more information. + - R : ndarray + The inconsistency matrix. It will be computed if necessary + if it is not passed. + + + :Returns: + + - T : ndarray + A vector of length ``n``. ``T[i]`` is the flat cluster number to + which original observation ``i`` belongs. + + Notes + ----- + This function is similar to MATLAB(TM) clusterdata function. """ X = np.asarray(X, order='c', dtype=np.double) @@ -1429,10 +1465,19 @@ def leaves_list(Z): """ - L = leaves_list(Z): + Returns a list of leaf node ids (corresponding to observation + vector index) as they appear in the tree from left to right. Z is + a linkage matrix. - Returns a list of leaf node ids as they appear in the tree from - left to right. Z is a linkage matrix. + :Arguments: + + - Z : ndarray + The hierarchical clustering encoded as a matrix. See + ``linkage`` for more information. + + :Returns: + - L : ndarray + The list of leaf node ids. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') @@ -1651,10 +1696,14 @@ def set_link_color_palette(palette): """ - set_link_color_palette(palette): - Changes the list of matplotlib color codes to use when coloring links with the dendrogram colorthreshold feature. + + :Arguments: + - palette : A list of matplotlib color codes. The order of + the color codes is the order in which the colors are cycled + through when color thresholding in the dendrogram. + """ if type(palette) not in (types.ListType, types.TupleType): @@ -2239,8 +2288,25 @@ def is_isomorphic(T1, T2): """ - Returns True iff two different cluster assignments T1 and T2 are - equivalent. T1 and T2 must be arrays of the same size. + + Determines if two different cluster assignments ``T1`` and + ``T2`` are equivalent. + + :Arguments: + - T1 : ndarray + An assignment of singleton cluster ids to flat cluster + ids. + + - T2 : ndarray + An assignment of singleton cluster ids to flat cluster + ids. + + :Returns: + + - b : boolean + Whether the flat cluster assignments ``T1`` and ``T2`` are + equivalent. + """ T1 = np.asarray(T1, order='c') T2 = np.asarray(T2, order='c') From scipy-svn at scipy.org Sat Nov 22 09:40:48 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 08:40:48 -0600 (CST) Subject: [Scipy-svn] r5166 - in trunk/scipy/stats: . tests Message-ID: <20081122144048.0E88539C088@scipy.org> Author: josef Date: 2008-11-22 08:40:43 -0600 (Sat, 22 Nov 2008) New Revision: 5166 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_stats.py Log: merge 2 versions of percentileofscore, "rank" as default for better backwards compatibility Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-22 10:40:35 UTC (rev 5165) +++ trunk/scipy/stats/stats.py 2008-11-22 14:40:43 UTC (rev 5166) @@ -1014,61 +1014,19 @@ return _interpolate(values[int(idx)], values[int(idx) + 1], idx % 1) -def percentileofscore(a, score): - """ - Percentile of a score. - - The percentile of a score is the proportion of the values in a given array equal to or - smaller than the score. - - Parameters - ----------- - a: ndarray - - score: float or int. - - Returns - ------- - pct: float (0-100), the percentile of score relative to a - - Examples - -------- - >>> percentileofscore([20,80,100],80) - 66.666666666666657 - >>>percentileofscore([20,80,100],99) - 66.666666666666657 - >>>percentileofscore([20,80,100],100) - 100.0 - >>>percentileofscore([20,80,100],1) - 0.0 - - """ - l=len(a) - a = np.array(a) - if not(any(a == score)): - a = np.append(a,score) - a_len = np.array(range(len(a))) - else: - a_len = np.array(range(len(a))) + 1.0 - - a = np.sort(a) - idx = [a == score] - pct = (np.mean(a_len[idx])/(l))*100.0 - - return pct - -def percentileofscore2(a, score, kind = 'mean' ): +def percentileofscore(a, score, kind = 'rank' ): ''' The percentile rank of a score relative to a list of scores a. - A percentileofscore2 of, for example, 80% means that 80% of the scores in a + A percentileofscore of for example 80% means that 80% of the scores in a are below the given score. In the case of gaps or ties, the exact definition depends on the optional kind: + "rank": average percentage ranking of score "weak": This kind corresponds to the definition of a cumulative distribution function, and means that 80% have a score lower or equal to the given score - "strict": A percentileofscore2 of 80% means that 80% have a strictly + "strict": A percentileofscore of 80% means that 80% have a strictly lower score "mean": is the average score between "weak" and "strict" and is used in testing @@ -1077,97 +1035,118 @@ Parameters ---------- - a: array_like + a: array like list or array of scores to which score is compared score: int or float score that is compared with elements in a kind: kind/type of percentile + 'rank' (default): average percentile ranks of score 'weak': percent of elements in a smaller or equal to score 'strict': percent of elements in a strictly smaller than to score - 'mean' (default): average score between 'weak' and 'strict' + 'mean': average score between 'weak' and 'strict' Returns ------- float: percentile-position of score (0-100) relative to a - >>> percentileofscore2([20,80,100],80) + >>> percentileofscore([20,80,100],80) + 66.666666666666657 + >>> percentileofscore([20,80,100],80,kind='mean') 50.0 - >>> percentileofscore2([20,80,100],80,kind='strict') + >>> percentileofscore([20,80,100],80,kind='strict') 33.333333333333329 - >>> percentileofscore2([20,80,100],80,kind='weak') + >>> percentileofscore([20,80,100],80,kind='weak') 66.666666666666657 - >>> percentileofscore2([1,2,3,4,5,6,7,8,9,10],4) #default kind = 'mean' + + >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4) #default kind = 'rank + 40.0 + >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'mean') 35.0 - >>> percentileofscore2([1,2,3,4,5,6,7,8,9,10],4,kind = 'strict') + >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'strict') 30.0 - >>> percentileofscore2([1,2,3,4,5,6,7,8,9,10],4,kind = 'weak') + >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'weak') 40.0 # multiple - 2 - >>> percentileofscore2([1,2,3,4,4,5,6,7,8,9],4,kind = 'strict') + >>> percentileofscore([1,2,3,4,4,5,6,7,8,9],4) + 45.0 + >>> percentileofscore([1,2,3,4,4,5,6,7,8,9],4,kind = 'mean') + 40.0 + >>> percentileofscore([1,2,3,4,4,5,6,7,8,9],4,kind = 'strict') 30.0 - >>> percentileofscore2([1,2,3,4,4,5,6,7,8,9],4,kind = 'weak') + >>> percentileofscore([1,2,3,4,4,5,6,7,8,9],4,kind = 'weak') 50.0 - >>> percentileofscore2([1,2,3,4,4,5,6,7,8,9],4,kind = 'mean') - 40.0 + # multiple - 3 - >>> percentileofscore2([1,2,3,4,4,4,5,6,7,8],4,kind = 'mean') + >>> percentileofscore([1,2,3,4,4,4,5,6,7,8],4) + 50.0 + >>> percentileofscore([1,2,3,4,4,4,5,6,7,8],4,kind = 'mean') 45.0 - >>> percentileofscore2([1,2,3,4,4,4,5,6,7,8],4,kind = 'strict') + >>> percentileofscore([1,2,3,4,4,4,5,6,7,8],4,kind = 'strict') 30.0 - >>> percentileofscore2([1,2,3,4,4,4,5,6,7,8],4,kind = 'weak') + >>> percentileofscore([1,2,3,4,4,4,5,6,7,8],4,kind = 'weak') 60.0 # missing - >>> percentileofscore2([1,2,3,5,6,7,8,9,10,11],4) + >>> percentileofscore([1,2,3,5,6,7,8,9,10,11],4) 30.0 - >>> percentileofscore2([1,2,3,5,6,7,8,9,10,11],4,kind = 'strict') + >>> percentileofscore([1,2,3,5,6,7,8,9,10,11],4,kind = 'mean') 30.0 - >>> percentileofscore2([1,2,3,5,6,7,8,9,10,11],4,kind = 'weak') + >>> percentileofscore([1,2,3,5,6,7,8,9,10,11],4,kind = 'strict') 30.0 + >>> percentileofscore([1,2,3,5,6,7,8,9,10,11],4,kind = 'weak') + 30.0 #larger numbers - >>> percentileofscore2([10,20,30,40,50,60,70,80,90,100],40) + >>> percentileofscore([10,20,30,40,50,60,70,80,90,100],40) + 40.0 + >>> percentileofscore([10,20,30,40,50,60,70,80,90,100],40,kind = 'mean') 35.0 - >>> percentileofscore2([10,20,30,40,50,60,70,80,90,100],40,kind = 'strict') + >>> percentileofscore([10,20,30,40,50,60,70,80,90,100],40,kind = 'strict') 30.0 - >>> percentileofscore2([10,20,30,40,50,60,70,80,90,100],40,kind = 'weak') + >>> percentileofscore([10,20,30,40,50,60,70,80,90,100],40,kind = 'weak') 40.0 - >>> percentileofscore2([10,20,30,40,40,40,50,60,70,80],40,kind = 'mean') + >>> percentileofscore([10,20,30,40,40,40,50,60,70,80],40,kind = 'mean') 45.0 - >>> percentileofscore2([10,20,30,40,40,40,50,60,70,80],40,kind = 'strict') + >>> percentileofscore([10,20,30,40,40,40,50,60,70,80],40,kind = 'strict') 30.0 - >>> percentileofscore2([10,20,30,40,40,40,50,60,70,80],40,kind = 'weak') + >>> percentileofscore([10,20,30,40,40,40,50,60,70,80],40,kind = 'weak') 60.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'mean') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'rank') 30.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'strict') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'mean') 30.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'weak') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'strict') 30.0 + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],40,kind = 'weak') + 30.0 #boundaries - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],10) + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],10) + 10.0 + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'mean') 5.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'strict') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'strict') 0.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'weak') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],10,kind = 'weak') 10.0 - - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],110) + + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],110) + 100.0 + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'mean') 95.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'strict') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'strict') 90.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'weak') + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'weak') 100.0 #out of bounds - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],200) + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],200) 100.0 - >>> percentileofscore2([ 10,20,30,50,60,70,80,90,100,110],0) + >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],0) 0.0 ''' @@ -1175,14 +1154,27 @@ a=np.array(a) n = len(a) - if kind == 'strict': + + if kind == 'rank': + if not(any(a == score)): + a = np.append(a,score) + a_len = np.array(range(len(a))) + else: + a_len = np.array(range(len(a))) + 1.0 + + a = np.sort(a) + idx = [a == score] + pct = (np.mean(a_len[idx])/(n))*100.0 + return pct + + elif kind == 'strict': return sum(a Author: josef Date: 2008-11-22 10:10:16 -0600 (Sat, 22 Nov 2008) New Revision: 5167 Modified: trunk/scipy/stats/distributions.py trunk/scipy/stats/tests/test_continuous_basic.py Log: genextreme: correct _argcheck for c close to zero, allow array argument in _cdf Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-11-22 14:40:43 UTC (rev 5166) +++ trunk/scipy/stats/distributions.py 2008-11-22 16:10:16 UTC (rev 5167) @@ -14,7 +14,7 @@ from numpy import alltrue, where, arange, put, putmask, \ ravel, take, ones, sum, shape, product, repeat, reshape, \ zeros, floor, logical_and, log, sqrt, exp, arctanh, tan, sin, arcsin, \ - arctan, tanh, ndarray, cos, cosh, sinh, newaxis, array + arctan, tanh, ndarray, cos, cosh, sinh, newaxis, array, log1p, expm1 from numpy import atleast_1d, polyval, angle, ceil, place, extract, \ any, argsort, argmax, vectorize, r_, asarray, nan, inf, pi, isnan, isinf, \ power @@ -49,6 +49,8 @@ 'poisson', 'planck', 'boltzmann', 'randint', 'zipf', 'dlaplace', ] +floatinfo = numpy.finfo(float) + errp = special.errprint arr = asarray gam = special.gamma @@ -1744,7 +1746,7 @@ ## Generalized Extreme Value ## c=0 is just gumbel distribution. -## This version does not accept c==0 +## This version does now accept c==0 ## Use gumbel_r for c==0 # new version by Per Brodtkorb, see ticket:767 @@ -1753,18 +1755,23 @@ class genextreme_gen(rv_continuous): def _argcheck(self, c): - self.b = where(c > 0, 1.0 / c, inf) - self.a = where(c < 0, 1.0 / c, -inf) - return (c==c) #True #(c!=0) #see ticket:793 + min = np.minimum + max = np.maximum + sml = floatinfo.machar.xmin + #self.b = where(c > 0, 1.0 / c,inf) + #self.a = where(c < 0, 1.0 / c, -inf) + self.b = where(c > 0, 1.0 / max(c, sml),inf) + self.a = where(c < 0, 1.0 / min(c,-sml), -inf) + return where(abs(c)==inf, 0, 1) #True #(c!=0) def _pdf(self, x, c): ## ex2 = 1-c*x ## pex2 = pow(ex2,1.0/c) ## p2 = exp(-pex2)*pex2/ex2 ## return p2 cx = c*x - # Note: fit method requires that _pdf accepts vector x - logex2 = where((x==x)*(c==0),0.0,np.log1p(-cx)) - logpex2 = where((x==x)*(c==0),-x,logex2/c) + + logex2 = where((c==0)*(x==x),0.0,log1p(-cx)) + logpex2 = where((c==0)*(x==x),-x,logex2/c) pex2 = exp(logpex2) # % Handle special cases logpdf = where((cx==1) | (cx==-inf),-inf,-pex2+logpex2-logex2) @@ -1775,15 +1782,13 @@ def _cdf(self, x, c): #return exp(-pow(1-c*x,1.0/c)) - loglogcdf = where(c==0,-x,np.log1p(-c*x)/c) + loglogcdf = where((c==0)*(x==x),-x,log1p(-c*x)/c) return exp(-exp(loglogcdf)) def _ppf(self, q, c): #return 1.0/c*(1.-(-log(q))**c) - logq = log(q); - x = -log(-logq) - # _rvs requires that _ppf allows vectorized q - return where((q==q)*(c==0),x,-np.expm1(-c*x)/c) + x = -log(-log(q)) + return where((c==0)*(x==x),x,-expm1(-c*x)/c) def _stats(self,c): g = lambda n : gam(n*c+1) @@ -1792,9 +1797,9 @@ g3 = g(3); g4 = g(4) g2mg12 = where(abs(c)<1e-7,(c*pi)**2.0/6.0,g2-g1**2.0) - gam2k = where(abs(c)<1e-7,pi**2.0/6.0, np.expm1(gamln(2.0*c+1.0)-2*gamln(c+1.0))/c**2.0); + gam2k = where(abs(c)<1e-7,pi**2.0/6.0, expm1(gamln(2.0*c+1.0)-2*gamln(c+1.0))/c**2.0); eps = 1e-14 - gamk = where(abs(c) Author: damian.eads Date: 2008-11-22 12:38:52 -0600 (Sat, 22 Nov 2008) New Revision: 5168 Modified: trunk/scipy/cluster/hierarchy.py Log: RSTifying more hierarchy docs. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-22 16:10:16 UTC (rev 5167) +++ trunk/scipy/cluster/hierarchy.py 2008-11-22 18:38:52 UTC (rev 5168) @@ -1470,7 +1470,6 @@ a linkage matrix. :Arguments: - - Z : ndarray The hierarchical clustering encoded as a matrix. See ``linkage`` for more information. @@ -2287,7 +2286,7 @@ return ( ((uiva + uivb) / 2), uwa+uwb, h, max_dist) def is_isomorphic(T1, T2): - """ + r""" Determines if two different cluster assignments ``T1`` and ``T2`` are equivalent. @@ -2302,7 +2301,6 @@ ids. :Returns: - - b : boolean Whether the flat cluster assignments ``T1`` and ``T2`` are equivalent. @@ -2336,17 +2334,24 @@ return True def maxdists(Z): - """ + r""" MD = maxdists(Z) - MD is a (n-1)-sized numpy array of doubles; MD[i] represents the - maximum distance between any cluster (including singletons) below - and including the node with index i. More specifically, - MD[i] = Z[Q(i)-n, 2].max() where Q(i) is the set of all node indices - below and including node i. + Returns the maximum distance between any cluster for each + non-singleton cluster. - Note that when Z[:,2] is monotonic, Z[:,2] and MD should not differ. - See linkage for more information on this issue. + :Arguments: + - Z : ndarray + The hierarchical clustering encoded as a matrix. See + ``linkage`` for more information. + + :Returns: + - MD : ndarray + A ``(n-1)`` sized numpy array of doubles; ``MD[i]`` represents + the maximum distance between any cluster (including + singletons) below and including the node with index i. More + specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the + set of all node indices below and including node i. """ Z = np.asarray(Z, order='c') is_valid_linkage(Z, throw=True, name='Z') @@ -2358,13 +2363,21 @@ return MD def maxinconsts(Z, R): - """ - MI = maxinconsts(Z, R) + r""" + Returns the maximum inconsistency coefficient for each + non-singleton cluster and its descendents. - Calculates the maximum inconsistency coefficient for each node - and its descendents. Z is a valid linkage matrix and R is a valid - inconsistency matrix. MI is a monotonic (n-1)-sized numpy array of - doubles. + :Arguments: + - Z : ndarray + The hierarchical clustering encoded as a matrix. See + ``linkage`` for more information. + + - R : ndarray + The inconsistency matrix. + + :Returns: + - MI : ndarray + A monotonic ``(n-1)``-sized numpy array of doubles. """ Z = np.asarray(Z, order='c') R = np.asarray(R, order='c') @@ -2378,13 +2391,29 @@ return MI def maxRstat(Z, R, i): - """ - MR = maxRstat(Z, R, i) + r""" + Returns the maximum statistic for each non-singleton cluster and + its descendents. - Calculates the maximum statistic for the i'th column of the - inconsistency matrix R for each non-singleton cluster node. MR[j] - is the maximum over R[Q(j)-n, i] where Q(j) the set of all node ids - corresponding to nodes below and including j. + :Arguments: + - Z : ndarray + The hierarchical clustering encoded as a matrix. See + ``linkage`` for more information. + + - R : ndarray + The inconsistency matrix. + + - i : int + The column of ``R`` to use as the statistic. + + :Returns: + + - MR : ndarray + Calculates the maximum statistic for the i'th column of the + inconsistency matrix ``R`` for each non-singleton cluster + node. ``MR[j]`` is the maximum over ``R[Q(j)-n, i]`` where + ``Q(j)`` the set of all node ids corresponding to nodes below + and including ``j``. """ Z = np.asarray(Z, order='c') R = np.asarray(R, order='c') @@ -2402,26 +2431,58 @@ return MR def leaders(Z, T): - """ + r""" (L, M) = leaders(Z, T): - For each flat cluster j of the k flat clusters represented in the - n-sized flat cluster assignment vector T, this function finds the - lowest cluster node i in the linkage tree Z such that: + Returns the root nodes in a hierarchical clustering corresponding + to a cut defined by a flat cluster assignment vector ``T``. See + the ``fcluster`` function for more information on the format of ``T``. - * leaf descendents belong only to flat cluster j (i.e. T[p]==j - for all p in S(i) where S(i) is the set of leaf ids of leaf - nodes descendent with cluster node i) + For each flat cluster :math:`j` of the :math:`k` flat clusters + represented in the n-sized flat cluster assignment vector ``T``, + this function finds the lowest cluster node :math:`i` in the linkage + tree Z such that: - * there does not exist a leaf that is not descendent with i - that also belongs to cluster j (i.e. T[q]!=j for all q not in S(i)). - If this condition is violated, T is not a valid cluster assignment - vector, and an exception will be thrown. + * leaf descendents belong only to flat cluster j + (i.e. ``T[p]==j`` for all :math:`p` in :math:`S(i)` where + :math:`S(i)` is the set of leaf ids of leaf nodes descendent + with cluster node :math:`i`) - Two k-sized numpy vectors are returned, L and M. L[j]=i is the linkage - cluster node id that is the leader of flat cluster with id M[j]. If - i < n, i corresponds to an original observation, otherwise it - corresponds to a non-singleton cluster. + * there does not exist a leaf that is not descendent with + :math:`i` that also belongs to cluster :math:`j` + (i.e. ``T[q]!=j`` for all :math:`q` not in :math:`S(i)`). If + this condition is violated, ``T`` is not a valid cluster + assignment vector, and an exception will be thrown. + + + :Arguments: + - Z : ndarray + The hierarchical clustering encoded as a matrix. See + ``linkage`` for more information. + + - T : ndarray + The flat cluster assignment vector. + + :Returns: (L, M) + + - L : ndarray + The leader linkage node id's stored as a k-element 1D + array where :math:`k` is the number of flat clusters found + in ``T``. + + ``L[j]=i`` is the linkage cluster node id that is the + leader of flat cluster with id M[j]. If ``i < n``, ``i`` + corresponds to an original observation, otherwise it + corresponds to a non-singleton cluster. + + For example: if ``L[3]=2`` and ``M[3]=8``, the flat cluster with + id 8's leader is linkage node 2. + + - M : ndarray + The leader linkage node id's stored as a k-element 1D + array where :math:`k` is the number of flat clusters found + in ``T``. This allows the set of flat cluster ids to be + any arbitrary set of :math:`k` integers. """ Z = np.asarray(Z, order='c') T = np.asarray(T, order='c') From scipy-svn at scipy.org Sat Nov 22 14:09:37 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 13:09:37 -0600 (CST) Subject: [Scipy-svn] r5169 - trunk/scipy/cluster Message-ID: <20081122190937.1C5E739C088@scipy.org> Author: damian.eads Date: 2008-11-22 13:09:35 -0600 (Sat, 22 Nov 2008) New Revision: 5169 Modified: trunk/scipy/cluster/hierarchy.py Log: RSTifying more hierarchy docs. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-22 18:38:52 UTC (rev 5168) +++ trunk/scipy/cluster/hierarchy.py 2008-11-22 19:09:35 UTC (rev 5169) @@ -699,7 +699,7 @@ :Returns: right : ClusterNode - The left child of the target node. + The left child of the target node. """ return self.right @@ -1696,7 +1696,7 @@ def set_link_color_palette(palette): """ Changes the list of matplotlib color codes to use when coloring - links with the dendrogram colorthreshold feature. + links with the dendrogram color_threshold feature. :Arguments: - palette : A list of matplotlib color codes. The order of @@ -1716,205 +1716,224 @@ _link_line_colors.remove(i) _link_line_colors.extend(list(palette)) -def dendrogram(Z, p=30, truncate_mode=None, colorthreshold=None, +def dendrogram(Z, p=30, truncate_mode=None, color_threshold=None, get_leaves=True, orientation='top', labels=None, count_sort=False, distance_sort=False, show_leaf_counts=True, no_plot=False, no_labels=False, color_list=None, leaf_font_size=None, leaf_rotation=None, leaf_label_func=None, no_leaves=False, show_contracted=False, link_color_func=None): - """ - R = dendrogram(Z) + r""" + Plots the hiearchical clustering defined by the linkage Z as a + dendrogram. The dendrogram illustrates how each cluster is + composed by drawing a U-shaped link between a non-singleton + cluster and its children. The height of the top of the U-link is + the distance between its children clusters. It is also the + cophenetic distance between original observations in the two + children clusters. It is expected that the distances in Z[:,2] be + monotonic, otherwise crossings appear in the dendrogram. - Plots the hiearchical clustering defined by the linkage Z as a - dendrogram. The dendrogram illustrates how each cluster is - composed by drawing a U-shaped link between a non-singleton - cluster and its children. The height of the top of the U-link - is the distance between its children clusters. It is also the - cophenetic distance between original observations in the - two children clusters. It is expected that the distances in - Z[:,2] be monotonic, otherwise crossings appear in the - dendrogram. + :Arguments: - R is a dictionary of the data structures computed to render the - dendrogram. Its keys are: + - Z : ndarray + The linkage matrix encoding the hierarchical clustering to + render as a dendrogram. See the ``linkage`` function for more + information on the format of ``Z``. - 'icoords': a list of lists [I1, I2, ..., Ip] where Ik is a - list of 4 independent variable coordinates corresponding to - the line that represents the k'th link painted. + - truncate_mode : string + The dendrogram can be hard to read when the original + observation matrix from which the linkage is derived is + large. Truncation is used to condense the dendrogram. There + are several modes: - 'dcoords': a list of lists [I2, I2, ..., Ip] where Ik is a - list of 4 independent variable coordinates corresponding to - the line that represents the k'th link painted. + * None/'none': no truncation is performed (Default) - 'ivl': a list of labels corresponding to the leaf nodes + * 'lastp': the last ``p`` non-singleton formed in the linkage + are the only non-leaf nodes in the linkage; they correspond + to to rows ``Z[n-p-2:end]`` in ``Z``. All other + non-singleton clusters are contracted into leaf nodes. - R = dendrogram(..., truncate_mode, p) + * 'mlab': This corresponds to MATLAB(TM) behavior. (not + implemented yet) - The dendrogram can be hard to read when the original observation - matrix from which the linkage is derived is large. Truncation - is used to condense the dendrogram. There are several modes: + * 'level'/'mtica': no more than ``p`` levels of the + dendrogram tree are displayed. This corresponds to + Mathematica(TM) behavior. - * None/'none': no truncation is performed + - p : int + The ``p`` parameter for ``truncate_mode``. +` + - color_threshold : double + For brevity, let :math:`t` be the ``color_threshold``. + Colors all the descendent links below a cluster node + :math:`k` the same color if :math:`k` is the first node below + the cut threshold :math:`t`. All links connecting nodes with + distances greater than or equal to the threshold are colored + blue. If :math:`t` is less than or equal to zero, all nodes + are colored blue. If ``color_threshold`` is ``None`` or + 'default', corresponding with MATLAB(TM) behavior, the + threshold is set to ``0.7*max(Z[:,2])``. - * 'lastp': the last p non-singleton formed in the linkage are - the only non-leaf nodes in the linkage; they correspond to - to rows Z[n-p-2:end] in Z. All other non-singleton clusters - are contracted into leaf nodes. + - get_leaves : bool + Includes a list ``R['leaves']=H`` in the result + dictionary. For each :math:`i`, ``H[i] == j``, cluster node + :math:`j` appears in the :math:`i` th position in the + left-to-right traversal of the leaves, where :math:`j < 2n-1` + and :math:`i < n`. - * 'mlab': This corresponds to MATLAB(TM) behavior. (not implemented yet) + - orientation : string + The direction to plot the dendrogram, which can be any + of the following strings - * 'level'/'mtica': no more than p levels of the dendrogram tree - are displayed. This corresponds to Mathematica(TM) behavior. + * 'top': plots the root at the top, and plot descendent + links going downwards. (default). - R = dendrogram(..., colorthreshold=t) + * 'bottom': plots the root at the bottom, and plot descendent + links going upwards. - Colors all the descendent links below a cluster node k the same color - if k is the first node below the cut threshold t. All links connecting - nodes with distances greater than or equal to the threshold are - colored blue. If t is less than or equal to zero, all nodes - are colored blue. If t is None or 'default', corresponding with - MATLAB(TM) behavior, the threshold is set to 0.7*max(Z[:,2]). + * 'left': plots the root at the left, and plot descendent + links going right. - R = dendrogram(..., get_leaves=True) + * 'right': plots the root at the right, and plot descendent + links going left. - Includes a list R['leaves']=H in the result dictionary. For each i, - H[i] == j, cluster node j appears in the i'th position in the - left-to-right traversal of the leaves, where j < 2n-1 and i < n. + - labels : ndarray + By default ``labels`` is ``None`` so the index of the + original observation is used to label the leaf nodes. - R = dendrogram(..., orientation) + Otherwise, this is an :math:`n` -sized list (or tuple). The + ``labels[i]`` value is the text to put under the :math:`i` th + leaf node only if it corresponds to an original observation + and not a non-singleton cluster. - Plots the dendrogram in a particular direction. The orientation - parameter can be any of: + - count_sort : string/bool + For each node n, the order (visually, from left-to-right) n's + two descendent links are plotted is determined by this + parameter, which can be any of the following values: - * 'top': plots the root at the top, and plot descendent - links going downwards. (default). + * False: nothing is done. - * 'bottom': plots the root at the bottom, and plot descendent - links going upwards. + * 'ascending'/True: the child with the minimum number of + original objects in its cluster is plotted first. - * 'left': plots the root at the left, and plot descendent - links going right. + * 'descendent': the child with the maximum number of + original objects in its cluster is plotted first. - * 'right': plots the root at the right, and plot descendent - links going left. + Note ``distance_sort`` and ``count_sort`` cannot both be + ``True``. - R = dendrogram(..., labels=None) + - distance_sort : string/bool + For each node n, the order (visually, from left-to-right) n's + two descendent links are plotted is determined by this + parameter, which can be any of the following values: - The labels parameter is a n-sized list (or tuple). The labels[i] - value is the text to put under the i'th leaf node only if it - corresponds to an original observation and not a non-singleton - cluster. + * False: nothing is done. - When labels=None, the index of the original observation is used - used. + * 'ascending'/True: the child with the minimum distance + between its direct descendents is plotted first. - R = dendrogram(..., count_sort) + * 'descending': the child with the maximum distance + between its direct descendents is plotted first. - When plotting a cluster node and its directly descendent links, - the order the two descendent links and their descendents are - plotted is determined by the count_sort parameter. Valid values - of count_sort are: + Note ``distance_sort`` and ``count_sort`` cannot both be + ``True``. - * False: nothing is done. + - show_leaf_counts : bool - * 'ascending'/True: the child with the minimum number of - original objects in its cluster is plotted first. + When ``True``, leaf nodes representing :math:`k>1` original + observation are labeled with the number of observations they + contain in parentheses. - * 'descendent': the child with the maximum number of - original objects in its cluster is plotted first. + - no_plot : bool + When ``True``, the final rendering is not performed. This is + useful if only the data structures computed for the rendering + are needed or if matplotlib is not available. - R = dendrogram(..., distance_sort) + - no_labels : bool + When ``True``, no labels appear next to the leaf nodes in the + rendering of the dendrogram. - When plotting a cluster node and its directly descendent links, - the order the two descendent links and their descendents are - plotted is determined by the distance_sort parameter. Valid - values of count_sort are: + - leaf_label_rotation : double - * False: nothing is done. + Specifies the angle (in degrees) to rotate the leaf + labels. When unspecified, the rotation based on the number of + nodes in the dendrogram. (Default=0) - * 'ascending'/True: the child with the minimum distance - between its direct descendents is plotted first. + - leaf_font_size : int + Specifies the font size (in points) of the leaf labels. When + unspecified, the size based on the number of nodes in the + dendrogram. - * 'descending': the child with the maximum distance - between its direct descendents is plotted first. + - leaf_label_func : lambda or function - Note that either count_sort or distance_sort must be False. + When leaf_label_func is a callable function, for each + leaf with cluster index :math:`k < 2n-1`. The function + is expected to return a string with the label for the + leaf. - R = dendrogram(..., show_leaf_counts) + Indices :math:`k < n` correspond to original observations + while indices :math:`k \geq n` correspond to non-singleton + clusters. - When show_leaf_counts=True, leaf nodes representing k>1 - original observation are labeled with the number of observations - they contain in parentheses. + For example, to label singletons with their node id and + non-singletons with their id, count, and inconsistency + coefficient, simply do:: - R = dendrogram(..., no_plot) + # First define the leaf label function. + def llf(id): + if id < n: + return str(id) + else: + return '[%d %d %1.2f]' % (id, count, R[n-id,3]) - When no_plot=True, the final rendering is not performed. This is - useful if only the data structures computed for the rendering - are needed or if matplotlib is not available. + # The text for the leaf nodes is going to be big so force + # a rotation of 90 degrees. + dendrogram(Z, leaf_label_func=llf, leaf_rotation=90) - R = dendrogram(..., no_labels) + - show_contracted : bool + When ``True`` the heights of non-singleton nodes contracted + into a leaf node are plotted as crosses along the link + connecting that leaf node. This really is only useful when + truncation is used (see ``truncate_mode`` parameter). - When no_labels=True, no labels appear next to the leaf nodes in - the rendering of the dendrogram. + - link_color_func : lambda/function When a callable function, + link_color_function is called with each non-singleton id + corresponding to each U-shaped link it will paint. The + function is expected to return the color to paint the link, + encoded as a matplotlib color string code. - R = dendrogram(..., leaf_label_rotation): + For example:: - Specifies the angle to which the leaf labels are rotated. When - unspecified, the rotation based on the number of nodes in the - dendrogram. + dendrogram(Z, link_color_func=lambda k: colors[k]) - R = dendrogram(..., leaf_font_size): + colors the direct links below each untruncated non-singleton node + ``k`` using ``colors[k]``. - Specifies the font size in points of the leaf labels. When - unspecified, the size based on the number of nodes - in the dendrogram. + :Returns: + - R : dict + A dictionary of data structures computed to render the + dendrogram. Its has the following keys: - R = dendrogram(..., leaf_label_func) + - 'icoords': a list of lists ``[I1, I2, ..., Ip]`` where + ``Ik`` is a list of 4 independent variable coordinates + corresponding to the line that represents the k'th link + painted. - When a callable function is passed, leaf_label_func is passed - cluster index k, and returns a string with the label for the - leaf. + - 'dcoords': a list of lists ``[I2, I2, ..., Ip]`` where + ``Ik`` is a list of 4 independent variable coordinates + corresponding to the line that represents the k'th link + painted. - Indices k < n correspond to original observations while indices - k >= n correspond to non-singleton clusters. + - 'ivl': a list of labels corresponding to the leaf nodes. - For example, to label singletons with their node id and - non-singletons with their id, count, and inconsistency coefficient, - we simply do - - # First define the leaf label function. - llf = lambda id: - if id < n: - return str(id) - else: - return '[%d %d %1.2f]' % (id, count, R[n-id,3]) - - # The text for the leaf nodes is going to be big so force - # a rotation of 90 degrees. - dendrogram(Z, leaf_label_func=llf, leaf_rotation=90) - - R = dendrogram(..., show_contracted=True) - - The heights of non-singleton nodes contracted into a leaf node - are plotted as crosses along the link connecting that leaf node. - This feature is only useful when truncation is used. - - R = dendrogram(..., link_color_func) - - When a link is painted, the function link_color_function is - called with the non-singleton id. This function is - expected to return a matplotlib color string, which represents - the color to paint the link. - - For example: - - dendrogram(Z, link_color_func=lambda k: colors[k]) - - colors the direct links below each untruncated non-singleton node - k using colors[k]. - + - 'leaves': for each i, ``H[i] == j``, cluster node + :math:`j` appears in the :math:`i` th position in the + left-to-right traversal of the leaves, where :math:`j < 2n-1` + and :math:`i < n`. If :math:`j` is less than :math:`n`, the + :math:`i` th leaf node corresponds to an original + observation. Otherwise, it corresponds to a non-singleton + cluster. """ # Features under consideration. @@ -1959,9 +1978,9 @@ ivl=None else: ivl=[] - if colorthreshold is None or \ - (type(colorthreshold) == types.StringType and colorthreshold=='default'): - colorthreshold = max(Z[:,2])*0.7 + if color_threshold is None or \ + (type(color_threshold) == types.StringType and color_threshold=='default'): + color_threshold = max(Z[:,2])*0.7 R={'icoord':icoord_list, 'dcoord':dcoord_list, 'ivl':ivl, 'leaves':lvs, 'color_list':color_list} props = {'cbt': False, 'cc':0} @@ -1971,7 +1990,7 @@ contraction_marks = None _dendrogram_calculate_info(Z=Z, p=p, truncate_mode=truncate_mode, \ - colorthreshold=colorthreshold, \ + color_threshold=color_threshold, \ get_leaves=get_leaves, \ orientation=orientation, \ labels=labels, \ @@ -2045,7 +2064,7 @@ def _dendrogram_calculate_info(Z, p, truncate_mode, \ - colorthreshold=np.inf, get_leaves=True, \ + color_threshold=np.inf, get_leaves=True, \ orientation='top', labels=None, \ count_sort=False, distance_sort=False, \ show_leaf_counts=False, i=-1, iv=0.0, \ @@ -2220,7 +2239,7 @@ (uiva, uwa, uah, uamd) = \ _dendrogram_calculate_info(Z=Z, p=p, \ truncate_mode=truncate_mode, \ - colorthreshold=colorthreshold, \ + color_threshold=color_threshold, \ get_leaves=get_leaves, \ orientation=orientation, \ labels=labels, \ @@ -2238,7 +2257,7 @@ link_color_func=link_color_func) h = Z[i-n, 2] - if h >= colorthreshold or colorthreshold <= 0: + if h >= color_threshold or color_threshold <= 0: c = 'b' if currently_below_threshold[0]: @@ -2251,7 +2270,7 @@ (uivb, uwb, ubh, ubmd) = \ _dendrogram_calculate_info(Z=Z, p=p, \ truncate_mode=truncate_mode, \ - colorthreshold=colorthreshold, \ + color_threshold=color_threshold, \ get_leaves=get_leaves, \ orientation=orientation, \ labels=labels, \ From scipy-svn at scipy.org Sat Nov 22 15:18:16 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 14:18:16 -0600 (CST) Subject: [Scipy-svn] r5170 - in trunk/scipy: cluster spatial Message-ID: <20081122201816.4143C39C088@scipy.org> Author: damian.eads Date: 2008-11-22 14:18:12 -0600 (Sat, 22 Nov 2008) New Revision: 5170 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/spatial/distance.py Log: Word-smithing some hierarchy and spatial documentation. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-22 19:09:35 UTC (rev 5169) +++ trunk/scipy/cluster/hierarchy.py 2008-11-22 20:18:12 UTC (rev 5170) @@ -331,6 +331,20 @@ Performs centroid/UPGMC linkage. See ``linkage`` for more information on the return structure and algorithm. + The following are common calling conventions: + + 1. Z = centroid(y) + + Performs centroid/UPGMC linkage on the condensed distance + matrix ``y``. See ``linkage`` for more information on the return + structure and algorithm. + + 2. Z = centroid(X) + + Performs centroid/UPGMC linkage on the observation matrix ``X`` + using Euclidean distance as the distance metric. See ``linkage`` + for more information on the return structure and algorithm. + :Parameters: Q : ndarray A condensed or redundant distance matrix. A condensed @@ -346,21 +360,6 @@ the ``linkage`` function documentation for more information on its structure. - Calling Conventions - ------------------- - - 1. Z = centroid(y) - - Performs centroid/UPGMC linkage on the condensed distance - matrix ``y``. See ``linkage`` for more information on the return - structure and algorithm. - - 2. Z = centroid(X) - - Performs centroid/UPGMC linkage on the observation matrix ``X`` - using Euclidean distance as the distance metric. See ``linkage`` - for more information on the return structure and algorithm. - :SeeAlso: - linkage: for advanced creation of hierarchical clusterings. """ @@ -371,18 +370,8 @@ Performs median/WPGMC linkage. See ``linkage`` for more information on the return structure and algorithm. - :Parameters: - Q : ndarray - A condensed or redundant distance matrix. A condensed - distance matrix is a flat array containing the upper - triangular of the distance matrix. This is the form that - ``pdist`` returns. Alternatively, a collection of - m observation vectors in n dimensions may be passed as - a m by n array. + The following are common calling conventions: - Calling Conventions - ------------------- - 1. Z = median(y) Performs median/WPGMC linkage on the condensed distance matrix @@ -395,6 +384,19 @@ using Euclidean distance as the distance metric. See linkage for more information on the return structure and algorithm. + :Parameters: + Q : ndarray + A condensed or redundant distance matrix. A condensed + distance matrix is a flat array containing the upper + triangular of the distance matrix. This is the form that + ``pdist`` returns. Alternatively, a collection of + m observation vectors in n dimensions may be passed as + a m by n array. + + :Returns: + - Z : ndarray + The hierarchical clustering encoded as a linkage matrix. + :SeeAlso: - linkage: for advanced creation of hierarchical clusterings. """ @@ -406,18 +408,8 @@ matrix. See linkage for more information on the return structure and algorithm. - :Parameters: - Q : ndarray - A condensed or redundant distance matrix. A condensed - distance matrix is a flat array containing the upper - triangular of the distance matrix. This is the form that - ``pdist`` returns. Alternatively, a collection of - m observation vectors in n dimensions may be passed as - a m by n array. + The following are common calling conventions: - Calling Conventions - ------------------- - 1. Z = ward(y) Performs Ward's linkage on the condensed distance matrix Z. See linkage for more information on the return structure and @@ -428,6 +420,19 @@ Euclidean distance as the distance metric. See linkage for more information on the return structure and algorithm. + :Parameters: + Q : ndarray + A condensed or redundant distance matrix. A condensed + distance matrix is a flat array containing the upper + triangular of the distance matrix. This is the form that + ``pdist`` returns. Alternatively, a collection of + m observation vectors in n dimensions may be passed as + a m by n array. + + :Returns: + - Z : ndarray + The hierarchical clustering encoded as a linkage matrix. + :SeeAlso: - linkage: for advanced creation of hierarchical clusterings. """ @@ -476,111 +481,109 @@ combined to form cluster :math:`u`. Let :math:`v` be any remaining cluster in the forest that is not :math:`u`. - :Parameters: - Q : ndarray - A condensed or redundant distance matrix. A condensed - distance matrix is a flat array containing the upper - triangular of the distance matrix. This is the form that - ``pdist`` returns. Alternatively, a collection of - :math:`m` observation vectors in n dimensions may be passed as - a :math:`m` by :math:`n` array. - method : string - The linkage algorithm to use. See the ``Linkage Methods`` - section below for full descriptions. - metric : string - The distance metric to use. See the ``distance.pdist`` - function for a list of valid distance metrics. - - Linkage Methods - --------------- - The following are methods for calculating the distance between the newly formed cluster :math:`u` and each :math:`v`. - * method=``single`` assigns + * method=``single`` assigns - .. math: - d(u,v) = \min(dist(u[i],v[j])) + .. math:: + d(u,v) = \min(dist(u[i],v[j])) - for all points :math:`i` in cluster :math:`u` and - :math:`j` in cluster :math:`v`. This is also known as the - Nearest Point Algorithm. + for all points :math:`i` in cluster :math:`u` and + :math:`j` in cluster :math:`v`. This is also known as the + Nearest Point Algorithm. - * method=``complete`` assigns + * method=``complete`` assigns - .. math: - d(u, v) = \max(dist(u[i],v[j])) + .. math:: + d(u, v) = \max(dist(u[i],v[j])) - for all points :math:`i` in cluster u and :math:`j` in - cluster :math:`v`. This is also known by the Farthest Point - Algorithm or Voor Hees Algorithm. + for all points :math:`i` in cluster u and :math:`j` in + cluster :math:`v`. This is also known by the Farthest Point + Algorithm or Voor Hees Algorithm. - * method=``average`` assigns + * method=``average`` assigns - .. math: - d(u,v) = \sum_{ij} \frac{d(u[i], v[j])} - {(|u|*|v|) + .. math:: + d(u,v) = \sum_{ij} \frac{d(u[i], v[j])} + {(|u|*|v|) - for all points :math:`i` and :math:`j` where :math:`|u|` - and :math:`|v|` are the cardinalities of clusters :math:`u` - and :math:`v`, respectively. This is also called the UPGMA - algorithm. This is called UPGMA. + for all points :math:`i` and :math:`j` where :math:`|u|` + and :math:`|v|` are the cardinalities of clusters :math:`u` + and :math:`v`, respectively. This is also called the UPGMA + algorithm. This is called UPGMA. - * method='weighted' assigns + * method='weighted' assigns - .. math: - d(u,v) = (dist(s,v) + dist(t,v))/2 + .. math:: + d(u,v) = (dist(s,v) + dist(t,v))/2 - where cluster u was formed with cluster s and t and v - is a remaining cluster in the forest. (also called WPGMA) + where cluster u was formed with cluster s and t and v + is a remaining cluster in the forest. (also called WPGMA) + * method='centroid' assigns - * method='centroid' assigns + .. math:: + dist(s,t) = euclid(c_s, c_t) - .. math: - dist(s,t) = euclid(c_s, c_t) + where :math:`c_s` and :math:`c_t` are the centroids of + clusters :math:`s` and :math:`t`, respectively. When two + clusters :math:`s` and :math:`t` are combined into a new + cluster :math:`u`, the new centroid is computed over all the + original objects in clusters :math:`s` and :math:`t`. The + distance then becomes the Euclidean distance between the + centroid of :math:`u` and the centroid of a remaining cluster + :math:`v` in the forest. This is also known as the UPGMC + algorithm. - where :math:`c_s` and :math:`c_t` are the centroids of - clusters :math:`s` and :math:`t`, respectively. When two - clusters :math:`s` and :math:`t` are combined into a new - cluster :math:`u`, the new centroid is computed over all the - original objects in clusters :math:`s` and :math:`t`. The - distance then becomes the Euclidean distance between the - centroid of :math:`u` and the centroid of a remaining cluster - :math:`v` in the forest. This is also known as the UPGMC - algorithm. + * method='median' assigns math:`$d(s,t)$` like the ``centroid`` + method. When two clusters s and t are combined into a new + cluster :math:`u`, the average of centroids s and t give the + new centroid :math:`u`. This is also known as the WPGMC + algorithm. - * method='median' assigns math:`$d(s,t)$` like the ``centroid`` - method. When two clusters s and t are combined into a new - cluster :math:`u`, the average of centroids s and t give the - new centroid :math:`u`. This is also known as the WPGMC - algorithm. + * method='ward' uses the Ward variance minimization algorithm. + The new entry :math:`d(u,v)` is computed as follows, - * method='ward' uses the Ward variance minimization algorithm. - The new entry :math:`d(u,v)` is computed as follows, + .. math:: - .. math: + d(u,v) = \sqrt{\frac{|v|+|s|} + {T}d(v,s)^2 + + \frac{|v|+|t|} + {T}d(v,t)^2 + + \frac{|v|} + {T}d(s,t)^2} - d(u,v) = \sqrt{\frac{|v|+|s|} - {T}d(v,s)^2 - + \frac{|v|+|t|} - {T}d(v,t)^2 - + \frac{|v|} - {T}d(s,t)^2} + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also + known as the incremental algorithm. - where :math:`u` is the newly joined cluster consisting of - clusters :math:`s` and :math:`t`, :math:`v` is an unused - cluster in the forest, :math:`T=|v|+|s|+|t|`, and - :math:`|*|` is the cardinality of its argument. This is also - known as the incremental algorithm. + Warning: When the minimum distance pair in the forest is chosen, there may + be two or more pairs with the same minimum distance. This + implementation may chose a different minimum than the MATLAB(TM) + version. - Warning - ------- + :Parameters: + - Q : ndarray + A condensed or redundant distance matrix. A condensed + distance matrix is a flat array containing the upper + triangular of the distance matrix. This is the form that + ``pdist`` returns. Alternatively, a collection of + :math:`m` observation vectors in n dimensions may be passed as + a :math:`m` by :math:`n` array. + - method : string + The linkage algorithm to use. See the ``Linkage Methods`` + section below for full descriptions. + - metric : string + The distance metric to use. See the ``distance.pdist`` + function for a list of valid distance metrics. - When the minimum distance pair in the forest is chosen, there may - be two or more pairs with the same minimum distance. This - implementation may chose a different minimum than the MATLAB(TM) - version. + :Returns: + + - Z : ndarray + The hierarchical clustering encoded as a linkage matrix. """ if not isinstance(method, str): raise TypeError("Argument 'method' must be a string.") @@ -788,6 +791,10 @@ the ClusterNode object is a leaf node, its count must be 1, and its distance is meaningless but set to 0. + Note: This function is provided for the convenience of the library + user. ClusterNodes are not used as input to any of the functions in this + library. + :Parameters: - Z : ndarray @@ -807,9 +814,6 @@ - L : list The pre-order traversal. - Note: This function is provided for the convenience of the library - user. ClusterNodes are not used as input to any of the functions in this - library. """ Z = np.asarray(Z, order='c') @@ -945,6 +949,9 @@ r""" Calculates inconsistency statistics on a linkage. + Note: This function behaves similarly to the MATLAB(TM) + inconsistent function. + :Parameters: - d : int The number of links up to ``d`` levels below each @@ -971,9 +978,6 @@ \frac{\mathtt{Z[i,2]}-\mathtt{R[i,0]}} {R[i,1]}. - - This function behaves similarly to the MATLAB(TM) inconsistent - function. """ Z = np.asarray(Z, order='c') Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-22 19:09:35 UTC (rev 5169) +++ trunk/scipy/spatial/distance.py 2008-11-22 20:18:12 UTC (rev 5170) @@ -283,10 +283,10 @@ Computes the Cosine distance between two n-vectors u and v, which is defined as - .. math:: + .. math:: - \frac{1-uv^T} - {||u||_2 ||v||_2}. + \frac{1-uv^T} + {||u||_2 ||v||_2}. :Parameters: u : ndarray @@ -341,7 +341,7 @@ ``u`` and ``v``. If ``u`` and ``v`` are boolean vectors, the Hamming distance is - .. math: + .. math:: \frac{c_{01} + c_{10}}{n} @@ -398,7 +398,7 @@ Computes the Kulsinski dissimilarity between two boolean n-vectors u and v, which is defined as - .. math: + .. math:: \frac{c_{TF} + c_{FT} - c_{TT} + n} {c_{FT} + c_{TF} + n} @@ -453,7 +453,7 @@ Computes the Manhattan distance between two n-vectors u and v, which is defined as - .. math: + .. math:: \sum_i {u_i-v_i}. @@ -476,7 +476,8 @@ Computes the Mahalanobis distance between two n-vectors ``u`` and ``v``, which is defiend as - .. math: + .. math:: + (u-v)V^{-1}(u-v)^T where ``VI`` is the inverse covariance matrix :math:`V^{-1}`. @@ -501,7 +502,8 @@ Computes the Chebyshev distance between two n-vectors u and v, which is defined as - .. math: + .. math:: + \max_i {|u_i-v_i|}. :Parameters: @@ -523,7 +525,7 @@ Computes the Bray-Curtis distance between two n-vectors ``u`` and ``v``, which is defined as - .. math: + .. math:: \sum{|u_i-v_i|} / \sum{|u_i+v_i|}. @@ -546,7 +548,7 @@ Computes the Canberra distance between two n-vectors u and v, which is defined as - .. math: + .. math:: \frac{\sum_i {|u_i-v_i|}} {\sum_i {|u_i|+|v_i|}}. @@ -610,7 +612,7 @@ which is defined as - .. math: + .. math:: \frac{R} \frac{c_{TT} + c_{FF} + \frac{R}{2}} @@ -639,7 +641,7 @@ Computes the Matching dissimilarity between two boolean n-vectors u and v, which is defined as - .. math: + .. math:: \frac{c_{TF} + c_{FT}}{n} @@ -667,7 +669,7 @@ Computes the Dice dissimilarity between two boolean n-vectors ``u`` and ``v``, which is - .. math: + .. math:: \frac{c_{TF} + c_{FT}} {2c_{TT} + c_{FT} + c_{TF}} @@ -700,7 +702,7 @@ Computes the Rogers-Tanimoto dissimilarity between two boolean n-vectors ``u`` and ``v``, which is defined as - .. math: + .. math:: \frac{R} {c_{TT} + c_{FF} + R} @@ -729,7 +731,7 @@ Computes the Russell-Rao dissimilarity between two boolean n-vectors ``u`` and ``v``, which is defined as - .. math: + .. math:: \frac{n - c_{TT}} {n} @@ -761,7 +763,7 @@ Computes the Sokal-Michener dissimilarity between two boolean vectors ``u`` and ``v``, which is defined as - .. math: + .. math:: \frac{2R} {S + 2R} @@ -797,7 +799,7 @@ Computes the Sokal-Sneath dissimilarity between two boolean vectors ``u`` and ``v``, - .. math: + .. math:: \frac{2R} {c_{TT} + 2R} @@ -838,33 +840,8 @@ this entry or to convert the condensed distance matrix to a redundant square matrix. - :Parameters: - X : ndarray - An m by n array of m original observations in an - n-dimensional space. - metric : string or function - The distance metric to use. The distance function can - be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', - 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', - 'jaccard', 'kulsinski', 'mahalanobis', 'matching', - 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', - 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'. - w : ndarray - The weight vector (for weighted Minkowski). - p : double - The p-norm to apply (for Minkowski, weighted and unweighted) - V : ndarray - The variance vector (for standardized Euclidean). - VI : ndarray - The inverse of the covariance matrix (for Mahalanobis). + The following are common calling conventions. - :Returns: - Y : ndarray - A condensed distance matrix. - - Calling Conventions - ------------------- - 1. ``Y = pdist(X, 'euclidean')`` Computes the distance between m points using Euclidean distance @@ -886,9 +863,9 @@ Computes the standardized Euclidean distance. The standardized Euclidean distance between two n-vectors ``u`` and ``v`` is - .. math: + .. math:: - sqrt(\sum {(u_i-v_i)^2 / V[x_i]}). + \sqrt{\sum {(u_i-v_i)^2 / V[x_i]}}. V is the variance vector; V[i] is the variance computed over all the i'th components of the points. If not passed, it is @@ -903,7 +880,7 @@ Computes the cosine distance between vectors u and v, - .. math: + .. math:: \frac{1 - uv^T} {{|u|}_2 {|v|}_2} @@ -914,7 +891,7 @@ Computes the correlation distance between vectors u and v. This is - .. math: + .. math:: \frac{1 - (u - \bar{u})(v - \bar{v})^T} {{|(u - \bar{u})|}{|(v - \bar{v})|}^T} @@ -942,7 +919,7 @@ maximum norm-1 distance between their respective elements. More precisely, the distance is given by - .. math: + .. math:: d(u,v) = max_i {|u_i-v_i|}. @@ -951,7 +928,7 @@ Computes the Canberra distance between the points. The Canberra distance between two points ``u`` and ``v`` is - .. math: + .. math:: d(u,v) = \sum_u {|u_i-v_i|} {|u_i|+|v_i|} @@ -963,7 +940,7 @@ Bray-Curtis distance between two points ``u`` and ``v`` is - .. math: + .. math:: d(u,v) = \frac{\sum_i {u_i-v_i}} {\sum_i {u_i+v_i}} @@ -1043,6 +1020,31 @@ dm = pdist(X, 'sokalsneath') + :Parameters: + X : ndarray + An m by n array of m original observations in an + n-dimensional space. + metric : string or function + The distance metric to use. The distance function can + be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', + 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', + 'jaccard', 'kulsinski', 'mahalanobis', 'matching', + 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', + 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'. + w : ndarray + The weight vector (for weighted Minkowski). + p : double + The p-norm to apply (for Minkowski, weighted and unweighted) + V : ndarray + The variance vector (for standardized Euclidean). + VI : ndarray + The inverse of the covariance matrix (for Mahalanobis). + + :Returns: + Y : ndarray + A condensed distance matrix. + + """ @@ -1592,9 +1594,9 @@ Computes the standardized Euclidean distance. The standardized Euclidean distance between two n-vectors ``u`` and ``v`` is - .. math: + .. math:: - sqrt(\sum {(u_i-v_i)^2 / V[x_i]}). + \sqrt{\sum {(u_i-v_i)^2 / V[x_i]}}. V is the variance vector; V[i] is the variance computed over all the i'th components of the points. If not passed, it is @@ -1609,7 +1611,7 @@ Computes the cosine distance between vectors u and v, - .. math: + .. math:: \frac{1 - uv^T} {{|u|}_2 {|v|}_2} @@ -1620,7 +1622,7 @@ Computes the correlation distance between vectors u and v. This is - .. math: + .. math:: \frac{1 - (u - n{|u|}_1){(v - n{|v|}_1)}^T} {{|(u - n{|u|}_1)|}_2 {|(v - n{|v|}_1)|}^T} @@ -1650,7 +1652,7 @@ maximum norm-1 distance between their respective elements. More precisely, the distance is given by - .. math: + .. math:: d(u,v) = max_i {|u_i-v_i|}. @@ -1659,7 +1661,7 @@ Computes the Canberra distance between the points. The Canberra distance between two points ``u`` and ``v`` is - .. math: + .. math:: d(u,v) = \sum_u {|u_i-v_i|} {|u_i|+|v_i|} @@ -1671,7 +1673,7 @@ Bray-Curtis distance between two points ``u`` and ``v`` is - .. math: + .. math:: d(u,v) = \frac{\sum_i {u_i-v_i}} {\sum_i {u_i+v_i}} From scipy-svn at scipy.org Sat Nov 22 17:47:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 16:47:23 -0600 (CST) Subject: [Scipy-svn] r5171 - in trunk/scipy/sparse: . linalg linalg/tests tests Message-ID: <20081122224723.C8B5A39C088@scipy.org> Author: wnbell Date: 2008-11-22 16:47:13 -0600 (Sat, 22 Nov 2008) New Revision: 5171 Modified: trunk/scipy/sparse/base.py trunk/scipy/sparse/linalg/interface.py trunk/scipy/sparse/linalg/tests/test_interface.py trunk/scipy/sparse/tests/test_base.py Log: LinearOperator now wraps user-defined matvec and matmat routines corrected sparse __mul__ handling of arguments with small shape Modified: trunk/scipy/sparse/base.py =================================================================== --- trunk/scipy/sparse/base.py 2008-11-22 20:18:12 UTC (rev 5170) +++ trunk/scipy/sparse/base.py 2008-11-22 22:47:13 UTC (rev 5171) @@ -291,8 +291,9 @@ # If it's a list or whatever, treat it like a matrix other = np.asanyarray(other) - if isdense(other) and np.asarray(other).squeeze().ndim <= 1: - ## + other = np.asanyarray(other) + + if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1: # dense row or column vector if other.shape != (N,) and other.shape != (N,1): raise ValueError('dimension mismatch') @@ -308,7 +309,7 @@ return result - elif len(other.shape) == 2: + elif other.ndim == 2: ## # dense 2D array or matrix ("multivector") Modified: trunk/scipy/sparse/linalg/interface.py =================================================================== --- trunk/scipy/sparse/linalg/interface.py 2008-11-22 20:18:12 UTC (rev 5170) +++ trunk/scipy/sparse/linalg/interface.py 2008-11-22 22:47:13 UTC (rev 5171) @@ -1,5 +1,4 @@ -import numpy -from numpy import matrix, ndarray, asarray, dot, atleast_2d, hstack +import numpy as np from scipy.sparse.sputils import isshape from scipy.sparse import isspmatrix @@ -20,13 +19,12 @@ shape : tuple Matrix dimensions (M,N) matvec : callable f(v) - Returns returns A * v + Returns returns A * v. Optional Parameters ------------------- rmatvec : callable f(v) - Returns A^H * v, where A^H represents the Hermitian - (conjugate) transpose of A. + Returns A^H * v, where A^H is the conjugate transpose of A. matmat : callable f(V) Returns A * V, where V is a dense matrix with dimensions (N,K). dtype : dtype @@ -36,6 +34,12 @@ -------- aslinearoperator : Construct LinearOperators + Notes + ----- + The user-defined matvec() function must properly handle the case + where v has shape (N,) as well as the (N,1) case. The shape of + the return type is handled internally by LinearOperator. + Examples -------- >>> from scipy.sparse.linalg import LinearOperator @@ -52,7 +56,7 @@ array([ 2., 3.]) """ - def __init__( self, shape, matvec, rmatvec=None, matmat=None, dtype=None ): + def __init__(self, shape, matvec, rmatvec=None, matmat=None, dtype=None): shape = tuple(shape) @@ -60,7 +64,7 @@ raise ValueError('invalid shape') self.shape = shape - self.matvec = matvec + self._matvec = matvec if rmatvec is None: def rmatvec(v): @@ -69,26 +73,118 @@ else: self.rmatvec = rmatvec - if matmat is None: + if matmat is not None: # matvec each column of V - def matmat(V): - V = asarray(V) - return hstack( [ matvec(col.reshape(-1,1)) for col in V.T ] ) - self.matmat = matmat - else: - self.matmat = matmat + self._matmat = matmat if dtype is not None: - self.dtype = numpy.dtype(dtype) + self.dtype = np.dtype(dtype) + + def _matmat(self, X): + """Default matrix-matrix multiplication handler. Falls back on + the user-defined matvec() routine, which is always provided. + """ + + return np.hstack( [ self.matvec(col.reshape(-1,1)) for col in X.T ] ) + + + def matvec(self, x): + """Matrix-vector multiplication + + Performs the operation y=A*x where A is an MxN linear + operator and x is a column vector or rank-1 array. + + Parameters + ---------- + x : {matrix, ndarray} + An array with shape (N,) or (N,1). + + Returns + ------- + y : {matrix, ndarray} + A matrix or ndarray with shape (M,) or (M,1) depending + on the type and shape of the x argument. + + Notes + ----- + This matvec wraps the user-specified matvec routine to ensure that + y has the correct shape and type. + + """ + + x = np.asanyarray(x) + + M,N = self.shape + + if x.shape != (N,) and x.shape != (N,1): + raise ValueError('dimension mismatch') + + y = self._matvec(x) + + if x.ndim == 2: + # If 'x' is a column vector, reshape the result + y = y.reshape(-1,1) + + if isinstance(x, np.matrix): + y = np.asmatrix(y) + + return y + + + def matmat(self, X): + """Matrix-matrix multiplication + + Performs the operation y=A*X where A is an MxN linear + operator and X dense N*K matrix or ndarray. + + Parameters + ---------- + X : {matrix, ndarray} + An array with shape (N,K). + + Returns + ------- + Y : {matrix, ndarray} + A matrix or ndarray with shape (M,K) depending on + the type of the X argument. + + Notes + ----- + This matmat wraps any user-specified matmat routine to ensure that + y has the correct type. + + """ + + X = np.asanyarray(X) + + if X.ndim != 2: + raise ValueError('expected rank-2 ndarray or matrix') + + M,N = self.shape + + if X.shape[0] != N: + raise ValueError('dimension mismatch') + + Y = self._matmat(X) + + if isinstance(Y, np.matrix): + Y = np.asmatrix(Y) + + return Y + + def __mul__(self,x): - x = numpy.asarray(x) + x = np.asarray(x) - if numpy.rank(x.squeeze()) == 1: + if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1: return self.matvec(x) + elif x.ndim == 2: + return self.matmat(x) else: - return self.matmat(x) + raise ValueError('expected rank-1 or rank-2 array or matrix') + def __repr__(self): M,N = self.shape if hasattr(self,'dtype'): @@ -121,18 +217,18 @@ if isinstance(A, LinearOperator): return A - elif isinstance(A, ndarray) or isinstance(A, matrix): - if len(A.shape) > 2: + elif isinstance(A, np.ndarray) or isinstance(A, np.matrix): + if A.ndim > 2: raise ValueError('array must have rank <= 2') - A = atleast_2d(asarray(A)) + A = np.atleast_2d(np.asarray(A)) def matvec(v): - return dot(A, v) + return np.dot(A, v) def rmatvec(v): - return dot(A.conj().transpose(), v) + return np.dot(A.conj().transpose(), v) def matmat(V): - return dot(A, V) + return np.dot(A, V) return LinearOperator(A.shape, matvec, rmatvec=rmatvec, matmat=matmat, dtype=A.dtype) @@ -147,13 +243,13 @@ matmat=matmat, dtype=A.dtype) else: - if hasattr(A,'shape') and hasattr(A,'matvec'): + if hasattr(A, 'shape') and hasattr(A, 'matvec'): rmatvec = None dtype = None - if hasattr(A,'rmatvec'): + if hasattr(A, 'rmatvec'): rmatvec = A.rmatvec - if hasattr(A,'dtype'): + if hasattr(A, 'dtype'): dtype = A.dtype return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec, dtype=dtype) Modified: trunk/scipy/sparse/linalg/tests/test_interface.py =================================================================== --- trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-22 20:18:12 UTC (rev 5170) +++ trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-22 22:47:13 UTC (rev 5171) @@ -1,62 +1,95 @@ -#!/usr/bin/env python -""" Test functions for the sparse.linalg.interface module +"""Test functions for the sparse.linalg.interface module """ from numpy.testing import * -import numpy -from numpy import array, matrix, dtype -from scipy.sparse import csr_matrix +import numpy as np +import scipy.sparse as sparse from scipy.sparse.linalg.interface import * -class TestInterface(TestCase): - def test_aslinearoperator(self): - cases = [] +class TestLinearOperator(TestCase): + def test_matvec(self): + def matvec(x): + # note, this matvec does not preserve type or shape + y = np.array([ 1*x[0] + 2*x[1] + 3*x[2], + 4*x[0] + 5*x[1] + 6*x[2]]) + return y - cases.append( matrix([[1,2,3],[4,5,6]]) ) - cases.append( array([[1,2,3],[4,5,6]]) ) - cases.append( csr_matrix([[1,2,3],[4,5,6]]) ) + A = LinearOperator((2,3), matvec) - class matlike: - def __init__(self): - self.dtype = dtype('int') - self.shape = (2,3) - def matvec(self,x): - y = array([ 1*x[0] + 2*x[1] + 3*x[2], - 4*x[0] + 5*x[1] + 6*x[2]]) - if len(x.shape) == 2: - y = y.reshape(-1,1) - return y + assert_equal(A.matvec(np.array([1,2,3])), [14,32]) + assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]]) + assert_equal(A * np.array([1,2,3]), [14,32]) + assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]]) + + assert_equal(A.matvec(np.matrix([[1],[2],[3]])), [[14],[32]]) + assert_equal(A * np.matrix([[1],[2],[3]]), [[14],[32]]) - def rmatvec(self,x): - return array([ 1*x[0] + 4*x[1], - 2*x[0] + 5*x[1], - 3*x[0] + 6*x[1]]) + assert( isinstance(A.matvec(np.array([1,2,3])), np.ndarray) ) + assert( isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray) ) + assert( isinstance(A * np.array([1,2,3]), np.ndarray) ) + assert( isinstance(A * np.array([[1],[2],[3]]), np.ndarray) ) - cases.append( matlike() ) + assert( isinstance(A.matvec(np.matrix([[1],[2],[3]])), np.ndarray) ) + assert( isinstance(A * np.matrix([[1],[2],[3]]), np.ndarray) ) + assert_raises(ValueError, A.matvec, np.array([1,2])) + assert_raises(ValueError, A.matvec, np.array([1,2,3,4])) + assert_raises(ValueError, A.matvec, np.array([[1],[2]])) + assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]])) - for M in cases: + +class TestAsLinearOperator(TestCase): + def setUp(self): + self.cases = [] + + def make_cases(dtype): + self.cases.append( np.matrix([[1,2,3],[4,5,6]], dtype=dtype) ) + self.cases.append( np.array([[1,2,3],[4,5,6]], dtype=dtype) ) + self.cases.append( sparse.csr_matrix([[1,2,3],[4,5,6]], dtype=dtype) ) + + class matlike: + def __init__(self, dtype): + self.dtype = np.dtype(dtype) + self.shape = (2,3) + def matvec(self,x): + y = np.array([ 1*x[0] + 2*x[1] + 3*x[2], + 4*x[0] + 5*x[1] + 6*x[2]], dtype=self.dtype) + if len(x.shape) == 2: + y = y.reshape(-1,1) + return y + + def rmatvec(self,x): + return np.array([ 1*x[0] + 4*x[1], + 2*x[0] + 5*x[1], + 3*x[0] + 6*x[1]], dtype=self.dtype) + self.cases.append( matlike('int') ) + + make_cases('int32') + make_cases('float32') + make_cases('float64') + + def test_basic(self): + + for M in self.cases: A = aslinearoperator(M) M,N = A.shape - assert_equal(A.matvec(array([1,2,3])), [14,32]) - assert_equal(A.matvec(array([[1],[2],[3]])), [[14],[32]]) + assert_equal(A.matvec(np.array([1,2,3])), [14,32]) + assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]]) - assert_equal(A * array([1,2,3]), [14,32]) - assert_equal(A * array([[1],[2],[3]]), [[14],[32]]) + assert_equal(A * np.array([1,2,3]), [14,32]) + assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]]) - assert_equal(A.rmatvec(array([1,2])), [9,12,15]) - assert_equal(A.rmatvec(array([[1],[2]])), [[9],[12],[15]]) + assert_equal(A.rmatvec(np.array([1,2])), [9,12,15]) + assert_equal(A.rmatvec(np.array([[1],[2]])), [[9],[12],[15]]) - assert_equal(A.matmat(array([[1,4],[2,5],[3,6]])), [[14,32],[32,77]] ) + assert_equal(A.matmat(np.array([[1,4],[2,5],[3,6]])), [[14,32],[32,77]] ) - assert_equal(A * array([[1,4],[2,5],[3,6]]), [[14,32],[32,77]] ) + assert_equal(A * np.array([[1,4],[2,5],[3,6]]), [[14,32],[32,77]] ) if hasattr(M,'dtype'): assert_equal(A.dtype, M.dtype) -if __name__ == "__main__": - nose.run(argv=['', __file__]) Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-11-22 20:18:12 UTC (rev 5170) +++ trunk/scipy/sparse/tests/test_base.py 2008-11-22 22:47:13 UTC (rev 5171) @@ -26,12 +26,12 @@ import scipy.sparse as sparse from scipy.sparse import csc_matrix, csr_matrix, dok_matrix, \ coo_matrix, lil_matrix, dia_matrix, bsr_matrix, \ - eye, SparseEfficiencyWarning + eye, isspmatrix, SparseEfficiencyWarning from scipy.sparse.sputils import supported_dtypes from scipy.sparse.linalg import splu -warnings.simplefilter('ignore',SparseEfficiencyWarning) +warnings.simplefilter('ignore', SparseEfficiencyWarning) #TODO check that spmatrix( ... , copy=X ) is respected @@ -347,7 +347,17 @@ assert_array_almost_equal([1,2,3,4]*M, dot([1,2,3,4], M.toarray())) row = matrix([[1,2,3,4]]) assert_array_almost_equal(row*M, row*M.todense()) + + def test_small_multiplication(self): + """test that A*x works for x with shape () (1,) and (1,1) + """ + A = self.spmatrix([[1],[2],[3]]) + assert(isspmatrix(A * array(1))) + assert_equal((A * array(1)).todense(), [[1],[2],[3]]) + assert_equal(A * array([1]), array([1,2,3])) + assert_equal(A * array([[1]]), array([[1],[2],[3]])) + def test_matvec(self): M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) col = matrix([1,2,3]).T From scipy-svn at scipy.org Sat Nov 22 18:14:50 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 17:14:50 -0600 (CST) Subject: [Scipy-svn] r5172 - in trunk/scipy/sparse/linalg: . tests Message-ID: <20081122231450.6420739C088@scipy.org> Author: wnbell Date: 2008-11-22 17:14:44 -0600 (Sat, 22 Nov 2008) New Revision: 5172 Modified: trunk/scipy/sparse/linalg/interface.py trunk/scipy/sparse/linalg/tests/test_interface.py Log: force rank-1 ndarray output when input is rank-1 ndarray Modified: trunk/scipy/sparse/linalg/interface.py =================================================================== --- trunk/scipy/sparse/linalg/interface.py 2008-11-22 22:47:13 UTC (rev 5171) +++ trunk/scipy/sparse/linalg/interface.py 2008-11-22 23:14:44 UTC (rev 5172) @@ -121,14 +121,20 @@ raise ValueError('dimension mismatch') y = self._matvec(x) - - if x.ndim == 2: - # If 'x' is a column vector, reshape the result - y = y.reshape(-1,1) - + if isinstance(x, np.matrix): y = np.asmatrix(y) + else: + y = np.asarray(y) + if x.ndim == 1: + y = y.reshape(M) + elif x.ndim == 2: + y = y.reshape(M,1) + else: + raise ValueError('invalid shape returned by user-defined matvec()') + + return y Modified: trunk/scipy/sparse/linalg/tests/test_interface.py =================================================================== --- trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-22 22:47:13 UTC (rev 5171) +++ trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-22 23:14:44 UTC (rev 5172) @@ -10,37 +10,47 @@ class TestLinearOperator(TestCase): - def test_matvec(self): - def matvec(x): - # note, this matvec does not preserve type or shape - y = np.array([ 1*x[0] + 2*x[1] + 3*x[2], - 4*x[0] + 5*x[1] + 6*x[2]]) - return y + def setUp(self): + self.matvecs = [] - A = LinearOperator((2,3), matvec) + # these matvecs do not preserve type or shape + def matvec1(x): + return np.array([ 1*x[0] + 2*x[1] + 3*x[2], + 4*x[0] + 5*x[1] + 6*x[2]]) + def matvec2(x): + return np.matrix(matvec1(x).reshape(2,1)) - assert_equal(A.matvec(np.array([1,2,3])), [14,32]) - assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]]) - assert_equal(A * np.array([1,2,3]), [14,32]) - assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]]) - - assert_equal(A.matvec(np.matrix([[1],[2],[3]])), [[14],[32]]) - assert_equal(A * np.matrix([[1],[2],[3]]), [[14],[32]]) + self.matvecs.append(matvec1) + self.matvecs.append(matvec2) - assert( isinstance(A.matvec(np.array([1,2,3])), np.ndarray) ) - assert( isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray) ) - assert( isinstance(A * np.array([1,2,3]), np.ndarray) ) - assert( isinstance(A * np.array([[1],[2],[3]]), np.ndarray) ) + def test_matvec(self): - assert( isinstance(A.matvec(np.matrix([[1],[2],[3]])), np.ndarray) ) - assert( isinstance(A * np.matrix([[1],[2],[3]]), np.ndarray) ) + for matvec in self.matvecs: + A = LinearOperator((2,3), matvec) + + assert_equal(A.matvec(np.array([1,2,3])), [14,32]) + assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]]) + assert_equal(A * np.array([1,2,3]), [14,32]) + assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]]) + + assert_equal(A.matvec(np.matrix([[1],[2],[3]])), [[14],[32]]) + assert_equal(A * np.matrix([[1],[2],[3]]), [[14],[32]]) + + assert( isinstance(A.matvec(np.array([1,2,3])), np.ndarray) ) + assert( isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray) ) + assert( isinstance(A * np.array([1,2,3]), np.ndarray) ) + assert( isinstance(A * np.array([[1],[2],[3]]), np.ndarray) ) + + assert( isinstance(A.matvec(np.matrix([[1],[2],[3]])), np.ndarray) ) + assert( isinstance(A * np.matrix([[1],[2],[3]]), np.ndarray) ) + + assert_raises(ValueError, A.matvec, np.array([1,2])) + assert_raises(ValueError, A.matvec, np.array([1,2,3,4])) + assert_raises(ValueError, A.matvec, np.array([[1],[2]])) + assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]])) + - assert_raises(ValueError, A.matvec, np.array([1,2])) - assert_raises(ValueError, A.matvec, np.array([1,2,3,4])) - assert_raises(ValueError, A.matvec, np.array([[1],[2]])) - assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]])) - class TestAsLinearOperator(TestCase): def setUp(self): self.cases = [] From scipy-svn at scipy.org Sat Nov 22 22:41:19 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 21:41:19 -0600 (CST) Subject: [Scipy-svn] r5173 - in trunk/scipy/stats: . tests Message-ID: <20081123034119.A99E139C088@scipy.org> Author: josef Date: 2008-11-22 21:41:15 -0600 (Sat, 22 Nov 2008) New Revision: 5173 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_stats.py Log: correction for friedmanchisquare ticket:113, add tests (including for mstats version) Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-22 23:14:44 UTC (rev 5172) +++ trunk/scipy/stats/stats.py 2008-11-23 03:41:15 UTC (rev 5173) @@ -190,6 +190,9 @@ import warnings import math +#friedmanchisquare patch uses python sum +pysum = sum # save it before it gets overwritten + # Scipy imports. from numpy import array, asarray, dot, ma, zeros, sum import scipy.special as special @@ -2139,22 +2142,39 @@ """Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated - probability value. It assumes 3 or more repeated measures. Only 3 - levels requires a minimum of 10 subjects in the study. Four levels - requires 5 subjects per level(??). + probability value. - Returns: chi-square statistic, associated p-value + This function uses Chisquared aproximation of Friedman Chisquared + distribution. This is exact only if n > 10 and factor levels > 6. + + Returns: friedman chi-square statistic, associated p-valueIt assumes 3 or more repeated measures. Only 3 """ k = len(args) if k < 3: raise ValueError, '\nLess than 3 levels. Friedman test not appropriate.\n' n = len(args[0]) + for i in range(1,k): + if len(args[i]) <> n: + raise ValueError, 'Unequal N in friedmanchisquare. Aborting.' + if n < 10 and k < 6: + print 'Warning: friedmanchisquare test using Chisquared aproximation' + + # Rank data data = apply(_support.abut,args) data = data.astype(float) for i in range(len(data)): data[i] = rankdata(data[i]) - ssbn = np.sum(np.sum(args,1)**2,axis=0) - chisq = 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1) + + # Handle ties + ties = 0 + for i in range(len(data)): + replist, repnum = scipy.stats.find_repeats(array(data[i])) + for t in repnum: + ties += t*(t*t-1) + c = 1 - ties / float(k*(k*k-1)*n) + + ssbn = pysum(pysum(data)**2) + chisq = ( 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1) ) / c return chisq, chisqprob(chisq,k-1) Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-22 23:14:44 UTC (rev 5172) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-23 03:41:15 UTC (rev 5173) @@ -956,5 +956,74 @@ assert_equal(stats.percentileofscore([ 10,20,30,50,60,70,80,90,100,110],0,kind = 'mean'),0.0) + +def test_friedmanchisquare(): + # see ticket:113 + # verified with matlab and R + #From Demsar "Statistical Comparisons of Classifiers over Multiple Data Sets" + #2006, Xf=9.28 (no tie handling, tie corrected Xf >=9.28) + x1 = [array([0.763, 0.599, 0.954, 0.628, 0.882, 0.936, 0.661, 0.583, + 0.775, 1.0, 0.94, 0.619, 0.972, 0.957]), + array([0.768, 0.591, 0.971, 0.661, 0.888, 0.931, 0.668, 0.583, + 0.838, 1.0, 0.962, 0.666, 0.981, 0.978]), + array([0.771, 0.590, 0.968, 0.654, 0.886, 0.916, 0.609, 0.563, + 0.866, 1.0, 0.965, 0.614, 0.9751, 0.946]), + array([0.798, 0.569, 0.967, 0.657, 0.898, 0.931, 0.685, 0.625, + 0.875, 1.0, 0.962, 0.669, 0.975, 0.970])] + + #From "Bioestadistica para las ciencias de la salud" Xf=18.95 p<0.001: + x2 = [array([4,3,5,3,5,3,2,5,4,4,4,3]), + array([2,2,1,2,3,1,2,3,2,1,1,3]), + array([2,4,3,3,4,3,3,4,4,1,2,1]), + array([3,5,4,3,4,4,3,3,3,4,4,4])] + + #From Jerrorl H. Zar, "Biostatistical Analysis"(example 12.6), Xf=10.68, 0.005 < p < 0.01: + #Probability from this example is inexact using Chisquare aproximation of Friedman Chisquare. + x3 = [array([7.0,9.9,8.5,5.1,10.3]), + array([5.3,5.7,4.7,3.5,7.7]), + array([4.9,7.6,5.5,2.8,8.4]), + array([8.8,8.9,8.1,3.3,9.1])] + + # Hollander & Wolfe (1973), p. 140ff. + # from R help file + xR = array( [5.40, 5.50, 5.55, + 5.85, 5.70, 5.75, + 5.20, 5.60, 5.50, + 5.55, 5.50, 5.40, + 5.90, 5.85, 5.70, + 5.45, 5.55, 5.60, + 5.40, 5.40, 5.35, + 5.45, 5.50, 5.35, + 5.25, 5.15, 5.00, + 5.85, 5.80, 5.70, + 5.25, 5.20, 5.10, + 5.65, 5.55, 5.45, + 5.60, 5.35, 5.45, + 5.05, 5.00, 4.95, + 5.50, 5.50, 5.40, + 5.45, 5.55, 5.50, + 5.55, 5.55, 5.35, + 5.45, 5.50, 5.55, + 5.50, 5.45, 5.25, + 5.65, 5.60, 5.40, + 5.70, 5.65, 5.55, + 6.30, 6.30, 6.25]) + xR = xR.reshape((len(xR)/3.0,3)).T + + #assert_array_almost_equal(stats.friedmanchisquare(xR[0],xR[1],xR[2]),(11.1429, 0.003805),3) + assert_array_almost_equal(stats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]),(10.2283464566929, 0.0167215803284414)) + assert_array_almost_equal(stats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]),(18.9428571428571, 0.000280938375189499)) + assert_array_almost_equal(stats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]),(10.68, 0.0135882729582176)) + np.testing.assert_raises(ValueError, stats.friedmanchisquare,x3[0],x3[1]) + + assert_array_almost_equal(stats.mstats.friedmanchisquare(xR[0],xR[1],xR[2]),(11.1429, 0.003805),4) + assert_array_almost_equal(stats.mstats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]),(10.2283464566929, 0.0167215803284414)) + # the following fails + #assert_array_almost_equal(stats.mstats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]),(18.9428571428571, 0.000280938375189499)) + assert_array_almost_equal(stats.mstats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]),(10.68, 0.0135882729582176)) + np.testing.assert_raises(ValueError,stats.mstats.friedmanchisquare,x3[0],x3[1]) + + + if __name__ == "__main__": run_module_suite() From scipy-svn at scipy.org Sat Nov 22 23:45:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 22 Nov 2008 22:45:38 -0600 (CST) Subject: [Scipy-svn] r5174 - trunk/scipy/stats/tests Message-ID: <20081123044538.807E139C088@scipy.org> Author: josef Date: 2008-11-22 22:45:36 -0600 (Sat, 22 Nov 2008) New Revision: 5174 Modified: trunk/scipy/stats/tests/test_stats.py Log: remove one friedmanchisquare test Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-11-23 03:41:15 UTC (rev 5173) +++ trunk/scipy/stats/tests/test_stats.py 2008-11-23 04:45:36 UTC (rev 5174) @@ -984,39 +984,13 @@ array([4.9,7.6,5.5,2.8,8.4]), array([8.8,8.9,8.1,3.3,9.1])] - # Hollander & Wolfe (1973), p. 140ff. - # from R help file - xR = array( [5.40, 5.50, 5.55, - 5.85, 5.70, 5.75, - 5.20, 5.60, 5.50, - 5.55, 5.50, 5.40, - 5.90, 5.85, 5.70, - 5.45, 5.55, 5.60, - 5.40, 5.40, 5.35, - 5.45, 5.50, 5.35, - 5.25, 5.15, 5.00, - 5.85, 5.80, 5.70, - 5.25, 5.20, 5.10, - 5.65, 5.55, 5.45, - 5.60, 5.35, 5.45, - 5.05, 5.00, 4.95, - 5.50, 5.50, 5.40, - 5.45, 5.55, 5.50, - 5.55, 5.55, 5.35, - 5.45, 5.50, 5.55, - 5.50, 5.45, 5.25, - 5.65, 5.60, 5.40, - 5.70, 5.65, 5.55, - 6.30, 6.30, 6.25]) - xR = xR.reshape((len(xR)/3.0,3)).T - #assert_array_almost_equal(stats.friedmanchisquare(xR[0],xR[1],xR[2]),(11.1429, 0.003805),3) assert_array_almost_equal(stats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]),(10.2283464566929, 0.0167215803284414)) assert_array_almost_equal(stats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]),(18.9428571428571, 0.000280938375189499)) assert_array_almost_equal(stats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]),(10.68, 0.0135882729582176)) np.testing.assert_raises(ValueError, stats.friedmanchisquare,x3[0],x3[1]) - assert_array_almost_equal(stats.mstats.friedmanchisquare(xR[0],xR[1],xR[2]),(11.1429, 0.003805),4) + # test using mstats assert_array_almost_equal(stats.mstats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]),(10.2283464566929, 0.0167215803284414)) # the following fails #assert_array_almost_equal(stats.mstats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]),(18.9428571428571, 0.000280938375189499)) From scipy-svn at scipy.org Sun Nov 23 03:53:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 23 Nov 2008 02:53:38 -0600 (CST) Subject: [Scipy-svn] r5175 - trunk/scipy/linalg Message-ID: <20081123085338.9C97839C088@scipy.org> Author: tzito Date: 2008-11-23 02:53:29 -0600 (Sun, 23 Nov 2008) New Revision: 5175 Modified: trunk/scipy/linalg/generic_flapack.pyf Log: Fix for ticket #795. Modified: trunk/scipy/linalg/generic_flapack.pyf =================================================================== --- trunk/scipy/linalg/generic_flapack.pyf 2008-11-23 04:45:36 UTC (rev 5174) +++ trunk/scipy/linalg/generic_flapack.pyf 2008-11-23 08:53:29 UTC (rev 5175) @@ -1459,7 +1459,7 @@ complex intent(out),dimension(n,m),depend(n,m) :: z integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n integer intent(hide),dimension(2*m) :: isuppz - integer intent(in),depend(n) :: lwork=2*n + integer intent(in),depend(n) :: lwork=18*n complex intent(hide),dimension(lwork) :: work integer intent(hide),depend(n) :: lrwork=24*n real intent(hide),dimension(lrwork) :: rwork @@ -1489,7 +1489,7 @@ complex*16 intent(out),dimension(n,m),depend(n,m) :: z integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n integer intent(hide),dimension(2*m) :: isuppz - integer intent(in),depend(n) :: lwork=2*n + integer intent(in),depend(n) :: lwork=18*n complex*16 intent(hide),dimension(lwork) :: work integer intent(hide),depend(n) :: lrwork=24*n double precision intent(hide),dimension(lrwork) :: rwork @@ -1550,7 +1550,7 @@ complex intent(in,copy),dimension(n,n) :: b integer intent(hide),depend(n,b) :: ldb=n real intent(out),dimension(n),depend(n) :: w - integer intent(hide) :: lwork=2*n-1 + integer intent(hide) :: lwork=18*n-1 complex intent(hide),dimension(lwork) :: work real intent(hide),dimension(3*n-2) :: rwork integer intent(out) :: info @@ -1570,7 +1570,7 @@ complex*16 intent(in,copy),dimension(n,n) :: b integer intent(hide),depend(n,b) :: ldb=n double precision intent(out),dimension(n),depend(n) :: w - integer intent(hide) :: lwork=2*n-1 + integer intent(hide) :: lwork=18*n-1 complex*16 intent(hide),dimension(lwork) :: work double precision intent(hide),dimension(3*n-2) :: rwork integer intent(out) :: info @@ -1752,7 +1752,7 @@ real intent(out),dimension(n),depend(n) :: w complex intent(out),dimension(n,m),depend(n,m) :: z integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n - integer intent(in),depend(n) :: lwork=2*n + integer intent(in),depend(n) :: lwork=18*n-1 complex intent(hide),dimension(lwork),depend(n,lwork) :: work real intent(hide),dimension(7*n) :: rwork integer intent(hide),dimension(5*n) :: iwork @@ -1783,7 +1783,7 @@ double precision intent(out),dimension(n),depend(n) :: w complex*16 intent(out),dimension(n,m),depend(n,m) :: z integer intent(hide),check(shape(z,0)==ldz),depend(n,z) :: ldz=n - integer intent(in),depend(n) :: lwork=2*n + integer intent(in),depend(n) :: lwork=18*n-1 complex*16 intent(hide),dimension(lwork),depend(n,lwork) :: work double precision intent(hide),dimension(7*n) :: rwork integer intent(hide),dimension(5*n) :: iwork From scipy-svn at scipy.org Sun Nov 23 04:31:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 23 Nov 2008 03:31:55 -0600 (CST) Subject: [Scipy-svn] r5176 - trunk/scipy/signal Message-ID: <20081123093155.2FE6E39C088@scipy.org> Author: cdavid Date: 2008-11-23 03:31:50 -0600 (Sun, 23 Nov 2008) New Revision: 5176 Modified: trunk/scipy/signal/setup.py Log: Add newsig.c as a dependency to sigtools module. Modified: trunk/scipy/signal/setup.py =================================================================== --- trunk/scipy/signal/setup.py 2008-11-23 08:53:29 UTC (rev 5175) +++ trunk/scipy/signal/setup.py 2008-11-23 09:31:50 UTC (rev 5176) @@ -10,7 +10,7 @@ config.add_extension('sigtools', sources=['sigtoolsmodule.c', 'firfilter.c','medianfilter.c'], - depends = ['sigtools.h'] + depends = ['sigtools.h', 'newsig.c'] ) config.add_extension('spline', From scipy-svn at scipy.org Sun Nov 23 23:12:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 23 Nov 2008 22:12:56 -0600 (CST) Subject: [Scipy-svn] r5177 - trunk/scipy/stats/tests Message-ID: <20081124041256.6E6B739C088@scipy.org> Author: josef Date: 2008-11-23 22:12:52 -0600 (Sun, 23 Nov 2008) New Revision: 5177 Modified: trunk/scipy/stats/tests/test_discrete_chisquare.py Log: correction to test Modified: trunk/scipy/stats/tests/test_discrete_chisquare.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-23 09:31:50 UTC (rev 5176) +++ trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-24 04:12:52 UTC (rev 5177) @@ -27,7 +27,7 @@ ''' # define parameters for test - n=50000 + n=2000 nsupp = 20 wsupp = 1.0/nsupp From scipy-svn at scipy.org Mon Nov 24 02:44:13 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 01:44:13 -0600 (CST) Subject: [Scipy-svn] r5178 - trunk/scipy/stats Message-ID: <20081124074413.C44DC39C27D@scipy.org> Author: cdavid Date: 2008-11-24 01:44:09 -0600 (Mon, 24 Nov 2008) New Revision: 5178 Modified: trunk/scipy/stats/stats.py Log: Fix missing namespace. Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-24 04:12:52 UTC (rev 5177) +++ trunk/scipy/stats/stats.py 2008-11-24 07:44:09 UTC (rev 5178) @@ -1159,7 +1159,7 @@ n = len(a) if kind == 'rank': - if not(any(a == score)): + if not(np.any(a == score)): a = np.append(a,score) a_len = np.array(range(len(a))) else: From scipy-svn at scipy.org Mon Nov 24 03:18:32 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 02:18:32 -0600 (CST) Subject: [Scipy-svn] r5179 - in trunk: doc doc/frontpage scipy/cluster scipy/linalg scipy/linalg/tests scipy/sparse scipy/sparse/linalg scipy/sparse/linalg/eigen/arpack scipy/sparse/linalg/eigen/arpack/tests scipy/sparse/linalg/tests scipy/sparse/tests scipy/stats scipy/stats/tests Message-ID: <20081124081832.3FE4A39C088@scipy.org> Author: jarrod.millman Date: 2008-11-24 02:18:25 -0600 (Mon, 24 Nov 2008) New Revision: 5179 Modified: trunk/doc/frontpage/conf.py trunk/doc/postprocess.py trunk/scipy/cluster/hierarchy.py trunk/scipy/linalg/decomp.py trunk/scipy/linalg/tests/test_decomp.py trunk/scipy/sparse/base.py trunk/scipy/sparse/linalg/eigen/arpack/setup.py trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py trunk/scipy/sparse/linalg/interface.py trunk/scipy/sparse/linalg/tests/test_interface.py trunk/scipy/sparse/tests/test_base.py trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_discrete_basic.py Log: ran reindent before tagging later tonight Modified: trunk/doc/frontpage/conf.py =================================================================== --- trunk/doc/frontpage/conf.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/doc/frontpage/conf.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -168,7 +168,7 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). -latex_documents = [ ] +latex_documents = [ ] # The name of an image file (relative to this directory) to place at the top of # the title page. Modified: trunk/doc/postprocess.py =================================================================== --- trunk/doc/postprocess.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/doc/postprocess.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -40,7 +40,7 @@ def process_tex(lines): """ Remove unnecessary section titles from the LaTeX file. - + """ new_lines = [] for line in lines: Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/cluster/hierarchy.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -973,9 +973,9 @@ deviation of the link heights, respectively; ``R[i,2]`` is the number of links included in the calculation; and ``R[i,3]`` is the inconsistency coefficient, - + .. math:: - + \frac{\mathtt{Z[i,2]}-\mathtt{R[i,0]}} {R[i,1]}. """ Modified: trunk/scipy/linalg/decomp.py =================================================================== --- trunk/scipy/linalg/decomp.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/linalg/decomp.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -207,7 +207,7 @@ def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, eigvals=None, type=1): """Solve an ordinary or generalized eigenvalue problem for a complex - Hermitian or real symmetric matrix. + Hermitian or real symmetric matrix. Find eigenvalues w and optionally eigenvectors v of matrix a, where b is positive definite:: @@ -262,8 +262,8 @@ type 2: inv(v).conj() a inv(v) = w type = 1 or 2: v.conj() b v = I type = 3 : v.conj() inv(b) v = I - - Raises LinAlgError if eigenvalue computation does not converge, + + Raises LinAlgError if eigenvalue computation does not converge, an error occurred, or b matrix is not definite positive. Note that if input matrices are not symmetric or hermitian, no error is reported but results will be wrong. @@ -296,7 +296,7 @@ cplx = cplx or False else: b1 = None - + # Set job for fortran routines _job = (eigvals_only and 'N') or 'V' @@ -321,17 +321,17 @@ pfx = 'he' else: pfx = 'sy' - + # Standard Eigenvalue Problem # Use '*evr' routines # FIXME: implement calculation of optimal lwork # for all lapack routines if b1 is None: (evr,) = get_lapack_funcs((pfx+'evr',), (a1,)) - if eigvals is None: + if eigvals is None: w, v, info = evr(a1, uplo=uplo, jobz=_job, range="A", il=1, iu=a1.shape[0], overwrite_a=overwrite_a) - else: + else: (lo, hi)= eigvals w_tot, v, info = evr(a1, uplo=uplo, jobz=_job, range="I", il=lo, iu=hi, overwrite_a=overwrite_a) @@ -367,7 +367,7 @@ return w else: return w, v - + elif info < 0: raise LinAlgError("illegal value in %i-th argument of internal" " fortran routine." % (-info)) @@ -579,7 +579,7 @@ def eigvalsh(a, b=None, lower=True, overwrite_a=False, overwrite_b=False, turbo=True, eigvals=None, type=1): """Solve an ordinary or generalized eigenvalue problem for a complex - Hermitian or real symmetric matrix. + Hermitian or real symmetric matrix. Find eigenvalues w of matrix a, where b is positive definite:: @@ -622,7 +622,7 @@ The N (1<=N<=M) selected eigenvalues, in ascending order, each repeated according to its multiplicity. - Raises LinAlgError if eigenvalue computation does not converge, + Raises LinAlgError if eigenvalue computation does not converge, an error occurred, or b matrix is not definite positive. Note that if input matrices are not symmetric or hermitian, no error is reported but results will be wrong. @@ -636,7 +636,7 @@ """ return eigh(a, b=b, lower=lower, eigvals_only=True, overwrite_a=overwrite_a, overwrite_b=overwrite_b, - turbo=turbo, eigvals=eigvals, type=type) + turbo=turbo, eigvals=eigvals, type=type) def eigvals_banded(a_band,lower=0,overwrite_a_band=0, select='a', select_range=None): Modified: trunk/scipy/linalg/tests/test_decomp.py =================================================================== --- trunk/scipy/linalg/tests/test_decomp.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/linalg/tests/test_decomp.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -515,7 +515,7 @@ # add antisymmetric matrix as imag part a = a1 +1j*(triu(a2)-tril(a2)) return a.astype(dtype) - + def eigenhproblem_standard(desc, dim, dtype, overwrite, lower, turbo, eigvals): @@ -524,7 +524,7 @@ a = _complex_symrand(dim, dtype) else: a = symrand(dim).astype(dtype) - + if overwrite: a_c = a.copy() else: @@ -559,7 +559,7 @@ assert_array_almost_equal(diag1_, w, DIGITS[dtype]) diag2_ = diag(dot(z.T.conj(), dot(b_c, z))).real assert_array_almost_equal(diag2_, ones(diag2_.shape[0]), DIGITS[dtype]) - + def test_eigh_integer(): a = array([[1,2],[2,7]]) b = array([[3,1],[1,5]]) Modified: trunk/scipy/sparse/base.py =================================================================== --- trunk/scipy/sparse/base.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/sparse/base.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -292,7 +292,7 @@ other = np.asanyarray(other) other = np.asanyarray(other) - + if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1: # dense row or column vector if other.shape != (N,) and other.shape != (N,1): Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -3,7 +3,7 @@ from os.path import join def needs_veclib_wrapper(info): - """Returns true if needs special veclib wrapper.""" + """Returns true if needs special veclib wrapper.""" import re r_accel = re.compile("Accelerate") r_vec = re.compile("vecLib") Modified: trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/sparse/linalg/eigen/arpack/tests/test_arpack.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -261,7 +261,7 @@ for typ in 'FD': for which in ['LI','LR','LM','SI','SR','SM']: for m in self.nonsymmetric: - self.eval_evec(m,typ,k,which) + self.eval_evec(m,typ,k,which) if __name__ == "__main__": run_module_suite() Modified: trunk/scipy/sparse/linalg/interface.py =================================================================== --- trunk/scipy/sparse/linalg/interface.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/sparse/linalg/interface.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -85,14 +85,14 @@ """Default matrix-matrix multiplication handler. Falls back on the user-defined matvec() routine, which is always provided. """ - + return np.hstack( [ self.matvec(col.reshape(-1,1)) for col in X.T ] ) def matvec(self, x): """Matrix-vector multiplication - Performs the operation y=A*x where A is an MxN linear + Performs the operation y=A*x where A is an MxN linear operator and x is a column vector or rank-1 array. Parameters @@ -103,7 +103,7 @@ Returns ------- y : {matrix, ndarray} - A matrix or ndarray with shape (M,) or (M,1) depending + A matrix or ndarray with shape (M,) or (M,1) depending on the type and shape of the x argument. Notes @@ -114,14 +114,14 @@ """ x = np.asanyarray(x) - + M,N = self.shape - + if x.shape != (N,) and x.shape != (N,1): raise ValueError('dimension mismatch') y = self._matvec(x) - + if isinstance(x, np.matrix): y = np.asmatrix(y) else: @@ -141,7 +141,7 @@ def matmat(self, X): """Matrix-matrix multiplication - Performs the operation y=A*X where A is an MxN linear + Performs the operation y=A*X where A is an MxN linear operator and X dense N*K matrix or ndarray. Parameters @@ -163,10 +163,10 @@ """ X = np.asanyarray(X) - + if X.ndim != 2: raise ValueError('expected rank-2 ndarray or matrix') - + M,N = self.shape if X.shape[0] != N: @@ -178,8 +178,8 @@ Y = np.asmatrix(Y) return Y - + def __mul__(self,x): x = np.asarray(x) Modified: trunk/scipy/sparse/linalg/tests/test_interface.py =================================================================== --- trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/sparse/linalg/tests/test_interface.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -4,7 +4,7 @@ from numpy.testing import * import numpy as np -import scipy.sparse as sparse +import scipy.sparse as sparse from scipy.sparse.linalg.interface import * @@ -27,30 +27,30 @@ for matvec in self.matvecs: A = LinearOperator((2,3), matvec) - + assert_equal(A.matvec(np.array([1,2,3])), [14,32]) assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]]) assert_equal(A * np.array([1,2,3]), [14,32]) assert_equal(A * np.array([[1],[2],[3]]), [[14],[32]]) - + assert_equal(A.matvec(np.matrix([[1],[2],[3]])), [[14],[32]]) assert_equal(A * np.matrix([[1],[2],[3]]), [[14],[32]]) - + assert( isinstance(A.matvec(np.array([1,2,3])), np.ndarray) ) assert( isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray) ) assert( isinstance(A * np.array([1,2,3]), np.ndarray) ) assert( isinstance(A * np.array([[1],[2],[3]]), np.ndarray) ) - + assert( isinstance(A.matvec(np.matrix([[1],[2],[3]])), np.ndarray) ) assert( isinstance(A * np.matrix([[1],[2],[3]]), np.ndarray) ) - + assert_raises(ValueError, A.matvec, np.array([1,2])) assert_raises(ValueError, A.matvec, np.array([1,2,3,4])) assert_raises(ValueError, A.matvec, np.array([[1],[2]])) assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]])) - + class TestAsLinearOperator(TestCase): def setUp(self): self.cases = [] @@ -102,4 +102,3 @@ if hasattr(M,'dtype'): assert_equal(A.dtype, M.dtype) - Modified: trunk/scipy/sparse/tests/test_base.py =================================================================== --- trunk/scipy/sparse/tests/test_base.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/sparse/tests/test_base.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -347,7 +347,7 @@ assert_array_almost_equal([1,2,3,4]*M, dot([1,2,3,4], M.toarray())) row = matrix([[1,2,3,4]]) assert_array_almost_equal(row*M, row*M.todense()) - + def test_small_multiplication(self): """test that A*x works for x with shape () (1,) and (1,1) """ Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/stats/stats.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -1034,8 +1034,8 @@ "mean": is the average score between "weak" and "strict" and is used in testing see: http://en.wikipedia.org/wiki/Percentile_rank - + Parameters ---------- a: array like @@ -1063,13 +1063,13 @@ >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4) #default kind = 'rank 40.0 - >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'mean') + >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'mean') 35.0 >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'strict') 30.0 >>> percentileofscore([1,2,3,4,5,6,7,8,9,10],4,kind = 'weak') 40.0 - + # multiple - 2 >>> percentileofscore([1,2,3,4,4,5,6,7,8,9],4) 45.0 @@ -1079,8 +1079,8 @@ 30.0 >>> percentileofscore([1,2,3,4,4,5,6,7,8,9],4,kind = 'weak') 50.0 - - + + # multiple - 3 >>> percentileofscore([1,2,3,4,4,4,5,6,7,8],4) 50.0 @@ -1090,7 +1090,7 @@ 30.0 >>> percentileofscore([1,2,3,4,4,4,5,6,7,8],4,kind = 'weak') 60.0 - + # missing >>> percentileofscore([1,2,3,5,6,7,8,9,10,11],4) 30.0 @@ -1143,9 +1143,9 @@ 90.0 >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],110,kind = 'weak') 100.0 - + #out of bounds >>> percentileofscore([ 10,20,30,50,60,70,80,90,100,110],200) 100.0 @@ -1154,7 +1154,7 @@ ''' - + a=np.array(a) n = len(a) @@ -1164,12 +1164,12 @@ a_len = np.array(range(len(a))) else: a_len = np.array(range(len(a))) + 1.0 - + a = np.sort(a) idx = [a == score] - pct = (np.mean(a_len[idx])/(n))*100.0 + pct = (np.mean(a_len[idx])/(n))*100.0 return pct - + elif kind == 'strict': return sum(a 10 and factor levels > 6. + distribution. This is exact only if n > 10 and factor levels > 6. Returns: friedman chi-square statistic, associated p-valueIt assumes 3 or more repeated measures. Only 3 """ @@ -2155,7 +2155,7 @@ n = len(args[0]) for i in range(1,k): if len(args[i]) <> n: - raise ValueError, 'Unequal N in friedmanchisquare. Aborting.' + raise ValueError, 'Unequal N in friedmanchisquare. Aborting.' if n < 10 and k < 6: print 'Warning: friedmanchisquare test using Chisquared aproximation' @@ -2172,7 +2172,7 @@ for t in repnum: ties += t*(t*t-1) c = 1 - ties / float(k*(k*k-1)*n) - + ssbn = pysum(pysum(data)**2) chisq = ( 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1) ) / c return chisq, chisqprob(chisq,k-1) Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-24 07:44:09 UTC (rev 5178) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-24 08:18:25 UTC (rev 5179) @@ -132,7 +132,7 @@ #next 3 functions copied from test_continous_extra # adjusted - + def check_ppf_limits(distfn,arg,msg): below,low,upp,above = distfn.ppf([-1,0,1,2], *arg) #print distfn.name, distfn.a, low, distfn.b, upp From scipy-svn at scipy.org Mon Nov 24 04:51:12 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 03:51:12 -0600 (CST) Subject: [Scipy-svn] r5180 - tags Message-ID: <20081124095112.9EC2839C0F1@scipy.org> Author: jarrod.millman Date: 2008-11-24 03:51:09 -0600 (Mon, 24 Nov 2008) New Revision: 5180 Added: tags/0.7.0b1/ Log: Create the 0.7.0b1 release tag. Copied: tags/0.7.0b1 (from rev 5179, trunk) From scipy-svn at scipy.org Mon Nov 24 04:54:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 03:54:28 -0600 (CST) Subject: [Scipy-svn] r5181 - tags/0.7.0b1/scipy Message-ID: <20081124095428.DBEBB39C088@scipy.org> Author: jarrod.millman Date: 2008-11-24 03:54:25 -0600 (Mon, 24 Nov 2008) New Revision: 5181 Modified: tags/0.7.0b1/scipy/version.py Log: making the release Modified: tags/0.7.0b1/scipy/version.py =================================================================== --- tags/0.7.0b1/scipy/version.py 2008-11-24 09:51:09 UTC (rev 5180) +++ tags/0.7.0b1/scipy/version.py 2008-11-24 09:54:25 UTC (rev 5181) @@ -1,5 +1,5 @@ -version = '0.7.0' -release=False +version = '0.7.0b1' +release=True if not release: import os From scipy-svn at scipy.org Mon Nov 24 17:09:46 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 16:09:46 -0600 (CST) Subject: [Scipy-svn] r5182 - in trunk/scipy/cluster: . src tests Message-ID: <20081124220946.F15CD39C0F1@scipy.org> Author: damian.eads Date: 2008-11-24 16:09:34 -0600 (Mon, 24 Nov 2008) New Revision: 5182 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/src/hierarchy.c trunk/scipy/cluster/tests/test_hierarchy.py Log: Added regression tests for scipy.cluster.hierarchy.maxdists. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-24 09:54:25 UTC (rev 5181) +++ trunk/scipy/cluster/hierarchy.py 2008-11-24 22:09:34 UTC (rev 5182) @@ -1212,7 +1212,7 @@ else: raise ValueError('Linkage matrix must have 4 columns.') if Z.shape[0] == 0: - raise ValueError('Linkage must be over at least one observation.') + raise ValueError('Linkage must be computed on at least two observations.') n = Z.shape[0] if n > 1: if ((Z[:,0] < 0).any() or @@ -2376,13 +2376,13 @@ specifically, ``MD[i] = Z[Q(i)-n, 2].max()`` where ``Q(i)`` is the set of all node indices below and including node i. """ - Z = np.asarray(Z, order='c') + Z = np.asarray(Z, order='c', dtype=np.double) is_valid_linkage(Z, throw=True, name='Z') n = Z.shape[0] + 1 MD = np.zeros((n-1,)) [Z] = _copy_arrays_if_base_present([Z]) - _hierarchy_wrap.get_max_dist_for_each_hierarchy_wrap(Z, MD, int(n)) + _hierarchy_wrap.get_max_dist_for_each_cluster_wrap(Z, MD, int(n)) return MD def maxinconsts(Z, R): Modified: trunk/scipy/cluster/src/hierarchy.c =================================================================== --- trunk/scipy/cluster/src/hierarchy.c 2008-11-24 09:54:25 UTC (rev 5181) +++ trunk/scipy/cluster/src/hierarchy.c 2008-11-24 22:09:34 UTC (rev 5182) @@ -841,7 +841,6 @@ /** Rows i+1 to j-1 lose one unit of space, so we move them up. */ /** Rows j to np-1 lose no space. We do nothing to them. */ - /** memcpy(rows[0], buf, sizeof(double) * rowsize[0] - k);*/ for (i = 0; i < mini; i++) { @@ -1418,7 +1417,8 @@ max_dist = CPY_MAX(max_dist, max_dists[rid-n]); } max_dists[ndid-n] = max_dist; - CPY_DEBUG_MSG("i=%d maxdist[i]=%5.5f verif=%5.5f\n", ndid-n, max_dist, max_dists[ndid-n]); + CPY_DEBUG_MSG("i=%d maxdist[i]=%5.5f verif=%5.5f\n", + ndid-n, max_dist, max_dists[ndid-n]); k--; } free(curNode); Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-24 09:54:25 UTC (rev 5181) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-24 22:09:34 UTC (rev 5182) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists from scipy.spatial.distance import squareform, pdist _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -685,15 +685,109 @@ Z = linkage(X, 'single') self.failUnless(is_monotonic(Z) == True) -def help_single_inconsistent_depth(self, i): - Y = squareform(_tdist) - Z = linkage(Y, 'single') - R = inconsistent(Z, i) - Rright = eo['inconsistent-single-tdist-depth-' + str(i)] - eps = 1e-05 - print np.abs(R - Rright).max() - self.failUnless(within_tol(R, Rright, eps)) +class TestMaxDists(TestCase): + def test_maxdists_empty_linkage(self): + "Tests maxdists(Z) on empty linkage. Expecting exception." + Z = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, maxdists, Z) + + def test_maxdists_one_cluster_linkage(self): + "Tests maxdists(Z) on linkage with one cluster." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + MD = maxdists(Z) + eps = 1e-15 + expectedMD = calculate_maximum_distances(Z) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxdists_Q_linkage_single(self): + "Tests maxdists(Z) on the Q data set using single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'single') + MD = maxdists(Z) + eps = 1e-15 + expectedMD = calculate_maximum_distances(Z) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxdists_Q_linkage_complete(self): + "Tests maxdists(Z) on the Q data set using complete linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'complete') + MD = maxdists(Z) + eps = 1e-15 + expectedMD = calculate_maximum_distances(Z) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxdists_Q_linkage_ward(self): + "Tests maxdists(Z) on the Q data set using Ward linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'ward') + MD = maxdists(Z) + eps = 1e-15 + expectedMD = calculate_maximum_distances(Z) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxdists_Q_linkage_centroid(self): + "Tests maxdists(Z) on the Q data set using centroid linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'centroid') + MD = maxdists(Z) + eps = 1e-15 + expectedMD = calculate_maximum_distances(Z) + print np.abs(expectedMD - MD) + print is_monotonic(Z) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxdists_Q_linkage_median(self): + "Tests maxdists(Z) on the Q data set using median linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'median') + MD = maxdists(Z) + eps = 1e-15 + expectedMD = calculate_maximum_distances(Z) + print np.abs(expectedMD - MD).max() + print is_monotonic(Z) + self.failUnless(within_tol(MD, expectedMD, eps)) + +def calculate_maximum_distances(Z): + "Used for testing correctness of maxdists. Very slow." + n = Z.shape[0] + 1 + B = np.zeros((n-1,)) + q = np.zeros((3,)) + for i in xrange(0, n - 1): + q[:] = 0.0 + L = Z[i, 0] + R = Z[i, 1] + if L >= n: + q[0] = B[L - n] + if R >= n: + q[1] = B[R - n] + q[2] = Z[i, 2] + B[i] = q.max() + return B + +def calculate_maximum_inconsistent(Z, R): + "Used for testing correctness of maxinconsts. Very slow." + n = Z.shape[0] + 1 + B = np.zeros((n-1,)) + q = np.zeros((3,)) + for i in xrange(0, n - 1): + q[:] = 0.0 + L = Z[i, 0] + R = Z[i, 1] + if L >= n: + q[0] = B[L - n] + if R >= n: + q[1] = B[R - n] + q[2] = R[i, 2] + B[i] = q.max() + return B + def within_tol(a, b, tol): return np.abs(a - b).max() < tol From scipy-svn at scipy.org Mon Nov 24 20:53:38 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 19:53:38 -0600 (CST) Subject: [Scipy-svn] r5183 - in trunk/tools: . osx Message-ID: <20081125015338.CDD7039C088@scipy.org> Author: jarrod.millman Date: 2008-11-24 19:51:43 -0600 (Mon, 24 Nov 2008) New Revision: 5183 Added: trunk/tools/osx/ trunk/tools/osx/README.txt trunk/tools/osx/build.py trunk/tools/osx/install_and_test.py Log: add os x bulid scripts Added: trunk/tools/osx/README.txt =================================================================== --- trunk/tools/osx/README.txt 2008-11-24 22:09:34 UTC (rev 5182) +++ trunk/tools/osx/README.txt 2008-11-25 01:51:43 UTC (rev 5183) @@ -0,0 +1,32 @@ +================================== + Building an OSX binary for scipy +================================== + +This directory contains the scripts to build a universal binary for +OSX. The binaries work on OSX 10.4 and 10.5. + +The docstring in build.py may contain more current details. + +Requirements +============ + +* bdist_mpkg v0.4.3 + +Build +===== + +The build script will build a scipy distribution using bdist_mpkg and +create the mac package (mpkg) bundled in a disk image (dmg). To run +the build script:: + + python build.py + +Install and test +---------------- + +The *install_and_test.py* script will find the scipy*.mpkg, install it +using the Mac installer and then run the scipy test suite. To run the +install and test:: + + python install_and_test.py + Added: trunk/tools/osx/build.py =================================================================== --- trunk/tools/osx/build.py 2008-11-24 22:09:34 UTC (rev 5182) +++ trunk/tools/osx/build.py 2008-11-25 01:51:43 UTC (rev 5183) @@ -0,0 +1,83 @@ +"""Python script to build the OSX universal binaries. + +This is a simple script, most of the heavy lifting is done in bdist_mpkg. + +To run this script: 'python build.py' + +Requires a svn version of scipy is installed, svn is used to revert +file changes made to the docs for the end-user install. Installer is +built using sudo so file permissions are correct when installed on +user system. Script will prompt for sudo pwd. + +""" + +import os +import shutil +import subprocess +from getpass import getuser + +SRC_DIR = '../../' + +BUILD_DIR = 'build' +DIST_DIR = 'dist' + +def remove_dirs(): + print 'Removing old build and distribution directories...' + print """The distribution is built as root, so the files have the correct + permissions when installed by the user. Chown them to user for removal.""" + if os.path.exists(BUILD_DIR): + cmd = 'sudo chown -R %s %s' % (getuser(), BUILD_DIR) + shellcmd(cmd) + shutil.rmtree(BUILD_DIR) + if os.path.exists(DIST_DIR): + cmd = 'sudo chown -R %s %s' % (getuser(), DIST_DIR) + shellcmd(cmd) + shutil.rmtree(DIST_DIR) + +def build_dist(): + print 'Building distribution... (using sudo)' + cmd = 'sudo python setupegg.py bdist_mpkg' + shellcmd(cmd) + +def build_dmg(): + print 'Building disk image...' + # Since we removed the dist directory at the start of the script, + # our pkg should be the only file there. + pkg = os.listdir(DIST_DIR)[0] + fn, ext = os.path.splitext(pkg) + dmg = fn + '.dmg' + srcfolder = os.path.join(DIST_DIR, pkg) + dstfolder = os.path.join(DIST_DIR, dmg) + # build disk image + cmd = 'sudo hdiutil create -srcfolder %s %s' % (srcfolder, dstfolder) + shellcmd(cmd) + +def shellcmd(cmd, verbose=True): + """Call a shell command.""" + if verbose: + print cmd + try: + subprocess.check_call(cmd, shell=True) + except subprocess.CalledProcessError, err: + msg = """ + Error while executing a shell command. + %s + """ % str(err) + raise Exception(msg) + +def build(): + + # change to source directory + cwd = os.getcwd() + os.chdir(SRC_DIR) + + # build distribution + remove_dirs() + build_dist() + build_dmg() + + # change back to original directory + os.chdir(cwd) + +if __name__ == '__main__': + build() Added: trunk/tools/osx/install_and_test.py =================================================================== --- trunk/tools/osx/install_and_test.py 2008-11-24 22:09:34 UTC (rev 5182) +++ trunk/tools/osx/install_and_test.py 2008-11-25 01:51:43 UTC (rev 5183) @@ -0,0 +1,49 @@ +#!/usr/bin/env python +"""Install the built package and run the tests.""" + +import os + +# FIXME: Should handle relative import better! +#from .build import DIST_DIR +from build import SRC_DIR, DIST_DIR, shellcmd + +clrgreen = '\033[0;32m' +clrnull = '\033[0m' +# print '\033[0;32m foobar \033[0m' +def color_print(msg): + """Add color to this print output.""" + clrmsg = clrgreen + msg + clrnull + print clrmsg + +distdir = os.path.join(SRC_DIR, DIST_DIR) + +# Find the package and build abspath to it +pkg = None +filelist = os.listdir(distdir) +for fn in filelist: + if fn.endswith('mpkg'): + pkg = fn + break +if pkg is None: + raise IOError, 'Package is not found in directory %s' % distdir + +pkgpath = os.path.abspath(os.path.join(SRC_DIR, DIST_DIR, pkg)) +color_print('Installing package: %s' % pkgpath) + +# Run the installer +print +color_print('Installer requires admin rights, you will be prompted for sudo') +print +cmd = 'sudo installer -verbose -package %s -target /' % pkgpath +#color_print(cmd) +shellcmd(cmd) + +# Null out the PYTHONPATH so we're sure to test the Installed version of scipy +os.environ['PYTHONPATH'] = '0' + +print +color_print('Install successful!') +color_print('Running scipy test suite!') +print +import scipy +scipy.test() From scipy-svn at scipy.org Mon Nov 24 21:46:28 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 20:46:28 -0600 (CST) Subject: [Scipy-svn] r5184 - in trunk/scipy/cluster: . tests Message-ID: <20081125024628.7572F39C088@scipy.org> Author: damian.eads Date: 2008-11-24 20:46:26 -0600 (Mon, 24 Nov 2008) New Revision: 5184 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for scipy.cluster.hierarchy.maxinconsts and scipy.cluster.hierarchy.maxRstat. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-25 01:51:43 UTC (rev 5183) +++ trunk/scipy/cluster/hierarchy.py 2008-11-25 02:46:26 UTC (rev 5184) @@ -2408,6 +2408,8 @@ is_valid_im(R, throw=True, name='R') n = Z.shape[0] + 1 + if Z.shape[0] != R.shape[0]: + raise ValueError("The inconsistency matrix and linkage matrix each have a different number of rows.") MI = np.zeros((n-1,)) [Z, R] = _copy_arrays_if_base_present([Z, R]) _hierarchy_wrap.get_max_Rfield_for_each_cluster_wrap(Z, R, MI, int(n), 3) @@ -2445,8 +2447,11 @@ if type(i) is not types.IntType: raise TypeError('The third argument must be an integer.') if i < 0 or i > 3: - return ValueError('i must be an integer between 0 and 3 inclusive.') + raise ValueError('i must be an integer between 0 and 3 inclusive.') + if Z.shape[0] != R.shape[0]: + raise ValueError("The inconsistency matrix and linkage matrix each have a different number of rows.") + n = Z.shape[0] + 1 MR = np.zeros((n-1,)) [Z, R] = _copy_arrays_if_base_present([Z, R]) Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 01:51:43 UTC (rev 5183) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 02:46:26 UTC (rev 5184) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists, maxinconsts, maxRstat from scipy.spatial.distance import squareform, pdist _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -738,8 +738,6 @@ MD = maxdists(Z) eps = 1e-15 expectedMD = calculate_maximum_distances(Z) - print np.abs(expectedMD - MD) - print is_monotonic(Z) self.failUnless(within_tol(MD, expectedMD, eps)) def test_maxdists_Q_linkage_median(self): @@ -750,10 +748,410 @@ MD = maxdists(Z) eps = 1e-15 expectedMD = calculate_maximum_distances(Z) - print np.abs(expectedMD - MD).max() - print is_monotonic(Z) self.failUnless(within_tol(MD, expectedMD, eps)) +class TestMaxInconsts(TestCase): + + def test_maxinconsts_empty_linkage(self): + "Tests maxinconsts(Z, R) on empty linkage. Expecting exception." + Z = np.zeros((0, 4), dtype=np.double) + R = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, maxinconsts, Z, R) + + def test_maxinconsts_difrow_linkage(self): + "Tests maxinconsts(Z, R) on linkage and inconsistency matrices with different numbers of clusters. Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.random.rand(2, 4) + self.failUnlessRaises(ValueError, maxinconsts, Z, R) + + def test_maxinconsts_one_cluster_linkage(self): + "Tests maxinconsts(Z, R) on linkage with one cluster." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + MD = maxinconsts(Z, R) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxinconsts_Q_linkage_single(self): + "Tests maxinconsts(Z, R) on the Q data set using single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'single') + R = inconsistent(Z) + MD = maxinconsts(Z, R) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxinconsts_Q_linkage_complete(self): + "Tests maxinconsts(Z, R) on the Q data set using complete linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'complete') + R = inconsistent(Z) + MD = maxinconsts(Z, R) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxinconsts_Q_linkage_ward(self): + "Tests maxinconsts(Z, R) on the Q data set using Ward linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'ward') + R = inconsistent(Z) + MD = maxinconsts(Z, R) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxinconsts_Q_linkage_centroid(self): + "Tests maxinconsts(Z, R) on the Q data set using centroid linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'centroid') + R = inconsistent(Z) + MD = maxinconsts(Z, R) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxinconsts_Q_linkage_median(self): + "Tests maxinconsts(Z, R) on the Q data set using median linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'median') + R = inconsistent(Z) + MD = maxinconsts(Z, R) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R) + self.failUnless(within_tol(MD, expectedMD, eps)) + +class TestMaxRStat(TestCase): + + def test_maxRstat_float_index(self): + "Tests maxRstat(Z, R, 3.3). Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + self.failUnlessRaises(TypeError, maxRstat, Z, R, 3.3) + + def test_maxRstat_neg_index(self): + "Tests maxRstat(Z, R, -1). Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + self.failUnlessRaises(ValueError, maxRstat, Z, R, -1) + + def test_maxRstat_oob_pos_index(self): + "Tests maxRstat(Z, R, 4). Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 4) + + def test_maxRstat_0_empty_linkage(self): + "Tests maxRstat(Z, R, 0) on empty linkage. Expecting exception." + Z = np.zeros((0, 4), dtype=np.double) + R = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 0) + + def test_maxRstat_0_difrow_linkage(self): + "Tests maxRstat(Z, R, 0) on linkage and inconsistency matrices with different numbers of clusters. Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.random.rand(2, 4) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 0) + + def test_maxRstat_0_one_cluster_linkage(self): + "Tests maxRstat(Z, R, 0) on linkage with one cluster." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + MD = maxRstat(Z, R, 0) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 0) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_0_Q_linkage_single(self): + "Tests maxRstat(Z, R, 0) on the Q data set using single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'single') + R = inconsistent(Z) + MD = maxRstat(Z, R, 0) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 0) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_0_Q_linkage_complete(self): + "Tests maxRstat(Z, R, 0) on the Q data set using complete linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'complete') + R = inconsistent(Z) + MD = maxRstat(Z, R, 0) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 0) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_0_Q_linkage_ward(self): + "Tests maxRstat(Z, R, 0) on the Q data set using Ward linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'ward') + R = inconsistent(Z) + MD = maxRstat(Z, R, 0) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 0) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_0_Q_linkage_centroid(self): + "Tests maxRstat(Z, R, 0) on the Q data set using centroid linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'centroid') + R = inconsistent(Z) + MD = maxRstat(Z, R, 0) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 0) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_0_Q_linkage_median(self): + "Tests maxRstat(Z, R, 0) on the Q data set using median linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'median') + R = inconsistent(Z) + MD = maxRstat(Z, R, 0) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 0) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_1_empty_linkage(self): + "Tests maxRstat(Z, R, 1) on empty linkage. Expecting exception." + Z = np.zeros((0, 4), dtype=np.double) + R = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 0) + + def test_maxRstat_1_difrow_linkage(self): + "Tests maxRstat(Z, R, 1) on linkage and inconsistency matrices with different numbers of clusters. Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.random.rand(2, 4) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 0) + + def test_maxRstat_1_one_cluster_linkage(self): + "Tests maxRstat(Z, R, 1) on linkage with one cluster." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + MD = maxRstat(Z, R, 1) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 1) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_1_Q_linkage_single(self): + "Tests maxRstat(Z, R, 1) on the Q data set using single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'single') + R = inconsistent(Z) + MD = maxRstat(Z, R, 1) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 1) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_1_Q_linkage_complete(self): + "Tests maxRstat(Z, R, 1) on the Q data set using complete linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'complete') + R = inconsistent(Z) + MD = maxRstat(Z, R, 1) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 1) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_1_Q_linkage_ward(self): + "Tests maxRstat(Z, R, 1) on the Q data set using Ward linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'ward') + R = inconsistent(Z) + MD = maxRstat(Z, R, 1) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 1) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_1_Q_linkage_centroid(self): + "Tests maxRstat(Z, R, 1) on the Q data set using centroid linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'centroid') + R = inconsistent(Z) + MD = maxRstat(Z, R, 1) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 1) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_1_Q_linkage_median(self): + "Tests maxRstat(Z, R, 1) on the Q data set using median linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'median') + R = inconsistent(Z) + MD = maxRstat(Z, R, 1) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 1) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_2_empty_linkage(self): + "Tests maxRstat(Z, R, 2) on empty linkage. Expecting exception." + Z = np.zeros((0, 4), dtype=np.double) + R = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 2) + + def test_maxRstat_2_difrow_linkage(self): + "Tests maxRstat(Z, R, 2) on linkage and inconsistency matrices with different numbers of clusters. Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.random.rand(2, 4) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 2) + + def test_maxRstat_2_one_cluster_linkage(self): + "Tests maxRstat(Z, R, 2) on linkage with one cluster." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + MD = maxRstat(Z, R, 2) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 2) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_2_Q_linkage_single(self): + "Tests maxRstat(Z, R, 2) on the Q data set using single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'single') + R = inconsistent(Z) + MD = maxRstat(Z, R, 2) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 2) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_2_Q_linkage_complete(self): + "Tests maxRstat(Z, R, 2) on the Q data set using complete linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'complete') + R = inconsistent(Z) + MD = maxRstat(Z, R, 2) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 2) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_2_Q_linkage_ward(self): + "Tests maxRstat(Z, R, 2) on the Q data set using Ward linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'ward') + R = inconsistent(Z) + MD = maxRstat(Z, R, 2) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 2) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_2_Q_linkage_centroid(self): + "Tests maxRstat(Z, R, 2) on the Q data set using centroid linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'centroid') + R = inconsistent(Z) + MD = maxRstat(Z, R, 2) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 2) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_2_Q_linkage_median(self): + "Tests maxRstat(Z, R, 2) on the Q data set using median linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'median') + R = inconsistent(Z) + MD = maxRstat(Z, R, 2) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 2) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_3_empty_linkage(self): + "Tests maxRstat(Z, R, 3) on empty linkage. Expecting exception." + Z = np.zeros((0, 4), dtype=np.double) + R = np.zeros((0, 4), dtype=np.double) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 3) + + def test_maxRstat_3_difrow_linkage(self): + "Tests maxRstat(Z, R, 3) on linkage and inconsistency matrices with different numbers of clusters. Expecting exception." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.random.rand(2, 4) + self.failUnlessRaises(ValueError, maxRstat, Z, R, 3) + + def test_maxRstat_3_one_cluster_linkage(self): + "Tests maxRstat(Z, R, 3) on linkage with one cluster." + Z = np.asarray([[0, 1, 0.3, 4]], dtype=np.double) + R = np.asarray([[0, 0, 0, 0.3]], dtype=np.double) + MD = maxRstat(Z, R, 3) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 3) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_3_Q_linkage_single(self): + "Tests maxRstat(Z, R, 3) on the Q data set using single linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'single') + R = inconsistent(Z) + MD = maxRstat(Z, R, 3) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 3) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_3_Q_linkage_complete(self): + "Tests maxRstat(Z, R, 3) on the Q data set using complete linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'complete') + R = inconsistent(Z) + MD = maxRstat(Z, R, 3) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 3) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_3_Q_linkage_ward(self): + "Tests maxRstat(Z, R, 3) on the Q data set using Ward linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'ward') + R = inconsistent(Z) + MD = maxRstat(Z, R, 3) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 3) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_3_Q_linkage_centroid(self): + "Tests maxRstat(Z, R, 3) on the Q data set using centroid linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'centroid') + R = inconsistent(Z) + MD = maxRstat(Z, R, 3) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 3) + self.failUnless(within_tol(MD, expectedMD, eps)) + + def test_maxRstat_3_Q_linkage_median(self): + "Tests maxRstat(Z, R, 3) on the Q data set using median linkage." + X = eo['Q-X'] + Y = pdist(X) + Z = linkage(X, 'median') + R = inconsistent(Z) + MD = maxRstat(Z, R, 3) + eps = 1e-15 + expectedMD = calculate_maximum_inconsistencies(Z, R, 3) + self.failUnless(within_tol(MD, expectedMD, eps)) + def calculate_maximum_distances(Z): "Used for testing correctness of maxdists. Very slow." n = Z.shape[0] + 1 @@ -761,30 +1159,31 @@ q = np.zeros((3,)) for i in xrange(0, n - 1): q[:] = 0.0 - L = Z[i, 0] - R = Z[i, 1] - if L >= n: - q[0] = B[L - n] - if R >= n: - q[1] = B[R - n] + left = Z[i, 0] + right = Z[i, 1] + if left >= n: + q[0] = B[left - n] + if right >= n: + q[1] = B[right - n] q[2] = Z[i, 2] B[i] = q.max() return B -def calculate_maximum_inconsistent(Z, R): +def calculate_maximum_inconsistencies(Z, R, k=3): "Used for testing correctness of maxinconsts. Very slow." n = Z.shape[0] + 1 B = np.zeros((n-1,)) q = np.zeros((3,)) + print R.shape for i in xrange(0, n - 1): q[:] = 0.0 - L = Z[i, 0] - R = Z[i, 1] - if L >= n: - q[0] = B[L - n] - if R >= n: - q[1] = B[R - n] - q[2] = R[i, 2] + left = Z[i, 0] + right = Z[i, 1] + if left >= n: + q[0] = B[left - n] + if right >= n: + q[1] = B[right - n] + q[2] = R[i, k] B[i] = q.max() return B From scipy-svn at scipy.org Mon Nov 24 22:41:53 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 21:41:53 -0600 (CST) Subject: [Scipy-svn] r5185 - in trunk/scipy/cluster: . tests Message-ID: <20081125034153.BFD97C7C00E@scipy.org> Author: damian.eads Date: 2008-11-24 21:41:51 -0600 (Mon, 24 Nov 2008) New Revision: 5185 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for scipy.cluster.hierarchy.is_valid_linkage. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-25 02:46:26 UTC (rev 5184) +++ trunk/scipy/cluster/hierarchy.py 2008-11-25 03:41:51 UTC (rev 5185) @@ -1198,9 +1198,9 @@ raise TypeError('Variable is not a valid array.') if Z.dtype != np.double: if name: - raise TypeError('Linkage matrix \'%s\' must contain doubles (double).' % name) + raise TypeError('Linkage matrix \'%s\' must contain doubles.' % name) else: - raise TypeError('Linkage matrix must contain doubles (double).') + raise TypeError('Linkage matrix must contain doubles.') if len(Z.shape) != 2: if name: raise ValueError('Linkage matrix \'%s\' must have shape=2 (i.e. be two-dimensional).' % name) @@ -1221,6 +1221,16 @@ raise ValueError('Linkage \'%s\' contains negative indices.' % name) else: raise ValueError('Linkage contains negative indices.') + if (Z[:, 2] < 0).any(): + if name: + raise ValueError('Linkage \'%s\' contains negative distances.' % name) + else: + raise ValueError('Linkage contains negative distances.') + if (Z[:, 3] < 0).any(): + if name: + raise ValueError('Linkage \'%s\' contains negative counts.' % name) + else: + raise ValueError('Linkage contains negative counts.') except Exception, e: if throw: raise Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 02:46:26 UTC (rev 5184) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 03:41:51 UTC (rev 5185) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists, maxinconsts, maxRstat +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists, maxinconsts, maxRstat, is_valid_linkage from scipy.spatial.distance import squareform, pdist _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -540,6 +540,81 @@ self.failUnless(is_isomorphic(a, b) == (not noniso)) self.failUnless(is_isomorphic(b, a) == (not noniso)) +class TestIsValidLinkage(TestCase): + + def test_is_valid_linkage_int_type(self): + "Tests is_valid_linkage(Z) with integer type." + Z = np.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=np.int) + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_5_columns(self): + "Tests is_valid_linkage(Z) with 5 columns." + Z = np.asarray([[0, 1, 3.0, 2, 5], + [3, 2, 4.0, 3, 3]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_3_columns(self): + "Tests is_valid_linkage(Z) with 3 columns." + Z = np.asarray([[0, 1, 3.0], + [3, 2, 4.0]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_empty(self): + "Tests is_valid_linkage(Z) with empty linkage." + Z = np.zeros((0, 4), dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_1x4(self): + "Tests is_valid_linkage(Z) on linkage over 2 observations." + Z = np.asarray([[0, 1, 3.0, 2]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == True) + + def test_is_valid_linkage_2x4(self): + "Tests is_valid_linkage(Z) on linkage over 3 observations." + Z = np.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == True) + + def test_is_valid_linkage_4_and_up(self): + "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3)." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + self.failUnless(is_valid_linkage(Z) == True) + + def test_is_valid_linkage_4_and_up_neg_index_left(self): + "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative indices (left)." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + Z[int(i/2),0] = -2 + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_4_and_up_neg_index_right(self): + "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative indices (right)." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + Z[int(i/2),1] = -2 + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_4_and_up_neg_dist(self): + "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative distances." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + Z[int(i/2),2] = -0.5 + self.failUnless(is_valid_linkage(Z) == False) + + def test_is_valid_linkage_4_and_up_neg_counts(self): + "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative counts." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + Z[int(i/2),3] = -2 + self.failUnless(is_valid_linkage(Z) == False) + class TestNumObsLinkage(TestCase): def test_num_obs_linkage_empty(self): From scipy-svn at scipy.org Mon Nov 24 23:23:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 22:23:51 -0600 (CST) Subject: [Scipy-svn] r5186 - in trunk/scipy/cluster: . tests Message-ID: <20081125042351.1239739C088@scipy.org> Author: damian.eads Date: 2008-11-24 22:23:49 -0600 (Mon, 24 Nov 2008) New Revision: 5186 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Covered a few more edge conditions for scipy.cluster.hierarchy.is_valid_linkage. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-25 03:41:51 UTC (rev 5185) +++ trunk/scipy/cluster/hierarchy.py 2008-11-25 04:23:49 UTC (rev 5186) @@ -1231,6 +1231,21 @@ raise ValueError('Linkage \'%s\' contains negative counts.' % name) else: raise ValueError('Linkage contains negative counts.') + if _check_hierarchy_uses_cluster_before_formed(Z): + if name: + raise ValueError('Linkage \'%s\' uses non-singleton cluster before its formed.' % name) + else: + raise ValueError('Linkage uses non-singleton cluster before its formed.') + if _check_hierarchy_uses_cluster_more_than_once(Z): + if name: + raise ValueError('Linkage \'%s\' uses the same cluster more than once.' % name) + else: + raise ValueError('Linkage uses the same cluster more than once.') + if _check_hierarchy_not_all_clusters_used(Z): + if name: + raise ValueError('Linkage \'%s\' does not use all clusters.' % name) + else: + raise ValueError('Linkage does not use all clusters.') except Exception, e: if throw: raise @@ -1239,6 +1254,32 @@ valid = False return valid +def _check_hierarchy_uses_cluster_before_formed(Z): + n = Z.shape[0] + 1 + for i in xrange(0, n - 1): + if Z[i, 0] >= n + i or Z[i, 1] >= n + i: + return True + return False + +def _check_hierarchy_uses_cluster_more_than_once(Z): + n = Z.shape[0] + 1 + chosen = set([]) + for i in xrange(0, n - 1): + if (Z[i, 0] in chosen) or (Z[i, 1] in chosen) or Z[i, 0] == Z[i, 1]: + return True + chosen.add(Z[i, 0]) + chosen.add(Z[i, 1]) + return False + +def _check_hierarchy_not_all_clusters_used(Z): + n = Z.shape[0] + 1 + chosen = set([]) + for i in xrange(0, n - 1): + chosen.add(int(Z[i, 0])) + chosen.add(int(Z[i, 1])) + must_chosen = set(range(0, 2 * n - 2)) + return len(must_chosen.difference(chosen)) > 0 + def num_obs_linkage(Z): """ Returns the number of original observations of the linkage matrix Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 03:41:51 UTC (rev 5185) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:23:49 UTC (rev 5186) @@ -547,23 +547,27 @@ Z = np.asarray([[0, 1, 3.0, 2], [3, 2, 4.0, 3]], dtype=np.int) self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(TypeError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_5_columns(self): "Tests is_valid_linkage(Z) with 5 columns." Z = np.asarray([[0, 1, 3.0, 2, 5], [3, 2, 4.0, 3, 3]], dtype=np.double) self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_3_columns(self): "Tests is_valid_linkage(Z) with 3 columns." Z = np.asarray([[0, 1, 3.0], [3, 2, 4.0]], dtype=np.double) self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_empty(self): "Tests is_valid_linkage(Z) with empty linkage." Z = np.zeros((0, 4), dtype=np.double) self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_1x4(self): "Tests is_valid_linkage(Z) on linkage over 2 observations." @@ -576,6 +580,35 @@ [3, 2, 4.0, 3]], dtype=np.double) self.failUnless(is_valid_linkage(Z) == True) + def test_is_valid_linkage_2x4_before1(self): + "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used before they're formed (case 1)." + Z = np.asarray([[0, 4, 3.0, 2], + [2, 3, 4.0, 3]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) + + + def test_is_valid_linkage_2x4_before2(self): + "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used before they're formed (case 1)." + Z = np.asarray([[0, 1, 3.0, 2], + [2, 5, 4.0, 3]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_2x4_twice1(self): + "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used twice (case 1)." + Z = np.asarray([[0, 1, 3.0, 2], + [3, 3, 4.0, 3]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) + + def test_is_valid_linkage_2x4_twice2(self): + "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used twice (case 1)." + Z = np.asarray([[0, 1, 3.0, 2], + [0, 1, 4.0, 3]], dtype=np.double) + self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) + def test_is_valid_linkage_4_and_up(self): "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3)." for i in xrange(4, 15, 3): @@ -590,6 +623,7 @@ Z = linkage(y) Z[int(i/2),0] = -2 self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_4_and_up_neg_index_right(self): "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative indices (right)." @@ -598,6 +632,7 @@ Z = linkage(y) Z[int(i/2),1] = -2 self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_4_and_up_neg_dist(self): "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative distances." @@ -606,6 +641,7 @@ Z = linkage(y) Z[int(i/2),2] = -0.5 self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) def test_is_valid_linkage_4_and_up_neg_counts(self): "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3) with negative counts." @@ -614,6 +650,7 @@ Z = linkage(y) Z[int(i/2),3] = -2 self.failUnless(is_valid_linkage(Z) == False) + self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) class TestNumObsLinkage(TestCase): @@ -718,28 +755,28 @@ "Tests is_monotonic(Z) on 3x4 linkage. Expecting True." Z = np.asarray([[0, 1, 0.3, 2], [2, 3, 0.4, 2], - [3, 4, 0.6, 4]], dtype=np.double) + [4, 5, 0.6, 4]], dtype=np.double) self.failUnless(is_monotonic(Z) == True) def test_is_monotonic_3x4_F1(self): "Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False." Z = np.asarray([[0, 1, 0.3, 2], [2, 3, 0.2, 2], - [3, 4, 0.6, 4]], dtype=np.double) + [4, 5, 0.6, 4]], dtype=np.double) self.failUnless(is_monotonic(Z) == False) def test_is_monotonic_3x4_F2(self): "Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False." Z = np.asarray([[0, 1, 0.8, 2], [2, 3, 0.4, 2], - [3, 4, 0.6, 4]], dtype=np.double) + [4, 5, 0.6, 4]], dtype=np.double) self.failUnless(is_monotonic(Z) == False) def test_is_monotonic_3x4_F3(self): "Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False" Z = np.asarray([[0, 1, 0.3, 2], [2, 3, 0.4, 2], - [3, 4, 0.2, 4]], dtype=np.double) + [4, 5, 0.2, 4]], dtype=np.double) self.failUnless(is_monotonic(Z) == False) def test_is_monotonic_tdist_linkage(self): From scipy-svn at scipy.org Mon Nov 24 23:24:44 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 22:24:44 -0600 (CST) Subject: [Scipy-svn] r5187 - trunk/scipy/cluster Message-ID: <20081125042444.DEE7C39C088@scipy.org> Author: damian.eads Date: 2008-11-24 22:24:42 -0600 (Mon, 24 Nov 2008) New Revision: 5187 Modified: trunk/scipy/cluster/hierarchy.py Log: Covered a few more edge conditions for scipy.cluster.hierarchy.is_valid_linkage. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-25 04:23:49 UTC (rev 5186) +++ trunk/scipy/cluster/hierarchy.py 2008-11-25 04:24:42 UTC (rev 5187) @@ -1241,11 +1241,11 @@ raise ValueError('Linkage \'%s\' uses the same cluster more than once.' % name) else: raise ValueError('Linkage uses the same cluster more than once.') - if _check_hierarchy_not_all_clusters_used(Z): - if name: - raise ValueError('Linkage \'%s\' does not use all clusters.' % name) - else: - raise ValueError('Linkage does not use all clusters.') +# if _check_hierarchy_not_all_clusters_used(Z): +# if name: +# raise ValueError('Linkage \'%s\' does not use all clusters.' % name) +# else: +# raise ValueError('Linkage does not use all clusters.') except Exception, e: if throw: raise From scipy-svn at scipy.org Mon Nov 24 23:46:25 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 22:46:25 -0600 (CST) Subject: [Scipy-svn] r5188 - in trunk/scipy/cluster: . tests Message-ID: <20081125044625.4D1E639C088@scipy.org> Author: damian.eads Date: 2008-11-24 22:46:23 -0600 (Mon, 24 Nov 2008) New Revision: 5188 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for scipy.hierarchy.leaves_list. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-25 04:24:42 UTC (rev 5187) +++ trunk/scipy/cluster/hierarchy.py 2008-11-25 04:46:23 UTC (rev 5188) @@ -1150,6 +1150,21 @@ raise ValueError('Inconsistency matrix \'%s\' must have at least one row.' % name) else: raise ValueError('Inconsistency matrix must have at least one row.') + if (R[:, 0] < 0).any(): + if name: + raise ValueError('Inconsistency matrix \'%s\' contains negative link height means.' % name) + else: + raise ValueError('Inconsistency matrix contains negative link height means.') + if (R[:, 1] < 0).any(): + if name: + raise ValueError('Inconsistency matrix \'%s\' contains negative link height standard deviations.' % name) + else: + raise ValueError('Inconsistency matrix contains negative link height standard deviations.') + if (R[:, 2] < 0).any(): + if name: + raise ValueError('Inconsistency matrix \'%s\' contains negative link counts.' % name) + else: + raise ValueError('Inconsistency matrix contains negative link counts.') except Exception, e: if throw: raise @@ -1164,10 +1179,10 @@ if it is a two dimensional nd-array (type double) with :math:`n` rows and 4 columns. The first two columns must contain indices between 0 and :math:`2n-1`. For a given row ``i``, - :math:`0 \leq \mathtt{Z[i,0]} \leq i+n-1` and - :math:`0 \leq Z[i,1] \leq i+n-1` (i.e. a cluster - cannot join another cluster unless the cluster being joined has - been generated.) + :math:`0 \leq \mathtt{Z[i,0]} \leq i+n-1` + and :math:`0 \leq Z[i,1] \leq i+n-1` + (i.e. a cluster cannot join another cluster unless the cluster + being joined has been generated.) :Arguments: Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:24:42 UTC (rev 5187) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:46:23 UTC (rev 5188) @@ -38,7 +38,7 @@ import numpy as np from numpy.testing import * -from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists, maxinconsts, maxRstat, is_valid_linkage +from scipy.cluster.hierarchy import linkage, from_mlab_linkage, to_mlab_linkage, num_obs_linkage, inconsistent, cophenet, from_mlab_linkage, fclusterdata, fcluster, is_isomorphic, single, complete, average, weighted, centroid, median, ward, leaders, correspond, is_monotonic, maxdists, maxinconsts, maxRstat, is_valid_linkage, is_valid_im, to_tree, leaves_list from scipy.spatial.distance import squareform, pdist _tdist = np.array([[0, 662, 877, 255, 412, 996], @@ -580,35 +580,6 @@ [3, 2, 4.0, 3]], dtype=np.double) self.failUnless(is_valid_linkage(Z) == True) - def test_is_valid_linkage_2x4_before1(self): - "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used before they're formed (case 1)." - Z = np.asarray([[0, 4, 3.0, 2], - [2, 3, 4.0, 3]], dtype=np.double) - self.failUnless(is_valid_linkage(Z) == False) - self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) - - - def test_is_valid_linkage_2x4_before2(self): - "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used before they're formed (case 1)." - Z = np.asarray([[0, 1, 3.0, 2], - [2, 5, 4.0, 3]], dtype=np.double) - self.failUnless(is_valid_linkage(Z) == False) - self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) - - def test_is_valid_linkage_2x4_twice1(self): - "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used twice (case 1)." - Z = np.asarray([[0, 1, 3.0, 2], - [3, 3, 4.0, 3]], dtype=np.double) - self.failUnless(is_valid_linkage(Z) == False) - self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) - - def test_is_valid_linkage_2x4_twice2(self): - "Tests is_valid_linkage(Z) on linkage over 3 observations with clusters used twice (case 1)." - Z = np.asarray([[0, 1, 3.0, 2], - [0, 1, 4.0, 3]], dtype=np.double) - self.failUnless(is_valid_linkage(Z) == False) - self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) - def test_is_valid_linkage_4_and_up(self): "Tests is_valid_linkage(Z) on linkage on observation sets between sizes 4 and 15 (step size 3)." for i in xrange(4, 15, 3): @@ -652,6 +623,84 @@ self.failUnless(is_valid_linkage(Z) == False) self.failUnlessRaises(ValueError, is_valid_linkage, Z, throw=True) +class TestIsValidInconsistent(TestCase): + + def test_is_valid_im_int_type(self): + "Tests is_valid_im(R) with integer type." + R = np.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=np.int) + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(TypeError, is_valid_im, R, throw=True) + + def test_is_valid_im_5_columns(self): + "Tests is_valid_im(R) with 5 columns." + R = np.asarray([[0, 1, 3.0, 2, 5], + [3, 2, 4.0, 3, 3]], dtype=np.double) + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_3_columns(self): + "Tests is_valid_im(R) with 3 columns." + R = np.asarray([[0, 1, 3.0], + [3, 2, 4.0]], dtype=np.double) + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_empty(self): + "Tests is_valid_im(R) with empty inconsistency matrix." + R = np.zeros((0, 4), dtype=np.double) + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_1x4(self): + "Tests is_valid_im(R) on im over 2 observations." + R = np.asarray([[0, 1, 3.0, 2]], dtype=np.double) + self.failUnless(is_valid_im(R) == True) + + def test_is_valid_im_2x4(self): + "Tests is_valid_im(R) on im over 3 observations." + R = np.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=np.double) + self.failUnless(is_valid_im(R) == True) + + def test_is_valid_im_4_and_up(self): + "Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 (step size 3)." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + R = inconsistent(Z) + self.failUnless(is_valid_im(R) == True) + + def test_is_valid_im_4_and_up_neg_index_left(self): + "Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 (step size 3) with negative link height means." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + R = inconsistent(Z) + R[int(i/2),0] = -2.0 + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_4_and_up_neg_index_right(self): + "Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 (step size 3) with negative link height standard deviations." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + R = inconsistent(Z) + R[int(i/2),1] = -2.0 + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(ValueError, is_valid_im, R, throw=True) + + def test_is_valid_im_4_and_up_neg_dist(self): + "Tests is_valid_im(R) on im on observation sets between sizes 4 and 15 (step size 3) with negative link counts." + for i in xrange(4, 15, 3): + y = np.random.rand(i*(i-1)/2) + Z = linkage(y) + R = inconsistent(Z) + R[int(i/2),2] = -0.5 + self.failUnless(is_valid_im(R) == False) + self.failUnlessRaises(ValueError, is_valid_im, R, throw=True) + class TestNumObsLinkage(TestCase): def test_num_obs_linkage_empty(self): @@ -678,6 +727,56 @@ Z = linkage(y) self.failUnless(num_obs_linkage(Z) == i) +class TestLeavesList(TestCase): + + def test_leaves_list_iris_single(self): + "Tests leaves_list(Z) on the Iris data set using single linkage." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'single') + node = to_tree(Z) + self.failUnless((node.pre_order() == leaves_list(Z)).all()) + + def test_leaves_list_iris_complete(self): + "Tests leaves_list(Z) on the Iris data set using complete linkage." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'complete') + node = to_tree(Z) + self.failUnless((node.pre_order() == leaves_list(Z)).all()) + + def test_leaves_list_iris_centroid(self): + "Tests leaves_list(Z) on the Iris data set using centroid linkage." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'centroid') + node = to_tree(Z) + self.failUnless((node.pre_order() == leaves_list(Z)).all()) + + def test_leaves_list_iris_median(self): + "Tests leaves_list(Z) on the Iris data set using median linkage." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'median') + node = to_tree(Z) + self.failUnless((node.pre_order() == leaves_list(Z)).all()) + + def test_leaves_list_iris_ward(self): + "Tests leaves_list(Z) on the Iris data set using ward linkage." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'ward') + node = to_tree(Z) + self.failUnless((node.pre_order() == leaves_list(Z)).all()) + + def test_leaves_list_iris_average(self): + "Tests leaves_list(Z) on the Iris data set using average linkage." + X = eo['iris'] + Y = pdist(X) + Z = linkage(X, 'average') + node = to_tree(Z) + self.failUnless((node.pre_order() == leaves_list(Z)).all()) + class TestCorrespond(TestCase): def test_correspond_empty(self): From scipy-svn at scipy.org Mon Nov 24 23:49:17 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 22:49:17 -0600 (CST) Subject: [Scipy-svn] r5189 - trunk/scipy/cluster/tests Message-ID: <20081125044917.19EAF39C088@scipy.org> Author: damian.eads Date: 2008-11-24 22:49:16 -0600 (Mon, 24 Nov 2008) New Revision: 5189 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for scipy.hierarchy.leaves_list. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:46:23 UTC (rev 5188) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:49:16 UTC (rev 5189) @@ -708,7 +708,6 @@ Z = np.zeros((0, 4), dtype=np.double) self.failUnlessRaises(ValueError, num_obs_linkage, Z) - def test_num_obs_linkage_1x4(self): "Tests num_obs_linkage(Z) on linkage over 2 observations." Z = np.asarray([[0, 1, 3.0, 2]], dtype=np.double) @@ -729,6 +728,19 @@ class TestLeavesList(TestCase): + def test_leaves_list_1x4(self): + "Tests leaves_list(Z) on a 1x4 linkage." + Z = np.asarray([[0, 1, 3.0, 2]], dtype=np.double) + node = to_tree(Z) + self.failUnless((leaves_list(Z) == [0, 1]).all()) + + def test_leaves_list_1x4(self): + "Tests leaves_list(Z) on a 1x4 linkage." + Z = np.asarray([[0, 1, 3.0, 2], + [3, 2, 4.0, 3]], dtype=np.double) + node = to_tree(Z) + self.failUnless((leaves_list(Z) == [0, 1, 2]).all()) + def test_leaves_list_iris_single(self): "Tests leaves_list(Z) on the Iris data set using single linkage." X = eo['iris'] From scipy-svn at scipy.org Mon Nov 24 23:51:41 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 22:51:41 -0600 (CST) Subject: [Scipy-svn] r5190 - trunk/scipy/cluster/tests Message-ID: <20081125045141.6687439C088@scipy.org> Author: damian.eads Date: 2008-11-24 22:51:40 -0600 (Mon, 24 Nov 2008) New Revision: 5190 Modified: trunk/scipy/cluster/tests/test_hierarchy.py Log: Wrote tests for scipy.hierarchy.leaves_list. Modified: trunk/scipy/cluster/tests/test_hierarchy.py =================================================================== --- trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:49:16 UTC (rev 5189) +++ trunk/scipy/cluster/tests/test_hierarchy.py 2008-11-25 04:51:40 UTC (rev 5190) @@ -734,8 +734,8 @@ node = to_tree(Z) self.failUnless((leaves_list(Z) == [0, 1]).all()) - def test_leaves_list_1x4(self): - "Tests leaves_list(Z) on a 1x4 linkage." + def test_leaves_list_2x4(self): + "Tests leaves_list(Z) on a 2x4 linkage." Z = np.asarray([[0, 1, 3.0, 2], [3, 2, 4.0, 3]], dtype=np.double) node = to_tree(Z) From scipy-svn at scipy.org Tue Nov 25 00:07:34 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Mon, 24 Nov 2008 23:07:34 -0600 (CST) Subject: [Scipy-svn] r5191 - trunk/scipy/cluster Message-ID: <20081125050734.C0DF039C088@scipy.org> Author: damian.eads Date: 2008-11-24 23:07:33 -0600 (Mon, 24 Nov 2008) New Revision: 5191 Modified: trunk/scipy/cluster/hierarchy.py Log: Minor changes to hierarchy.to_tree. Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-25 04:51:40 UTC (rev 5190) +++ trunk/scipy/cluster/hierarchy.py 2008-11-25 05:07:33 UTC (rev 5191) @@ -827,21 +827,6 @@ # Create a list full of None's to store the node objects d = [None] * (n*2-1) - # If we encounter a cluster being combined more than once, the matrix - # must be corrupt. - if len(np.unique(Z[:, 0:2].reshape((2 * (n - 1),)))) != 2 * (n - 1): - raise ValueError('Corrupt matrix Z. Some clusters are more than once.') - # If a cluster index is out of bounds, report an error. - if (Z[:, 0:2] >= 2 * n - 1).any(): - raise ValueError('Corrupt matrix Z. Some cluster indices (first and second) are out of bounds.') - if (Z[:, 0:2] < 0).any(): - raise ValueError('Corrupt matrix Z. Some cluster indices (first and second columns) are negative.') - if (Z[:, 2] < 0).any(): - raise ValueError('Corrupt matrix Z. Some distances (third column) are negative.') - - if (Z[:, 3] < 0).any(): - raise ValueError('Some counts (fourth column) are negative.') - # Create the nodes corresponding to the n original objects. for i in xrange(0, n): d[i] = ClusterNode(i) From scipy-svn at scipy.org Tue Nov 25 08:40:18 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 25 Nov 2008 07:40:18 -0600 (CST) Subject: [Scipy-svn] r5192 - trunk/scipy/stats/tests Message-ID: <20081125134018.9A38239C088@scipy.org> Author: josef Date: 2008-11-25 07:40:11 -0600 (Tue, 25 Nov 2008) New Revision: 5192 Modified: trunk/scipy/stats/tests/test_continuous_basic.py trunk/scipy/stats/tests/test_continuous_extra.py trunk/scipy/stats/tests/test_discrete_basic.py trunk/scipy/stats/tests/test_discrete_chisquare.py Log: decorate all new distributions test as slow Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-25 05:07:33 UTC (rev 5191) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-25 13:40:11 UTC (rev 5192) @@ -44,7 +44,7 @@ ['frechet_r', (1.8928171603534227,)], ['gamma', (1.9932305483800778,)], ['gausshyper', (13.763771604130699, 3.1189636648681431, - 2.5145980350183019, 5.1811649903971615)], + 2.5145980350183019, 5.1811649903971615)], #veryslow ['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)], ['genextreme', (3.3184017469423535,)], ['gengamma', (4.4162385429431925, 3.1193091679242761)], @@ -89,8 +89,8 @@ ['powerlognorm', (2.1413923530064087, 0.44639540782048337)], ['powernorm', (4.4453652254590779,)], ['rayleigh', ()], - ['rdist', (3.8266985793976525,)], - ['rdist', (541.0,)], # from ticket #758 + ['rdist', (3.8266985793976525,)], #veryslow + ['rdist', (541.0,)], # from ticket #758 #veryslow ['recipinvgauss', (0.63004267809369119,)], ['reciprocal', (0.0062309367010521255, 1.0062309367010522)], ['rice', (0.7749725210111873,)], @@ -122,6 +122,7 @@ ## ['genextreme', (-0.01,)] ## ] + at npt.dec.slow def test_cont_basic(): for distname, arg in distcont[:]: distfn = getattr(stats, distname) @@ -215,6 +216,7 @@ distmiss = [[dist,args] for dist,args in distcont if dist in distmissing] + at npt.dec.slow def test_missing_distributions(): # K-S test of distributions missing in test_distributions.py for dist, args in distmiss: Modified: trunk/scipy/stats/tests/test_continuous_extra.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-25 05:07:33 UTC (rev 5191) +++ trunk/scipy/stats/tests/test_continuous_extra.py 2008-11-25 13:40:11 UTC (rev 5192) @@ -16,6 +16,7 @@ DECIMAL = 5 + at npt.dec.slow def test_cont_extra(): for distname, arg in distcont[:]: distfn = getattr(stats, distname) @@ -27,6 +28,7 @@ yield check_loc_scale, distfn, arg, distname + \ ' loc, scale test' + at npt.dec.slow def _est_cont_skip(): for distname, arg in distcont: distfn = getattr(stats, distname) Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-25 05:07:33 UTC (rev 5191) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-25 13:40:11 UTC (rev 5192) @@ -24,7 +24,7 @@ # looking closer, mean, var should be inf for arg=2 - + at npt.dec.slow def test_discrete_basic(): for distname, arg in distdiscrete: distfn = getattr(stats,distname) @@ -41,9 +41,8 @@ skurt = stats.kurtosis(rvs) sskew = stats.skew(rvs) yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname - yield check_entropy, distfn, arg, distname + \ - ' entropy nan test' - + + at npt.dec.slow def test_discrete_extra(): for distname, arg in distdiscrete: distfn = getattr(stats,distname) @@ -51,7 +50,10 @@ ' ppf limit test' yield check_isf_limits, distfn, arg, distname + \ ' isf limit test' + yield check_entropy, distfn, arg, distname + \ + ' entropy nan test' + at npt.dec.slow def _est_discrete_private(): #testing private methods mostly for debugging # some tests might fail by design, Modified: trunk/scipy/stats/tests/test_discrete_chisquare.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-25 05:07:33 UTC (rev 5191) +++ trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-25 13:40:11 UTC (rev 5192) @@ -78,6 +78,7 @@ assert (pval > alpha), 'chisquare - test for %s' \ 'at arg = %s with pval = %s' % (distname,str(arg),str(pval)) + at dec.slow def test_discrete_rvs_cdf(): distdiscrete = [ ['bernoulli',(0.3,)], From scipy-svn at scipy.org Tue Nov 25 12:21:47 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 25 Nov 2008 11:21:47 -0600 (CST) Subject: [Scipy-svn] r5193 - trunk/scipy/linalg Message-ID: <20081125172147.3B93339C2EA@scipy.org> Author: tzito Date: 2008-11-25 11:21:38 -0600 (Tue, 25 Nov 2008) New Revision: 5193 Modified: trunk/scipy/linalg/generic_flapack.pyf Log: Fix for ticket #593. Modified: trunk/scipy/linalg/generic_flapack.pyf =================================================================== --- trunk/scipy/linalg/generic_flapack.pyf 2008-11-25 13:40:11 UTC (rev 5192) +++ trunk/scipy/linalg/generic_flapack.pyf 2008-11-25 17:21:38 UTC (rev 5193) @@ -1015,8 +1015,8 @@ depend(ldvr,n), dimension(ldvr,n),intent(out) :: vr integer intent(hide),depend(n,compute_vr) :: ldvr=(compute_vr?n:1) - integer optional,intent(in),depend(n,compute_vl,compute_vr) :: lwork=8*n - check((lwork==-1) || (lwork>=MAX(1,8*n))) :: lwork + integer optional,intent(in),depend(n,compute_vl,compute_vr) :: lwork=2*n + check((lwork==-1) || (lwork>=MAX(1,2*n))) :: lwork intent(out), dimension(MAX(lwork,1)), depend(lwork) :: work intent(hide), dimension(8*n), depend(n) :: rwork From scipy-svn at scipy.org Tue Nov 25 19:35:24 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Tue, 25 Nov 2008 18:35:24 -0600 (CST) Subject: [Scipy-svn] r5194 - trunk/scipy/spatial/tests Message-ID: <20081126003524.2371439C088@scipy.org> Author: peridot Date: 2008-11-25 18:35:21 -0600 (Tue, 25 Nov 2008) New Revision: 5194 Modified: trunk/scipy/spatial/tests/test_kdtree.py Log: Fix test failure due to roundoff error. Modified: trunk/scipy/spatial/tests/test_kdtree.py =================================================================== --- trunk/scipy/spatial/tests/test_kdtree.py 2008-11-25 17:21:38 UTC (rev 5193) +++ trunk/scipy/spatial/tests/test_kdtree.py 2008-11-26 00:35:21 UTC (rev 5194) @@ -413,7 +413,7 @@ assert_equal(ds.shape, (m,n)) for i in range(m): for j in range(n): - assert_equal(distance(xs[i],ys[j]),ds[i,j]) + assert_almost_equal(distance(xs[i],ys[j]),ds[i,j]) def test_distance_matrix_looping(): m = 10 n = 11 From scipy-svn at scipy.org Wed Nov 26 13:24:04 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 26 Nov 2008 12:24:04 -0600 (CST) Subject: [Scipy-svn] r5195 - trunk/scipy/signal Message-ID: <20081126182404.3067139C1EC@scipy.org> Author: oliphant Date: 2008-11-26 12:24:03 -0600 (Wed, 26 Nov 2008) New Revision: 5195 Modified: trunk/scipy/signal/signaltools.py Log: Add lfilter_zi so that filtfilt will work. Modified: trunk/scipy/signal/signaltools.py =================================================================== --- trunk/scipy/signal/signaltools.py 2008-11-26 00:35:21 UTC (rev 5194) +++ trunk/scipy/signal/signaltools.py 2008-11-26 18:24:03 UTC (rev 5195) @@ -12,7 +12,7 @@ ravel, size, less_equal, sum, r_, iscomplexobj, take, \ argsort, allclose, expand_dims, unique, prod, sort, reshape, \ transpose, dot, any, mean, cosh, arccosh, \ - arccos, concatenate + arccos, concatenate, flipud import numpy as np from scipy.misc import factorial @@ -1509,6 +1509,33 @@ ret = transpose(ret,tuple(olddims)) return ret +def lfilter_zi(b,a): + #compute the zi state from the filter parameters. see [Gust96]. + + #Based on: + # [Gust96] Fredrik Gustafsson, Determining the initial states in + # forward-backward filtering, IEEE Transactions on + # Signal Processing, pp. 988--992, April 1996, + # Volume 44, Issue 4 + + n=max(len(a),len(b)) + + zin = (np.eye(n-1) - np.hstack((-a[1:n,newaxis], + np.vstack((np.eye(n-2),zeros(n-2)))))) + + zid= b[1:n] - a[1:n]*b[0] + + zi_matrix=linalg.inv(zin)*(np.matrix(zid).transpose()) + zi_return=[] + + #convert the result into a regular array (not a matrix) + for i in range(len(zi_matrix)): + zi_return.append(float(zi_matrix[i][0])) + + return array(zi_return) + + + def filtfilt(b,a,x): # FIXME: For now only accepting 1d arrays ntaps=max(len(a),len(b)) From scipy-svn at scipy.org Wed Nov 26 14:24:24 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 26 Nov 2008 13:24:24 -0600 (CST) Subject: [Scipy-svn] r5196 - trunk/scipy/stats/tests Message-ID: <20081126192424.E67DB39C088@scipy.org> Author: josef Date: 2008-11-26 13:24:18 -0600 (Wed, 26 Nov 2008) New Revision: 5196 Modified: trunk/scipy/stats/tests/test_continuous_basic.py Log: merge tests to speed up, reuse rvs across tests Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-26 18:24:03 UTC (rev 5195) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-26 19:24:18 UTC (rev 5196) @@ -122,10 +122,23 @@ ## ['genextreme', (-0.01,)] ## ] +distmissing = ['wald', 'gausshyper', 'genexpon', 'rv_continuous', + 'loglaplace', 'rdist', 'semicircular', 'invweibull', 'ksone', + 'cosine', 'kstwobign', 'truncnorm', 'mielke', 'recipinvgauss', 'levy', + 'johnsonsu', 'levy_l', 'powernorm', 'wrapcauchy', + 'johnsonsb', 'truncexpon', 'rice', 'invnorm', 'invgamma', + 'powerlognorm'] + +distmiss = [[dist,args] for dist,args in distcont if dist in distmissing] +distslow = ['rdist', 'gausshyper', 'recipinvgauss', 'ksone', 'genexpon', + 'vonmises', 'rice', 'mielke', 'semicircular', 'cosine'] + + @npt.dec.slow def test_cont_basic(): for distname, arg in distcont[:]: distfn = getattr(stats, distname) + np.random.seed(765456) rvs = distfn.rvs(size=1000,*arg) sm = rvs.mean() sv = rvs.var() @@ -140,6 +153,9 @@ yield check_sf_isf, distfn, arg, distname yield check_pdf, distfn, arg, distname #yield check_oth, distfn, arg # is still missing + if distname in distmissing: + alpha = 0.01 + yield check_distribution_rvs, dist, args, alpha, rvs @@ -207,17 +223,10 @@ npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg= msg + ' - cdf-pdf relationship') -distmissing = ['wald', 'gausshyper', 'genexpon', 'rv_continuous', - 'loglaplace', 'rdist', 'semicircular', 'invweibull', 'ksone', - 'cosine', 'kstwobign', 'truncnorm', 'mielke', 'recipinvgauss', 'levy', - 'johnsonsu', 'levy_l', 'powernorm', 'wrapcauchy', - 'johnsonsb', 'truncexpon', 'rice', 'invnorm', 'invgamma', - 'powerlognorm'] -distmiss = [[dist,args] for dist,args in distcont if dist in distmissing] @npt.dec.slow -def test_missing_distributions(): +def _est_missing_distributions_old(): # K-S test of distributions missing in test_distributions.py for dist, args in distmiss: distfunc = getattr(stats, dist) @@ -233,6 +242,15 @@ assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ "; alpha = " + str(alpha) + "\nargs = " + str(args) +def check_distribution_rvs(dist, args, alpha, rvs): + #test from scipy.stats.tests + #this version reuses existing random variables + D,pval = stats.kstest(rvs, dist, args=args, N=1000) + if (pval < alpha): + D,pval = stats.kstest(dist,'',args=args, N=1000) + assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ + "; alpha = " + str(alpha) + "\nargs = " + str(args) + if __name__ == "__main__": #nose.run(argv=['', __file__]) nose.runmodule(argv=[__file__,'-s'], exit=False) From scipy-svn at scipy.org Wed Nov 26 14:29:05 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 26 Nov 2008 13:29:05 -0600 (CST) Subject: [Scipy-svn] r5197 - trunk/scipy/stats/tests Message-ID: <20081126192905.6AC8739C088@scipy.org> Author: josef Date: 2008-11-26 13:29:03 -0600 (Wed, 26 Nov 2008) New Revision: 5197 Modified: trunk/scipy/stats/tests/test_continuous_basic.py Log: split distributions in fast and slow, remove slow decorator from fast dists, add 17seconds to "not slow" tests Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-26 19:24:18 UTC (rev 5196) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-26 19:29:03 UTC (rev 5197) @@ -131,12 +131,15 @@ distmiss = [[dist,args] for dist,args in distcont if dist in distmissing] distslow = ['rdist', 'gausshyper', 'recipinvgauss', 'ksone', 'genexpon', - 'vonmises', 'rice', 'mielke', 'semicircular', 'cosine'] + 'vonmises', 'rice', 'mielke', 'semicircular', 'cosine', 'invweibull', + 'powerlognorm', 'johnsonsu', 'kstwobign'] +#distslow are sorted by speed (very slow to slow) - at npt.dec.slow + def test_cont_basic(): for distname, arg in distcont[:]: + if distname in distslow: continue distfn = getattr(stats, distname) np.random.seed(765456) rvs = distfn.rvs(size=1000,*arg) @@ -158,7 +161,34 @@ yield check_distribution_rvs, dist, args, alpha, rvs + at npt.dec.slow +def test_cont_basic_slow(): + # same as above for slow distributions + for distname, arg in distcont[:]: + if distname not in distslow: continue + distfn = getattr(stats, distname) + np.random.seed(765456) + rvs = distfn.rvs(size=1000,*arg) + sm = rvs.mean() + sv = rvs.var() + skurt = stats.kurtosis(rvs) + sskew = stats.skew(rvs) + m,v = distfn.stats(*arg) + yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, distname + \ + 'sample mean test' + yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + yield check_moment, distfn, arg, m, v, distname + yield check_cdf_ppf, distfn, arg, distname + yield check_sf_isf, distfn, arg, distname + yield check_pdf, distfn, arg, distname + #yield check_oth, distfn, arg # is still missing + if distname in distmissing: + alpha = 0.01 + yield check_distribution_rvs, dist, args, alpha, rvs + + + def check_moment(distfn, arg, m, v, msg): m1 = distfn.moment(1,*arg) m2 = distfn.moment(2,*arg) From scipy-svn at scipy.org Wed Nov 26 15:44:56 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 26 Nov 2008 14:44:56 -0600 (CST) Subject: [Scipy-svn] r5198 - trunk/scipy/stats/tests Message-ID: <20081126204456.3769339C088@scipy.org> Author: josef Date: 2008-11-26 14:44:53 -0600 (Wed, 26 Nov 2008) New Revision: 5198 Removed: trunk/scipy/stats/tests/test_discrete_chisquare.py Modified: trunk/scipy/stats/tests/test_discrete_basic.py Log: merge tests for speedup, remove slow decorator from basic tests of discrete dists Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-26 19:29:03 UTC (rev 5197) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-11-26 20:44:53 UTC (rev 5198) @@ -24,23 +24,29 @@ # looking closer, mean, var should be inf for arg=2 - at npt.dec.slow +#@npt.dec.slow def test_discrete_basic(): for distname, arg in distdiscrete: distfn = getattr(stats,distname) #assert stats.dlaplace.rvs(0.8) != None - rvs = distfn.rvs(size=10000,*arg) + np.random.seed(9765456) + rvs = distfn.rvs(size=2000,*arg) m,v = distfn.stats(*arg) #yield npt.assert_almost_equal(rvs.mean(), m, decimal=4,err_msg='mean') #yield npt.assert_almost_equal, rvs.mean(), m, 2, 'mean' # does not work - yield check_sample_meanvar, rvs.mean(), m, distname + 'sample mean test' - yield check_sample_meanvar, rvs.var(), v, distname + 'sample var test' - yield check_cdf_ppf, distfn, arg, distname - yield check_pmf_cdf, distfn, arg, distname - yield check_oth, distfn, arg, distname + yield check_sample_meanvar, rvs.mean(), m, distname + ' sample mean test' + yield check_sample_meanvar, rvs.var(), v, distname + ' sample var test' + yield check_cdf_ppf, distfn, arg, distname + ' cdf_ppf' + yield check_pmf_cdf, distfn, arg, distname + ' pmf_cdf' + yield check_oth, distfn, arg, distname + ' oth' skurt = stats.kurtosis(rvs) sskew = stats.skew(rvs) - yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + yield check_sample_skew_kurt, distfn, arg, skurt, sskew, \ + distname + ' skew_kurt' + if not distname in ['logser']: #known failure + alpha = 0.01 + yield check_discrete_chisquare, distfn, arg, rvs, alpha, \ + distname + ' chisquare' @npt.dec.slow def test_discrete_extra(): @@ -53,8 +59,8 @@ yield check_entropy, distfn, arg, distname + \ ' entropy nan test' - at npt.dec.slow -def _est_discrete_private(): + at npt.dec.skipif(True) +def test_discrete_private(): #testing private methods mostly for debugging # some tests might fail by design, # e.g. incorrect definition of distfn.a and distfn.b @@ -173,6 +179,77 @@ #print 'Entropy =', ent assert not np.isnan(ent), msg + 'test Entropy is nan'\ + + +def check_discrete_chisquare(distfn, arg, rvs, alpha, msg): + '''perform chisquare test for random sample of a discrete distribution + + Parameters + ---------- + distname : string + name of distribution function + arg : sequence + parameters of distribution + alpha : float + significance level, threshold for p-value + + Returns + ------- + result : bool + 0 if test passes, 1 if test fails + + uses global variable debug for printing results + ''' + + # define parameters for test +## n=2000 + n = len(rvs) + nsupp = 20 + wsupp = 1.0/nsupp + +## distfn = getattr(stats, distname) +## np.random.seed(9765456) +## rvs = distfn.rvs(size=n,*arg) + + # construct intervals with minimum mass 1/nsupp + # intervalls are left-half-open as in a cdf difference + distsupport = xrange(max(distfn.a, -1000), min(distfn.b, 1000) + 1) + last = 0 + distsupp = [max(distfn.a, -1000)] + distmass = [] + for ii in distsupport: + current = distfn.cdf(ii,*arg) + if current - last >= wsupp-1e-14: + distsupp.append(ii) + distmass.append(current - last) + last = current + if current > (1-wsupp): + break + if distsupp[-1] < distfn.b: + distsupp.append(distfn.b) + distmass.append(1-last) + distsupp = np.array(distsupp) + distmass = np.array(distmass) + + # convert intervals to right-half-open as required by histogram + histsupp = distsupp+1e-8 + histsupp[0] = distfn.a + + # find sample frequencies and perform chisquare test + freq,hsupp = np.histogram(rvs,histsupp,new=True) + cdfs = distfn.cdf(distsupp,*arg) + (chis,pval) = stats.chisquare(np.array(freq),n*distmass) + + assert (pval > alpha), 'chisquare - test for %s' \ + 'at arg = %s with pval = %s' % (msg,str(arg),str(pval)) + + + + + + + + if __name__ == "__main__": #nose.run(argv=['', __file__]) nose.runmodule(argv=[__file__,'-s'], exit=False) Deleted: trunk/scipy/stats/tests/test_discrete_chisquare.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-26 19:29:03 UTC (rev 5197) +++ trunk/scipy/stats/tests/test_discrete_chisquare.py 2008-11-26 20:44:53 UTC (rev 5198) @@ -1,124 +0,0 @@ - -import numpy as np -from scipy import stats -from numpy.testing import dec - -debug = False - - -def check_discrete_chisquare(distname, arg, alpha = 0.01): - '''perform chisquare test for random sample of a discrete distribution - - Parameters - ---------- - distname : string - name of distribution function - arg : sequence - parameters of distribution - alpha : float - significance level, threshold for p-value - - Returns - ------- - result : bool - 0 if test passes, 1 if test fails - - uses global variable debug for printing results - ''' - - # define parameters for test - n=2000 - nsupp = 20 - wsupp = 1.0/nsupp - - distfn = getattr(stats, distname) - np.random.seed(9765456) - rvs = distfn.rvs(size=n,*arg) - - # construct intervals with minimum mass 1/nsupp - # intervalls are left-half-open as in a cdf difference - distsupport = xrange(max(distfn.a, -1000), min(distfn.b, 1000) + 1) - last = 0 - distsupp = [max(distfn.a, -1000)] - distmass = [] - for ii in distsupport: - current = distfn.cdf(ii,*arg) - if current - last >= wsupp-1e-14: - distsupp.append(ii) - distmass.append(current - last) - last = current - if current > (1-wsupp): - break - if distsupp[-1] < distfn.b: - distsupp.append(distfn.b) - distmass.append(1-last) - distsupp = np.array(distsupp) - distmass = np.array(distmass) - - # convert intervals to right-half-open as required by histogram - histsupp = distsupp+1e-8 - histsupp[0] = distfn.a - - # find sample frequencies and perform chisquare test - freq,hsupp = np.histogram(rvs,histsupp,new=True) - cdfs = distfn.cdf(distsupp,*arg) - (chis,pval) = stats.chisquare(np.array(freq),n*distmass) - - # print and return results - if debug: - print 'chis,pval:', chis, pval - print 'len(distsupp), len(distmass), len(hsupp), len(freq)' - print len(distsupp), len(distmass), len(hsupp), len(freq) - print 'distsupp', distsupp - print 'distmass', n*np.array(distmass) - print 'freq', freq - print 'itemfreq', stats.itemfreq(rvs) - print 'n*pmf', n*distfn.pmf(list(distsupport)[:10],*arg) - - assert (pval > alpha), 'chisquare - test for %s' \ - 'at arg = %s with pval = %s' % (distname,str(arg),str(pval)) - - at dec.slow -def test_discrete_rvs_cdf(): - distdiscrete = [ - ['bernoulli',(0.3,)], - ['binom', (5, 0.4)], - ['boltzmann',(1.4, 19)], - ['dlaplace', (0.8,)], - ['geom', (0.5,)], - ['hypergeom',(30, 12, 6)], - ['logser', (0.6,)], - ['nbinom', (5, 0.5)], - ['planck', (4.1,)], - ['poisson', (0.6,)], - ['randint', (7, 31)], - ['zipf', (2,)] ] - - distknownfail = ['logser'] - - for distname, arg in distdiscrete: #[['nbinom', (5, 0.5)]]: #distdiscrete: - if distname in distknownfail: - continue - if debug: - print distname - yield check_discrete_chisquare, distname, arg - - -# decorator does not seem to work correctly with yield ???? -# I get error instead of yield -# drop failing test for now - at dec.knownfailureif(True, "This test is known to fail") -def _est_discrete_rvs_cdf_fail(): - distknownfail = [ ['logser', (0.6,)]] - for distname, arg in distknownfail: - if debug: - print distname - yield check_discrete_chisquare, distname, arg - - - - - -if __name__ == '__main__': - import nose - nose.run(argv=['', __file__]) From scipy-svn at scipy.org Wed Nov 26 19:17:49 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Wed, 26 Nov 2008 18:17:49 -0600 (CST) Subject: [Scipy-svn] r5199 - trunk/scipy/sparse/linalg/eigen/arpack Message-ID: <20081127001749.4B36C39C088@scipy.org> Author: cdavid Date: 2008-11-26 18:17:41 -0600 (Wed, 26 Nov 2008) New Revision: 5199 Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py Log: Make sure all cases of fortran wrapper for ABI issues are included in sdist-generated tarball. Modified: trunk/scipy/sparse/linalg/eigen/arpack/setup.py =================================================================== --- trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-26 20:44:53 UTC (rev 5198) +++ trunk/scipy/sparse/linalg/eigen/arpack/setup.py 2008-11-27 00:17:41 UTC (rev 5199) @@ -42,7 +42,13 @@ arpack_sources += [join('ARPACK', 'FWRAPPERS', 'dummy.f')] config.add_library('arpack', sources=arpack_sources, - include_dirs=[join('ARPACK', 'SRC')]) + include_dirs=[join('ARPACK', 'SRC')], + depends = [join('ARPACK', 'FWRAPPERS', + 'veclib_cabi_f.f'), + join('ARPACK', 'FWRAPPERS', + 'veclib_cabi_c.c'), + join('ARPACK', 'FWRAPPERS', + 'dummy.f')]) config.add_extension('_arpack', From scipy-svn at scipy.org Thu Nov 27 03:46:51 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 27 Nov 2008 02:46:51 -0600 (CST) Subject: [Scipy-svn] r5200 - trunk/scipy/linalg Message-ID: <20081127084651.78A7239C088@scipy.org> Author: tzito Date: 2008-11-27 02:46:40 -0600 (Thu, 27 Nov 2008) New Revision: 5200 Modified: trunk/scipy/linalg/decomp.py Log: Warning about 'econ' in linalg.qr is now raised only if user explicitly set 'econ'. Modified: trunk/scipy/linalg/decomp.py =================================================================== --- trunk/scipy/linalg/decomp.py 2008-11-27 00:17:41 UTC (rev 5199) +++ trunk/scipy/linalg/decomp.py 2008-11-27 08:46:40 UTC (rev 5200) @@ -1112,7 +1112,7 @@ raise TypeError, msg return b -def qr(a,overwrite_a=0,lwork=None,econ=False,mode='qr'): +def qr(a, overwrite_a=0, lwork=None, econ=None, mode='qr'): """Compute QR decomposition of a matrix. Calculate the decomposition :lm:`A = Q R` where Q is unitary/orthogonal @@ -1129,7 +1129,8 @@ is computed. econ : boolean Whether to compute the economy-size QR decomposition, making shapes - of Q and R (M, K) and (K, N) instead of (M,M) and (M,N). K=min(M,N) + of Q and R (M, K) and (K, N) instead of (M,M) and (M,N). K=min(M,N). + Default is False. mode : {'qr', 'r'} Determines what information is to be returned: either both Q and R or only R. @@ -1168,9 +1169,13 @@ ((9, 6), (6, 6)) """ - warn("""\ -qr econ argument will be removed after scipy 0.7. The economy transform will -then be available through the mode='economic' argument.""", DeprecationWarning) + if econ is None: + econ = False + else: + warn("qr econ argument will be removed after scipy 0.7." + "The economy transform will then be available through" + "the mode='economic' argument.", DeprecationWarning) + a1 = asarray_chkfinite(a) if len(a1.shape) != 2: raise ValueError("expected 2D array") From scipy-svn at scipy.org Thu Nov 27 03:52:02 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 27 Nov 2008 02:52:02 -0600 (CST) Subject: [Scipy-svn] r5201 - trunk/scipy/linalg Message-ID: <20081127085202.6632539C088@scipy.org> Author: tzito Date: 2008-11-27 02:51:56 -0600 (Thu, 27 Nov 2008) New Revision: 5201 Modified: trunk/scipy/linalg/decomp.py Log: Fixed typo in linalg.qr warning string. Modified: trunk/scipy/linalg/decomp.py =================================================================== --- trunk/scipy/linalg/decomp.py 2008-11-27 08:46:40 UTC (rev 5200) +++ trunk/scipy/linalg/decomp.py 2008-11-27 08:51:56 UTC (rev 5201) @@ -1172,8 +1172,8 @@ if econ is None: econ = False else: - warn("qr econ argument will be removed after scipy 0.7." - "The economy transform will then be available through" + warn("qr econ argument will be removed after scipy 0.7. " + "The economy transform will then be available through " "the mode='economic' argument.", DeprecationWarning) a1 = asarray_chkfinite(a) From scipy-svn at scipy.org Thu Nov 27 15:15:33 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 27 Nov 2008 14:15:33 -0600 (CST) Subject: [Scipy-svn] r5202 - trunk/doc/source Message-ID: <20081127201533.5965839C249@scipy.org> Author: ptvirtan Date: 2008-11-27 14:15:20 -0600 (Thu, 27 Nov 2008) New Revision: 5202 Added: trunk/doc/source/release.rst Modified: trunk/doc/source/index.rst Log: Include release notes in build Sphinx documentation Modified: trunk/doc/source/index.rst =================================================================== --- trunk/doc/source/index.rst 2008-11-27 08:51:56 UTC (rev 5201) +++ trunk/doc/source/index.rst 2008-11-27 20:15:20 UTC (rev 5202) @@ -9,6 +9,7 @@ :maxdepth: 1 tutorial/index + release Reference --------- Added: trunk/doc/source/release.rst =================================================================== --- trunk/doc/source/release.rst 2008-11-27 08:51:56 UTC (rev 5201) +++ trunk/doc/source/release.rst 2008-11-27 20:15:20 UTC (rev 5202) @@ -0,0 +1,5 @@ +************* +Release Notes +************* + +.. include:: ../release/0.7.0-notes.rst From scipy-svn at scipy.org Thu Nov 27 15:15:55 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Thu, 27 Nov 2008 14:15:55 -0600 (CST) Subject: [Scipy-svn] r5203 - trunk/doc/release Message-ID: <20081127201555.6F73A39C249@scipy.org> Author: ptvirtan Date: 2008-11-27 14:15:45 -0600 (Thu, 27 Nov 2008) New Revision: 5203 Modified: trunk/doc/release/0.7.0-notes.rst Log: Release notes: write a blurb about documentation Modified: trunk/doc/release/0.7.0-notes.rst =================================================================== --- trunk/doc/release/0.7.0-notes.rst 2008-11-27 20:15:20 UTC (rev 5202) +++ trunk/doc/release/0.7.0-notes.rst 2008-11-27 20:15:45 UTC (rev 5203) @@ -146,8 +146,17 @@ Major documentation improvements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -TODO +Scipy documentation is now more accessible than previously; you can +view a HTML reference manual online at http://docs.scipy.org/ or +download it as a PDF file. An updated tutorial is also available, and +it shows how to use several essential parts of Scipy. +Nevertheless, more effort is still needed on the documentation front. +Luckily, contributing to Scipy documentation is now easier than +before: if you find that a part of it requires improvements, and want +to help us out, please register a user name in our web-based +documentation editor at http://docs.scipy.org/ and correct the issues. + Bug fixes in the interpolation package ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -155,8 +164,8 @@ to be incorrect if interpolated data had more than 2 dimensions and the axis keyword was set to a non-default value. This is fixed in 0.7.0: - http://projects.scipy.org/scipy/scipy/ticket/289 - http://projects.scipy.org/scipy/scipy/ticket/660 + - http://projects.scipy.org/scipy/scipy/ticket/289 + - http://projects.scipy.org/scipy/scipy/ticket/660 Users of ``scipy.interpolate.interp1d`` may need to revise their code if it relies on the incorrect behavior. From scipy-svn at scipy.org Sat Nov 29 05:53:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 29 Nov 2008 04:53:20 -0600 (CST) Subject: [Scipy-svn] r5204 - trunk/scipy/cluster/src Message-ID: <20081129105320.C1A2039C2F8@scipy.org> Author: stefan Date: 2008-11-29 04:53:10 -0600 (Sat, 29 Nov 2008) New Revision: 5204 Modified: trunk/scipy/cluster/src/vq.c Log: Remove tabs and clean whitespace at end of lines. Modified: trunk/scipy/cluster/src/vq.c =================================================================== --- trunk/scipy/cluster/src/vq.c 2008-11-27 20:15:45 UTC (rev 5203) +++ trunk/scipy/cluster/src/vq.c 2008-11-29 10:53:10 UTC (rev 5204) @@ -18,8 +18,8 @@ #if 0 -static int float_vq_1d(const float *in, int n, - const float *init, int ncode, +static int float_vq_1d(const float *in, int n, + const float *init, int ncode, npy_intp *code, float *mdist) { int i, j; @@ -46,46 +46,46 @@ float *code_book, int Ncodes, int Nfeatures, npy_intp* code, float *lowest_dist) { - int i,j,k=0; - float dist, diff; + int i,j,k=0; + float dist, diff; - *lowest_dist = (float) rbig; - for(i = 0; i < Ncodes; i++) { - dist = 0; - for(j=0; j < Nfeatures; j++) { - diff = code_book[k] - obs[j]; - dist += diff*diff; - k++; - } - dist = (float)sqrt(dist); - if (dist < *lowest_dist) { - *code = i; - *lowest_dist = dist; - } - } + *lowest_dist = (float) rbig; + for(i = 0; i < Ncodes; i++) { + dist = 0; + for(j=0; j < Nfeatures; j++) { + diff = code_book[k] - obs[j]; + dist += diff*diff; + k++; + } + dist = (float)sqrt(dist); + if (dist < *lowest_dist) { + *code = i; + *lowest_dist = dist; + } + } return 0; } int float_tvq( float* obs, - float* code_book, + float* code_book, int Nobs, int Ncodes, int Nfeatures, npy_intp* codes, float* lowest_dist) { int i; - for( i = 0; i < Nobs; i++) { - float_vq_obs( + for( i = 0; i < Nobs; i++) { + float_vq_obs( &(obs[i*Nfeatures]), code_book,Ncodes, Nfeatures, &(codes[i]), &(lowest_dist[i])); - } + } return 0; } #if 0 -static int double_vq_1d(const double *in, int n, - const double *init, int ncode, +static int double_vq_1d(const double *in, int n, + const double *init, int ncode, npy_intp *code, double *mdist) { int i, j; @@ -112,40 +112,39 @@ double *code_book, int Ncodes, int Nfeatures, npy_intp* code, double *lowest_dist) { - int i,j,k=0; - double dist, diff; + int i,j,k=0; + double dist, diff; - *lowest_dist = (double) rbig; - for(i = 0; i < Ncodes; i++) { - dist = 0; - for(j=0; j < Nfeatures; j++) { - diff = code_book[k] - obs[j]; - dist += diff*diff; - k++; - } - dist = (double)sqrt(dist); - if (dist < *lowest_dist) { - *code = i; - *lowest_dist = dist; - } - } + *lowest_dist = (double) rbig; + for(i = 0; i < Ncodes; i++) { + dist = 0; + for(j=0; j < Nfeatures; j++) { + diff = code_book[k] - obs[j]; + dist += diff*diff; + k++; + } + dist = (double)sqrt(dist); + if (dist < *lowest_dist) { + *code = i; + *lowest_dist = dist; + } + } return 0; } int double_tvq( double* obs, - double* code_book, + double* code_book, int Nobs, int Ncodes, int Nfeatures, npy_intp* codes, double* lowest_dist) { int i; - for( i = 0; i < Nobs; i++) { - double_vq_obs( + for( i = 0; i < Nobs; i++) { + double_vq_obs( &(obs[i*Nfeatures]), code_book,Ncodes, Nfeatures, &(codes[i]), &(lowest_dist[i])); - } + } return 0; } - From scipy-svn at scipy.org Sat Nov 29 07:41:36 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 29 Nov 2008 06:41:36 -0600 (CST) Subject: [Scipy-svn] r5205 - in trunk/scipy/optimize: . tests Message-ID: <20081129124136.CAB9B39C089@scipy.org> Author: stefan Date: 2008-11-29 06:41:23 -0600 (Sat, 29 Nov 2008) New Revision: 5205 Modified: trunk/scipy/optimize/optimize.py trunk/scipy/optimize/tests/test_optimize.py Log: In `fminbound`, raise an error if non-scalar bounds are specified [patch by Neil Muller]. Closes #544. Modified: trunk/scipy/optimize/optimize.py =================================================================== --- trunk/scipy/optimize/optimize.py 2008-11-29 10:53:10 UTC (rev 5204) +++ trunk/scipy/optimize/optimize.py 2008-11-29 12:41:23 UTC (rev 5205) @@ -1136,7 +1136,7 @@ func : callable f(x,*args) Objective function to be minimized (must accept and return scalars). - x1, x2 : ndarray + x1, x2 : float or array scalar The optimization bounds. args : tuple Extra arguments passed to function. @@ -1176,6 +1176,12 @@ """ + # Test bounds are of correct form + x1 = atleast_1d(x1) + x2 = atleast_1d(x2) + if len(x1) != 1 or len(x2) != 1: + raise ValueError, "Optimisation bounds must be scalars" \ + " or length 1 arrays" if x1 > x2: raise ValueError, "The lower bound exceeds the upper bound." Modified: trunk/scipy/optimize/tests/test_optimize.py =================================================================== --- trunk/scipy/optimize/tests/test_optimize.py 2008-11-29 10:53:10 UTC (rev 5204) +++ trunk/scipy/optimize/tests/test_optimize.py 2008-11-29 12:41:23 UTC (rev 5205) @@ -147,8 +147,22 @@ assert max((err1,err2,err3,err4)) < 1e-6 + def test_fminbound(self): + """Test fminbound + """ + x = optimize.fminbound(lambda x: (x - 1.5)**2 - 0.8, 0, 1) + assert abs(x - 1) < 1e-5 + x = optimize.fminbound(lambda x: (x - 1.5)**2 - 0.8, 1, 5) + assert abs(x - 1.5) < 1e-6 + x = optimize.fminbound(lambda x: (x - 1.5)**2 - 0.8, + numpy.array([1]), numpy.array([5])) + assert abs(x - 1.5) < 1e-6 + assert_raises(ValueError, + optimize.fminbound, lambda x: (x - 1.5)**2 - 0.8, 5, 1) + assert_raises(ValueError, + optimize.fminbound, lambda x: (x - 1.5)**2 - 0.8, + np.zeros(2), 1) - class TestTnc(TestCase): """TNC non-linear optimization. From scipy-svn at scipy.org Sat Nov 29 08:42:58 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 29 Nov 2008 07:42:58 -0600 (CST) Subject: [Scipy-svn] r5206 - trunk/scipy Message-ID: <20081129134258.8441939C089@scipy.org> Author: stefan Date: 2008-11-29 07:42:49 -0600 (Sat, 29 Nov 2008) New Revision: 5206 Modified: trunk/scipy/__init__.py Log: Clean up __init__. Modified: trunk/scipy/__init__.py =================================================================== --- trunk/scipy/__init__.py 2008-11-29 12:41:23 UTC (rev 5205) +++ trunk/scipy/__init__.py 2008-11-29 13:42:49 UTC (rev 5206) @@ -37,9 +37,9 @@ __doc__ += """ Contents -------- +SciPy imports all the functions from the NumPy namespace, and in +addition provides:""" - numpy name space -""" del _num # Remove the linalg imported from numpy so that the scipy.linalg package can be # imported. @@ -63,19 +63,6 @@ pkgload = PackageLoader() pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True) -# Remove subpackage names from __all__ such that they are not imported via -# "from scipy import *". This works around a numpy bug present in < 1.2. -subpackages = """cluster constants fftpack integrate interpolate io lib linalg -linsolve maxentropy misc ndimage odr optimize signal sparse special -splinalg stats stsci weave""".split() -for name in subpackages: - try: - __all__.remove(name) - except ValueError: - pass - -del name, subpackages - if __doc__: __doc__ += """ From scipy-svn at scipy.org Sat Nov 29 20:28:23 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sat, 29 Nov 2008 19:28:23 -0600 (CST) Subject: [Scipy-svn] r5207 - trunk/scipy/optimize Message-ID: <20081130012823.6356939C089@scipy.org> Author: ptvirtan Date: 2008-11-29 19:28:12 -0600 (Sat, 29 Nov 2008) New Revision: 5207 Modified: trunk/scipy/optimize/__minpack.h Log: Remove a debug printf from __minpack.h. The printf occurred only when LMDIF returned with error status "invalid input parameters". What was printed was only input parameters to optimize.leastsq and the shape of the return value from user's function -- which the user knows anyway. Modified: trunk/scipy/optimize/__minpack.h =================================================================== --- trunk/scipy/optimize/__minpack.h 2008-11-29 13:42:49 UTC (rev 5206) +++ trunk/scipy/optimize/__minpack.h 2008-11-30 01:28:12 UTC (rev 5207) @@ -477,10 +477,6 @@ RESTORE_FUNC(); - if (info == 0) { - printf("%d %d %d %f %f %f %d %f",n, m, ldfjac, ftol, xtol, gtol, maxfev, factor); - } - if (info < 0) goto fail; /* Python error */ free(wa); From scipy-svn at scipy.org Sun Nov 30 09:48:19 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 30 Nov 2008 08:48:19 -0600 (CST) Subject: [Scipy-svn] r5208 - in trunk/doc: . source Message-ID: <20081130144819.86F0539C30B@scipy.org> Author: ptvirtan Date: 2008-11-30 08:48:09 -0600 (Sun, 30 Nov 2008) New Revision: 5208 Modified: trunk/doc/ trunk/doc/Makefile trunk/doc/source/conf.py Log: Fetch Sphinx extensions from Numpy's SVN, via svn:externals Property changes on: trunk/doc ___________________________________________________________________ Name: svn:externals + sphinxext http://svn.scipy.org/svn/numpy/trunk/doc/sphinxext Modified: trunk/doc/Makefile =================================================================== --- trunk/doc/Makefile 2008-11-30 01:28:12 UTC (rev 5207) +++ trunk/doc/Makefile 2008-11-30 14:48:09 UTC (rev 5208) @@ -48,15 +48,12 @@ find build/dist -type d -print0 | xargs -0r chmod g+s generate: build/generate-stamp -build/generate-stamp: $(wildcard source/*.rst) ext +build/generate-stamp: $(wildcard source/*.rst) mkdir -p build - ./ext/autosummary_generate.py source/*.rst \ + ./sphinxext/autosummary_generate.py source/*.rst \ -p dump.xml -o source/generated touch build/generate-stamp -ext: - svn co http://sphinx.googlecode.com/svn/contrib/trunk/numpyext ext - html: generate mkdir -p build/html build/doctrees $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) build/html Modified: trunk/doc/source/conf.py =================================================================== --- trunk/doc/source/conf.py 2008-11-30 01:28:12 UTC (rev 5207) +++ trunk/doc/source/conf.py 2008-11-30 14:48:09 UTC (rev 5208) @@ -5,7 +5,7 @@ # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. -sys.path.append(os.path.abspath('../ext')) +sys.path.append(os.path.abspath('../sphinxext')) # Check Sphinx version import sphinx From scipy-svn at scipy.org Sun Nov 30 10:19:26 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 30 Nov 2008 09:19:26 -0600 (CST) Subject: [Scipy-svn] r5209 - in trunk/scipy: cluster spatial Message-ID: <20081130151926.DABB439C30B@scipy.org> Author: ptvirtan Date: 2008-11-30 09:19:11 -0600 (Sun, 30 Nov 2008) New Revision: 5209 Modified: trunk/scipy/cluster/hierarchy.py trunk/scipy/spatial/distance.py Log: Fix bad latex in docstrings Modified: trunk/scipy/cluster/hierarchy.py =================================================================== --- trunk/scipy/cluster/hierarchy.py 2008-11-30 14:48:09 UTC (rev 5208) +++ trunk/scipy/cluster/hierarchy.py 2008-11-30 15:19:11 UTC (rev 5209) @@ -506,7 +506,7 @@ .. math:: d(u,v) = \sum_{ij} \frac{d(u[i], v[j])} - {(|u|*|v|) + {(|u|*|v|)} for all points :math:`i` and :math:`j` where :math:`|u|` and :math:`|v|` are the cardinalities of clusters :math:`u` Modified: trunk/scipy/spatial/distance.py =================================================================== --- trunk/scipy/spatial/distance.py 2008-11-30 14:48:09 UTC (rev 5208) +++ trunk/scipy/spatial/distance.py 2008-11-30 15:19:11 UTC (rev 5209) @@ -449,7 +449,7 @@ return np.sqrt(((u-v)**2 / V).sum()) def cityblock(u, v): - """ + r""" Computes the Manhattan distance between two n-vectors u and v, which is defined as @@ -472,7 +472,7 @@ return abs(u-v).sum() def mahalanobis(u, v, VI): - """ + r""" Computes the Mahalanobis distance between two n-vectors ``u`` and ``v``, which is defiend as @@ -498,7 +498,7 @@ return np.sqrt(np.dot(np.dot((u-v),VI),(u-v).T).sum()) def chebyshev(u, v): - """ + r""" Computes the Chebyshev distance between two n-vectors u and v, which is defined as @@ -521,7 +521,7 @@ return max(abs(u-v)) def braycurtis(u, v): - """ + r""" Computes the Bray-Curtis distance between two n-vectors ``u`` and ``v``, which is defined as @@ -544,7 +544,7 @@ return abs(u-v).sum() / abs(u+v).sum() def canberra(u, v): - """ + r""" Computes the Canberra distance between two n-vectors u and v, which is defined as @@ -607,15 +607,14 @@ return (nft, ntf) def yule(u, v): - """ + r""" Computes the Yule dissimilarity between two boolean n-vectors u and v, which is defined as .. math:: - \frac{R} - \frac{c_{TT} + c_{FF} + \frac{R}{2}} + \frac{R}{c_{TT} + c_{FF} + \frac{R}{2}} where :math:`c_{ij}` is the number of occurrences of :math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for @@ -637,7 +636,7 @@ return float(2.0 * ntf * nft) / float(ntt * nff + ntf * nft) def matching(u, v): - """ + r""" Computes the Matching dissimilarity between two boolean n-vectors u and v, which is defined as @@ -665,7 +664,7 @@ return float(nft + ntf) / float(len(u)) def dice(u, v): - """ + r""" Computes the Dice dissimilarity between two boolean n-vectors ``u`` and ``v``, which is @@ -698,7 +697,7 @@ return float(ntf + nft) / float(2.0 * ntt + ntf + nft) def rogerstanimoto(u, v): - """ + r""" Computes the Rogers-Tanimoto dissimilarity between two boolean n-vectors ``u`` and ``v``, which is defined as @@ -727,7 +726,7 @@ return float(2.0 * (ntf + nft)) / float(ntt + nff + (2.0 * (ntf + nft))) def russellrao(u, v): - """ + r""" Computes the Russell-Rao dissimilarity between two boolean n-vectors ``u`` and ``v``, which is defined as @@ -759,7 +758,7 @@ return float(len(u) - ntt) / float(len(u)) def sokalmichener(u, v): - """ + r""" Computes the Sokal-Michener dissimilarity between two boolean vectors ``u`` and ``v``, which is defined as @@ -795,7 +794,7 @@ return float(2.0 * (ntf + nft))/float(ntt + nff + 2.0 * (ntf + nft)) def sokalsneath(u, v): - """ + r""" Computes the Sokal-Sneath dissimilarity between two boolean vectors ``u`` and ``v``, @@ -829,7 +828,7 @@ def pdist(X, metric='euclidean', p=2, V=None, VI=None): - """ + r""" Computes the pairwise distances between m original observations in n-dimensional space. Returns a condensed distance matrix Y. For each :math:`i` and :math:`j` (where :math:`i Author: josef Date: 2008-11-30 21:44:26 -0600 (Sun, 30 Nov 2008) New Revision: 5210 Modified: trunk/scipy/stats/tests/test_continuous_basic.py Log: sample_meanvar test wasn't run, use t-test for sample mean, chisquare test for variance, change parameters of distributions for some new known failures. Skip sample skew, kurtosis test, because of imprecision and known failures Modified: trunk/scipy/stats/tests/test_continuous_basic.py =================================================================== --- trunk/scipy/stats/tests/test_continuous_basic.py 2008-11-30 15:19:11 UTC (rev 5209) +++ trunk/scipy/stats/tests/test_continuous_basic.py 2008-12-01 03:44:26 UTC (rev 5210) @@ -13,9 +13,18 @@ These tests currently check only/mostly for serious errors and exceptions, not for numerically exact results. + + +TODO: +* make functioning test for skew and kurtosis + still known failures - skip for now + + """ -DECIMAL = 2 # specify the precision of the tests +#currently not used +DECIMAL = 0 # specify the precision of the tests +DECIMAL_kurt = 0 distcont = [ ['alpha', (3.5704770516650459,)], @@ -24,7 +33,7 @@ ['beta', (2.3098496451481823, 0.62687954300963677)], ['betaprime', (5, 6)], # avoid unbound error in entropy with (100, 86)], ['bradford', (0.29891359763170633,)], - ['burr', (0.94839838075366045, 4.3820284068855795)], + ['burr', (10.5, 4.3)], #incorrect mean and var for(0.94839838075366045, 4.3820284068855795)], ['cauchy', ()], ['chi', (78,)], ['chi2', (55,)], @@ -46,7 +55,7 @@ ['gausshyper', (13.763771604130699, 3.1189636648681431, 2.5145980350183019, 5.1811649903971615)], #veryslow ['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)], - ['genextreme', (3.3184017469423535,)], + ['genextreme', (-0.1,)], # sample mean test fails for (3.3184017469423535,)], ['gengamma', (4.4162385429431925, 3.1193091679242761)], ['genhalflogistic', (0.77274727809929322,)], ['genlogistic', (0.41192440799679475,)], @@ -61,7 +70,7 @@ ['hypsecant', ()], ['invgamma', (2.0668996136993067,)], ['invnorm', (0.14546264555347513,)], - ['invweibull', (0.58847112119264788,)], + ['invweibull', (10.58,)], # sample mean test fails at(0.58847112119264788,)] ['johnsonsb', (4.3172675099141058, 3.1837781130785063)], ['johnsonsu', (2.554395574161155, 2.2482281679651965)], ['ksone', (22,)], # new added @@ -78,7 +87,8 @@ ['lognorm', (0.95368226960575331,)], ['lomax', (1.8771398388773268,)], ['maxwell', ()], - ['mielke', (4.6420495492121487, 0.59707419545516938)], + ['mielke', (10.4, 3.6)], # sample mean test fails for (4.6420495492121487, 0.59707419545516938)], + # mielke: good results if 2nd parameter >2, weird mean or var below ['nakagami', (4.9673794866666237,)], ['ncf', (27, 27, 0.41578441799226107)], ['nct', (14, 0.24045031331198066)], @@ -89,8 +99,9 @@ ['powerlognorm', (2.1413923530064087, 0.44639540782048337)], ['powernorm', (4.4453652254590779,)], ['rayleigh', ()], - ['rdist', (3.8266985793976525,)], #veryslow - ['rdist', (541.0,)], # from ticket #758 #veryslow + ['rdist', (0.9,)], # feels also slow +# ['rdist', (3.8266985793976525,)], #veryslow, especially rvs + #['rdist', (541.0,)], # from ticket #758 #veryslow ['recipinvgauss', (0.63004267809369119,)], ['reciprocal', (0.0062309367010521255, 1.0062309367010522)], ['rice', (0.7749725210111873,)], @@ -122,6 +133,13 @@ ## ['genextreme', (-0.01,)] ## ] +##distcont = [['gumbel_l', ()], +## ['gumbel_r', ()], +## ['norm', ()] +## ] + +##distcont = [['norm', ()]] + distmissing = ['wald', 'gausshyper', 'genexpon', 'rv_continuous', 'loglaplace', 'rdist', 'semicircular', 'invweibull', 'ksone', 'cosine', 'kstwobign', 'truncnorm', 'mielke', 'recipinvgauss', 'levy', @@ -135,27 +153,28 @@ 'powerlognorm', 'johnsonsu', 'kstwobign'] #distslow are sorted by speed (very slow to slow) - - def test_cont_basic(): + # this test skips slow distributions for distname, arg in distcont[:]: if distname in distslow: continue distfn = getattr(stats, distname) np.random.seed(765456) - rvs = distfn.rvs(size=1000,*arg) + sn = 1000 + rvs = distfn.rvs(size=sn,*arg) sm = rvs.mean() sv = rvs.var() skurt = stats.kurtosis(rvs) sskew = stats.skew(rvs) m,v = distfn.stats(*arg) - yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, distname + \ + + yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, sn, distname + \ 'sample mean test' - yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + # the sample skew kurtosis test has known failures, not very good distance measure + #yield check_sample_skew_kurt, distfn, arg, sskew, skurt, distname yield check_moment, distfn, arg, m, v, distname yield check_cdf_ppf, distfn, arg, distname yield check_sf_isf, distfn, arg, distname yield check_pdf, distfn, arg, distname - #yield check_oth, distfn, arg # is still missing if distname in distmissing: alpha = 0.01 yield check_distribution_rvs, dist, args, alpha, rvs @@ -168,15 +187,17 @@ if distname not in distslow: continue distfn = getattr(stats, distname) np.random.seed(765456) - rvs = distfn.rvs(size=1000,*arg) + sn = 1000 + rvs = distfn.rvs(size=sn,*arg) sm = rvs.mean() sv = rvs.var() skurt = stats.kurtosis(rvs) sskew = stats.skew(rvs) m,v = distfn.stats(*arg) - yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, distname + \ + yield check_sample_meanvar_, distfn, arg, m, v, sm, sv, sn, distname + \ 'sample mean test' - yield check_sample_skew_kurt, distfn, arg, skurt, sskew, distname + # the sample skew kurtosis test has known failures, not very good distance measure + #yield check_sample_skew_kurt, distfn, arg, sskew, skurt, distname yield check_moment, distfn, arg, m, v, distname yield check_cdf_ppf, distfn, arg, distname yield check_sf_isf, distfn, arg, distname @@ -207,21 +228,61 @@ msg + ' - 2nd moment -infinite, m2=%s' % str(m2) #np.isnan(m2) temporary special treatment for loggamma -def check_sample_meanvar_(distfn, arg, m, v, sm, sv, msg): - check_sample_meanvar, sm, m, msg + 'sample mean test' - check_sample_meanvar, sv, v, msg + 'sample var test' +def check_sample_meanvar_(distfn, arg, m, v, sm, sv, sn, msg): + #this did not work, skipped silently by nose + #check_sample_meanvar, sm, m, msg + 'sample mean test' + #check_sample_meanvar, sv, v, msg + 'sample var test' + if not np.isinf(m): + check_sample_mean(sm, sv, sn, m) + if not np.isinf(v): + check_sample_var(sv, sn, v) +## check_sample_meanvar( sm, m, msg + 'sample mean test') +## check_sample_meanvar( sv, v, msg + 'sample var test') -def check_sample_skew_kurt(distfn, arg, sk, ss, msg): - k,s = distfn.stats(moment='ks',*arg) - check_sample_meanvar, sk, k, msg + 'sample skew test' - check_sample_meanvar, ss, s, msg + 'sample kurtosis test' +def check_sample_mean(sm,v,n, popmean): + """ +from stats.stats.ttest_1samp(a, popmean): +Calculates the t-obtained for the independent samples T-test on ONE group +of scores a, given a population mean. +Returns: t-value, two-tailed prob +""" +## a = asarray(a) +## x = np.mean(a) +## v = np.var(a, ddof=1) +## n = len(a) + df = n-1 + svar = ((n-1)*v) / float(df) #looks redundant + t = (sm-popmean)/np.sqrt(svar*(1.0/n)) + prob = stats.betai(0.5*df,0.5,df/(df+t*t)) + + #return t,prob + assert prob>0.01, 'mean fail, t,prob = %f, %f, m,sm=%f,%f' % (t,prob,popmean,sm) + +def check_sample_var(sv,n, popvar): + ''' +two-sided chisquare test for sample variance equal to hypothesized variance + ''' + df = n-1 + chi2 = (n-1)*popvar/float(popvar) + pval = stats.chisqprob(chi2,df)*2 + assert pval>0.01, 'var fail, t,pval = %f, %f, v,sv=%f,%f' % (chi2,pval,popvar,sv) + + + +def check_sample_skew_kurt(distfn, arg, ss, sk, msg): + skew,kurt = distfn.stats(moments='sk',*arg) +## skew = distfn.stats(moment='s',*arg)[()] +## kurt = distfn.stats(moment='k',*arg)[()] + check_sample_meanvar( sk, kurt, msg + 'sample kurtosis test') + check_sample_meanvar( ss, skew, msg + 'sample skew test') + def check_sample_meanvar(sm,m,msg): - if not np.isinf(m): + if not np.isinf(m) and not np.isnan(m): npt.assert_almost_equal(sm, m, decimal=DECIMAL, err_msg= msg + \ ' - finite moment') - else: - assert abs(sm) > 10000, 'infinite moment, sm = ' + str(sm) +## else: +## assert abs(sm) > 10000, 'infinite moment, sm = ' + str(sm) def check_cdf_ppf(distfn,arg,msg): npt.assert_almost_equal(distfn.cdf(distfn.ppf([0.001,0.5,0.990], *arg), *arg), @@ -254,24 +315,6 @@ decimal=DECIMAL, err_msg= msg + ' - cdf-pdf relationship') - - at npt.dec.slow -def _est_missing_distributions_old(): - # K-S test of distributions missing in test_distributions.py - for dist, args in distmiss: - distfunc = getattr(stats, dist) - alpha = 0.01 - yield check_distribution, dist, args, alpha - - -def check_distribution(dist, args, alpha): - #test from scipy.stats.tests - D,pval = stats.kstest(dist,'', args=args, N=1000) - if (pval < alpha): - D,pval = stats.kstest(dist,'',args=args, N=1000) - assert (pval > alpha), "D = " + str(D) + "; pval = " + str(pval) + \ - "; alpha = " + str(alpha) + "\nargs = " + str(args) - def check_distribution_rvs(dist, args, alpha, rvs): #test from scipy.stats.tests #this version reuses existing random variables From scipy-svn at scipy.org Sun Nov 30 22:49:03 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 30 Nov 2008 21:49:03 -0600 (CST) Subject: [Scipy-svn] r5211 - trunk/scipy/stats Message-ID: <20081201034903.4270239C107@scipy.org> Author: josef Date: 2008-11-30 21:49:01 -0600 (Sun, 30 Nov 2008) New Revision: 5211 Modified: trunk/scipy/stats/distributions.py Log: correct incorrect formulas for mean or variance of gumbel_l, rayleigh, truncexpon and truncnorm Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-12-01 03:44:26 UTC (rev 5210) +++ trunk/scipy/stats/distributions.py 2008-12-01 03:49:01 UTC (rev 5211) @@ -702,7 +702,7 @@ if g1 is None: mu3 = None else: - mu3 = g1*np.power(mu2,1.5) #(mu2**1.5) breaks down for nan and nin + mu3 = g1*np.power(mu2,1.5) #(mu2**1.5) breaks down for nan and inf default = valarray(shape(cond), self.badvalue) output = [] @@ -1985,8 +1985,8 @@ def _ppf(self, q): return log(-log(1-q)) def _stats(self): - return _EULER, pi*pi/6.0, \ - 12*sqrt(6)/pi**3 * _ZETA3, 12.0/5 + return -_EULER, pi*pi/6.0, \ + -12*sqrt(6)/pi**3 * _ZETA3, 12.0/5 def _entropy(self): return 1.0608407169541684911 gumbel_l = gumbel_l_gen(name='gumbel_l',longname="A left-skewed Gumbel", @@ -2931,7 +2931,7 @@ return sqrt(-2*log(1-q)) def _stats(self): val = 4-pi - return pi/2, val/2, 2*(pi-3)*sqrt(pi)/val**1.5, \ + return np.sqrt(pi/2), val/2, 2*(pi-3)*sqrt(pi)/val**1.5, \ 6*pi/val-16/val**2 def _entropy(self): return _EULER/2.0 + 1 - 0.5*log(2) @@ -3092,7 +3092,16 @@ def _ppf(self, q, b): return -log(1-q+q*exp(-b)) def _munp(self, n, b): - return gam(n+1)-special.gammainc(1+n,b) + #wrong answer with formula, same as in continuous.pdf + #return gam(n+1)-special.gammainc(1+n,b) + if n == 1: + return (1-(b+1)*np.exp(-b))/(1-np.exp(-b)) + elif n == 2: + return 2*(1-0.5*(b*b+2*b+2)*np.exp(-b))/(1-np.exp(-b)) + else: + #return generic for higher moments + #return rv_continuous._mom1_sc(self,n, b) + return self._mom1_sc(n, b) def _entropy(self, b): eB = exp(b) return log(eB-1)+(1+eB*(b-1.0))/(1.0-eB) @@ -3126,7 +3135,7 @@ nA, nB = self.na, self.nb d = nB - nA pA, pB = norm._pdf(a), norm._pdf(b) - mu = (pB - pA) / d + mu = (pA - pB) / d #correction sign mu2 = 1 + (a*pA - b*pB) / d - mu*mu return mu, mu2, None, None truncnorm = truncnorm_gen(name='truncnorm', longname="A truncated normal", From scipy-svn at scipy.org Sun Nov 30 22:54:20 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 30 Nov 2008 21:54:20 -0600 (CST) Subject: [Scipy-svn] r5212 - trunk/scipy/stats Message-ID: <20081201035420.624EB39C0F1@scipy.org> Author: josef Date: 2008-11-30 21:54:14 -0600 (Sun, 30 Nov 2008) New Revision: 5212 Modified: trunk/scipy/stats/distributions.py Log: moment method now consistently returns non-central moments, before 3rd and 4th moments were either central nor non-central Modified: trunk/scipy/stats/distributions.py =================================================================== --- trunk/scipy/stats/distributions.py 2008-12-01 03:49:01 UTC (rev 5211) +++ trunk/scipy/stats/distributions.py 2008-12-01 03:54:14 UTC (rev 5212) @@ -766,6 +766,17 @@ return tuple(output) def moment(self, n, *args): + """n'th non-central moment of distribution + + Parameters: + ----------- + n: int, n>=1 + + *args: + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + + """ if (floor(n) != n): raise ValueError, "Moment must be an integer." if (n < 0): raise ValueError, "Moment must be positive." @@ -781,14 +792,22 @@ if mu is None: return self._munp(1,*args) else: return mu elif (n==2): - if mu2 is None or mu is None: return self._munp(2,*args) + if mu2 is None or mu is None: + return self._munp(2,*args) else: return mu2 + mu*mu elif (n==3): - if g1 is None or mu2 is None: return self._munp(3,*args) - else: return g1*(mu2**1.5) + if g1 is None or mu2 is None: + return self._munp(3,*args) + else: + mu3 = g1*(mu2**1.5) # 3rd central moment + return mu3+3*mu*mu2+mu**3 # 3rd non-central moment else: # (n==4) - if g2 is None or mu2 is None: return self._munp(4,*args) - else: return (g2+3.0)*(mu2**2.0) + if g2 is None or mu2 is None: + return self._munp(4,*args) + else: + mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment + mu3 = g1*(mu2**1.5) # 3rd central moment + return mu4+4*mu*mu3+6*mu*mu*mu2+mu**4 else: return self._munp(n,*args) @@ -3929,6 +3948,18 @@ return tuple(output) def moment(self, n, *args, **kwds): # Non-central moments in standard form. + """n'th non-central moment of the distribution + + + Parameters: + ----------- + n: int, n>=1 + + *args: + The shape parameter(s) for the distribution (see docstring of the + instance object for more information) + + """ if (floor(n) != n): raise ValueError, "Moment must be an integer." if (n < 0): raise ValueError, "Moment must be positive." @@ -3947,11 +3978,18 @@ if mu2 is None or mu is None: return self._munp(2,*args) else: return mu2 + mu*mu elif (n==3): - if g1 is None or mu2 is None: return self._munp(3,*args) - else: return g1*(mu2**1.5) + if (g1 is None) or (mu2 is None) or (mu is None): + return self._munp(3,*args) + else: + mu3 = g1*(mu2**1.5) # 3rd central moment + return mu3+3*mu*mu2+mu**3 # 3rd non-central moment else: # (n==4) - if g2 is None or mu2 is None: return self._munp(4,*args) - else: return (g2+3.0)*(mu2**2.0) + if (g2 is None) or (g1 is None) or (mu is None) or (mu2 is None): + return self._munp(4,*args) + else: + mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment + mu3 = g1*(mu2**1.5) # 3rd central moment + return mu4+4*mu*mu3+6*mu*mu*mu2+mu**4 else: return self._munp(n,*args) From scipy-svn at scipy.org Sun Nov 30 23:08:11 2008 From: scipy-svn at scipy.org (scipy-svn at scipy.org) Date: Sun, 30 Nov 2008 22:08:11 -0600 (CST) Subject: [Scipy-svn] r5213 - in trunk/scipy/stats: . tests Message-ID: <20081201040811.1B79039C0F1@scipy.org> Author: josef Date: 2008-11-30 22:08:07 -0600 (Sun, 30 Nov 2008) New Revision: 5213 Modified: trunk/scipy/stats/stats.py trunk/scipy/stats/tests/test_discrete_basic.py trunk/scipy/stats/tests/test_stats.py Log: correct and enhance stats.kstest, see ticket:395 Modified: trunk/scipy/stats/stats.py =================================================================== --- trunk/scipy/stats/stats.py 2008-12-01 03:54:14 UTC (rev 5212) +++ trunk/scipy/stats/stats.py 2008-12-01 04:08:07 UTC (rev 5213) @@ -1946,23 +1946,101 @@ import scipy.stats import distributions -def kstest(rvs, cdf, args=(), N=20): - """Return the D-value and the p-value for a Kolmogorov-Smirnov test of - the null that N RV's generated by the rvs fits the cdf given the extra - arguments. rvs needs to accept the size= keyword if a function. rvs - can also be a vector of RVs. +def kstest(rvs, cdf, args=(), N=20, alternative = 'unequal', mode='approx'): + """Return the D-value and the p-value for a Kolmogorov-Smirnov test - cdf can be a function or a string indicating the distribution type. - if the p-value is greater than the significance level (say 5%), then we + This performs a test of the distribution of random variables G(x) against + a given distribution F(x). Under the null hypothesis the two distributions + are identical, G(x)=F(x). The alternative hypothesis can be either + 'unequal' (default), 'smaller' or 'larger'. In the two one-sided test, + the alternative is that the empirical cumulative distribution function, + of the random variable is "smaller" or "larger" then the cumulative + distribution function of the hypothesis F(x), G(x)<=F(x), resp. G(x)>=F(x). + + If the p-value is greater than the significance level (say 5%), then we cannot reject the hypothesis that the data come from the given distribution. + + Parameters + ---------- + rvs : string or array or callable + string: name of a distribution in scipy.stats + array: random variables + callable: function to generate random variables, + requires keyword argument size + cdf : string or callable + string: name of a distribution in scipy.stats + if rvs is a string then cdf can evaluate to False + or be the same as rvs + callable: function to evaluate cdf + + args : distribution parameters used if rvs or cdf are strings + N : sample size if rvs is string or callable + alternative : 'unequal' (default), 'smaller' or 'larger' + defines the alternative hypothesis (see explanation) + mode : 'approx' (default) or 'asymp' + defines distribution used for calculating p-value + 'approx' : use approximation to exact distribution of test statistic + 'asymp' : use asymptotic distribution of test statistic + + + Returns + ------- + D: test statistic either D, D+ or D- + p-value + + Examples + -------- + + >>> x = np.linspace(-15,15,9) + >>> kstest(x,'norm') + (0.44435602715924361, 0.038850142705171065) + + >>> np.random.seed(987654321) + >>> kstest('norm','',N=100) + (0.058352892479417884, 0.88531190944151261) + + is equivalent to this + >>> np.random.seed(987654321) + >>> kstest(stats.norm.rvs(size=100),'norm') + (0.058352892479417884, 0.88531190944151261) + + test against one-sided alternative hypothesis + --------------------------------------------- + >>> np.random.seed(987654321) + >>> # shift distribution to larger values, so that cdf_dgp(x)< norm.cdf(x) + >>> x = stats.norm.rvs(loc=0.2, size=100) + >>> kstest(x,'norm', alternative = 'smaller') + (0.12464329735846891, 0.040989164077641749) + >>> # reject equal distribution against alternative hypothesis: smaller + >>> kstest(x,'norm', alternative = 'larger') + (0.0072115233216311081, 0.98531158590396395) + >>> # don't reject equal distribution against alternative hypothesis: larger + >>> kstest(x,'norm', mode='asymp') + (0.12464329735846891, 0.08944488871182088) + + + testing t distributed random variables against normal distribution + ------------------------------------------------------------------ + >>> np.random.seed(987654321) + >>> stats.kstest(stats.t.rvs(100,size=100),'norm') + (0.062018929165471248, 0.44505373063343567) + >>> np.random.seed(987654321) + >>> stats.kstest(stats.t.rvs(3,size=100),'norm') + (0.12101689575982888, 0.049143106661937996) """ if isinstance(rvs, basestring): - cdf = getattr(scipy.stats, rvs).cdf - rvs = getattr(scipy.stats, rvs).rvs + #cdf = getattr(stats, rvs).cdf + if (not cdf) or (cdf == rvs): + cdf = getattr(distributions, rvs).cdf + rvs = getattr(distributions, rvs).rvs + else: + raise AttributeError, 'if rvs is string, cdf has to be the same distribution' + + if isinstance(cdf, basestring): - cdf = getattr(scipy.stats, cdf).cdf + cdf = getattr(distributions, cdf).cdf if callable(rvs): kwds = {'size':N} vals = np.sort(rvs(*args,**kwds)) @@ -1970,11 +2048,27 @@ vals = np.sort(rvs) N = len(vals) cdfvals = cdf(vals, *args) - D1 = np.absolute(cdfvals - np.arange(1.0, N+1)/N).max() -# D2 = amax(abs(cdfvals - arange(0.0,N)/N)) -# D = max(D1,D2) - D = D1 - return D, distributions.ksone.sf(D,N) + + if alternative in ['unequal', 'larger']: + Dplus = (np.arange(1.0, N+1)/N - cdfvals).max() + if alternative == 'larger': + return Dplus, distributions.ksone.sf(Dplus,N) + + if alternative in ['unequal', 'smaller']: + Dmin = (cdfvals - np.arange(0.0, N)/N).max() + if alternative == 'smaller': + return Dmin, distributions.ksone.sf(Dmin,N) + + if alternative == 'unequal': + D = np.max([Dplus,Dmin]) + if mode == 'asymp': + return D, distributions.kstwobign.sf(D*np.sqrt(N)) + if mode == 'approx': + pval_two = distributions.kstwobign.sf(D*np.sqrt(N)) + if N > 2666 or pval_two > 0.80 - N*0.3/1000.0 : + return D, distributions.kstwobign.sf(D*np.sqrt(N)) + else: + return D, distributions.ksone.sf(D,N)*2 def chisquare(f_obs, f_exp=None): """ Calculates a one-way chi square for array of observed frequencies Modified: trunk/scipy/stats/tests/test_discrete_basic.py =================================================================== --- trunk/scipy/stats/tests/test_discrete_basic.py 2008-12-01 03:54:14 UTC (rev 5212) +++ trunk/scipy/stats/tests/test_discrete_basic.py 2008-12-01 04:08:07 UTC (rev 5213) @@ -244,12 +244,6 @@ 'at arg = %s with pval = %s' % (msg,str(arg),str(pval)) - - - - - - if __name__ == "__main__": #nose.run(argv=['', __file__]) nose.runmodule(argv=[__file__,'-s'], exit=False) Modified: trunk/scipy/stats/tests/test_stats.py =================================================================== --- trunk/scipy/stats/tests/test_stats.py 2008-12-01 03:54:14 UTC (rev 5212) +++ trunk/scipy/stats/tests/test_stats.py 2008-12-01 04:08:07 UTC (rev 5213) @@ -997,7 +997,32 @@ assert_array_almost_equal(stats.mstats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]),(10.68, 0.0135882729582176)) np.testing.assert_raises(ValueError,stats.mstats.friedmanchisquare,x3[0],x3[1]) +def test_kstest(): + #from numpy.testing import assert_almost_equal + + # comparing with values from R + x = np.linspace(-1,1,9) + D,p = stats.kstest(x,'norm') + assert_almost_equal( D, 0.15865525393145705, 12) + assert_almost_equal( p, 0.95164069201518386, 1) + x = np.linspace(-15,15,9) + D,p = stats.kstest(x,'norm') + assert_almost_equal( D, 0.44435602715924361, 15) + assert_almost_equal( p, 0.038850140086788665, 8) + # the following tests rely on deterministicaly replicated rvs + np.random.seed(987654321) + x = stats.norm.rvs(loc=0.2, size=100) + D,p = stats.kstest(x, 'norm', mode='asymp') + assert_almost_equal( D, 0.12464329735846891, 15) + assert_almost_equal( p, 0.089444888711820769, 15) + assert_almost_equal( np.array(stats.kstest(x, 'norm', mode='asymp')), + np.array((0.12464329735846891, 0.089444888711820769)), 15) + assert_almost_equal( np.array(stats.kstest(x,'norm', alternative = 'smaller')), + np.array((0.12464329735846891, 0.040989164077641749)), 15) + assert_almost_equal( np.array(stats.kstest(x,'norm', alternative = 'larger')), + np.array((0.0072115233216310994, 0.98531158590396228)), 14) + if __name__ == "__main__": run_module_suite()