def test_single_value(self): """Test casting for a single value.""" expected = np.array([[3, 3]] * 10) for x in (3, [3], [[3]]): result = _as_pairs(x, 10) assert_equal(result, expected) # Test with dtype=object obj = object() assert_equal(_as_pairs(obj, 10), np.array([[obj, obj]] * 10))
def test_as_index(self): """Test results if `as_index=True`.""" assert_equal(_as_pairs([2.6, 3.3], 10, as_index=True), np.array([[3, 3]] * 10, dtype=np.intp)) assert_equal(_as_pairs([2.6, 4.49], 10, as_index=True), np.array([[3, 4]] * 10, dtype=np.intp)) for x in (-3, [-3], [[-3]], [-3, 4], [3, -4], [[-3, 4]], [[4, -3]], [[1, 2]] * 9 + [[1, -2]]): with pytest.raises(ValueError, match="negative values"): _as_pairs(x, 10, as_index=True)
def test_with_none(self): expected = ((None, None), (None, None), (None, None)) assert_equal( _as_pairs(None, 3, as_index=False), expected ) assert_equal( _as_pairs(None, 3, as_index=True), expected )
def test_single_value(self): """Test casting for a single value.""" expected = np.array([[3, 3]] * 10) for x in (3, [3], [[3]]): result = _as_pairs(x, 10) assert_equal(result, expected) # Test with dtype=object obj = object() assert_equal( _as_pairs(obj, 10), np.array([[obj, obj]] * 10) )
def test_as_index(self): """Test results if `as_index=True`.""" assert_equal( _as_pairs([2.6, 3.3], 10, as_index=True), np.array([[3, 3]] * 10, dtype=np.intp) ) assert_equal( _as_pairs([2.6, 4.49], 10, as_index=True), np.array([[3, 4]] * 10, dtype=np.intp) ) for x in (-3, [-3], [[-3]], [-3, 4], [3, -4], [[-3, 4]], [[4, -3]], [[1, 2]] * 9 + [[1, -2]]): with pytest.raises(ValueError, match="negative values"): _as_pairs(x, 10, as_index=True)
def crop(ar, crop_width, copy=False, order='K'): """Crop array `ar` by `crop_width` along each dimension. Parameters ---------- ar : array-like of rank N Input array. crop_width : {sequence, int} Number of values to remove from the edges of each axis. ``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies unique crop widths at the start and end of each axis. ``((before, after),)`` specifies a fixed start and end crop for every axis. ``(n,)`` or ``n`` for integer ``n`` is a shortcut for before = after = ``n`` for all axes. copy : bool, optional If `True`, ensure the returned array is a contiguous copy. Normally, a crop operation will return a discontiguous view of the underlying input array. order : {'C', 'F', 'A', 'K'}, optional If ``copy==True``, control the memory layout of the copy. See ``np.copy``. Returns ------- cropped : array The cropped array. If ``copy=False`` (default), this is a sliced view of the input array. """ ar = np.array(ar, copy=False) crops = _as_pairs(crop_width, ar.ndim, as_index=True) slices = tuple(slice(a, ar.shape[i] - b) for i, (a, b) in enumerate(crops)) if copy: cropped = np.array(ar[slices], order=order, copy=True) else: cropped = ar[slices] return cropped
def test_two_values(self): """Test proper casting for two different values.""" # Broadcasting in the first dimension with numbers expected = np.array([[3, 4]] * 10) for x in ([3, 4], [[3, 4]]): result = _as_pairs(x, 10) assert_equal(result, expected) # and with dtype=object obj = object() assert_equal(_as_pairs(["a", obj], 10), np.array([["a", obj]] * 10)) # Broadcasting in the second / last dimension with numbers assert_equal(_as_pairs([[3], [4]], 2), np.array([[3, 3], [4, 4]])) # and with dtype=object assert_equal(_as_pairs([["a"], [obj]], 2), np.array([["a", "a"], [obj, obj]]))
def test_pass_through(self): """Test if `x` already matching desired output are passed through.""" expected = np.arange(12).reshape((6, 2)) assert_equal( _as_pairs(expected, 6), expected )
def crop(ar, crop_width): #from skimage.util import crop from numpy.lib.arraypad import _as_pairs crops = _as_pairs(crop_width, ar.ndim, as_index=True) slices = tuple(slice(a, ar.shape[i] - b) for i, (a, b) in enumerate(crops)) cropped = ar[slices] return cropped
def crop(ar, crop_width, copy=False, order='K'): """Crop array `ar` by `crop_width` along each dimension. Parameters ---------- ar : array-like of rank N Input array. crop_width : {sequence, int} Number of values to remove from the edges of each axis. ``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies unique crop widths at the start and end of each axis. ``((before, after),)`` specifies a fixed start and end crop for every axis. ``(n,)`` or ``n`` for integer ``n`` is a shortcut for before = after = ``n`` for all axes. copy : bool, optional If `True`, ensure the returned array is a contiguous copy. Normally, a crop operation will return a discontiguous view of the underlying input array. order : {'C', 'F', 'A', 'K'}, optional If ``copy==True``, control the memory layout of the copy. See ``np.copy``. Returns ------- cropped : array The cropped array. If ``copy=False`` (default), this is a sliced view of the input array. """ # Since arraycrop is in the critical import path, we lazy import distutils # to check the version of numpy # After numpy 1.15, a new backward compatible function have been # implemented. # See https://github.com/numpy/numpy/pull/11966 from distutils.version import LooseVersion as Version old_numpy = Version(np.__version__) < Version('1.16') if old_numpy: from numpy.lib.arraypad import _validate_lengths else: from numpy.lib.arraypad import _as_pairs ar = np.array(ar, copy=False) if old_numpy: crops = _validate_lengths(ar, crop_width) else: crops = _as_pairs(crop_width, ar.ndim, as_index=True) slices = tuple(slice(a, ar.shape[i] - b) for i, (a, b) in enumerate(crops)) if copy: cropped = np.array(ar[slices], order=order, copy=True) else: cropped = ar[slices] return cropped
def test_exceptions(self): """Ensure faulty usage is discovered.""" with pytest.raises(ValueError, match="more dimensions than allowed"): _as_pairs([[[3]]], 10) with pytest.raises(ValueError, match="could not be broadcast"): _as_pairs([[1, 2], [3, 4]], 3) with pytest.raises(ValueError, match="could not be broadcast"): _as_pairs(np.ones((2, 3)), 3)
def test_two_values(self): """Test proper casting for two different values.""" # Broadcasting in the first dimension with numbers expected = np.array([[3, 4]] * 10) for x in ([3, 4], [[3, 4]]): result = _as_pairs(x, 10) assert_equal(result, expected) # and with dtype=object obj = object() assert_equal( _as_pairs(["a", obj], 10), np.array([["a", obj]] * 10) ) # Broadcasting in the second / last dimension with numbers assert_equal( _as_pairs([[3], [4]], 2), np.array([[3, 3], [4, 4]]) ) # and with dtype=object assert_equal( _as_pairs([["a"], [obj]], 2), np.array([["a", "a"], [obj, obj]]) )
def crop(ar, crop_width, copy=False, order='K'): """Crop array `ar` by `crop_width` along each dimension. Parameters ---------- ar : array-like of rank N Input array. crop_width : {sequence, int} Number of values to remove from the edges of each axis. ``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies unique crop widths at the start and end of each axis. ``((before, after),)`` specifies a fixed start and end crop for every axis. ``(n,)`` or ``n`` for integer ``n`` is a shortcut for before = after = ``n`` for all axes. copy : bool, optional If `True`, ensure the returned array is a contiguous copy. Normally, a crop operation will return a discontiguous view of the underlying input array. order : {'C', 'F', 'A', 'K'}, optional If ``copy==True``, control the memory layout of the copy. See ``np.copy``. Returns ------- cropped : array The cropped array. If ``copy=False`` (default), this is a sliced view of the input array. """ ar = np.array(ar, copy=False) if old_numpy: crops = _validate_lengths(ar, crop_width) else: crops = _as_pairs(crop_width, ar.ndim, as_index=True) slices = tuple(slice(a, ar.shape[i] - b) for i, (a, b) in enumerate(crops)) if copy: cropped = np.array(ar[slices], order=order, copy=True) else: cropped = ar[slices] return cropped
def validate_lengths(ar, crop_width): return _as_pairs(crop_width, ar.ndim, as_index=True)