예제 #1
0
 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))
예제 #2
0
 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)
예제 #3
0
 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
     )
예제 #4
0
 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
     )
예제 #5
0
 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)
     )
예제 #6
0
 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)
예제 #7
0
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
예제 #8
0
    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]]))
예제 #9
0
 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
     )
예제 #10
0
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
예제 #11
0
 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
     )
예제 #12
0
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
예제 #13
0
 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)
예제 #14
0
 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)
예제 #15
0
    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]])
        )
예제 #16
0
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
예제 #17
0
 def validate_lengths(ar, crop_width):
     return _as_pairs(crop_width, ar.ndim, as_index=True)