def test_main_versions(): assert_(NumpyVersion('1.8.0') == '1.8.0') for ver in ['1.9.0', '2.0.0', '1.8.1']: assert_(NumpyVersion('1.8.0') < ver) for ver in ['1.7.0', '1.7.1', '0.9.9']: assert_(NumpyVersion('1.8.0') > ver)
def test_alpha_beta_rc(): assert_(NumpyVersion('1.8.0rc1') == '1.8.0rc1') for ver in ['1.8.0', '1.8.0rc2']: assert_(NumpyVersion('1.8.0rc1') < ver) for ver in ['1.8.0a2', '1.8.0b3', '1.7.2rc4']: assert_(NumpyVersion('1.8.0rc1') > ver) assert_(NumpyVersion('1.8.0b1') > '1.8.0a2')
def test_logsumexp(): """Test whether logsumexp() function correctly handles large inputs.""" a = np.arange(200) desired = np.log(np.sum(np.exp(a))) assert_almost_equal(logsumexp(a), desired) # Now test with large numbers b = [1000, 1000] desired = 1000.0 + np.log(2.0) assert_almost_equal(logsumexp(b), desired) n = 1000 b = np.ones(n) * 10000 desired = 10000.0 + np.log(n) assert_almost_equal(logsumexp(b), desired) x = np.array([1e-40] * 1000000) logx = np.log(x) X = np.vstack([x, x]) logX = np.vstack([logx, logx]) assert_array_almost_equal(np.exp(logsumexp(logX)), X.sum()) assert_array_almost_equal(np.exp(logsumexp(logX, axis=0)), X.sum(axis=0)) assert_array_almost_equal(np.exp(logsumexp(logX, axis=1)), X.sum(axis=1)) # Handling special values properly with np.errstate(divide='ignore'): assert_equal(logsumexp(np.inf), np.inf) assert_equal(logsumexp(-np.inf), -np.inf) assert_equal(logsumexp(np.nan), np.nan) # Handling an array with different magnitudes on the axes assert_array_almost_equal(logsumexp([[1e10, 1e-10], [-1e10, -np.inf]], axis=-1), [1e10, -1e10]) # Test keeping dimensions assert_array_almost_equal(logsumexp([[1e10, 1e-10], [-1e10, -np.inf]], axis=-1, keepdims=True), [[1e10], [-1e10]]) # Test multiple axes if NumpyVersion(np.__version__) >= NumpyVersion('1.7.0'): assert_array_almost_equal(logsumexp([[1e10, 1e-10], [-1e10, -np.inf]], axis=(-1,-2)), 1e10)
def generic_gradient_magnitude(input, derivative, output=None, mode="reflect", cval=0.0, extra_arguments=(), extra_keywords=None): """Gradient magnitude using a provided gradient function. Parameters ---------- %(input)s derivative : callable Callable with the following signature:: derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords) See `extra_arguments`, `extra_keywords` below. `derivative` can assume that `input` and `output` are ndarrays. Note that the output from `derivative` is modified inplace; be careful to copy important inputs before returning them. %(output)s %(mode)s %(cval)s %(extra_keywords)s %(extra_arguments)s """ if extra_keywords is None: extra_keywords = {} input = numpy.asarray(input) output, return_value = _ni_support._get_output(output, input) axes = list(range(input.ndim)) if len(axes) > 0: derivative(input, axes[0], output, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(output, output, output) for ii in range(1, len(axes)): tmp = derivative(input, axes[ii], output.dtype, mode, cval, *extra_arguments, **extra_keywords) numpy.multiply(tmp, tmp, tmp) output += tmp # This allows the sqrt to work with a different default casting if NumpyVersion(numpy.__version__) > '1.6.1': numpy.sqrt(output, output, casting='unsafe') else: numpy.sqrt(output, output) else: output[...] = input[...] return return_value
def check_logit_out(self, dtype, expected): a = np.linspace(0,1,10) a = np.array(a, dtype=dtype) olderr = np.seterr(divide='ignore') try: actual = logit(a) finally: np.seterr(**olderr) if NumpyVersion(np.__version__) >= '1.6.0': assert_almost_equal(actual, expected) else: assert_almost_equal(actual[1:-1], expected[1:-1]) assert_equal(actual.dtype, np.dtype(dtype))
def _compare(self, other): if not isinstance(other, (string_types, NumpyVersion)): raise ValueError("Invalid object to compare with NumpyVersion.") if isinstance(other, string_types): other = NumpyVersion(other) vercmp = self._compare_version(other) if vercmp == 0: # Same x.y.z version, check for alpha/beta/rc vercmp = self._compare_pre_release(other) if vercmp == 0: # Same version and same pre-release, check if dev version if self.is_devversion is other.is_devversion: vercmp = 0 elif self.is_devversion: vercmp = -1 else: vercmp = 1 return vercmp
def test_dev_version(): assert_(NumpyVersion('1.9.0.dev-Unknown') < '1.9.0') for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev-ffffffff']: assert_(NumpyVersion('1.9.0.dev-f16acvda') < ver) assert_(NumpyVersion('1.9.0.dev-f16acvda') == '1.9.0.dev-11111111')
def test_version_1_point_10(): # regression test for gh-2998. assert_(NumpyVersion('1.9.0') < '1.10.0') assert_(NumpyVersion('1.11.0') < '1.11.1') assert_(NumpyVersion('1.11.0') == '1.11.0') assert_(NumpyVersion('1.99.11') < '1.99.12')
"""Functions copypasted from newer versions of numpy. """ from __future__ import division, print_function, absolute_import import warnings import numpy as np from scipy.lib._version import NumpyVersion if NumpyVersion(np.__version__) > '1.7.0.dev': _assert_warns = np.testing.assert_warns else: def _assert_warns(warning_class, func, *args, **kw): r""" Fail unless the given callable throws the specified warning. This definition is copypasted from numpy 1.9.0.dev. The version in earlier numpy returns None. Parameters ---------- warning_class : class The class defining the warning that `func` is expected to throw. func : callable The callable to test. *args : Arguments Arguments passed to `func`. **kwargs : Kwargs
elif N < match: match = N p35 *= 3 if p35 == target: return p35 if p35 < match: match = p35 p5 *= 5 if p5 == target: return p5 if p5 < match: match = p5 return match if NumpyVersion(np.__version__) >= '1.7.1': np_matrix_rank = np.linalg.matrix_rank else: def np_matrix_rank(M, tol=None): """ Return matrix rank of array using SVD method Rank of the array is the number of SVD singular values of the array that are greater than `tol`. Parameters ---------- M : {(M,), (M, N)} array_like array of <=2 dimensions tol : {None, float}, optional threshold below which SVD values are considered zero. If `tol` is None, and ``S`` is an array with singular values for `M`, and
class TestWelch(TestCase): def test_real_onesided_even(self): x = np.zeros(16) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8) assert_allclose(f, np.linspace(0, 0.5, 5)) assert_allclose( p, np.array( [0.08333333, 0.15277778, 0.22222222, 0.22222222, 0.11111111])) def test_real_onesided_odd(self): x = np.zeros(16) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=9) assert_allclose(f, np.arange(5.0) / 9.0) assert_allclose( p, np.array( [0.15958226, 0.24193954, 0.24145223, 0.24100919, 0.12188675])) def test_real_twosided(self): x = np.zeros(16) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8, return_onesided=False) assert_allclose(f, fftpack.fftfreq(8, 1.0)) assert_allclose( p, np.array([ 0.08333333, 0.07638889, 0.11111111, 0.11111111, 0.11111111, 0.11111111, 0.11111111, 0.07638889 ])) def test_real_spectrum(self): x = np.zeros(16) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8, scaling='spectrum') assert_allclose(f, np.linspace(0, 0.5, 5)) assert_allclose( p, np.array([ 0.015625, 0.028645833333333332, 0.041666666666666664, 0.041666666666666664, 0.020833333333333332 ])) def test_integer_onesided_even(self): x = np.zeros(16, dtype=np.int) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8) assert_allclose(f, np.linspace(0, 0.5, 5)) assert_allclose( p, np.array( [0.08333333, 0.15277778, 0.22222222, 0.22222222, 0.11111111])) def test_integer_onesided_odd(self): x = np.zeros(16, dtype=np.int) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=9) assert_allclose(f, np.arange(5.0) / 9.0) assert_allclose( p, np.array( [0.15958226, 0.24193954, 0.24145223, 0.24100919, 0.12188675])) def test_integer_twosided(self): x = np.zeros(16, dtype=np.int) x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8, return_onesided=False) assert_allclose(f, fftpack.fftfreq(8, 1.0)) assert_allclose( p, np.array([ 0.08333333, 0.07638889, 0.11111111, 0.11111111, 0.11111111, 0.11111111, 0.11111111, 0.07638889 ])) def test_complex(self): x = np.zeros(16, np.complex128) x[0] = 1.0 + 2.0j x[8] = 1.0 + 2.0j f, p = welch(x, nperseg=8) assert_allclose(f, fftpack.fftfreq(8, 1.0)) assert_allclose( p, np.array([ 0.41666667, 0.38194444, 0.55555556, 0.55555556, 0.55555556, 0.55555556, 0.55555556, 0.38194444 ])) def test_unk_scaling(self): assert_raises(ValueError, welch, np.zeros(4, np.complex128), scaling='foo', nperseg=4) def test_detrend_linear(self): x = np.arange(10, dtype=np.float64) + 0.04 f, p = welch(x, nperseg=10, detrend='linear') assert_allclose(p, np.zeros_like(p), atol=1e-15) def test_no_detrending(self): x = np.arange(10, dtype=np.float64) + 0.04 f1, p1 = welch(x, nperseg=10, detrend=False) f2, p2 = welch(x, nperseg=10, detrend=lambda x: x) assert_allclose(f1, f2, atol=1e-15) assert_allclose(p1, p2, atol=1e-15) def test_detrend_external(self): x = np.arange(10, dtype=np.float64) + 0.04 f, p = welch(x, nperseg=10, detrend=lambda seg: signal.detrend(seg, type='l')) assert_allclose(p, np.zeros_like(p), atol=1e-15) def test_detrend_external_nd_m1(self): x = np.arange(40, dtype=np.float64) + 0.04 x = x.reshape((2, 2, 10)) f, p = welch(x, nperseg=10, detrend=lambda seg: signal.detrend(seg, type='l')) assert_allclose(p, np.zeros_like(p), atol=1e-15) def test_detrend_external_nd_0(self): x = np.arange(20, dtype=np.float64) + 0.04 x = x.reshape((2, 1, 10)) x = np.rollaxis(x, 2, 0) f, p = welch(x, nperseg=10, axis=0, detrend=lambda seg: signal.detrend(seg, axis=0, type='l')) assert_allclose(p, np.zeros_like(p), atol=1e-15) def test_nd_axis_m1(self): x = np.arange(20, dtype=np.float64) + 0.04 x = x.reshape((2, 1, 10)) f, p = welch(x, nperseg=10) assert_array_equal(p.shape, (2, 1, 6)) assert_allclose(p[0, 0, :], p[1, 0, :], atol=1e-13, rtol=1e-13) f0, p0 = welch(x[0, 0, :], nperseg=10) assert_allclose(p0[np.newaxis, :], p[1, :], atol=1e-13, rtol=1e-13) def test_nd_axis_0(self): x = np.arange(20, dtype=np.float64) + 0.04 x = x.reshape((10, 2, 1)) f, p = welch(x, nperseg=10, axis=0) assert_array_equal(p.shape, (6, 2, 1)) assert_allclose(p[:, 0, 0], p[:, 1, 0], atol=1e-13, rtol=1e-13) f0, p0 = welch(x[:, 0, 0], nperseg=10) assert_allclose(p0, p[:, 1, 0], atol=1e-13, rtol=1e-13) def test_window_external(self): x = np.zeros(16) x[0] = 1 x[8] = 1 f, p = welch(x, 10, 'hanning', 8) win = signal.get_window('hanning', 8) fe, pe = welch(x, 10, win, 8) assert_array_almost_equal_nulp(p, pe) assert_array_almost_equal_nulp(f, fe) def test_empty_input(self): f, p = welch([]) assert_array_equal(f.shape, (0, )) assert_array_equal(p.shape, (0, )) for shape in [(0, ), (3, 0), (0, 5, 2)]: f, p = welch(np.empty(shape)) assert_array_equal(f.shape, shape) assert_array_equal(p.shape, shape) def test_short_data(self): x = np.zeros(8) x[0] = 1 with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) f, p = welch(x) f1, p1 = welch(x, nperseg=8) assert_allclose(f, f1) assert_allclose(p, p1) def test_window_long_or_nd(self): with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) assert_raises(ValueError, welch, np.zeros(4), 1, np.array([1, 1, 1, 1, 1])) assert_raises(ValueError, welch, np.zeros(4), 1, np.arange(6).reshape((2, 3))) def test_nondefault_noverlap(self): x = np.zeros(64) x[::8] = 1 f, p = welch(x, nperseg=16, noverlap=4) q = np.array([ 0, 1. / 12., 1. / 3., 1. / 5., 1. / 3., 1. / 5., 1. / 3., 1. / 5., 1. / 6. ]) assert_allclose(p, q, atol=1e-12) def test_bad_noverlap(self): assert_raises(ValueError, welch, np.zeros(4), 1, 'hanning', 2, 7) def test_nfft_too_short(self): assert_raises(ValueError, welch, np.ones(12), nfft=3, nperseg=4) def test_real_onesided_even_32(self): x = np.zeros(16, 'f') x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8) assert_allclose(f, np.linspace(0, 0.5, 5)) q = np.array( [0.08333333, 0.15277778, 0.22222222, 0.22222222, 0.11111111], 'f') assert_allclose(p, q) assert_(p.dtype == q.dtype) def test_real_onesided_odd_32(self): x = np.zeros(16, 'f') x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=9) assert_allclose(f, np.arange(5.0) / 9.0) q = np.array( [0.15958226, 0.24193954, 0.24145223, 0.24100919, 0.12188675], 'f') assert_allclose(p, q, atol=1e-7) assert_(p.dtype == q.dtype) @dec.skipif(NumpyVersion(np.__version__) < '1.8.0') def test_real_twosided_32(self): x = np.zeros(16, 'f') x[0] = 1 x[8] = 1 f, p = welch(x, nperseg=8, return_onesided=False) assert_allclose(f, fftpack.fftfreq(8, 1.0)) q = np.array([ 0.08333333, 0.07638889, 0.11111111, 0.11111111, 0.11111111, 0.11111111, 0.11111111, 0.07638889 ], 'f') assert_allclose(p, q) assert_(p.dtype == q.dtype) @dec.skipif(NumpyVersion(np.__version__) < '1.8.0') def test_complex_32(self): x = np.zeros(16, 'F') x[0] = 1.0 + 2.0j x[8] = 1.0 + 2.0j f, p = welch(x, nperseg=8) assert_allclose(f, fftpack.fftfreq(8, 1.0)) q = np.array([ 0.41666667, 0.38194444, 0.55555556, 0.55555556, 0.55555556, 0.55555556, 0.55555556, 0.38194444 ], 'f') assert_allclose(p, q) assert_(p.dtype == q.dtype, 'dtype mismatch, %s, %s' % (p.dtype, q.dtype))
class TestPeriodogram(TestCase): def test_real_onesided_even(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_real_onesided_odd(self): x = np.zeros(15) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.arange(8.0) / 15.0) q = np.ones(8) q[0] = 0 q[-1] /= 2.0 q *= 2.0 / 15.0 assert_allclose(p, q, atol=1e-15) def test_real_twosided(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftpack.fftfreq(16, 1.0)) q = np.ones(16) / 16.0 q[0] = 0 assert_allclose(p, q) def test_real_spectrum(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, scaling='spectrum') g, q = periodogram(x, scaling='density') assert_allclose(f, np.linspace(0, 0.5, 9)) assert_allclose(p, q / 16.0) def test_integer_even(self): x = np.zeros(16, dtype=np.int) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_integer_odd(self): x = np.zeros(15, dtype=np.int) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.arange(8.0) / 15.0) q = np.ones(8) q[0] = 0 q[-1] /= 2.0 q *= 2.0 / 15.0 assert_allclose(p, q, atol=1e-15) def test_integer_twosided(self): x = np.zeros(16, dtype=np.int) x[0] = 1 f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftpack.fftfreq(16, 1.0)) q = np.ones(16) / 16.0 q[0] = 0 assert_allclose(p, q) def test_complex(self): x = np.zeros(16, np.complex128) x[0] = 1.0 + 2.0j f, p = periodogram(x) assert_allclose(f, fftpack.fftfreq(16, 1.0)) q = 5.0 * np.ones(16) / 16.0 q[0] = 0 assert_allclose(p, q) def test_unk_scaling(self): assert_raises(ValueError, periodogram, np.zeros(4, np.complex128), scaling='foo') def test_nd_axis_m1(self): x = np.zeros(20, dtype=np.float64) x = x.reshape((2, 1, 10)) x[:, :, 0] = 1.0 f, p = periodogram(x) assert_array_equal(p.shape, (2, 1, 6)) assert_array_almost_equal_nulp(p[0, 0, :], p[1, 0, :], 60) f0, p0 = periodogram(x[0, 0, :]) assert_array_almost_equal_nulp(p0[np.newaxis, :], p[1, :], 60) def test_nd_axis_0(self): x = np.zeros(20, dtype=np.float64) x = x.reshape((10, 2, 1)) x[0, :, :] = 1.0 f, p = periodogram(x, axis=0) assert_array_equal(p.shape, (6, 2, 1)) assert_array_almost_equal_nulp(p[:, 0, 0], p[:, 1, 0], 60) f0, p0 = periodogram(x[:, 0, 0]) assert_array_almost_equal_nulp(p0, p[:, 1, 0]) def test_window_external(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, 10, 'hanning') win = signal.get_window('hanning', 16) fe, pe = periodogram(x, 10, win) assert_array_almost_equal_nulp(p, pe) assert_array_almost_equal_nulp(f, fe) def test_padded_fft(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x) fp, pp = periodogram(x, nfft=32) assert_allclose(f, fp[::2]) assert_allclose(p, pp[::2]) assert_array_equal(pp.shape, (17, )) def test_empty_input(self): f, p = periodogram([]) assert_array_equal(f.shape, (0, )) assert_array_equal(p.shape, (0, )) for shape in [(0, ), (3, 0), (0, 5, 2)]: f, p = periodogram(np.empty(shape)) assert_array_equal(f.shape, shape) assert_array_equal(p.shape, shape) def test_short_nfft(self): x = np.zeros(18) x[0] = 1 f, p = periodogram(x, nfft=16) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_nfft_is_xshape(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x, nfft=16) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_real_onesided_even_32(self): x = np.zeros(16, 'f') x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9, 'f') q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) assert_(p.dtype == q.dtype) def test_real_onesided_odd_32(self): x = np.zeros(15, 'f') x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.arange(8.0) / 15.0) q = np.ones(8, 'f') q[0] = 0 q[-1] /= 2.0 q *= 2.0 / 15.0 assert_allclose(p, q, atol=1e-7) assert_(p.dtype == q.dtype) @dec.skipif(NumpyVersion(np.__version__) < '1.8.0') def test_real_twosided_32(self): x = np.zeros(16, 'f') x[0] = 1 f, p = periodogram(x, return_onesided=False) assert_allclose(f, fftpack.fftfreq(16, 1.0)) q = np.ones(16, 'f') / 16.0 q[0] = 0 assert_allclose(p, q) assert_(p.dtype == q.dtype) @dec.skipif(NumpyVersion(np.__version__) < '1.8.0') def test_complex_32(self): x = np.zeros(16, 'F') x[0] = 1.0 + 2.0j f, p = periodogram(x) assert_allclose(f, fftpack.fftfreq(16, 1.0)) q = 5.0 * np.ones(16, 'f') / 16.0 q[0] = 0 assert_allclose(p, q) assert_(p.dtype == q.dtype)
[1, 2, np.inf, 0, 2], [2, np.inf, np.inf, 2, 0]], dtype=float) undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5) undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf undirected_pred = np.array([[-9999, 0, 0, 0, 0], [1, -9999, 0, 1, 1], [2, 0, -9999, 0, 0], [3, 3, 0, -9999, 3], [4, 4, 0, 4, -9999]], dtype=float) methods = ['auto', 'FW', 'D', 'BF', 'J'] @dec.skipif(NumpyVersion(np.__version__) < '1.6.0', "Can't test arrays with infs.") def test_dijkstra_limit(): limits = [0, 2, np.inf] results = [undirected_SP_limit_0, undirected_SP_limit_2, undirected_SP] def check(limit, result): SP = dijkstra(undirected_G, directed=False, limit=limit) assert_array_almost_equal(SP, result) for limit, result in zip(limits, results): yield check, limit, result
[2, np.inf, np.inf, 2, 0]], dtype=float) undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5) undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf undirected_pred = np.array( [[-9999, 0, 0, 0, 0], [1, -9999, 0, 1, 1], [2, 0, -9999, 0, 0], [3, 3, 0, -9999, 3], [4, 4, 0, 4, -9999]], dtype=float) methods = ['auto', 'FW', 'D', 'BF', 'J'] @dec.skipif( NumpyVersion(np.__version__) < '1.6.0', "Can't test arrays with infs.") def test_dijkstra_limit(): limits = [0, 2, np.inf] results = [undirected_SP_limit_0, undirected_SP_limit_2, undirected_SP] def check(limit, result): SP = dijkstra(undirected_G, directed=False, limit=limit) assert_array_almost_equal(SP, result) for limit, result in zip(limits, results): yield check, limit, result @dec.skipif( NumpyVersion(np.__version__) < '1.6.0', "Can't test arrays with infs.") def test_directed():
def test_dev_a_b_rc_mixed(): assert_(NumpyVersion('1.9.0a2.dev-f16acvda') == '1.9.0a2.dev-11111111') assert_(NumpyVersion('1.9.0a2.dev-6acvda54') < '1.9.0a2')
from __future__ import division, print_function, absolute_import import numpy import numpy as np from numpy import (exp, log, asarray, arange, newaxis, hstack, product, array, zeros, eye, poly1d, r_, sum, fromstring, isfinite, squeeze, amax, reshape) from scipy.lib._version import NumpyVersion __all__ = [ 'logsumexp', 'central_diff_weights', 'derivative', 'pade', 'lena', 'ascent', 'face' ] _NUMPY_170 = (NumpyVersion(numpy.__version__) >= NumpyVersion('1.7.0')) def logsumexp(a, axis=None, b=None, keepdims=False): """Compute the log of the sum of exponentials of input elements. Parameters ---------- a : array_like Input array. axis : None or int or tuple of ints, optional Axis or axes over which the sum is taken. By default `axis` is None, and all elements are summed. Tuple of ints is not accepted if NumPy version is lower than 1.7.0. .. versionadded:: 0.11.0
from __future__ import division, print_function, absolute_import import inspect import warnings import numpy as np import numpy.testing as npt from scipy.lib._version import NumpyVersion from scipy import stats NUMPY_BELOW_1_7 = NumpyVersion(np.__version__) < '1.7.0' def check_normalization(distfn, args, distname): norm_moment = distfn.moment(0, *args) npt.assert_allclose(norm_moment, 1.0) # this is a temporary plug: either ncf or expect is problematic; # best be marked as a knownfail, but I've no clue how to do it. if distname == "ncf": atol, rtol = 1e-5, 0 else: atol, rtol = 1e-7, 1e-7 normalization_expect = distfn.expect(lambda x: 1, args=args) npt.assert_allclose(normalization_expect, 1.0, atol=atol, rtol=rtol, err_msg=distname, verbose=True) normalization_cdf = distfn.cdf(distfn.b, *args)
class TestUtilities(object): """ Check that utility functions work. """ def test_find_simplex(self): # Simple check that simplex finding works points = np.array([(0, 0), (0, 1), (1, 1), (1, 0)], dtype=np.double) tri = qhull.Delaunay(points) # +---+ # |\ 0| # | \ | # |1 \| # +---+ assert_equal(tri.vertices, [[1, 3, 2], [3, 1, 0]]) for p in [(0.25, 0.25, 1), (0.75, 0.75, 0), (0.3, 0.2, 1)]: i = tri.find_simplex(p[:2]) assert_equal(i, p[2], err_msg='%r' % (p, )) j = qhull.tsearch(tri, p[:2]) assert_equal(i, j) def test_plane_distance(self): # Compare plane distance from hyperplane equations obtained from Qhull # to manually computed plane equations x = np.array([(0, 0), (1, 1), (1, 0), (0.99189033, 0.37674127), (0.99440079, 0.45182168)], dtype=np.double) p = np.array([0.99966555, 0.15685619], dtype=np.double) tri = qhull.Delaunay(x) z = tri.lift_points(x) pz = tri.lift_points(p) dist = tri.plane_distance(p) for j, v in enumerate(tri.vertices): x1 = z[v[0]] x2 = z[v[1]] x3 = z[v[2]] n = np.cross(x1 - x3, x2 - x3) n /= np.sqrt(np.dot(n, n)) n *= -np.sign(n[2]) d = np.dot(n, pz - x3) assert_almost_equal(dist[j], d) def test_convex_hull(self): # Simple check that the convex hull seems to works points = np.array([(0, 0), (0, 1), (1, 1), (1, 0)], dtype=np.double) tri = qhull.Delaunay(points) # +---+ # |\ 0| # | \ | # |1 \| # +---+ assert_equal(tri.convex_hull, [[3, 2], [1, 2], [1, 0], [3, 0]]) def _check_barycentric_transforms(self, tri, err_msg="", unit_cube=False, unit_cube_tol=0): """Check that a triangulation has reasonable barycentric transforms""" vertices = tri.points[tri.vertices] sc = 1 / (tri.ndim + 1.0) centroids = vertices.sum(axis=1) * sc # Either: (i) the simplex has a `nan` barycentric transform, # or, (ii) the centroid is in the simplex def barycentric_transform(tr, x): ndim = tr.shape[1] r = tr[:, -1, :] Tinv = tr[:, :-1, :] return np.einsum('ijk,ik->ij', Tinv, x - r) eps = np.finfo(float).eps c = barycentric_transform(tri.transform, centroids) olderr = np.seterr(invalid="ignore") try: ok = np.isnan(c).all(axis=1) | (abs(c - sc) / sc < 0.1).all(axis=1) finally: np.seterr(**olderr) assert_(ok.all(), "%s %s" % (err_msg, np.where(~ok))) # Invalid simplices must be (nearly) zero volume q = vertices[:, :-1, :] - vertices[:, -1, None, :] volume = np.array( [np.linalg.det(q[k, :, :]) for k in range(tri.nsimplex)]) ok = np.isfinite(tri.transform[:, 0, 0]) | (volume < np.sqrt(eps)) assert_(ok.all(), "%s %s" % (err_msg, np.where(~ok))) # Also, find_simplex for the centroid should end up in some # simplex for the non-degenerate cases j = tri.find_simplex(centroids) ok = (j != -1) | np.isnan(tri.transform[:, 0, 0]) assert_(ok.all(), "%s %s" % (err_msg, np.where(~ok))) if unit_cube: # If in unit cube, no interior point should be marked out of hull at_boundary = (centroids <= unit_cube_tol).any(axis=1) at_boundary |= (centroids >= 1 - unit_cube_tol).any(axis=1) ok = (j != -1) | at_boundary assert_(ok.all(), "%s %s" % (err_msg, np.where(~ok))) @dec.skipif( NumpyVersion(np.__version__) < '1.6.0', "No einsum in numpy 1.5.x") def test_degenerate_barycentric_transforms(self): # The triangulation should not produce invalid barycentric # transforms that stump the simplex finding data = np.load( os.path.join(os.path.dirname(__file__), 'data', 'degenerate_pointset.npz')) points = data['c'] data.close() tri = qhull.Delaunay(points) # Check that there are not too many invalid simplices bad_count = np.isnan(tri.transform[:, 0, 0]).sum() assert_(bad_count < 20, bad_count) # Check the transforms self._check_barycentric_transforms(tri) @dec.slow @dec.skipif( NumpyVersion(np.__version__) < '1.6.0', "No einsum in numpy 1.5.x") def test_more_barycentric_transforms(self): # Triangulate some "nasty" grids eps = np.finfo(float).eps npoints = {2: 70, 3: 11, 4: 5, 5: 3} for ndim in xrange(2, 6): # Generate an uniform grid in n-d unit cube x = np.linspace(0, 1, npoints[ndim]) grid = np.c_[list( map(np.ravel, np.broadcast_arrays(*np.ix_(*([x] * ndim)))))].T err_msg = "ndim=%d" % ndim # Check using regular grid tri = qhull.Delaunay(grid) self._check_barycentric_transforms(tri, err_msg=err_msg, unit_cube=True) # Check with eps-perturbations np.random.seed(1234) m = (np.random.rand(grid.shape[0]) < 0.2) grid[m, :] += 2 * eps * (np.random.rand(*grid[m, :].shape) - 0.5) tri = qhull.Delaunay(grid) self._check_barycentric_transforms(tri, err_msg=err_msg, unit_cube=True, unit_cube_tol=2 * eps) # Check with duplicated data tri = qhull.Delaunay(np.r_[grid, grid]) self._check_barycentric_transforms(tri, err_msg=err_msg, unit_cube=True, unit_cube_tol=2 * eps) # Check with larger perturbations np.random.seed(4321) m = (np.random.rand(grid.shape[0]) < 0.2) grid[m, :] += 1000 * eps * (np.random.rand(*grid[m, :].shape) - 0.5) tri = qhull.Delaunay(grid) self._check_barycentric_transforms(tri, err_msg=err_msg, unit_cube=True, unit_cube_tol=1500 * eps) # Check with yet larger perturbations np.random.seed(4321) m = (np.random.rand(grid.shape[0]) < 0.2) grid[m, :] += 1e6 * eps * (np.random.rand(*grid[m, :].shape) - 0.5) tri = qhull.Delaunay(grid) self._check_barycentric_transforms(tri, err_msg=err_msg, unit_cube=True, unit_cube_tol=1e7 * eps)
iflag = np.cumsum(flag) - 1 iperm = perm.argsort() if return_index: return aux[flag], perm[flag], iflag[iperm] else: return aux[flag], iflag[iperm] else: return aux[flag], perm[flag] else: ar.sort() flag = np.concatenate(([True], ar[1:] != ar[:-1])) return ar[flag] if NumpyVersion(np.__version__) > '1.7.0-dev': _compat_unique = np.unique else: _compat_unique = _compat_unique_impl def _compat_bincount_impl(x, weights=None, minlength=None): """ Bincount with minlength keyword added for Numpy 1.5. """ if weights is None: x = np.bincount(x) else: x = np.bincount(x, weights=weights) if minlength is not None: if x.shape[0] < minlength:
from __future__ import division, print_function, absolute_import import sys import numpy as np from numpy.testing import assert_, assert_allclose, dec import scipy.special.orthogonal as orth from scipy.lib._version import NumpyVersion from scipy.special._testutils import FuncData # Early Numpy versions have bugs in ufunc keyword argument parsing numpy_version_requirement = dec.skipif( NumpyVersion(np.__version__) < '1.6.0' and sys.version_info[0] >= 3, "Bug in Numpy < 1.6 on Python 3") def test_eval_chebyt(): n = np.arange(0, 10000, 7) x = 2*np.random.rand() - 1 v1 = np.cos(n*np.arccos(x)) v2 = orth.eval_chebyt(n, x) assert_(np.allclose(v1, v2, rtol=1e-15)) def test_eval_genlaguerre_restriction(): # check it returns nan for alpha <= -1 assert_(np.isnan(orth.eval_genlaguerre(0, -1, 0))) assert_(np.isnan(orth.eval_genlaguerre(0.1, -1, 0)))