def test_0d(self): # gh-580 x = np.unravel_index(0, ()) assert_equal(x, ()) assert_raises_regex(ValueError, "0d array", np.unravel_index, [0], ()) assert_raises_regex( ValueError, "out of bounds", np.unravel_index, [1], ())
def test_invalid_nesting(self, block): msg = 'depths are mismatched' assert_raises_regex(ValueError, msg, block, [1, [2]]) assert_raises_regex(ValueError, msg, block, [1, []]) assert_raises_regex(ValueError, msg, block, [[1], 2]) assert_raises_regex(ValueError, msg, block, [[], 2]) assert_raises_regex(ValueError, msg, block, [ [[1], [2]], [[3, 4]], [5] # missing brackets ])
def test_waverec_invalid_inputs(): # input must be list or tuple assert_raises(ValueError, pywt.waverec, np.ones(8), 'haar') # input list cannot be empty assert_raises(ValueError, pywt.waverec, [], 'haar') # 'array_to_coeffs must specify 'output_format' to perform waverec x = [3, 7, 1, 1, -2, 5, 4, 6] coeffs = pywt.wavedec(x, 'db1') arr, coeff_slices = pywt.coeffs_to_array(coeffs) coeffs_from_arr = pywt.array_to_coeffs(arr, coeff_slices) message = "Wrong coefficient format, if using 'array_to_coeffs' please specify the 'output_format' parameter" assert_raises_regex(AttributeError, message, pywt.waverec, coeffs_from_arr, 'haar')
def test_density_normed_redundancy(self): v = np.arange(10) bins = np.array([0, 1, 3, 6, 10]) with assert_raises_regex(TypeError, "Cannot specify both"): hist_dd, edges_dd = histogramdd((v,), (bins,), density=True, normed=True)
def test_write_version(): f = BytesIO() arr = np.arange(1) # These should pass. format.write_array(f, arr, version=(1, 0)) format.write_array(f, arr) format.write_array(f, arr, version=None) format.write_array(f, arr) format.write_array(f, arr, version=(2, 0)) format.write_array(f, arr) # These should all fail. bad_versions = [ (1, 1), (0, 0), (0, 1), (2, 2), (255, 255), ] for version in bad_versions: with assert_raises_regex(ValueError, 'we only support format version.*'): format.write_array(f, arr, version=version)
def test_no_wrapper(self): array = np.array(1) func = dispatched_one_arg.__wrapped__ with assert_raises_regex(AttributeError, '__wrapped__'): array.__array_function__(func=func, types=(np.ndarray,), args=(array,), kwargs={})
def test_unexpected_kwarg(self): # ensure than an appropriate TypeError # is raised when array2string receives # an unexpected kwarg with assert_raises_regex(TypeError, 'nonsense'): np.array2string(np.array([1, 2, 3]), nonsense=None)
def test_rmod(self): assert_(("%s" % self.A) == str(self.A)) assert_(("%r" % self.A) == repr(self.A)) for ob in [42, object()]: with assert_raises_regex( TypeError, "unsupported operand type.* and 'chararray'"): ob % self.A
def test_not_implemented(self): class MyArray(object): def __array_function__(self, func, types, args, kwargs): return NotImplemented array = MyArray() with assert_raises_regex(TypeError, 'no implementation found'): dispatched_one_arg(array)
def test_too_many_duck_arrays(self): namespace = dict(__array_function__=_return_not_implemented) types = [type('A' + str(i), (object,), namespace) for i in range(33)] relevant_args = [t() for t in types] actual = _get_implementing_args(relevant_args[:32]) assert_equal(actual, relevant_args[:32]) with assert_raises_regex(TypeError, 'distinct argument types'): _get_implementing_args(relevant_args)
def test_broadcast_kwargs(): # ensure that a TypeError is appropriately raised when # np.broadcast_arrays() is called with any keyword # argument other than 'subok' x = np.arange(10) y = np.arange(10) with assert_raises_regex(TypeError, r'broadcast_arrays\(\) got an unexpected keyword*'): broadcast_arrays(x, y, dtype='float64')
def test_ediff1d_forbidden_type_casts(self, ary, prepend, append): # verify resolution of gh-11490 # specifically, raise an appropriate # Exception when attempting to append or # prepend with an incompatible type msg = 'cannot convert' with assert_raises_regex(ValueError, msg): ediff1d(ary=ary, to_end=append, to_begin=prepend)
def test_rmul(self): A = self.A for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0]*r, A[0, 1]*r], [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) assert_array_equal(Ar, (r * self.A)) for ob in [object(), 'qrs']: with assert_raises_regex(ValueError, 'Can only multiply by integers'): ob * A
def test_not_implemented(self): MyArray, implements = _new_duck_type_and_implements() @array_function_dispatch(lambda array: (array,)) def func(array): return array array = np.array(1) assert_(func(array) is array) with assert_raises_regex(TypeError, 'no implementation found'): func(MyArray())
def test_exceptions(self): # test axis must be in bounds for ndim in [1, 2, 3]: a = np.ones((1,)*ndim) np.concatenate((a, a), axis=0) # OK assert_raises(np.AxisError, np.concatenate, (a, a), axis=ndim) assert_raises(np.AxisError, np.concatenate, (a, a), axis=-(ndim + 1)) # Scalars cannot be concatenated assert_raises(ValueError, concatenate, (0,)) assert_raises(ValueError, concatenate, (np.array(0),)) # dimensionality must match assert_raises_regex( ValueError, r"all the input arrays must have same number of dimensions, but " r"the array at index 0 has 1 dimension\(s\) and the array at " r"index 1 has 2 dimension\(s\)", np.concatenate, (np.zeros(1), np.zeros((1, 1)))) # test shapes must match except for concatenation axis a = np.ones((1, 2, 3)) b = np.ones((2, 2, 3)) axis = list(range(3)) for i in range(3): np.concatenate((a, b), axis=axis[0]) # OK assert_raises_regex( ValueError, "all the input array dimensions for the concatenation axis " "must match exactly, but along dimension {}, the array at " "index 0 has size 1 and the array at index 1 has size 2" .format(i), np.concatenate, (a, b), axis=axis[1]) assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2]) a = np.moveaxis(a, -1, 0) b = np.moveaxis(b, -1, 0) axis.append(axis.pop(0)) # No arrays to concatenate raises ValueError assert_raises(ValueError, concatenate, ())
def test_not_implemented(self): MyArray, implements = _new_duck_type_and_implements() @array_function_dispatch(lambda array: (array,), module='my') def func(array): return array array = np.array(1) assert_(func(array) is array) assert_equal(func.__module__, 'my') with assert_raises_regex( TypeError, "no implementation found for 'my.func'"): func(MyArray())
def test_method(self): class Other(object): __array_function__ = _return_not_implemented class NoOverrideSub(np.ndarray): pass class OverrideSub(np.ndarray): __array_function__ = _return_not_implemented array = np.array([1]) other = Other() no_override_sub = array.view(NoOverrideSub) override_sub = array.view(OverrideSub) result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray,), args=(array, 1.), kwargs={}) assert_equal(result, 'original') result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray, Other), args=(array, other), kwargs={}) assert_(result is NotImplemented) result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray, NoOverrideSub), args=(array, no_override_sub), kwargs={}) assert_equal(result, 'original') result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray, OverrideSub), args=(array, override_sub), kwargs={}) assert_equal(result, 'original') with assert_raises_regex(TypeError, 'no implementation found'): np.concatenate((array, other)) expected = np.concatenate((array, array)) result = np.concatenate((array, no_override_sub)) assert_equal(result, expected.view(NoOverrideSub)) result = np.concatenate((array, override_sub)) assert_equal(result, expected.view(OverrideSub))
def test_bad_arguments(): X, y = make_blobs(100, random_state=42) mst = MSTClustering() assert_raises_regex(ValueError, "Must specify either cutoff or cutoff_frac", mst.fit, X, y) mst = MSTClustering(cutoff=-1) assert_raises_regex(ValueError, "cutoff must be positive", mst.fit, X) mst = MSTClustering() msg = "Must call fit\(\) before get_graph_segments()" assert_raises_regex(ValueError, msg, mst.get_graph_segments) mst = MSTClustering(cutoff=0, metric='precomputed') mst.fit(pairwise_distances(X)) msg = "Cannot use ``get_graph_segments`` with precomputed metric." assert_raises_regex(ValueError, msg, mst.get_graph_segments)
def test_hetero_shape_handling(self): # raise error with high dimensionality and # shape mismatch a = np.zeros((3, 3, 7, 3), int) with assert_raises_regex(ValueError, "equal length"): fill_diagonal(a, 2)
def test_empty_lists(self, block): assert_raises_regex(ValueError, 'empty', block, []) assert_raises_regex(ValueError, 'empty', block, [[]]) assert_raises_regex(ValueError, 'empty', block, [[1], []])
def test_stack(): # non-iterable input assert_raises(TypeError, stack, 1) # 0d input for input_ in [(1, 2, 3), [np.int32(1), np.int32(2), np.int32(3)], [np.array(1), np.array(2), np.array(3)]]: assert_array_equal(stack(input_), [1, 2, 3]) # 1d input examples a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) r1 = array([[1, 2, 3], [4, 5, 6]]) assert_array_equal(np.stack((a, b)), r1) assert_array_equal(np.stack((a, b), axis=1), r1.T) # all input types assert_array_equal(np.stack(list([a, b])), r1) assert_array_equal(np.stack(array([a, b])), r1) # all shapes for 1d input arrays = [np.random.randn(3) for _ in range(10)] axes = [0, 1, -1, -2] expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=2) assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=-3) # all shapes for 2d input arrays = [np.random.randn(3, 4) for _ in range(10)] axes = [0, 1, 2, -1, -2, -3] expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10), (3, 4, 10), (3, 10, 4), (10, 3, 4)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) # empty arrays assert_(stack([[], [], []]).shape == (3, 0)) assert_(stack([[], [], []], axis=1).shape == (0, 3)) # out out = np.zeros_like(r1) np.stack((a, b), out=out) assert_array_equal(out, r1) # edge cases assert_raises_regex(ValueError, 'need at least one array', stack, []) assert_raises_regex(ValueError, 'must have the same shape', stack, [1, np.arange(3)]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.zeros((3, 3)), np.zeros(3)], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(2), np.arange(3)]) # generator is deprecated with assert_warns(FutureWarning): result = stack((x for x in range(3))) assert_array_equal(result, np.array([0, 1, 2]))
def test_gradient_descent_non_match_parameters_gradients_not_ordered(): W = shared_floatx(numpy.array([[1, 2], [3, 4]])) z = shared_floatx(5) assert_raises_regex(ValueError, "fixed order", GradientDescent, parameters=[z], gradients={W: 2 * W})
def test_gradient_descent_parameters_no_cost(): W = shared_floatx(numpy.array([[1, 2], [3, 4]])) assert_raises_regex(ValueError, "no cost", GradientDescent, parameters=[W])
def test_stack(): # 2018-04-29: copied here from core.tests.test_shape_base # check np.matrix cannot be stacked m = np.matrix([[1, 2], [3, 4]]) assert_raises_regex(ValueError, 'shape too large to be a matrix', np.stack, [m, m])
def test_arr_weights_mismatch(self): a = np.arange(10) + .5 w = np.arange(11) + .5 with assert_raises_regex(ValueError, "same shape as"): h, b = histogram(a, range=[1, 9], weights=w, density=True)
def test_stack(): # non-iterable input assert_raises(TypeError, stack, 1) # 0d input for input_ in [(1, 2, 3), [np.int32(1), np.int32(2), np.int32(3)], [np.array(1), np.array(2), np.array(3)]]: assert_array_equal(stack(input_), [1, 2, 3]) # 1d input examples a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) r1 = array([[1, 2, 3], [4, 5, 6]]) assert_array_equal(np.stack((a, b)), r1) assert_array_equal(np.stack((a, b), axis=1), r1.T) # all input types assert_array_equal(np.stack(list([a, b])), r1) assert_array_equal(np.stack(array([a, b])), r1) # all shapes for 1d input arrays = [np.random.randn(3) for _ in range(10)] axes = [0, 1, -1, -2] expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=2) assert_raises_regex(np.AxisError, 'out of bounds', stack, arrays, axis=-3) # all shapes for 2d input arrays = [np.random.randn(3, 4) for _ in range(10)] axes = [0, 1, 2, -1, -2, -3] expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10), (3, 4, 10), (3, 10, 4), (10, 3, 4)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) # empty arrays assert_(stack([[], [], []]).shape == (3, 0)) assert_(stack([[], [], []], axis=1).shape == (0, 3)) # out out = np.zeros_like(r1) np.stack((a, b), out=out) assert_array_equal(out, r1) # edge cases assert_raises_regex(ValueError, 'need at least one array', stack, []) assert_raises_regex(ValueError, 'must have the same shape', stack, [1, np.arange(3)]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.zeros( (3, 3)), np.zeros(3)], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(2), np.arange(3)]) # generator is deprecated with assert_warns(FutureWarning): result = stack((x for x in range(3))) assert_array_equal(result, np.array([0, 1, 2]))
def test_aggregation_buffer_name_uniqueness(): x1 = tensor.scalar('x') x2 = tensor.scalar('x') assert_raises_regex(ValueError, 'unique', AggregationBuffer, [x1, x2])
def test_tuple(self, block): assert_raises_regex(TypeError, 'tuple', block, ([1, 2], [3, 4])) assert_raises_regex(TypeError, 'tuple', block, [(1, 2), (3, 4)])
def test_einsum_errors(self): for do_opt in [True, False]: # Need enough arguments assert_raises(ValueError, np.einsum, optimize=do_opt) assert_raises(ValueError, np.einsum, "", optimize=do_opt) # subscripts must be a string assert_raises(TypeError, np.einsum, 0, 0, optimize=do_opt) # out parameter must be an array assert_raises(TypeError, np.einsum, "", 0, out='test', optimize=do_opt) # order parameter must be a valid order assert_raises(TypeError, np.einsum, "", 0, order='W', optimize=do_opt) # casting parameter must be a valid casting assert_raises(ValueError, np.einsum, "", 0, casting='blah', optimize=do_opt) # dtype parameter must be a valid dtype assert_raises(TypeError, np.einsum, "", 0, dtype='bad_data_type', optimize=do_opt) # other keyword arguments are rejected assert_raises(TypeError, np.einsum, "", 0, bad_arg=0, optimize=do_opt) # issue 4528 revealed a segfault with this call assert_raises(TypeError, np.einsum, *(None,)*63, optimize=do_opt) # number of operands must match count in subscripts string assert_raises(ValueError, np.einsum, "", 0, 0, optimize=do_opt) assert_raises(ValueError, np.einsum, ",", 0, [0], [0], optimize=do_opt) assert_raises(ValueError, np.einsum, ",", [0], optimize=do_opt) # can't have more subscripts than dimensions in the operand assert_raises(ValueError, np.einsum, "i", 0, optimize=do_opt) assert_raises(ValueError, np.einsum, "ij", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, "...i", 0, optimize=do_opt) assert_raises(ValueError, np.einsum, "i...j", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, "i...", 0, optimize=do_opt) assert_raises(ValueError, np.einsum, "ij...", [0, 0], optimize=do_opt) # invalid ellipsis assert_raises(ValueError, np.einsum, "i..", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, ".i...", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, "j->..j", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, "j->.j...", [0, 0], optimize=do_opt) # invalid subscript character assert_raises(ValueError, np.einsum, "i%...", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, "...j$", [0, 0], optimize=do_opt) assert_raises(ValueError, np.einsum, "i->&", [0, 0], optimize=do_opt) # output subscripts must appear in input assert_raises(ValueError, np.einsum, "i->ij", [0, 0], optimize=do_opt) # output subscripts may only be specified once assert_raises(ValueError, np.einsum, "ij->jij", [[0, 0], [0, 0]], optimize=do_opt) # dimensions much match when being collapsed assert_raises(ValueError, np.einsum, "ii", np.arange(6).reshape(2, 3), optimize=do_opt) assert_raises(ValueError, np.einsum, "ii->i", np.arange(6).reshape(2, 3), optimize=do_opt) # broadcasting to new dimensions must be enabled explicitly assert_raises(ValueError, np.einsum, "i", np.arange(6).reshape(2, 3), optimize=do_opt) assert_raises(ValueError, np.einsum, "i->i", [[0, 1], [0, 1]], out=np.arange(4).reshape(2, 2), optimize=do_opt) with assert_raises_regex(ValueError, "'b'"): # gh-11221 - 'c' erroneously appeared in the error message a = np.ones((3, 3, 4, 5, 6)) b = np.ones((3, 4, 5)) np.einsum('aabcb,abc', a, b)
def test_error_shape_mismatch(self): x = np.zeros((3, 3, 2, 3), int) with assert_raises_regex(ValueError, "equal length"): diag_indices_from(x)
def test_error_small_input(self): x = np.ones(7) with assert_raises_regex(ValueError, "at least 2-d"): diag_indices_from(x)
def test_invalid_range(self): # start of range must be < end of range vals = np.linspace(0.0, 1.0, num=100) with assert_raises_regex(ValueError, "max must be larger than"): np.histogram(vals, range=[0.1, 0.01])
def test_bin_array_dims(self): # gracefully handle bins object > 1 dimension vals = np.linspace(0.0, 1.0, num=100) bins = np.array([[0, 0.5], [0.6, 1.0]]) with assert_raises_regex(ValueError, "must be 1d"): np.histogram(vals, bins=bins)
def test_real_distance_out_of_range(): ints = Real(1, 10) assert_raises_regex(RuntimeError, "compute distance for values within", ints.distance, 11, 10)
def test_stack(): # 0d input for input_ in [(1, 2, 3), [np.int32(1), np.int32(2), np.int32(3)], [np.array(1), np.array(2), np.array(3)]]: assert_array_equal(stack(input_), [1, 2, 3]) # 1d input examples a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) r1 = array([[1, 2, 3], [4, 5, 6]]) assert_array_equal(np.stack((a, b)), r1) assert_array_equal(np.stack((a, b), axis=1), r1.T) # all input types assert_array_equal(np.stack(list([a, b])), r1) assert_array_equal(np.stack(array([a, b])), r1) # all shapes for 1d input arrays = [np.random.randn(3) for _ in range(10)] axes = [0, 1, -1, -2] expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) assert_raises_regex(IndexError, 'out of bounds', stack, arrays, axis=2) assert_raises_regex(IndexError, 'out of bounds', stack, arrays, axis=-3) # all shapes for 2d input arrays = [np.random.randn(3, 4) for _ in range(10)] axes = [0, 1, 2, -1, -2, -3] expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10), (3, 4, 10), (3, 10, 4), (10, 3, 4)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) # empty arrays assert_(stack([[], [], []]).shape == (3, 0)) assert_(stack([[], [], []], axis=1).shape == (0, 3)) # edge cases assert_raises_regex(ValueError, 'need at least one array', stack, []) assert_raises_regex(ValueError, 'must have the same shape', stack, [1, np.arange(3)]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.zeros((3, 3)), np.zeros(3)], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(2), np.arange(3)]) # np.matrix m = np.matrix([[1, 2], [3, 4]]) assert_raises_regex(ValueError, 'shape too large to be a matrix', stack, [m, m])
def test_empty_indices(self): msg1 = 'indices must be integral: the provided empty sequence was' msg2 = 'only int indices permitted' assert_raises_regex(TypeError, msg1, np.unravel_index, [], (10, 3, 5)) assert_raises_regex(TypeError, msg1, np.unravel_index, (), (10, 3, 5)) assert_raises_regex(TypeError, msg2, np.unravel_index, np.array([]), (10, 3, 5)) assert_equal(np.unravel_index(np.array([], dtype=int), (10, 3, 5)), [[], [], []]) assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], []), (10, 3)) assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], ['abc']), (10, 3)) assert_raises_regex(TypeError, msg2, np.ravel_multi_index, (np.array([]), np.array([])), (5, 3)) assert_equal( np.ravel_multi_index( (np.array([], dtype=int), np.array([], dtype=int)), (5, 3)), []) assert_equal( np.ravel_multi_index(np.array([[], []], dtype=int), (5, 3)), [])
def test_assert_raises_regex_context_manager(): with assert_raises_regex(ValueError, 'no deprecation warning'): raise ValueError('no deprecation warning')
def test_invalid_dimension(): assert_raises_regex(ValueError, "has to be a list or tuple", space_check_dimension, "23") # single value fixes dimension of space space_check_dimension((23, ))
def test_gradient_descent_parameters_no_parameters(): W = shared_floatx(numpy.array([[1, 2], [3, 4]])) assert_raises_regex(ValueError, "no parameters", GradientDescent, cost=W.sum())
def test_stack(): # 2018-04-29: copied here from core.tests.test_shape_base # check np.matrix cannot be stacked m = np.matrix([[1, 2], [3, 4]]) assert_raises_regex(ValueError, "shape too large to be a matrix", np.stack, [m, m])
def test_stack(): # 0d input for input_ in [(1, 2, 3), [np.int32(1), np.int32(2), np.int32(3)], [np.array(1), np.array(2), np.array(3)]]: assert_array_equal(stack(input_), [1, 2, 3]) # 1d input examples a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) r1 = array([[1, 2, 3], [4, 5, 6]]) assert_array_equal(np.stack((a, b)), r1) assert_array_equal(np.stack((a, b), axis=1), r1.T) # all input types assert_array_equal(np.stack(list([a, b])), r1) assert_array_equal(np.stack(array([a, b])), r1) # all shapes for 1d input arrays = [np.random.randn(3) for _ in range(10)] axes = [0, 1, -1, -2] expected_shapes = [(10, 3), (3, 10), (3, 10), (10, 3)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) assert_raises_regex(IndexError, 'out of bounds', stack, arrays, axis=2) assert_raises_regex(IndexError, 'out of bounds', stack, arrays, axis=-3) # all shapes for 2d input arrays = [np.random.randn(3, 4) for _ in range(10)] axes = [0, 1, 2, -1, -2, -3] expected_shapes = [(10, 3, 4), (3, 10, 4), (3, 4, 10), (3, 4, 10), (3, 10, 4), (10, 3, 4)] for axis, expected_shape in zip(axes, expected_shapes): assert_equal(np.stack(arrays, axis).shape, expected_shape) # empty arrays assert_(stack([[], [], []]).shape == (3, 0)) assert_(stack([[], [], []], axis=1).shape == (0, 3)) # edge cases assert_raises_regex(ValueError, 'need at least one array', stack, []) assert_raises_regex(ValueError, 'must have the same shape', stack, [1, np.arange(3)]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1]) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(3), 1], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.zeros( (3, 3)), np.zeros(3)], axis=1) assert_raises_regex(ValueError, 'must have the same shape', stack, [np.arange(2), np.arange(3)]) # np.matrix m = np.matrix([[1, 2], [3, 4]]) assert_raises_regex(ValueError, 'shape too large to be a matrix', stack, [m, m])
def test_aggregation_buffer_name_none(): assert_raises_regex(ValueError, 'must have names', AggregationBuffer, [theano.tensor.scalar()])
def test_low_dim_handling(self): # raise error with low dimensionality a = np.zeros(3, int) with assert_raises_regex(ValueError, "at least 2-d"): fill_diagonal(a, 5)