def test_against_numpy_convolve(self, cpx, na, nv, mode): a = self.create_vector(na, cpx) v = self.create_vector(nv, cpx) if mode is None: y1 = np.convolve(v, a) A = convolution_matrix(a, nv) else: y1 = np.convolve(v, a, mode) A = convolution_matrix(a, nv, mode) y2 = A @ v assert_array_almost_equal(y1, y2)
def test_convolution_matrix(): 'test convolution_matrix vs. numpy.convolve for various parameters' def test_vector(n, cpx): 'make a complex or real test vector of length n' if cpx: return np.random.normal(size=(n, 2))\ .astype(np.float64).view(np.complex128).ravel() else: return np.random.normal(size=(n,)) # first arg must be a 1d array, otherwise ValueError with assert_raises(ValueError): convolution_matrix(1, 4) # mode must be in ('full','valid','same') with assert_raises(ValueError): convolution_matrix((1, 1), 4, mode='invalid argument') array_sizes = (2, 9, 100) for cpx, na, nv, mode in itertools.product( (False, True), array_sizes, array_sizes, (None, 'full', 'valid', 'same')): a = test_vector(na, cpx) v = test_vector(nv, cpx) if mode is None: y1 = np.convolve(v, a) A = convolution_matrix(a, nv) else: y1 = np.convolve(v, a, mode) A = convolution_matrix(a, nv, mode) y2 = A @ v assert_array_almost_equal(y1, y2) if mode == 'full': for i in range(A.shape[0]): for j in range(A.shape[1]): assert_equal(A[i, j], (a[i-j] if (0 <= (i-j) < len(a)) else 0))
def test_bad_mode(self): # mode must be in ('full', 'valid', 'same') with pytest.raises(ValueError, match='mode.*must be one of'): convolution_matrix((1, 1), 4, mode='invalid argument')
def test_empty_first_arg(self): # first arg must have at least one value with pytest.raises(ValueError, match=r'len\(a\)'): convolution_matrix([], 4)
def test_bad_first_arg(self): # first arg must be a 1d array, otherwise ValueError with pytest.raises(ValueError, match='one-dimensional'): convolution_matrix(1, 4)
def test_bad_n(self): # n must be a positive integer with pytest.raises(ValueError, match='n must be a positive integer'): convolution_matrix([1, 2, 3], 0)